xref: /spdk/lib/blob/blobstore.c (revision 3225f86bc248c13417669e566b99d5ca41bc6a1c)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "spdk/blob.h"
37 #include "spdk/crc32.h"
38 #include "spdk/env.h"
39 #include "spdk/queue.h"
40 #include "spdk/thread.h"
41 #include "spdk/bit_array.h"
42 #include "spdk/likely.h"
43 #include "spdk/util.h"
44 
45 #include "spdk_internal/assert.h"
46 #include "spdk_internal/log.h"
47 
48 #include "blobstore.h"
49 
50 #define BLOB_CRC32C_INITIAL    0xffffffffUL
51 
52 static int spdk_bs_register_md_thread(struct spdk_blob_store *bs);
53 static int spdk_bs_unregister_md_thread(struct spdk_blob_store *bs);
54 static void _spdk_blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno);
55 static void _spdk_blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
56 		uint64_t cluster, spdk_blob_op_complete cb_fn, void *cb_arg);
57 
58 static int _spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
59 				uint16_t value_len, bool internal);
60 static int _spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
61 				      const void **value, size_t *value_len, bool internal);
62 static int _spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal);
63 
64 static void
65 _spdk_blob_verify_md_op(struct spdk_blob *blob)
66 {
67 	assert(blob != NULL);
68 	assert(spdk_get_thread() == blob->bs->md_thread);
69 	assert(blob->state != SPDK_BLOB_STATE_LOADING);
70 }
71 
72 static struct spdk_blob_list *
73 _spdk_bs_get_snapshot_entry(struct spdk_blob_store *bs, spdk_blob_id blobid)
74 {
75 	struct spdk_blob_list *snapshot_entry = NULL;
76 
77 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
78 		if (snapshot_entry->id == blobid) {
79 			break;
80 		}
81 	}
82 
83 	return snapshot_entry;
84 }
85 
86 static void
87 _spdk_bs_claim_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
88 {
89 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
90 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == false);
91 	assert(bs->num_free_clusters > 0);
92 
93 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %u\n", cluster_num);
94 
95 	spdk_bit_array_set(bs->used_clusters, cluster_num);
96 	bs->num_free_clusters--;
97 }
98 
99 static int
100 _spdk_blob_insert_cluster(struct spdk_blob *blob, uint32_t cluster_num, uint64_t cluster)
101 {
102 	uint64_t *cluster_lba = &blob->active.clusters[cluster_num];
103 
104 	_spdk_blob_verify_md_op(blob);
105 
106 	if (*cluster_lba != 0) {
107 		return -EEXIST;
108 	}
109 
110 	*cluster_lba = _spdk_bs_cluster_to_lba(blob->bs, cluster);
111 	return 0;
112 }
113 
114 static int
115 _spdk_bs_allocate_cluster(struct spdk_blob *blob, uint32_t cluster_num,
116 			  uint64_t *lowest_free_cluster, bool update_map)
117 {
118 	pthread_mutex_lock(&blob->bs->used_clusters_mutex);
119 	*lowest_free_cluster = spdk_bit_array_find_first_clear(blob->bs->used_clusters,
120 			       *lowest_free_cluster);
121 	if (*lowest_free_cluster == UINT32_MAX) {
122 		/* No more free clusters. Cannot satisfy the request */
123 		pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
124 		return -ENOSPC;
125 	}
126 
127 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %lu for blob %lu\n", *lowest_free_cluster, blob->id);
128 	_spdk_bs_claim_cluster(blob->bs, *lowest_free_cluster);
129 	pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
130 
131 	if (update_map) {
132 		_spdk_blob_insert_cluster(blob, cluster_num, *lowest_free_cluster);
133 	}
134 
135 	return 0;
136 }
137 
138 static void
139 _spdk_bs_release_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
140 {
141 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
142 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == true);
143 	assert(bs->num_free_clusters < bs->total_clusters);
144 
145 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Releasing cluster %u\n", cluster_num);
146 
147 	pthread_mutex_lock(&bs->used_clusters_mutex);
148 	spdk_bit_array_clear(bs->used_clusters, cluster_num);
149 	bs->num_free_clusters++;
150 	pthread_mutex_unlock(&bs->used_clusters_mutex);
151 }
152 
153 static void
154 _spdk_blob_xattrs_init(struct spdk_blob_xattr_opts *xattrs)
155 {
156 	xattrs->count = 0;
157 	xattrs->names = NULL;
158 	xattrs->ctx = NULL;
159 	xattrs->get_value = NULL;
160 }
161 
162 void
163 spdk_blob_opts_init(struct spdk_blob_opts *opts)
164 {
165 	opts->num_clusters = 0;
166 	opts->thin_provision = false;
167 	_spdk_blob_xattrs_init(&opts->xattrs);
168 }
169 
170 void
171 spdk_blob_open_opts_init(struct spdk_blob_open_opts *opts)
172 {
173 	opts->clear_method = BLOB_CLEAR_WITH_DEFAULT;
174 }
175 
176 static struct spdk_blob *
177 _spdk_blob_alloc(struct spdk_blob_store *bs, spdk_blob_id id)
178 {
179 	struct spdk_blob *blob;
180 
181 	blob = calloc(1, sizeof(*blob));
182 	if (!blob) {
183 		return NULL;
184 	}
185 
186 	blob->id = id;
187 	blob->bs = bs;
188 
189 	blob->parent_id = SPDK_BLOBID_INVALID;
190 
191 	blob->state = SPDK_BLOB_STATE_DIRTY;
192 	blob->active.num_pages = 1;
193 	blob->active.pages = calloc(1, sizeof(*blob->active.pages));
194 	if (!blob->active.pages) {
195 		free(blob);
196 		return NULL;
197 	}
198 
199 	blob->active.pages[0] = _spdk_bs_blobid_to_page(id);
200 
201 	TAILQ_INIT(&blob->xattrs);
202 	TAILQ_INIT(&blob->xattrs_internal);
203 
204 	return blob;
205 }
206 
207 static void
208 _spdk_xattrs_free(struct spdk_xattr_tailq *xattrs)
209 {
210 	struct spdk_xattr	*xattr, *xattr_tmp;
211 
212 	TAILQ_FOREACH_SAFE(xattr, xattrs, link, xattr_tmp) {
213 		TAILQ_REMOVE(xattrs, xattr, link);
214 		free(xattr->name);
215 		free(xattr->value);
216 		free(xattr);
217 	}
218 }
219 
220 static void
221 _spdk_blob_free(struct spdk_blob *blob)
222 {
223 	assert(blob != NULL);
224 
225 	free(blob->active.clusters);
226 	free(blob->clean.clusters);
227 	free(blob->active.pages);
228 	free(blob->clean.pages);
229 
230 	_spdk_xattrs_free(&blob->xattrs);
231 	_spdk_xattrs_free(&blob->xattrs_internal);
232 
233 	if (blob->back_bs_dev) {
234 		blob->back_bs_dev->destroy(blob->back_bs_dev);
235 	}
236 
237 	free(blob);
238 }
239 
240 struct freeze_io_ctx {
241 	struct spdk_bs_cpl cpl;
242 	struct spdk_blob *blob;
243 };
244 
245 static void
246 _spdk_blob_io_sync(struct spdk_io_channel_iter *i)
247 {
248 	spdk_for_each_channel_continue(i, 0);
249 }
250 
251 static void
252 _spdk_blob_execute_queued_io(struct spdk_io_channel_iter *i)
253 {
254 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
255 	struct spdk_bs_channel *ch = spdk_io_channel_get_ctx(_ch);
256 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
257 	struct spdk_bs_request_set	*set;
258 	struct spdk_bs_user_op_args	*args;
259 	spdk_bs_user_op_t *op, *tmp;
260 
261 	TAILQ_FOREACH_SAFE(op, &ch->queued_io, link, tmp) {
262 		set = (struct spdk_bs_request_set *)op;
263 		args = &set->u.user_op;
264 
265 		if (args->blob == ctx->blob) {
266 			TAILQ_REMOVE(&ch->queued_io, op, link);
267 			spdk_bs_user_op_execute(op);
268 		}
269 	}
270 
271 	spdk_for_each_channel_continue(i, 0);
272 }
273 
274 static void
275 _spdk_blob_io_cpl(struct spdk_io_channel_iter *i, int status)
276 {
277 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
278 
279 	ctx->cpl.u.blob_basic.cb_fn(ctx->cpl.u.blob_basic.cb_arg, 0);
280 
281 	free(ctx);
282 }
283 
284 static void
285 _spdk_blob_freeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
286 {
287 	struct freeze_io_ctx *ctx;
288 
289 	ctx = calloc(1, sizeof(*ctx));
290 	if (!ctx) {
291 		cb_fn(cb_arg, -ENOMEM);
292 		return;
293 	}
294 
295 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
296 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
297 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
298 	ctx->blob = blob;
299 
300 	/* Freeze I/O on blob */
301 	blob->frozen_refcnt++;
302 
303 	if (blob->frozen_refcnt == 1) {
304 		spdk_for_each_channel(blob->bs, _spdk_blob_io_sync, ctx, _spdk_blob_io_cpl);
305 	} else {
306 		cb_fn(cb_arg, 0);
307 		free(ctx);
308 	}
309 }
310 
311 static void
312 _spdk_blob_unfreeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
313 {
314 	struct freeze_io_ctx *ctx;
315 
316 	ctx = calloc(1, sizeof(*ctx));
317 	if (!ctx) {
318 		cb_fn(cb_arg, -ENOMEM);
319 		return;
320 	}
321 
322 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
323 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
324 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
325 	ctx->blob = blob;
326 
327 	assert(blob->frozen_refcnt > 0);
328 
329 	blob->frozen_refcnt--;
330 
331 	if (blob->frozen_refcnt == 0) {
332 		spdk_for_each_channel(blob->bs, _spdk_blob_execute_queued_io, ctx, _spdk_blob_io_cpl);
333 	} else {
334 		cb_fn(cb_arg, 0);
335 		free(ctx);
336 	}
337 }
338 
339 static int
340 _spdk_blob_mark_clean(struct spdk_blob *blob)
341 {
342 	uint64_t *clusters = NULL;
343 	uint32_t *pages = NULL;
344 
345 	assert(blob != NULL);
346 
347 	if (blob->active.num_clusters) {
348 		assert(blob->active.clusters);
349 		clusters = calloc(blob->active.num_clusters, sizeof(*blob->active.clusters));
350 		if (!clusters) {
351 			return -ENOMEM;
352 		}
353 		memcpy(clusters, blob->active.clusters, blob->active.num_clusters * sizeof(*clusters));
354 	}
355 
356 	if (blob->active.num_pages) {
357 		assert(blob->active.pages);
358 		pages = calloc(blob->active.num_pages, sizeof(*blob->active.pages));
359 		if (!pages) {
360 			free(clusters);
361 			return -ENOMEM;
362 		}
363 		memcpy(pages, blob->active.pages, blob->active.num_pages * sizeof(*pages));
364 	}
365 
366 	free(blob->clean.clusters);
367 	free(blob->clean.pages);
368 
369 	blob->clean.num_clusters = blob->active.num_clusters;
370 	blob->clean.clusters = blob->active.clusters;
371 	blob->clean.num_pages = blob->active.num_pages;
372 	blob->clean.pages = blob->active.pages;
373 
374 	blob->active.clusters = clusters;
375 	blob->active.pages = pages;
376 
377 	/* If the metadata was dirtied again while the metadata was being written to disk,
378 	 *  we do not want to revert the DIRTY state back to CLEAN here.
379 	 */
380 	if (blob->state == SPDK_BLOB_STATE_LOADING) {
381 		blob->state = SPDK_BLOB_STATE_CLEAN;
382 	}
383 
384 	return 0;
385 }
386 
387 static int
388 _spdk_blob_deserialize_xattr(struct spdk_blob *blob,
389 			     struct spdk_blob_md_descriptor_xattr *desc_xattr, bool internal)
390 {
391 	struct spdk_xattr                       *xattr;
392 
393 	if (desc_xattr->length != sizeof(desc_xattr->name_length) +
394 	    sizeof(desc_xattr->value_length) +
395 	    desc_xattr->name_length + desc_xattr->value_length) {
396 		return -EINVAL;
397 	}
398 
399 	xattr = calloc(1, sizeof(*xattr));
400 	if (xattr == NULL) {
401 		return -ENOMEM;
402 	}
403 
404 	xattr->name = malloc(desc_xattr->name_length + 1);
405 	if (xattr->name == NULL) {
406 		free(xattr);
407 		return -ENOMEM;
408 	}
409 	memcpy(xattr->name, desc_xattr->name, desc_xattr->name_length);
410 	xattr->name[desc_xattr->name_length] = '\0';
411 
412 	xattr->value = malloc(desc_xattr->value_length);
413 	if (xattr->value == NULL) {
414 		free(xattr->name);
415 		free(xattr);
416 		return -ENOMEM;
417 	}
418 	xattr->value_len = desc_xattr->value_length;
419 	memcpy(xattr->value,
420 	       (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
421 	       desc_xattr->value_length);
422 
423 	TAILQ_INSERT_TAIL(internal ? &blob->xattrs_internal : &blob->xattrs, xattr, link);
424 
425 	return 0;
426 }
427 
428 
429 static int
430 _spdk_blob_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob *blob)
431 {
432 	struct spdk_blob_md_descriptor *desc;
433 	size_t	cur_desc = 0;
434 	void *tmp;
435 
436 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
437 	while (cur_desc < sizeof(page->descriptors)) {
438 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
439 			if (desc->length == 0) {
440 				/* If padding and length are 0, this terminates the page */
441 				break;
442 			}
443 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
444 			struct spdk_blob_md_descriptor_flags	*desc_flags;
445 
446 			desc_flags = (struct spdk_blob_md_descriptor_flags *)desc;
447 
448 			if (desc_flags->length != sizeof(*desc_flags) - sizeof(*desc)) {
449 				return -EINVAL;
450 			}
451 
452 			if ((desc_flags->invalid_flags | SPDK_BLOB_INVALID_FLAGS_MASK) !=
453 			    SPDK_BLOB_INVALID_FLAGS_MASK) {
454 				return -EINVAL;
455 			}
456 
457 			if ((desc_flags->data_ro_flags | SPDK_BLOB_DATA_RO_FLAGS_MASK) !=
458 			    SPDK_BLOB_DATA_RO_FLAGS_MASK) {
459 				blob->data_ro = true;
460 				blob->md_ro = true;
461 			}
462 
463 			if ((desc_flags->md_ro_flags | SPDK_BLOB_MD_RO_FLAGS_MASK) !=
464 			    SPDK_BLOB_MD_RO_FLAGS_MASK) {
465 				blob->md_ro = true;
466 			}
467 
468 			if ((desc_flags->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
469 				blob->data_ro = true;
470 				blob->md_ro = true;
471 			}
472 
473 			blob->invalid_flags = desc_flags->invalid_flags;
474 			blob->data_ro_flags = desc_flags->data_ro_flags;
475 			blob->md_ro_flags = desc_flags->md_ro_flags;
476 
477 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
478 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
479 			unsigned int				i, j;
480 			unsigned int				cluster_count = blob->active.num_clusters;
481 
482 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
483 
484 			if (desc_extent_rle->length == 0 ||
485 			    (desc_extent_rle->length % sizeof(desc_extent_rle->extents[0]) != 0)) {
486 				return -EINVAL;
487 			}
488 
489 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
490 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
491 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
492 						if (!spdk_bit_array_get(blob->bs->used_clusters,
493 									desc_extent_rle->extents[i].cluster_idx + j)) {
494 							return -EINVAL;
495 						}
496 					}
497 					cluster_count++;
498 				}
499 			}
500 
501 			if (cluster_count == 0) {
502 				return -EINVAL;
503 			}
504 			tmp = realloc(blob->active.clusters, cluster_count * sizeof(uint64_t));
505 			if (tmp == NULL) {
506 				return -ENOMEM;
507 			}
508 			blob->active.clusters = tmp;
509 			blob->active.cluster_array_size = cluster_count;
510 
511 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
512 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
513 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
514 						blob->active.clusters[blob->active.num_clusters++] = _spdk_bs_cluster_to_lba(blob->bs,
515 								desc_extent_rle->extents[i].cluster_idx + j);
516 					} else if (spdk_blob_is_thin_provisioned(blob)) {
517 						blob->active.clusters[blob->active.num_clusters++] = 0;
518 					} else {
519 						return -EINVAL;
520 					}
521 				}
522 			}
523 
524 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
525 			int rc;
526 
527 			rc = _spdk_blob_deserialize_xattr(blob,
528 							  (struct spdk_blob_md_descriptor_xattr *) desc, false);
529 			if (rc != 0) {
530 				return rc;
531 			}
532 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
533 			int rc;
534 
535 			rc = _spdk_blob_deserialize_xattr(blob,
536 							  (struct spdk_blob_md_descriptor_xattr *) desc, true);
537 			if (rc != 0) {
538 				return rc;
539 			}
540 		} else {
541 			/* Unrecognized descriptor type.  Do not fail - just continue to the
542 			 *  next descriptor.  If this descriptor is associated with some feature
543 			 *  defined in a newer version of blobstore, that version of blobstore
544 			 *  should create and set an associated feature flag to specify if this
545 			 *  blob can be loaded or not.
546 			 */
547 		}
548 
549 		/* Advance to the next descriptor */
550 		cur_desc += sizeof(*desc) + desc->length;
551 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
552 			break;
553 		}
554 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
555 	}
556 
557 	return 0;
558 }
559 
560 static int
561 _spdk_blob_parse(const struct spdk_blob_md_page *pages, uint32_t page_count,
562 		 struct spdk_blob *blob)
563 {
564 	const struct spdk_blob_md_page *page;
565 	uint32_t i;
566 	int rc;
567 
568 	assert(page_count > 0);
569 	assert(pages[0].sequence_num == 0);
570 	assert(blob != NULL);
571 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
572 	assert(blob->active.clusters == NULL);
573 
574 	/* The blobid provided doesn't match what's in the MD, this can
575 	 * happen for example if a bogus blobid is passed in through open.
576 	 */
577 	if (blob->id != pages[0].id) {
578 		SPDK_ERRLOG("Blobid (%lu) doesn't match what's in metadata (%lu)\n",
579 			    blob->id, pages[0].id);
580 		return -ENOENT;
581 	}
582 
583 	for (i = 0; i < page_count; i++) {
584 		page = &pages[i];
585 
586 		assert(page->id == blob->id);
587 		assert(page->sequence_num == i);
588 
589 		rc = _spdk_blob_parse_page(page, blob);
590 		if (rc != 0) {
591 			return rc;
592 		}
593 	}
594 
595 	return 0;
596 }
597 
598 static int
599 _spdk_blob_serialize_add_page(const struct spdk_blob *blob,
600 			      struct spdk_blob_md_page **pages,
601 			      uint32_t *page_count,
602 			      struct spdk_blob_md_page **last_page)
603 {
604 	struct spdk_blob_md_page *page;
605 
606 	assert(pages != NULL);
607 	assert(page_count != NULL);
608 
609 	if (*page_count == 0) {
610 		assert(*pages == NULL);
611 		*page_count = 1;
612 		*pages = spdk_malloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
613 				     NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
614 	} else {
615 		assert(*pages != NULL);
616 		(*page_count)++;
617 		*pages = spdk_realloc(*pages,
618 				      SPDK_BS_PAGE_SIZE * (*page_count),
619 				      SPDK_BS_PAGE_SIZE);
620 	}
621 
622 	if (*pages == NULL) {
623 		*page_count = 0;
624 		*last_page = NULL;
625 		return -ENOMEM;
626 	}
627 
628 	page = &(*pages)[*page_count - 1];
629 	memset(page, 0, sizeof(*page));
630 	page->id = blob->id;
631 	page->sequence_num = *page_count - 1;
632 	page->next = SPDK_INVALID_MD_PAGE;
633 	*last_page = page;
634 
635 	return 0;
636 }
637 
638 /* Transform the in-memory representation 'xattr' into an on-disk xattr descriptor.
639  * Update required_sz on both success and failure.
640  *
641  */
642 static int
643 _spdk_blob_serialize_xattr(const struct spdk_xattr *xattr,
644 			   uint8_t *buf, size_t buf_sz,
645 			   size_t *required_sz, bool internal)
646 {
647 	struct spdk_blob_md_descriptor_xattr	*desc;
648 
649 	*required_sz = sizeof(struct spdk_blob_md_descriptor_xattr) +
650 		       strlen(xattr->name) +
651 		       xattr->value_len;
652 
653 	if (buf_sz < *required_sz) {
654 		return -1;
655 	}
656 
657 	desc = (struct spdk_blob_md_descriptor_xattr *)buf;
658 
659 	desc->type = internal ? SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL : SPDK_MD_DESCRIPTOR_TYPE_XATTR;
660 	desc->length = sizeof(desc->name_length) +
661 		       sizeof(desc->value_length) +
662 		       strlen(xattr->name) +
663 		       xattr->value_len;
664 	desc->name_length = strlen(xattr->name);
665 	desc->value_length = xattr->value_len;
666 
667 	memcpy(desc->name, xattr->name, desc->name_length);
668 	memcpy((void *)((uintptr_t)desc->name + desc->name_length),
669 	       xattr->value,
670 	       desc->value_length);
671 
672 	return 0;
673 }
674 
675 static void
676 _spdk_blob_serialize_extent_rle(const struct spdk_blob *blob,
677 				uint64_t start_cluster, uint64_t *next_cluster,
678 				uint8_t **buf, size_t *buf_sz)
679 {
680 	struct spdk_blob_md_descriptor_extent_rle *desc_extent_rle;
681 	size_t cur_sz;
682 	uint64_t i, extent_idx;
683 	uint64_t lba, lba_per_cluster, lba_count;
684 
685 	/* The buffer must have room for at least one extent */
686 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc_extent_rle->extents[0]);
687 	if (*buf_sz < cur_sz) {
688 		*next_cluster = start_cluster;
689 		return;
690 	}
691 
692 	desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)*buf;
693 	desc_extent_rle->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE;
694 
695 	lba_per_cluster = _spdk_bs_cluster_to_lba(blob->bs, 1);
696 
697 	lba = blob->active.clusters[start_cluster];
698 	lba_count = lba_per_cluster;
699 	extent_idx = 0;
700 	for (i = start_cluster + 1; i < blob->active.num_clusters; i++) {
701 		if ((lba + lba_count) == blob->active.clusters[i] && lba != 0) {
702 			/* Run-length encode sequential non-zero LBA */
703 			lba_count += lba_per_cluster;
704 			continue;
705 		} else if (lba == 0 && blob->active.clusters[i] == 0) {
706 			/* Run-length encode unallocated clusters */
707 			lba_count += lba_per_cluster;
708 			continue;
709 		}
710 		desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
711 		desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
712 		extent_idx++;
713 
714 		cur_sz += sizeof(desc_extent_rle->extents[extent_idx]);
715 
716 		if (*buf_sz < cur_sz) {
717 			/* If we ran out of buffer space, return */
718 			*next_cluster = i;
719 			goto finish;
720 		}
721 
722 		lba = blob->active.clusters[i];
723 		lba_count = lba_per_cluster;
724 	}
725 
726 	desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
727 	desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
728 	extent_idx++;
729 
730 	*next_cluster = blob->active.num_clusters;
731 
732 finish:
733 	desc_extent_rle->length = sizeof(desc_extent_rle->extents[0]) * extent_idx;
734 	*buf_sz -= sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
735 	*buf += sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
736 
737 	return;
738 }
739 
740 static int
741 _spdk_blob_serialize_extents_rle(const struct spdk_blob *blob,
742 				 struct spdk_blob_md_page **pages,
743 				 struct spdk_blob_md_page *cur_page,
744 				 uint32_t *page_count, uint8_t **buf,
745 				 size_t *remaining_sz)
746 {
747 	uint64_t				last_cluster;
748 	int					rc;
749 
750 	last_cluster = 0;
751 	while (last_cluster < blob->active.num_clusters) {
752 		_spdk_blob_serialize_extent_rle(blob, last_cluster, &last_cluster, buf, remaining_sz);
753 
754 		if (last_cluster == blob->active.num_clusters) {
755 			break;
756 		}
757 
758 		rc = _spdk_blob_serialize_add_page(blob, pages, page_count, &cur_page);
759 		if (rc < 0) {
760 			return rc;
761 		}
762 
763 		*buf = (uint8_t *)cur_page->descriptors;
764 		*remaining_sz = sizeof(cur_page->descriptors);
765 	}
766 
767 	return 0;
768 }
769 
770 static void
771 _spdk_blob_serialize_flags(const struct spdk_blob *blob,
772 			   uint8_t *buf, size_t *buf_sz)
773 {
774 	struct spdk_blob_md_descriptor_flags *desc;
775 
776 	/*
777 	 * Flags get serialized first, so we should always have room for the flags
778 	 *  descriptor.
779 	 */
780 	assert(*buf_sz >= sizeof(*desc));
781 
782 	desc = (struct spdk_blob_md_descriptor_flags *)buf;
783 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_FLAGS;
784 	desc->length = sizeof(*desc) - sizeof(struct spdk_blob_md_descriptor);
785 	desc->invalid_flags = blob->invalid_flags;
786 	desc->data_ro_flags = blob->data_ro_flags;
787 	desc->md_ro_flags = blob->md_ro_flags;
788 
789 	*buf_sz -= sizeof(*desc);
790 }
791 
792 static int
793 _spdk_blob_serialize_xattrs(const struct spdk_blob *blob,
794 			    const struct spdk_xattr_tailq *xattrs, bool internal,
795 			    struct spdk_blob_md_page **pages,
796 			    struct spdk_blob_md_page *cur_page,
797 			    uint32_t *page_count, uint8_t **buf,
798 			    size_t *remaining_sz)
799 {
800 	const struct spdk_xattr	*xattr;
801 	int	rc;
802 
803 	TAILQ_FOREACH(xattr, xattrs, link) {
804 		size_t required_sz = 0;
805 
806 		rc = _spdk_blob_serialize_xattr(xattr,
807 						*buf, *remaining_sz,
808 						&required_sz, internal);
809 		if (rc < 0) {
810 			/* Need to add a new page to the chain */
811 			rc = _spdk_blob_serialize_add_page(blob, pages, page_count,
812 							   &cur_page);
813 			if (rc < 0) {
814 				spdk_free(*pages);
815 				*pages = NULL;
816 				*page_count = 0;
817 				return rc;
818 			}
819 
820 			*buf = (uint8_t *)cur_page->descriptors;
821 			*remaining_sz = sizeof(cur_page->descriptors);
822 
823 			/* Try again */
824 			required_sz = 0;
825 			rc = _spdk_blob_serialize_xattr(xattr,
826 							*buf, *remaining_sz,
827 							&required_sz, internal);
828 
829 			if (rc < 0) {
830 				spdk_free(*pages);
831 				*pages = NULL;
832 				*page_count = 0;
833 				return rc;
834 			}
835 		}
836 
837 		*remaining_sz -= required_sz;
838 		*buf += required_sz;
839 	}
840 
841 	return 0;
842 }
843 
844 static int
845 _spdk_blob_serialize(const struct spdk_blob *blob, struct spdk_blob_md_page **pages,
846 		     uint32_t *page_count)
847 {
848 	struct spdk_blob_md_page		*cur_page;
849 	int					rc;
850 	uint8_t					*buf;
851 	size_t					remaining_sz;
852 
853 	assert(pages != NULL);
854 	assert(page_count != NULL);
855 	assert(blob != NULL);
856 	assert(blob->state == SPDK_BLOB_STATE_DIRTY);
857 
858 	*pages = NULL;
859 	*page_count = 0;
860 
861 	/* A blob always has at least 1 page, even if it has no descriptors */
862 	rc = _spdk_blob_serialize_add_page(blob, pages, page_count, &cur_page);
863 	if (rc < 0) {
864 		return rc;
865 	}
866 
867 	buf = (uint8_t *)cur_page->descriptors;
868 	remaining_sz = sizeof(cur_page->descriptors);
869 
870 	/* Serialize flags */
871 	_spdk_blob_serialize_flags(blob, buf, &remaining_sz);
872 	buf += sizeof(struct spdk_blob_md_descriptor_flags);
873 
874 	/* Serialize xattrs */
875 	rc = _spdk_blob_serialize_xattrs(blob, &blob->xattrs, false,
876 					 pages, cur_page, page_count, &buf, &remaining_sz);
877 	if (rc < 0) {
878 		return rc;
879 	}
880 
881 	/* Serialize internal xattrs */
882 	rc = _spdk_blob_serialize_xattrs(blob, &blob->xattrs_internal, true,
883 					 pages, cur_page, page_count, &buf, &remaining_sz);
884 	if (rc < 0) {
885 		return rc;
886 	}
887 
888 	/* Serialize extents */
889 	rc = _spdk_blob_serialize_extents_rle(blob, pages, cur_page, page_count, &buf, &remaining_sz);
890 
891 	return rc;
892 }
893 
894 struct spdk_blob_load_ctx {
895 	struct spdk_blob		*blob;
896 
897 	struct spdk_blob_md_page	*pages;
898 	uint32_t			num_pages;
899 	spdk_bs_sequence_t	        *seq;
900 
901 	spdk_bs_sequence_cpl		cb_fn;
902 	void				*cb_arg;
903 };
904 
905 static uint32_t
906 _spdk_blob_md_page_calc_crc(void *page)
907 {
908 	uint32_t		crc;
909 
910 	crc = BLOB_CRC32C_INITIAL;
911 	crc = spdk_crc32c_update(page, SPDK_BS_PAGE_SIZE - 4, crc);
912 	crc ^= BLOB_CRC32C_INITIAL;
913 
914 	return crc;
915 
916 }
917 
918 static void
919 _spdk_blob_load_final(void *cb_arg, int bserrno)
920 {
921 	struct spdk_blob_load_ctx	*ctx = cb_arg;
922 	struct spdk_blob		*blob = ctx->blob;
923 
924 	_spdk_blob_mark_clean(blob);
925 
926 	ctx->cb_fn(ctx->seq, ctx->cb_arg, bserrno);
927 
928 	/* Free the memory */
929 	spdk_free(ctx->pages);
930 	free(ctx);
931 }
932 
933 static void
934 _spdk_blob_load_snapshot_cpl(void *cb_arg, struct spdk_blob *snapshot, int bserrno)
935 {
936 	struct spdk_blob_load_ctx	*ctx = cb_arg;
937 	struct spdk_blob		*blob = ctx->blob;
938 
939 	if (bserrno != 0) {
940 		goto error;
941 	}
942 
943 	blob->back_bs_dev = spdk_bs_create_blob_bs_dev(snapshot);
944 
945 	if (blob->back_bs_dev == NULL) {
946 		bserrno = -ENOMEM;
947 		goto error;
948 	}
949 
950 	_spdk_blob_load_final(ctx, bserrno);
951 	return;
952 
953 error:
954 	SPDK_ERRLOG("Snapshot fail\n");
955 	_spdk_blob_free(blob);
956 	ctx->cb_fn(ctx->seq, NULL, bserrno);
957 	spdk_free(ctx->pages);
958 	free(ctx);
959 }
960 
961 static void
962 _spdk_blob_load_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
963 {
964 	struct spdk_blob_load_ctx	*ctx = cb_arg;
965 	struct spdk_blob		*blob = ctx->blob;
966 	struct spdk_blob_md_page	*page;
967 	const void			*value;
968 	size_t				len;
969 	int				rc;
970 	uint32_t			crc;
971 
972 	if (bserrno) {
973 		SPDK_ERRLOG("Metadata page read failed: %d\n", bserrno);
974 		_spdk_blob_free(blob);
975 		ctx->cb_fn(seq, NULL, bserrno);
976 		spdk_free(ctx->pages);
977 		free(ctx);
978 		return;
979 	}
980 
981 	page = &ctx->pages[ctx->num_pages - 1];
982 	crc = _spdk_blob_md_page_calc_crc(page);
983 	if (crc != page->crc) {
984 		SPDK_ERRLOG("Metadata page %d crc mismatch\n", ctx->num_pages);
985 		_spdk_blob_free(blob);
986 		ctx->cb_fn(seq, NULL, -EINVAL);
987 		spdk_free(ctx->pages);
988 		free(ctx);
989 		return;
990 	}
991 
992 	if (page->next != SPDK_INVALID_MD_PAGE) {
993 		uint32_t next_page = page->next;
994 		uint64_t next_lba = _spdk_bs_page_to_lba(blob->bs, blob->bs->md_start + next_page);
995 		uint64_t max_md_lba = _spdk_bs_page_to_lba(blob->bs, blob->bs->md_start + blob->bs->md_len);
996 
997 		if (next_lba >= max_md_lba) {
998 			assert(false);
999 		}
1000 
1001 		/* Read the next page */
1002 		ctx->num_pages++;
1003 		ctx->pages = spdk_realloc(ctx->pages, (sizeof(*page) * ctx->num_pages),
1004 					  sizeof(*page));
1005 		if (ctx->pages == NULL) {
1006 			ctx->cb_fn(seq, ctx->cb_arg, -ENOMEM);
1007 			free(ctx);
1008 			return;
1009 		}
1010 
1011 		spdk_bs_sequence_read_dev(seq, &ctx->pages[ctx->num_pages - 1],
1012 					  next_lba,
1013 					  _spdk_bs_byte_to_lba(blob->bs, sizeof(*page)),
1014 					  _spdk_blob_load_cpl, ctx);
1015 		return;
1016 	}
1017 
1018 	/* Parse the pages */
1019 	rc = _spdk_blob_parse(ctx->pages, ctx->num_pages, blob);
1020 	if (rc) {
1021 		_spdk_blob_free(blob);
1022 		ctx->cb_fn(seq, NULL, rc);
1023 		spdk_free(ctx->pages);
1024 		free(ctx);
1025 		return;
1026 	}
1027 
1028 	if (spdk_blob_is_thin_provisioned(blob)) {
1029 		rc = _spdk_blob_get_xattr_value(blob, BLOB_SNAPSHOT, &value, &len, true);
1030 		if (rc == 0) {
1031 			if (len != sizeof(spdk_blob_id)) {
1032 				_spdk_blob_free(blob);
1033 				ctx->cb_fn(seq, NULL, -EINVAL);
1034 				spdk_free(ctx->pages);
1035 				free(ctx);
1036 				return;
1037 			}
1038 			/* open snapshot blob and continue in the callback function */
1039 			blob->parent_id = *(spdk_blob_id *)value;
1040 			spdk_bs_open_blob(blob->bs, blob->parent_id,
1041 					  _spdk_blob_load_snapshot_cpl, ctx);
1042 			return;
1043 		} else {
1044 			/* add zeroes_dev for thin provisioned blob */
1045 			blob->back_bs_dev = spdk_bs_create_zeroes_dev();
1046 		}
1047 	} else {
1048 		/* standard blob */
1049 		blob->back_bs_dev = NULL;
1050 	}
1051 	_spdk_blob_load_final(ctx, bserrno);
1052 }
1053 
1054 /* Load a blob from disk given a blobid */
1055 static void
1056 _spdk_blob_load(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1057 		spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1058 {
1059 	struct spdk_blob_load_ctx *ctx;
1060 	struct spdk_blob_store *bs;
1061 	uint32_t page_num;
1062 	uint64_t lba;
1063 
1064 	_spdk_blob_verify_md_op(blob);
1065 
1066 	bs = blob->bs;
1067 
1068 	ctx = calloc(1, sizeof(*ctx));
1069 	if (!ctx) {
1070 		cb_fn(seq, cb_arg, -ENOMEM);
1071 		return;
1072 	}
1073 
1074 	ctx->blob = blob;
1075 	ctx->pages = spdk_realloc(ctx->pages, SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE);
1076 	if (!ctx->pages) {
1077 		free(ctx);
1078 		cb_fn(seq, cb_arg, -ENOMEM);
1079 		return;
1080 	}
1081 	ctx->num_pages = 1;
1082 	ctx->cb_fn = cb_fn;
1083 	ctx->cb_arg = cb_arg;
1084 	ctx->seq = seq;
1085 
1086 	page_num = _spdk_bs_blobid_to_page(blob->id);
1087 	lba = _spdk_bs_page_to_lba(blob->bs, bs->md_start + page_num);
1088 
1089 	blob->state = SPDK_BLOB_STATE_LOADING;
1090 
1091 	spdk_bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1092 				  _spdk_bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE),
1093 				  _spdk_blob_load_cpl, ctx);
1094 }
1095 
1096 struct spdk_blob_persist_ctx {
1097 	struct spdk_blob		*blob;
1098 
1099 	struct spdk_bs_super_block	*super;
1100 
1101 	struct spdk_blob_md_page	*pages;
1102 
1103 	spdk_bs_sequence_t		*seq;
1104 	spdk_bs_sequence_cpl		cb_fn;
1105 	void				*cb_arg;
1106 };
1107 
1108 static void
1109 spdk_bs_batch_clear_dev(struct spdk_blob_persist_ctx *ctx, spdk_bs_batch_t *batch, uint64_t lba,
1110 			uint32_t lba_count)
1111 {
1112 	switch (ctx->blob->clear_method) {
1113 	case BLOB_CLEAR_WITH_DEFAULT:
1114 	case BLOB_CLEAR_WITH_UNMAP:
1115 		spdk_bs_batch_unmap_dev(batch, lba, lba_count);
1116 		break;
1117 	case BLOB_CLEAR_WITH_WRITE_ZEROES:
1118 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1119 		break;
1120 	case BLOB_CLEAR_WITH_NONE:
1121 	default:
1122 		break;
1123 	}
1124 }
1125 
1126 static void
1127 _spdk_blob_persist_complete(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1128 {
1129 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1130 	struct spdk_blob		*blob = ctx->blob;
1131 
1132 	if (bserrno == 0) {
1133 		_spdk_blob_mark_clean(blob);
1134 	}
1135 
1136 	/* Call user callback */
1137 	ctx->cb_fn(seq, ctx->cb_arg, bserrno);
1138 
1139 	/* Free the memory */
1140 	spdk_free(ctx->pages);
1141 	free(ctx);
1142 }
1143 
1144 static void
1145 _spdk_blob_persist_clear_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1146 {
1147 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1148 	struct spdk_blob		*blob = ctx->blob;
1149 	struct spdk_blob_store		*bs = blob->bs;
1150 	size_t				i;
1151 
1152 	/* Release all clusters that were truncated */
1153 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1154 		uint32_t cluster_num = _spdk_bs_lba_to_cluster(bs, blob->active.clusters[i]);
1155 
1156 		/* Nothing to release if it was not allocated */
1157 		if (blob->active.clusters[i] != 0) {
1158 			_spdk_bs_release_cluster(bs, cluster_num);
1159 		}
1160 	}
1161 
1162 	if (blob->active.num_clusters == 0) {
1163 		free(blob->active.clusters);
1164 		blob->active.clusters = NULL;
1165 		blob->active.cluster_array_size = 0;
1166 	} else if (blob->active.num_clusters != blob->active.cluster_array_size) {
1167 #ifndef __clang_analyzer__
1168 		void *tmp;
1169 
1170 		/* scan-build really can't figure reallocs, workaround it */
1171 		tmp = realloc(blob->active.clusters, sizeof(uint64_t) * blob->active.num_clusters);
1172 		assert(tmp != NULL);
1173 		blob->active.clusters = tmp;
1174 #endif
1175 		blob->active.cluster_array_size = blob->active.num_clusters;
1176 	}
1177 
1178 	_spdk_blob_persist_complete(seq, ctx, bserrno);
1179 }
1180 
1181 static void
1182 _spdk_blob_persist_clear_clusters(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1183 {
1184 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1185 	struct spdk_blob		*blob = ctx->blob;
1186 	struct spdk_blob_store		*bs = blob->bs;
1187 	spdk_bs_batch_t			*batch;
1188 	size_t				i;
1189 	uint64_t			lba;
1190 	uint32_t			lba_count;
1191 
1192 	/* Clusters don't move around in blobs. The list shrinks or grows
1193 	 * at the end, but no changes ever occur in the middle of the list.
1194 	 */
1195 
1196 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_clear_clusters_cpl, ctx);
1197 
1198 	/* Clear all clusters that were truncated */
1199 	lba = 0;
1200 	lba_count = 0;
1201 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1202 		uint64_t next_lba = blob->active.clusters[i];
1203 		uint32_t next_lba_count = _spdk_bs_cluster_to_lba(bs, 1);
1204 
1205 		if (next_lba > 0 && (lba + lba_count) == next_lba) {
1206 			/* This cluster is contiguous with the previous one. */
1207 			lba_count += next_lba_count;
1208 			continue;
1209 		}
1210 
1211 		/* This cluster is not contiguous with the previous one. */
1212 
1213 		/* If a run of LBAs previously existing, clear them now */
1214 		if (lba_count > 0) {
1215 			spdk_bs_batch_clear_dev(ctx, batch, lba, lba_count);
1216 		}
1217 
1218 		/* Start building the next batch */
1219 		lba = next_lba;
1220 		if (next_lba > 0) {
1221 			lba_count = next_lba_count;
1222 		} else {
1223 			lba_count = 0;
1224 		}
1225 	}
1226 
1227 	/* If we ended with a contiguous set of LBAs, clear them now */
1228 	if (lba_count > 0) {
1229 		spdk_bs_batch_clear_dev(ctx, batch, lba, lba_count);
1230 	}
1231 
1232 	spdk_bs_batch_close(batch);
1233 }
1234 
1235 static void
1236 _spdk_blob_persist_zero_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1237 {
1238 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1239 	struct spdk_blob		*blob = ctx->blob;
1240 	struct spdk_blob_store		*bs = blob->bs;
1241 	size_t				i;
1242 
1243 	/* This loop starts at 1 because the first page is special and handled
1244 	 * below. The pages (except the first) are never written in place,
1245 	 * so any pages in the clean list must be zeroed.
1246 	 */
1247 	for (i = 1; i < blob->clean.num_pages; i++) {
1248 		spdk_bit_array_clear(bs->used_md_pages, blob->clean.pages[i]);
1249 	}
1250 
1251 	if (blob->active.num_pages == 0) {
1252 		uint32_t page_num;
1253 
1254 		page_num = _spdk_bs_blobid_to_page(blob->id);
1255 		spdk_bit_array_clear(bs->used_md_pages, page_num);
1256 	}
1257 
1258 	/* Move on to clearing clusters */
1259 	_spdk_blob_persist_clear_clusters(seq, ctx, 0);
1260 }
1261 
1262 static void
1263 _spdk_blob_persist_zero_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1264 {
1265 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1266 	struct spdk_blob		*blob = ctx->blob;
1267 	struct spdk_blob_store		*bs = blob->bs;
1268 	uint64_t			lba;
1269 	uint32_t			lba_count;
1270 	spdk_bs_batch_t			*batch;
1271 	size_t				i;
1272 
1273 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_zero_pages_cpl, ctx);
1274 
1275 	lba_count = _spdk_bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE);
1276 
1277 	/* This loop starts at 1 because the first page is special and handled
1278 	 * below. The pages (except the first) are never written in place,
1279 	 * so any pages in the clean list must be zeroed.
1280 	 */
1281 	for (i = 1; i < blob->clean.num_pages; i++) {
1282 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + blob->clean.pages[i]);
1283 
1284 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1285 	}
1286 
1287 	/* The first page will only be zeroed if this is a delete. */
1288 	if (blob->active.num_pages == 0) {
1289 		uint32_t page_num;
1290 
1291 		/* The first page in the metadata goes where the blobid indicates */
1292 		page_num = _spdk_bs_blobid_to_page(blob->id);
1293 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + page_num);
1294 
1295 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1296 	}
1297 
1298 	spdk_bs_batch_close(batch);
1299 }
1300 
1301 static void
1302 _spdk_blob_persist_write_page_root(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1303 {
1304 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1305 	struct spdk_blob		*blob = ctx->blob;
1306 	struct spdk_blob_store		*bs = blob->bs;
1307 	uint64_t			lba;
1308 	uint32_t			lba_count;
1309 	struct spdk_blob_md_page	*page;
1310 
1311 	if (blob->active.num_pages == 0) {
1312 		/* Move on to the next step */
1313 		_spdk_blob_persist_zero_pages(seq, ctx, 0);
1314 		return;
1315 	}
1316 
1317 	lba_count = _spdk_bs_byte_to_lba(bs, sizeof(*page));
1318 
1319 	page = &ctx->pages[0];
1320 	/* The first page in the metadata goes where the blobid indicates */
1321 	lba = _spdk_bs_page_to_lba(bs, bs->md_start + _spdk_bs_blobid_to_page(blob->id));
1322 
1323 	spdk_bs_sequence_write_dev(seq, page, lba, lba_count,
1324 				   _spdk_blob_persist_zero_pages, ctx);
1325 }
1326 
1327 static void
1328 _spdk_blob_persist_write_page_chain(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1329 {
1330 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1331 	struct spdk_blob		*blob = ctx->blob;
1332 	struct spdk_blob_store		*bs = blob->bs;
1333 	uint64_t			lba;
1334 	uint32_t			lba_count;
1335 	struct spdk_blob_md_page	*page;
1336 	spdk_bs_batch_t			*batch;
1337 	size_t				i;
1338 
1339 	/* Clusters don't move around in blobs. The list shrinks or grows
1340 	 * at the end, but no changes ever occur in the middle of the list.
1341 	 */
1342 
1343 	lba_count = _spdk_bs_byte_to_lba(bs, sizeof(*page));
1344 
1345 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_write_page_root, ctx);
1346 
1347 	/* This starts at 1. The root page is not written until
1348 	 * all of the others are finished
1349 	 */
1350 	for (i = 1; i < blob->active.num_pages; i++) {
1351 		page = &ctx->pages[i];
1352 		assert(page->sequence_num == i);
1353 
1354 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + blob->active.pages[i]);
1355 
1356 		spdk_bs_batch_write_dev(batch, page, lba, lba_count);
1357 	}
1358 
1359 	spdk_bs_batch_close(batch);
1360 }
1361 
1362 static int
1363 _spdk_blob_resize(struct spdk_blob *blob, uint64_t sz)
1364 {
1365 	uint64_t	i;
1366 	uint64_t	*tmp;
1367 	uint64_t	lfc; /* lowest free cluster */
1368 	uint64_t	num_clusters;
1369 	struct spdk_blob_store *bs;
1370 
1371 	bs = blob->bs;
1372 
1373 	_spdk_blob_verify_md_op(blob);
1374 
1375 	if (blob->active.num_clusters == sz) {
1376 		return 0;
1377 	}
1378 
1379 	if (blob->active.num_clusters < blob->active.cluster_array_size) {
1380 		/* If this blob was resized to be larger, then smaller, then
1381 		 * larger without syncing, then the cluster array already
1382 		 * contains spare assigned clusters we can use.
1383 		 */
1384 		num_clusters = spdk_min(blob->active.cluster_array_size,
1385 					sz);
1386 	} else {
1387 		num_clusters = blob->active.num_clusters;
1388 	}
1389 
1390 	/* Do two passes - one to verify that we can obtain enough clusters
1391 	 * and another to actually claim them.
1392 	 */
1393 
1394 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1395 		lfc = 0;
1396 		for (i = num_clusters; i < sz; i++) {
1397 			lfc = spdk_bit_array_find_first_clear(bs->used_clusters, lfc);
1398 			if (lfc == UINT32_MAX) {
1399 				/* No more free clusters. Cannot satisfy the request */
1400 				return -ENOSPC;
1401 			}
1402 			lfc++;
1403 		}
1404 	}
1405 
1406 	if (sz > num_clusters) {
1407 		/* Expand the cluster array if necessary.
1408 		 * We only shrink the array when persisting.
1409 		 */
1410 		tmp = realloc(blob->active.clusters, sizeof(uint64_t) * sz);
1411 		if (sz > 0 && tmp == NULL) {
1412 			return -ENOMEM;
1413 		}
1414 		memset(tmp + blob->active.cluster_array_size, 0,
1415 		       sizeof(uint64_t) * (sz - blob->active.cluster_array_size));
1416 		blob->active.clusters = tmp;
1417 		blob->active.cluster_array_size = sz;
1418 	}
1419 
1420 	blob->state = SPDK_BLOB_STATE_DIRTY;
1421 
1422 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1423 		lfc = 0;
1424 		for (i = num_clusters; i < sz; i++) {
1425 			_spdk_bs_allocate_cluster(blob, i, &lfc, true);
1426 			lfc++;
1427 		}
1428 	}
1429 
1430 	blob->active.num_clusters = sz;
1431 
1432 	return 0;
1433 }
1434 
1435 static void
1436 _spdk_blob_persist_start(struct spdk_blob_persist_ctx *ctx)
1437 {
1438 	spdk_bs_sequence_t *seq = ctx->seq;
1439 	struct spdk_blob *blob = ctx->blob;
1440 	struct spdk_blob_store *bs = blob->bs;
1441 	uint64_t i;
1442 	uint32_t page_num;
1443 	void *tmp;
1444 	int rc;
1445 
1446 	if (blob->active.num_pages == 0) {
1447 		/* This is the signal that the blob should be deleted.
1448 		 * Immediately jump to the clean up routine. */
1449 		assert(blob->clean.num_pages > 0);
1450 		blob->state = SPDK_BLOB_STATE_CLEAN;
1451 		_spdk_blob_persist_zero_pages(seq, ctx, 0);
1452 		return;
1453 
1454 	}
1455 
1456 	/* Generate the new metadata */
1457 	rc = _spdk_blob_serialize(blob, &ctx->pages, &blob->active.num_pages);
1458 	if (rc < 0) {
1459 		_spdk_blob_persist_complete(seq, ctx, rc);
1460 		return;
1461 	}
1462 
1463 	assert(blob->active.num_pages >= 1);
1464 
1465 	/* Resize the cache of page indices */
1466 	tmp = realloc(blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
1467 	if (!tmp) {
1468 		_spdk_blob_persist_complete(seq, ctx, -ENOMEM);
1469 		return;
1470 	}
1471 	blob->active.pages = tmp;
1472 
1473 	/* Assign this metadata to pages. This requires two passes -
1474 	 * one to verify that there are enough pages and a second
1475 	 * to actually claim them. */
1476 	page_num = 0;
1477 	/* Note that this loop starts at one. The first page location is fixed by the blobid. */
1478 	for (i = 1; i < blob->active.num_pages; i++) {
1479 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1480 		if (page_num == UINT32_MAX) {
1481 			_spdk_blob_persist_complete(seq, ctx, -ENOMEM);
1482 			return;
1483 		}
1484 		page_num++;
1485 	}
1486 
1487 	page_num = 0;
1488 	blob->active.pages[0] = _spdk_bs_blobid_to_page(blob->id);
1489 	for (i = 1; i < blob->active.num_pages; i++) {
1490 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1491 		ctx->pages[i - 1].next = page_num;
1492 		/* Now that previous metadata page is complete, calculate the crc for it. */
1493 		ctx->pages[i - 1].crc = _spdk_blob_md_page_calc_crc(&ctx->pages[i - 1]);
1494 		blob->active.pages[i] = page_num;
1495 		spdk_bit_array_set(bs->used_md_pages, page_num);
1496 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming page %u for blob %lu\n", page_num, blob->id);
1497 		page_num++;
1498 	}
1499 	ctx->pages[i - 1].crc = _spdk_blob_md_page_calc_crc(&ctx->pages[i - 1]);
1500 	/* Start writing the metadata from last page to first */
1501 	blob->state = SPDK_BLOB_STATE_CLEAN;
1502 	_spdk_blob_persist_write_page_chain(seq, ctx, 0);
1503 }
1504 
1505 static void
1506 _spdk_blob_persist_dirty_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1507 {
1508 	struct spdk_blob_persist_ctx *ctx = cb_arg;
1509 
1510 	ctx->blob->bs->clean = 0;
1511 
1512 	spdk_free(ctx->super);
1513 
1514 	_spdk_blob_persist_start(ctx);
1515 }
1516 
1517 static void
1518 _spdk_bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
1519 		     struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg);
1520 
1521 
1522 static void
1523 _spdk_blob_persist_dirty(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1524 {
1525 	struct spdk_blob_persist_ctx *ctx = cb_arg;
1526 
1527 	ctx->super->clean = 0;
1528 	if (ctx->super->size == 0) {
1529 		ctx->super->size = ctx->blob->bs->dev->blockcnt * ctx->blob->bs->dev->blocklen;
1530 	}
1531 
1532 	_spdk_bs_write_super(seq, ctx->blob->bs, ctx->super, _spdk_blob_persist_dirty_cpl, ctx);
1533 }
1534 
1535 
1536 /* Write a blob to disk */
1537 static void
1538 _spdk_blob_persist(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1539 		   spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1540 {
1541 	struct spdk_blob_persist_ctx *ctx;
1542 
1543 	_spdk_blob_verify_md_op(blob);
1544 
1545 	if (blob->state == SPDK_BLOB_STATE_CLEAN) {
1546 		cb_fn(seq, cb_arg, 0);
1547 		return;
1548 	}
1549 
1550 	ctx = calloc(1, sizeof(*ctx));
1551 	if (!ctx) {
1552 		cb_fn(seq, cb_arg, -ENOMEM);
1553 		return;
1554 	}
1555 	ctx->blob = blob;
1556 	ctx->seq = seq;
1557 	ctx->cb_fn = cb_fn;
1558 	ctx->cb_arg = cb_arg;
1559 
1560 	if (blob->bs->clean) {
1561 		ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
1562 					  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1563 		if (!ctx->super) {
1564 			cb_fn(seq, cb_arg, -ENOMEM);
1565 			free(ctx);
1566 			return;
1567 		}
1568 
1569 		spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(blob->bs, 0),
1570 					  _spdk_bs_byte_to_lba(blob->bs, sizeof(*ctx->super)),
1571 					  _spdk_blob_persist_dirty, ctx);
1572 	} else {
1573 		_spdk_blob_persist_start(ctx);
1574 	}
1575 }
1576 
1577 struct spdk_blob_copy_cluster_ctx {
1578 	struct spdk_blob *blob;
1579 	uint8_t *buf;
1580 	uint64_t page;
1581 	uint64_t new_cluster;
1582 	spdk_bs_sequence_t *seq;
1583 };
1584 
1585 static void
1586 _spdk_blob_allocate_and_copy_cluster_cpl(void *cb_arg, int bserrno)
1587 {
1588 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1589 	struct spdk_bs_request_set *set = (struct spdk_bs_request_set *)ctx->seq;
1590 	TAILQ_HEAD(, spdk_bs_request_set) requests;
1591 	spdk_bs_user_op_t *op;
1592 
1593 	TAILQ_INIT(&requests);
1594 	TAILQ_SWAP(&set->channel->need_cluster_alloc, &requests, spdk_bs_request_set, link);
1595 
1596 	while (!TAILQ_EMPTY(&requests)) {
1597 		op = TAILQ_FIRST(&requests);
1598 		TAILQ_REMOVE(&requests, op, link);
1599 		if (bserrno == 0) {
1600 			spdk_bs_user_op_execute(op);
1601 		} else {
1602 			spdk_bs_user_op_abort(op);
1603 		}
1604 	}
1605 
1606 	spdk_free(ctx->buf);
1607 	free(ctx);
1608 }
1609 
1610 static void
1611 _spdk_blob_insert_cluster_cpl(void *cb_arg, int bserrno)
1612 {
1613 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1614 
1615 	if (bserrno) {
1616 		if (bserrno == -EEXIST) {
1617 			/* The metadata insert failed because another thread
1618 			 * allocated the cluster first. Free our cluster
1619 			 * but continue without error. */
1620 			bserrno = 0;
1621 		}
1622 		_spdk_bs_release_cluster(ctx->blob->bs, ctx->new_cluster);
1623 	}
1624 
1625 	spdk_bs_sequence_finish(ctx->seq, bserrno);
1626 }
1627 
1628 static void
1629 _spdk_blob_write_copy_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1630 {
1631 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1632 	uint32_t cluster_number;
1633 
1634 	if (bserrno) {
1635 		/* The write failed, so jump to the final completion handler */
1636 		spdk_bs_sequence_finish(seq, bserrno);
1637 		return;
1638 	}
1639 
1640 	cluster_number = _spdk_bs_page_to_cluster(ctx->blob->bs, ctx->page);
1641 
1642 	_spdk_blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
1643 					       _spdk_blob_insert_cluster_cpl, ctx);
1644 }
1645 
1646 static void
1647 _spdk_blob_write_copy(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1648 {
1649 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1650 
1651 	if (bserrno != 0) {
1652 		/* The read failed, so jump to the final completion handler */
1653 		spdk_bs_sequence_finish(seq, bserrno);
1654 		return;
1655 	}
1656 
1657 	/* Write whole cluster */
1658 	spdk_bs_sequence_write_dev(seq, ctx->buf,
1659 				   _spdk_bs_cluster_to_lba(ctx->blob->bs, ctx->new_cluster),
1660 				   _spdk_bs_cluster_to_lba(ctx->blob->bs, 1),
1661 				   _spdk_blob_write_copy_cpl, ctx);
1662 }
1663 
1664 static void
1665 _spdk_bs_allocate_and_copy_cluster(struct spdk_blob *blob,
1666 				   struct spdk_io_channel *_ch,
1667 				   uint64_t io_unit, spdk_bs_user_op_t *op)
1668 {
1669 	struct spdk_bs_cpl cpl;
1670 	struct spdk_bs_channel *ch;
1671 	struct spdk_blob_copy_cluster_ctx *ctx;
1672 	uint32_t cluster_start_page;
1673 	uint32_t cluster_number;
1674 	int rc;
1675 
1676 	ch = spdk_io_channel_get_ctx(_ch);
1677 
1678 	if (!TAILQ_EMPTY(&ch->need_cluster_alloc)) {
1679 		/* There are already operations pending. Queue this user op
1680 		 * and return because it will be re-executed when the outstanding
1681 		 * cluster allocation completes. */
1682 		TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
1683 		return;
1684 	}
1685 
1686 	/* Round the io_unit offset down to the first page in the cluster */
1687 	cluster_start_page = _spdk_bs_io_unit_to_cluster_start(blob, io_unit);
1688 
1689 	/* Calculate which index in the metadata cluster array the corresponding
1690 	 * cluster is supposed to be at. */
1691 	cluster_number = _spdk_bs_io_unit_to_cluster_number(blob, io_unit);
1692 
1693 	ctx = calloc(1, sizeof(*ctx));
1694 	if (!ctx) {
1695 		spdk_bs_user_op_abort(op);
1696 		return;
1697 	}
1698 
1699 	assert(blob->bs->cluster_sz % blob->back_bs_dev->blocklen == 0);
1700 
1701 	ctx->blob = blob;
1702 	ctx->page = cluster_start_page;
1703 
1704 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
1705 		ctx->buf = spdk_malloc(blob->bs->cluster_sz, blob->back_bs_dev->blocklen,
1706 				       NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1707 		if (!ctx->buf) {
1708 			SPDK_ERRLOG("DMA allocation for cluster of size = %" PRIu32 " failed.\n",
1709 				    blob->bs->cluster_sz);
1710 			free(ctx);
1711 			spdk_bs_user_op_abort(op);
1712 			return;
1713 		}
1714 	}
1715 
1716 	rc = _spdk_bs_allocate_cluster(blob, cluster_number, &ctx->new_cluster, false);
1717 	if (rc != 0) {
1718 		spdk_free(ctx->buf);
1719 		free(ctx);
1720 		spdk_bs_user_op_abort(op);
1721 		return;
1722 	}
1723 
1724 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1725 	cpl.u.blob_basic.cb_fn = _spdk_blob_allocate_and_copy_cluster_cpl;
1726 	cpl.u.blob_basic.cb_arg = ctx;
1727 
1728 	ctx->seq = spdk_bs_sequence_start(_ch, &cpl);
1729 	if (!ctx->seq) {
1730 		_spdk_bs_release_cluster(blob->bs, ctx->new_cluster);
1731 		spdk_free(ctx->buf);
1732 		free(ctx);
1733 		spdk_bs_user_op_abort(op);
1734 		return;
1735 	}
1736 
1737 	/* Queue the user op to block other incoming operations */
1738 	TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
1739 
1740 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
1741 		/* Read cluster from backing device */
1742 		spdk_bs_sequence_read_bs_dev(ctx->seq, blob->back_bs_dev, ctx->buf,
1743 					     _spdk_bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page),
1744 					     _spdk_bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz),
1745 					     _spdk_blob_write_copy, ctx);
1746 	} else {
1747 		_spdk_blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
1748 						       _spdk_blob_insert_cluster_cpl, ctx);
1749 	}
1750 }
1751 
1752 static void
1753 _spdk_blob_calculate_lba_and_lba_count(struct spdk_blob *blob, uint64_t io_unit, uint64_t length,
1754 				       uint64_t *lba,	uint32_t *lba_count)
1755 {
1756 	*lba_count = length;
1757 
1758 	if (!_spdk_bs_io_unit_is_allocated(blob, io_unit)) {
1759 		assert(blob->back_bs_dev != NULL);
1760 		*lba = _spdk_bs_io_unit_to_back_dev_lba(blob, io_unit);
1761 		*lba_count = _spdk_bs_io_unit_to_back_dev_lba(blob, *lba_count);
1762 	} else {
1763 		*lba = _spdk_bs_blob_io_unit_to_lba(blob, io_unit);
1764 	}
1765 }
1766 
1767 struct op_split_ctx {
1768 	struct spdk_blob *blob;
1769 	struct spdk_io_channel *channel;
1770 	uint64_t io_unit_offset;
1771 	uint64_t io_units_remaining;
1772 	void *curr_payload;
1773 	enum spdk_blob_op_type op_type;
1774 	spdk_bs_sequence_t *seq;
1775 };
1776 
1777 static void
1778 _spdk_blob_request_submit_op_split_next(void *cb_arg, int bserrno)
1779 {
1780 	struct op_split_ctx	*ctx = cb_arg;
1781 	struct spdk_blob	*blob = ctx->blob;
1782 	struct spdk_io_channel	*ch = ctx->channel;
1783 	enum spdk_blob_op_type	op_type = ctx->op_type;
1784 	uint8_t			*buf = ctx->curr_payload;
1785 	uint64_t		offset = ctx->io_unit_offset;
1786 	uint64_t		length = ctx->io_units_remaining;
1787 	uint64_t		op_length;
1788 
1789 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
1790 		spdk_bs_sequence_finish(ctx->seq, bserrno);
1791 		free(ctx);
1792 		return;
1793 	}
1794 
1795 	op_length = spdk_min(length, _spdk_bs_num_io_units_to_cluster_boundary(blob,
1796 			     offset));
1797 
1798 	/* Update length and payload for next operation */
1799 	ctx->io_units_remaining -= op_length;
1800 	ctx->io_unit_offset += op_length;
1801 	if (op_type == SPDK_BLOB_WRITE || op_type == SPDK_BLOB_READ) {
1802 		ctx->curr_payload += op_length * blob->bs->io_unit_size;
1803 	}
1804 
1805 	switch (op_type) {
1806 	case SPDK_BLOB_READ:
1807 		spdk_blob_io_read(blob, ch, buf, offset, op_length,
1808 				  _spdk_blob_request_submit_op_split_next, ctx);
1809 		break;
1810 	case SPDK_BLOB_WRITE:
1811 		spdk_blob_io_write(blob, ch, buf, offset, op_length,
1812 				   _spdk_blob_request_submit_op_split_next, ctx);
1813 		break;
1814 	case SPDK_BLOB_UNMAP:
1815 		spdk_blob_io_unmap(blob, ch, offset, op_length,
1816 				   _spdk_blob_request_submit_op_split_next, ctx);
1817 		break;
1818 	case SPDK_BLOB_WRITE_ZEROES:
1819 		spdk_blob_io_write_zeroes(blob, ch, offset, op_length,
1820 					  _spdk_blob_request_submit_op_split_next, ctx);
1821 		break;
1822 	case SPDK_BLOB_READV:
1823 	case SPDK_BLOB_WRITEV:
1824 		SPDK_ERRLOG("readv/write not valid\n");
1825 		spdk_bs_sequence_finish(ctx->seq, -EINVAL);
1826 		free(ctx);
1827 		break;
1828 	}
1829 }
1830 
1831 static void
1832 _spdk_blob_request_submit_op_split(struct spdk_io_channel *ch, struct spdk_blob *blob,
1833 				   void *payload, uint64_t offset, uint64_t length,
1834 				   spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1835 {
1836 	struct op_split_ctx *ctx;
1837 	spdk_bs_sequence_t *seq;
1838 	struct spdk_bs_cpl cpl;
1839 
1840 	assert(blob != NULL);
1841 
1842 	ctx = calloc(1, sizeof(struct op_split_ctx));
1843 	if (ctx == NULL) {
1844 		cb_fn(cb_arg, -ENOMEM);
1845 		return;
1846 	}
1847 
1848 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1849 	cpl.u.blob_basic.cb_fn = cb_fn;
1850 	cpl.u.blob_basic.cb_arg = cb_arg;
1851 
1852 	seq = spdk_bs_sequence_start(ch, &cpl);
1853 	if (!seq) {
1854 		free(ctx);
1855 		cb_fn(cb_arg, -ENOMEM);
1856 		return;
1857 	}
1858 
1859 	ctx->blob = blob;
1860 	ctx->channel = ch;
1861 	ctx->curr_payload = payload;
1862 	ctx->io_unit_offset = offset;
1863 	ctx->io_units_remaining = length;
1864 	ctx->op_type = op_type;
1865 	ctx->seq = seq;
1866 
1867 	_spdk_blob_request_submit_op_split_next(ctx, 0);
1868 }
1869 
1870 static void
1871 _spdk_blob_request_submit_op_single(struct spdk_io_channel *_ch, struct spdk_blob *blob,
1872 				    void *payload, uint64_t offset, uint64_t length,
1873 				    spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1874 {
1875 	struct spdk_bs_cpl cpl;
1876 	uint64_t lba;
1877 	uint32_t lba_count;
1878 
1879 	assert(blob != NULL);
1880 
1881 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1882 	cpl.u.blob_basic.cb_fn = cb_fn;
1883 	cpl.u.blob_basic.cb_arg = cb_arg;
1884 
1885 	_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
1886 
1887 	if (blob->frozen_refcnt) {
1888 		/* This blob I/O is frozen */
1889 		spdk_bs_user_op_t *op;
1890 		struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_ch);
1891 
1892 		op = spdk_bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
1893 		if (!op) {
1894 			cb_fn(cb_arg, -ENOMEM);
1895 			return;
1896 		}
1897 
1898 		TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
1899 
1900 		return;
1901 	}
1902 
1903 	switch (op_type) {
1904 	case SPDK_BLOB_READ: {
1905 		spdk_bs_batch_t *batch;
1906 
1907 		batch = spdk_bs_batch_open(_ch, &cpl);
1908 		if (!batch) {
1909 			cb_fn(cb_arg, -ENOMEM);
1910 			return;
1911 		}
1912 
1913 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1914 			/* Read from the blob */
1915 			spdk_bs_batch_read_dev(batch, payload, lba, lba_count);
1916 		} else {
1917 			/* Read from the backing block device */
1918 			spdk_bs_batch_read_bs_dev(batch, blob->back_bs_dev, payload, lba, lba_count);
1919 		}
1920 
1921 		spdk_bs_batch_close(batch);
1922 		break;
1923 	}
1924 	case SPDK_BLOB_WRITE:
1925 	case SPDK_BLOB_WRITE_ZEROES: {
1926 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1927 			/* Write to the blob */
1928 			spdk_bs_batch_t *batch;
1929 
1930 			if (lba_count == 0) {
1931 				cb_fn(cb_arg, 0);
1932 				return;
1933 			}
1934 
1935 			batch = spdk_bs_batch_open(_ch, &cpl);
1936 			if (!batch) {
1937 				cb_fn(cb_arg, -ENOMEM);
1938 				return;
1939 			}
1940 
1941 			if (op_type == SPDK_BLOB_WRITE) {
1942 				spdk_bs_batch_write_dev(batch, payload, lba, lba_count);
1943 			} else {
1944 				spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1945 			}
1946 
1947 			spdk_bs_batch_close(batch);
1948 		} else {
1949 			/* Queue this operation and allocate the cluster */
1950 			spdk_bs_user_op_t *op;
1951 
1952 			op = spdk_bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
1953 			if (!op) {
1954 				cb_fn(cb_arg, -ENOMEM);
1955 				return;
1956 			}
1957 
1958 			_spdk_bs_allocate_and_copy_cluster(blob, _ch, offset, op);
1959 		}
1960 		break;
1961 	}
1962 	case SPDK_BLOB_UNMAP: {
1963 		spdk_bs_batch_t *batch;
1964 
1965 		batch = spdk_bs_batch_open(_ch, &cpl);
1966 		if (!batch) {
1967 			cb_fn(cb_arg, -ENOMEM);
1968 			return;
1969 		}
1970 
1971 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1972 			spdk_bs_batch_unmap_dev(batch, lba, lba_count);
1973 		}
1974 
1975 		spdk_bs_batch_close(batch);
1976 		break;
1977 	}
1978 	case SPDK_BLOB_READV:
1979 	case SPDK_BLOB_WRITEV:
1980 		SPDK_ERRLOG("readv/write not valid\n");
1981 		cb_fn(cb_arg, -EINVAL);
1982 		break;
1983 	}
1984 }
1985 
1986 static void
1987 _spdk_blob_request_submit_op(struct spdk_blob *blob, struct spdk_io_channel *_channel,
1988 			     void *payload, uint64_t offset, uint64_t length,
1989 			     spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1990 {
1991 	assert(blob != NULL);
1992 
1993 	if (blob->data_ro && op_type != SPDK_BLOB_READ) {
1994 		cb_fn(cb_arg, -EPERM);
1995 		return;
1996 	}
1997 
1998 	if (offset + length > _spdk_bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
1999 		cb_fn(cb_arg, -EINVAL);
2000 		return;
2001 	}
2002 	if (length <= _spdk_bs_num_io_units_to_cluster_boundary(blob, offset)) {
2003 		_spdk_blob_request_submit_op_single(_channel, blob, payload, offset, length,
2004 						    cb_fn, cb_arg, op_type);
2005 	} else {
2006 		_spdk_blob_request_submit_op_split(_channel, blob, payload, offset, length,
2007 						   cb_fn, cb_arg, op_type);
2008 	}
2009 }
2010 
2011 struct rw_iov_ctx {
2012 	struct spdk_blob *blob;
2013 	struct spdk_io_channel *channel;
2014 	spdk_blob_op_complete cb_fn;
2015 	void *cb_arg;
2016 	bool read;
2017 	int iovcnt;
2018 	struct iovec *orig_iov;
2019 	uint64_t io_unit_offset;
2020 	uint64_t io_units_remaining;
2021 	uint64_t io_units_done;
2022 	struct iovec iov[0];
2023 };
2024 
2025 static void
2026 _spdk_rw_iov_done(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2027 {
2028 	assert(cb_arg == NULL);
2029 	spdk_bs_sequence_finish(seq, bserrno);
2030 }
2031 
2032 static void
2033 _spdk_rw_iov_split_next(void *cb_arg, int bserrno)
2034 {
2035 	struct rw_iov_ctx *ctx = cb_arg;
2036 	struct spdk_blob *blob = ctx->blob;
2037 	struct iovec *iov, *orig_iov;
2038 	int iovcnt;
2039 	size_t orig_iovoff;
2040 	uint64_t io_units_count, io_units_to_boundary, io_unit_offset;
2041 	uint64_t byte_count;
2042 
2043 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
2044 		ctx->cb_fn(ctx->cb_arg, bserrno);
2045 		free(ctx);
2046 		return;
2047 	}
2048 
2049 	io_unit_offset = ctx->io_unit_offset;
2050 	io_units_to_boundary = _spdk_bs_num_io_units_to_cluster_boundary(blob, io_unit_offset);
2051 	io_units_count = spdk_min(ctx->io_units_remaining, io_units_to_boundary);
2052 	/*
2053 	 * Get index and offset into the original iov array for our current position in the I/O sequence.
2054 	 *  byte_count will keep track of how many bytes remaining until orig_iov and orig_iovoff will
2055 	 *  point to the current position in the I/O sequence.
2056 	 */
2057 	byte_count = ctx->io_units_done * blob->bs->io_unit_size;
2058 	orig_iov = &ctx->orig_iov[0];
2059 	orig_iovoff = 0;
2060 	while (byte_count > 0) {
2061 		if (byte_count >= orig_iov->iov_len) {
2062 			byte_count -= orig_iov->iov_len;
2063 			orig_iov++;
2064 		} else {
2065 			orig_iovoff = byte_count;
2066 			byte_count = 0;
2067 		}
2068 	}
2069 
2070 	/*
2071 	 * Build an iov array for the next I/O in the sequence.  byte_count will keep track of how many
2072 	 *  bytes of this next I/O remain to be accounted for in the new iov array.
2073 	 */
2074 	byte_count = io_units_count * blob->bs->io_unit_size;
2075 	iov = &ctx->iov[0];
2076 	iovcnt = 0;
2077 	while (byte_count > 0) {
2078 		assert(iovcnt < ctx->iovcnt);
2079 		iov->iov_len = spdk_min(byte_count, orig_iov->iov_len - orig_iovoff);
2080 		iov->iov_base = orig_iov->iov_base + orig_iovoff;
2081 		byte_count -= iov->iov_len;
2082 		orig_iovoff = 0;
2083 		orig_iov++;
2084 		iov++;
2085 		iovcnt++;
2086 	}
2087 
2088 	ctx->io_unit_offset += io_units_count;
2089 	ctx->io_units_remaining -= io_units_count;
2090 	ctx->io_units_done += io_units_count;
2091 	iov = &ctx->iov[0];
2092 
2093 	if (ctx->read) {
2094 		spdk_blob_io_readv(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2095 				   io_units_count, _spdk_rw_iov_split_next, ctx);
2096 	} else {
2097 		spdk_blob_io_writev(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2098 				    io_units_count, _spdk_rw_iov_split_next, ctx);
2099 	}
2100 }
2101 
2102 static void
2103 _spdk_blob_request_submit_rw_iov(struct spdk_blob *blob, struct spdk_io_channel *_channel,
2104 				 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
2105 				 spdk_blob_op_complete cb_fn, void *cb_arg, bool read)
2106 {
2107 	struct spdk_bs_cpl	cpl;
2108 
2109 	assert(blob != NULL);
2110 
2111 	if (!read && blob->data_ro) {
2112 		cb_fn(cb_arg, -EPERM);
2113 		return;
2114 	}
2115 
2116 	if (length == 0) {
2117 		cb_fn(cb_arg, 0);
2118 		return;
2119 	}
2120 
2121 	if (offset + length > _spdk_bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
2122 		cb_fn(cb_arg, -EINVAL);
2123 		return;
2124 	}
2125 
2126 	/*
2127 	 * For now, we implement readv/writev using a sequence (instead of a batch) to account for having
2128 	 *  to split a request that spans a cluster boundary.  For I/O that do not span a cluster boundary,
2129 	 *  there will be no noticeable difference compared to using a batch.  For I/O that do span a cluster
2130 	 *  boundary, the target LBAs (after blob offset to LBA translation) may not be contiguous, so we need
2131 	 *  to allocate a separate iov array and split the I/O such that none of the resulting
2132 	 *  smaller I/O cross a cluster boundary.  These smaller I/O will be issued in sequence (not in parallel)
2133 	 *  but since this case happens very infrequently, any performance impact will be negligible.
2134 	 *
2135 	 * This could be optimized in the future to allocate a big enough iov array to account for all of the iovs
2136 	 *  for all of the smaller I/Os, pre-build all of the iov arrays for the smaller I/Os, then issue them
2137 	 *  in a batch.  That would also require creating an intermediate spdk_bs_cpl that would get called
2138 	 *  when the batch was completed, to allow for freeing the memory for the iov arrays.
2139 	 */
2140 	if (spdk_likely(length <= _spdk_bs_num_io_units_to_cluster_boundary(blob, offset))) {
2141 		uint32_t lba_count;
2142 		uint64_t lba;
2143 
2144 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2145 		cpl.u.blob_basic.cb_fn = cb_fn;
2146 		cpl.u.blob_basic.cb_arg = cb_arg;
2147 
2148 		if (blob->frozen_refcnt) {
2149 			/* This blob I/O is frozen */
2150 			enum spdk_blob_op_type op_type;
2151 			spdk_bs_user_op_t *op;
2152 			struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_channel);
2153 
2154 			op_type = read ? SPDK_BLOB_READV : SPDK_BLOB_WRITEV;
2155 			op = spdk_bs_user_op_alloc(_channel, &cpl, op_type, blob, iov, iovcnt, offset, length);
2156 			if (!op) {
2157 				cb_fn(cb_arg, -ENOMEM);
2158 				return;
2159 			}
2160 
2161 			TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
2162 
2163 			return;
2164 		}
2165 
2166 		_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
2167 
2168 		if (read) {
2169 			spdk_bs_sequence_t *seq;
2170 
2171 			seq = spdk_bs_sequence_start(_channel, &cpl);
2172 			if (!seq) {
2173 				cb_fn(cb_arg, -ENOMEM);
2174 				return;
2175 			}
2176 
2177 			if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
2178 				spdk_bs_sequence_readv_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
2179 			} else {
2180 				spdk_bs_sequence_readv_bs_dev(seq, blob->back_bs_dev, iov, iovcnt, lba, lba_count,
2181 							      _spdk_rw_iov_done, NULL);
2182 			}
2183 		} else {
2184 			if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
2185 				spdk_bs_sequence_t *seq;
2186 
2187 				seq = spdk_bs_sequence_start(_channel, &cpl);
2188 				if (!seq) {
2189 					cb_fn(cb_arg, -ENOMEM);
2190 					return;
2191 				}
2192 
2193 				spdk_bs_sequence_writev_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
2194 			} else {
2195 				/* Queue this operation and allocate the cluster */
2196 				spdk_bs_user_op_t *op;
2197 
2198 				op = spdk_bs_user_op_alloc(_channel, &cpl, SPDK_BLOB_WRITEV, blob, iov, iovcnt, offset,
2199 							   length);
2200 				if (!op) {
2201 					cb_fn(cb_arg, -ENOMEM);
2202 					return;
2203 				}
2204 
2205 				_spdk_bs_allocate_and_copy_cluster(blob, _channel, offset, op);
2206 			}
2207 		}
2208 	} else {
2209 		struct rw_iov_ctx *ctx;
2210 
2211 		ctx = calloc(1, sizeof(struct rw_iov_ctx) + iovcnt * sizeof(struct iovec));
2212 		if (ctx == NULL) {
2213 			cb_fn(cb_arg, -ENOMEM);
2214 			return;
2215 		}
2216 
2217 		ctx->blob = blob;
2218 		ctx->channel = _channel;
2219 		ctx->cb_fn = cb_fn;
2220 		ctx->cb_arg = cb_arg;
2221 		ctx->read = read;
2222 		ctx->orig_iov = iov;
2223 		ctx->iovcnt = iovcnt;
2224 		ctx->io_unit_offset = offset;
2225 		ctx->io_units_remaining = length;
2226 		ctx->io_units_done = 0;
2227 
2228 		_spdk_rw_iov_split_next(ctx, 0);
2229 	}
2230 }
2231 
2232 static struct spdk_blob *
2233 _spdk_blob_lookup(struct spdk_blob_store *bs, spdk_blob_id blobid)
2234 {
2235 	struct spdk_blob *blob;
2236 
2237 	TAILQ_FOREACH(blob, &bs->blobs, link) {
2238 		if (blob->id == blobid) {
2239 			return blob;
2240 		}
2241 	}
2242 
2243 	return NULL;
2244 }
2245 
2246 static void
2247 _spdk_blob_get_snapshot_and_clone_entries(struct spdk_blob *blob,
2248 		struct spdk_blob_list **snapshot_entry, struct spdk_blob_list **clone_entry)
2249 {
2250 	assert(blob != NULL);
2251 	*snapshot_entry = NULL;
2252 	*clone_entry = NULL;
2253 
2254 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
2255 		return;
2256 	}
2257 
2258 	TAILQ_FOREACH(*snapshot_entry, &blob->bs->snapshots, link) {
2259 		if ((*snapshot_entry)->id == blob->parent_id) {
2260 			break;
2261 		}
2262 	}
2263 
2264 	if (*snapshot_entry != NULL) {
2265 		TAILQ_FOREACH(*clone_entry, &(*snapshot_entry)->clones, link) {
2266 			if ((*clone_entry)->id == blob->id) {
2267 				break;
2268 			}
2269 		}
2270 
2271 		assert(clone_entry != NULL);
2272 	}
2273 }
2274 
2275 static int
2276 _spdk_bs_channel_create(void *io_device, void *ctx_buf)
2277 {
2278 	struct spdk_blob_store		*bs = io_device;
2279 	struct spdk_bs_channel		*channel = ctx_buf;
2280 	struct spdk_bs_dev		*dev;
2281 	uint32_t			max_ops = bs->max_channel_ops;
2282 	uint32_t			i;
2283 
2284 	dev = bs->dev;
2285 
2286 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_bs_request_set));
2287 	if (!channel->req_mem) {
2288 		return -1;
2289 	}
2290 
2291 	TAILQ_INIT(&channel->reqs);
2292 
2293 	for (i = 0; i < max_ops; i++) {
2294 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
2295 	}
2296 
2297 	channel->bs = bs;
2298 	channel->dev = dev;
2299 	channel->dev_channel = dev->create_channel(dev);
2300 
2301 	if (!channel->dev_channel) {
2302 		SPDK_ERRLOG("Failed to create device channel.\n");
2303 		free(channel->req_mem);
2304 		return -1;
2305 	}
2306 
2307 	TAILQ_INIT(&channel->need_cluster_alloc);
2308 	TAILQ_INIT(&channel->queued_io);
2309 
2310 	return 0;
2311 }
2312 
2313 static void
2314 _spdk_bs_channel_destroy(void *io_device, void *ctx_buf)
2315 {
2316 	struct spdk_bs_channel *channel = ctx_buf;
2317 	spdk_bs_user_op_t *op;
2318 
2319 	while (!TAILQ_EMPTY(&channel->need_cluster_alloc)) {
2320 		op = TAILQ_FIRST(&channel->need_cluster_alloc);
2321 		TAILQ_REMOVE(&channel->need_cluster_alloc, op, link);
2322 		spdk_bs_user_op_abort(op);
2323 	}
2324 
2325 	while (!TAILQ_EMPTY(&channel->queued_io)) {
2326 		op = TAILQ_FIRST(&channel->queued_io);
2327 		TAILQ_REMOVE(&channel->queued_io, op, link);
2328 		spdk_bs_user_op_abort(op);
2329 	}
2330 
2331 	free(channel->req_mem);
2332 	channel->dev->destroy_channel(channel->dev, channel->dev_channel);
2333 }
2334 
2335 static void
2336 _spdk_bs_dev_destroy(void *io_device)
2337 {
2338 	struct spdk_blob_store *bs = io_device;
2339 	struct spdk_blob	*blob, *blob_tmp;
2340 
2341 	bs->dev->destroy(bs->dev);
2342 
2343 	TAILQ_FOREACH_SAFE(blob, &bs->blobs, link, blob_tmp) {
2344 		TAILQ_REMOVE(&bs->blobs, blob, link);
2345 		_spdk_blob_free(blob);
2346 	}
2347 
2348 	pthread_mutex_destroy(&bs->used_clusters_mutex);
2349 
2350 	spdk_bit_array_free(&bs->used_blobids);
2351 	spdk_bit_array_free(&bs->used_md_pages);
2352 	spdk_bit_array_free(&bs->used_clusters);
2353 	/*
2354 	 * If this function is called for any reason except a successful unload,
2355 	 * the unload_cpl type will be NONE and this will be a nop.
2356 	 */
2357 	spdk_bs_call_cpl(&bs->unload_cpl, bs->unload_err);
2358 
2359 	free(bs);
2360 }
2361 
2362 static int
2363 _spdk_bs_blob_list_add(struct spdk_blob *blob)
2364 {
2365 	spdk_blob_id snapshot_id;
2366 	struct spdk_blob_list *snapshot_entry = NULL;
2367 	struct spdk_blob_list *clone_entry = NULL;
2368 
2369 	assert(blob != NULL);
2370 
2371 	snapshot_id = blob->parent_id;
2372 	if (snapshot_id == SPDK_BLOBID_INVALID) {
2373 		return 0;
2374 	}
2375 
2376 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, snapshot_id);
2377 	if (snapshot_entry == NULL) {
2378 		/* Snapshot not found */
2379 		snapshot_entry = calloc(1, sizeof(struct spdk_blob_list));
2380 		if (snapshot_entry == NULL) {
2381 			return -ENOMEM;
2382 		}
2383 		snapshot_entry->id = snapshot_id;
2384 		TAILQ_INIT(&snapshot_entry->clones);
2385 		TAILQ_INSERT_TAIL(&blob->bs->snapshots, snapshot_entry, link);
2386 	} else {
2387 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
2388 			if (clone_entry->id == blob->id) {
2389 				break;
2390 			}
2391 		}
2392 	}
2393 
2394 	if (clone_entry == NULL) {
2395 		/* Clone not found */
2396 		clone_entry = calloc(1, sizeof(struct spdk_blob_list));
2397 		if (clone_entry == NULL) {
2398 			return -ENOMEM;
2399 		}
2400 		clone_entry->id = blob->id;
2401 		TAILQ_INIT(&clone_entry->clones);
2402 		TAILQ_INSERT_TAIL(&snapshot_entry->clones, clone_entry, link);
2403 		snapshot_entry->clone_count++;
2404 	}
2405 
2406 	return 0;
2407 }
2408 
2409 static void
2410 _spdk_bs_blob_list_remove(struct spdk_blob *blob)
2411 {
2412 	struct spdk_blob_list *snapshot_entry = NULL;
2413 	struct spdk_blob_list *clone_entry = NULL;
2414 
2415 	_spdk_blob_get_snapshot_and_clone_entries(blob, &snapshot_entry, &clone_entry);
2416 
2417 	if (snapshot_entry == NULL) {
2418 		return;
2419 	}
2420 
2421 	blob->parent_id = SPDK_BLOBID_INVALID;
2422 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
2423 	free(clone_entry);
2424 
2425 	snapshot_entry->clone_count--;
2426 }
2427 
2428 static int
2429 _spdk_bs_blob_list_free(struct spdk_blob_store *bs)
2430 {
2431 	struct spdk_blob_list *snapshot_entry;
2432 	struct spdk_blob_list *snapshot_entry_tmp;
2433 	struct spdk_blob_list *clone_entry;
2434 	struct spdk_blob_list *clone_entry_tmp;
2435 
2436 	TAILQ_FOREACH_SAFE(snapshot_entry, &bs->snapshots, link, snapshot_entry_tmp) {
2437 		TAILQ_FOREACH_SAFE(clone_entry, &snapshot_entry->clones, link, clone_entry_tmp) {
2438 			TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
2439 			free(clone_entry);
2440 		}
2441 		TAILQ_REMOVE(&bs->snapshots, snapshot_entry, link);
2442 		free(snapshot_entry);
2443 	}
2444 
2445 	return 0;
2446 }
2447 
2448 static void
2449 _spdk_bs_free(struct spdk_blob_store *bs)
2450 {
2451 	_spdk_bs_blob_list_free(bs);
2452 
2453 	spdk_bs_unregister_md_thread(bs);
2454 	spdk_io_device_unregister(bs, _spdk_bs_dev_destroy);
2455 }
2456 
2457 void
2458 spdk_bs_opts_init(struct spdk_bs_opts *opts)
2459 {
2460 	opts->cluster_sz = SPDK_BLOB_OPTS_CLUSTER_SZ;
2461 	opts->num_md_pages = SPDK_BLOB_OPTS_NUM_MD_PAGES;
2462 	opts->max_md_ops = SPDK_BLOB_OPTS_MAX_MD_OPS;
2463 	opts->max_channel_ops = SPDK_BLOB_OPTS_DEFAULT_CHANNEL_OPS;
2464 	opts->clear_method = BS_CLEAR_WITH_UNMAP;
2465 	memset(&opts->bstype, 0, sizeof(opts->bstype));
2466 	opts->iter_cb_fn = NULL;
2467 	opts->iter_cb_arg = NULL;
2468 }
2469 
2470 static int
2471 _spdk_bs_opts_verify(struct spdk_bs_opts *opts)
2472 {
2473 	if (opts->cluster_sz == 0 || opts->num_md_pages == 0 || opts->max_md_ops == 0 ||
2474 	    opts->max_channel_ops == 0) {
2475 		SPDK_ERRLOG("Blobstore options cannot be set to 0\n");
2476 		return -1;
2477 	}
2478 
2479 	return 0;
2480 }
2481 
2482 static int
2483 _spdk_bs_alloc(struct spdk_bs_dev *dev, struct spdk_bs_opts *opts, struct spdk_blob_store **_bs)
2484 {
2485 	struct spdk_blob_store	*bs;
2486 	uint64_t dev_size;
2487 	int rc;
2488 
2489 	dev_size = dev->blocklen * dev->blockcnt;
2490 	if (dev_size < opts->cluster_sz) {
2491 		/* Device size cannot be smaller than cluster size of blobstore */
2492 		SPDK_INFOLOG(SPDK_LOG_BLOB, "Device size %" PRIu64 " is smaller than cluster size %" PRIu32 "\n",
2493 			     dev_size, opts->cluster_sz);
2494 		return -ENOSPC;
2495 	}
2496 	if (opts->cluster_sz < SPDK_BS_PAGE_SIZE) {
2497 		/* Cluster size cannot be smaller than page size */
2498 		SPDK_ERRLOG("Cluster size %" PRIu32 " is smaller than page size %d\n",
2499 			    opts->cluster_sz, SPDK_BS_PAGE_SIZE);
2500 		return -EINVAL;
2501 	}
2502 	bs = calloc(1, sizeof(struct spdk_blob_store));
2503 	if (!bs) {
2504 		return -ENOMEM;
2505 	}
2506 
2507 	TAILQ_INIT(&bs->blobs);
2508 	TAILQ_INIT(&bs->snapshots);
2509 	bs->dev = dev;
2510 	bs->md_thread = spdk_get_thread();
2511 	assert(bs->md_thread != NULL);
2512 
2513 	/*
2514 	 * Do not use _spdk_bs_lba_to_cluster() here since blockcnt may not be an
2515 	 *  even multiple of the cluster size.
2516 	 */
2517 	bs->cluster_sz = opts->cluster_sz;
2518 	bs->total_clusters = dev->blockcnt / (bs->cluster_sz / dev->blocklen);
2519 	bs->pages_per_cluster = bs->cluster_sz / SPDK_BS_PAGE_SIZE;
2520 	bs->num_free_clusters = bs->total_clusters;
2521 	bs->used_clusters = spdk_bit_array_create(bs->total_clusters);
2522 	bs->io_unit_size = dev->blocklen;
2523 	if (bs->used_clusters == NULL) {
2524 		free(bs);
2525 		return -ENOMEM;
2526 	}
2527 
2528 	bs->max_channel_ops = opts->max_channel_ops;
2529 	bs->super_blob = SPDK_BLOBID_INVALID;
2530 	memcpy(&bs->bstype, &opts->bstype, sizeof(opts->bstype));
2531 
2532 	/* The metadata is assumed to be at least 1 page */
2533 	bs->used_md_pages = spdk_bit_array_create(1);
2534 	bs->used_blobids = spdk_bit_array_create(0);
2535 
2536 	pthread_mutex_init(&bs->used_clusters_mutex, NULL);
2537 
2538 	spdk_io_device_register(bs, _spdk_bs_channel_create, _spdk_bs_channel_destroy,
2539 				sizeof(struct spdk_bs_channel), "blobstore");
2540 	rc = spdk_bs_register_md_thread(bs);
2541 	if (rc == -1) {
2542 		spdk_io_device_unregister(bs, NULL);
2543 		pthread_mutex_destroy(&bs->used_clusters_mutex);
2544 		spdk_bit_array_free(&bs->used_blobids);
2545 		spdk_bit_array_free(&bs->used_md_pages);
2546 		spdk_bit_array_free(&bs->used_clusters);
2547 		free(bs);
2548 		/* FIXME: this is a lie but don't know how to get a proper error code here */
2549 		return -ENOMEM;
2550 	}
2551 
2552 	*_bs = bs;
2553 	return 0;
2554 }
2555 
2556 /* START spdk_bs_load, spdk_bs_load_ctx will used for both load and unload. */
2557 
2558 struct spdk_bs_load_ctx {
2559 	struct spdk_blob_store		*bs;
2560 	struct spdk_bs_super_block	*super;
2561 
2562 	struct spdk_bs_md_mask		*mask;
2563 	bool				in_page_chain;
2564 	uint32_t			page_index;
2565 	uint32_t			cur_page;
2566 	struct spdk_blob_md_page	*page;
2567 
2568 	spdk_bs_sequence_t			*seq;
2569 	spdk_blob_op_with_handle_complete	iter_cb_fn;
2570 	void					*iter_cb_arg;
2571 	struct spdk_blob			*blob;
2572 	spdk_blob_id				blobid;
2573 };
2574 
2575 static void
2576 _spdk_bs_load_ctx_fail(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2577 {
2578 	assert(bserrno != 0);
2579 
2580 	spdk_free(ctx->super);
2581 	spdk_bs_sequence_finish(seq, bserrno);
2582 	_spdk_bs_free(ctx->bs);
2583 	free(ctx);
2584 }
2585 
2586 static void
2587 _spdk_bs_set_mask(struct spdk_bit_array *array, struct spdk_bs_md_mask *mask)
2588 {
2589 	uint32_t i = 0;
2590 
2591 	while (true) {
2592 		i = spdk_bit_array_find_first_set(array, i);
2593 		if (i >= mask->length) {
2594 			break;
2595 		}
2596 		mask->mask[i / 8] |= 1U << (i % 8);
2597 		i++;
2598 	}
2599 }
2600 
2601 static int
2602 _spdk_bs_load_mask(struct spdk_bit_array **array_ptr, struct spdk_bs_md_mask *mask)
2603 {
2604 	struct spdk_bit_array *array;
2605 	uint32_t i;
2606 
2607 	if (spdk_bit_array_resize(array_ptr, mask->length) < 0) {
2608 		return -ENOMEM;
2609 	}
2610 
2611 	array = *array_ptr;
2612 	for (i = 0; i < mask->length; i++) {
2613 		if (mask->mask[i / 8] & (1U << (i % 8))) {
2614 			spdk_bit_array_set(array, i);
2615 		}
2616 	}
2617 
2618 	return 0;
2619 }
2620 
2621 static void
2622 _spdk_bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2623 		     struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2624 {
2625 	/* Update the values in the super block */
2626 	super->super_blob = bs->super_blob;
2627 	memcpy(&super->bstype, &bs->bstype, sizeof(bs->bstype));
2628 	super->crc = _spdk_blob_md_page_calc_crc(super);
2629 	spdk_bs_sequence_write_dev(seq, super, _spdk_bs_page_to_lba(bs, 0),
2630 				   _spdk_bs_byte_to_lba(bs, sizeof(*super)),
2631 				   cb_fn, cb_arg);
2632 }
2633 
2634 static void
2635 _spdk_bs_write_used_clusters(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2636 {
2637 	struct spdk_bs_load_ctx	*ctx = arg;
2638 	uint64_t	mask_size, lba, lba_count;
2639 
2640 	/* Write out the used clusters mask */
2641 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2642 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
2643 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2644 	if (!ctx->mask) {
2645 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2646 		return;
2647 	}
2648 
2649 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_CLUSTERS;
2650 	ctx->mask->length = ctx->bs->total_clusters;
2651 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_clusters));
2652 
2653 	_spdk_bs_set_mask(ctx->bs->used_clusters, ctx->mask);
2654 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
2655 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
2656 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2657 }
2658 
2659 static void
2660 _spdk_bs_write_used_md(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2661 {
2662 	struct spdk_bs_load_ctx	*ctx = arg;
2663 	uint64_t	mask_size, lba, lba_count;
2664 
2665 	if (seq->bserrno) {
2666 		_spdk_bs_load_ctx_fail(seq, ctx, seq->bserrno);
2667 		return;
2668 	}
2669 
2670 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
2671 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
2672 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2673 	if (!ctx->mask) {
2674 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2675 		return;
2676 	}
2677 
2678 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_PAGES;
2679 	ctx->mask->length = ctx->super->md_len;
2680 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_md_pages));
2681 
2682 	_spdk_bs_set_mask(ctx->bs->used_md_pages, ctx->mask);
2683 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
2684 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
2685 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2686 }
2687 
2688 static void
2689 _spdk_bs_write_used_blobids(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2690 {
2691 	struct spdk_bs_load_ctx	*ctx = arg;
2692 	uint64_t	mask_size, lba, lba_count;
2693 
2694 	if (ctx->super->used_blobid_mask_len == 0) {
2695 		/*
2696 		 * This is a pre-v3 on-disk format where the blobid mask does not get
2697 		 *  written to disk.
2698 		 */
2699 		cb_fn(seq, arg, 0);
2700 		return;
2701 	}
2702 
2703 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2704 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2705 				 SPDK_MALLOC_DMA);
2706 	if (!ctx->mask) {
2707 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2708 		return;
2709 	}
2710 
2711 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_BLOBIDS;
2712 	ctx->mask->length = ctx->super->md_len;
2713 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_blobids));
2714 
2715 	_spdk_bs_set_mask(ctx->bs->used_blobids, ctx->mask);
2716 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2717 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2718 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2719 }
2720 
2721 static void
2722 _spdk_blob_set_thin_provision(struct spdk_blob *blob)
2723 {
2724 	_spdk_blob_verify_md_op(blob);
2725 	blob->invalid_flags |= SPDK_BLOB_THIN_PROV;
2726 	blob->state = SPDK_BLOB_STATE_DIRTY;
2727 }
2728 
2729 static void _spdk_bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno);
2730 
2731 static void
2732 _spdk_bs_delete_corrupted_blob_cpl(void *cb_arg, int bserrno)
2733 {
2734 	struct spdk_bs_load_ctx *ctx = cb_arg;
2735 	spdk_blob_id id;
2736 	int64_t page_num;
2737 
2738 	/* Iterate to next blob (we can't use spdk_bs_iter_next function as our
2739 	 * last blob has been removed */
2740 	page_num = _spdk_bs_blobid_to_page(ctx->blobid);
2741 	page_num++;
2742 	page_num = spdk_bit_array_find_first_set(ctx->bs->used_blobids, page_num);
2743 	if (page_num >= spdk_bit_array_capacity(ctx->bs->used_blobids)) {
2744 		_spdk_bs_load_iter(ctx, NULL, -ENOENT);
2745 		return;
2746 	}
2747 
2748 	id = _spdk_bs_page_to_blobid(page_num);
2749 
2750 	spdk_bs_open_blob(ctx->bs, id, _spdk_bs_load_iter, ctx);
2751 }
2752 
2753 static void
2754 _spdk_bs_delete_corrupted_close_cb(void *cb_arg, int bserrno)
2755 {
2756 	struct spdk_bs_load_ctx *ctx = cb_arg;
2757 
2758 	if (bserrno != 0) {
2759 		SPDK_ERRLOG("Failed to close corrupted blob\n");
2760 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2761 		return;
2762 	}
2763 
2764 	spdk_bs_delete_blob(ctx->bs, ctx->blobid, _spdk_bs_delete_corrupted_blob_cpl, ctx);
2765 }
2766 
2767 static void
2768 _spdk_bs_delete_corrupted_blob(void *cb_arg, int bserrno)
2769 {
2770 	struct spdk_bs_load_ctx *ctx = cb_arg;
2771 	uint64_t i;
2772 
2773 	if (bserrno != 0) {
2774 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
2775 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2776 		return;
2777 	}
2778 
2779 	/* Snapshot and clone have the same copy of cluster map at this point.
2780 	 * Let's clear cluster map for snpashot now so that it won't be cleared
2781 	 * for clone later when we remove snapshot. Also set thin provision to
2782 	 * pass data corruption check */
2783 	for (i = 0; i < ctx->blob->active.num_clusters; i++) {
2784 		ctx->blob->active.clusters[i] = 0;
2785 	}
2786 
2787 	ctx->blob->md_ro = false;
2788 
2789 	_spdk_blob_set_thin_provision(ctx->blob);
2790 
2791 	ctx->blobid = ctx->blob->id;
2792 
2793 	spdk_blob_close(ctx->blob, _spdk_bs_delete_corrupted_close_cb, ctx);
2794 }
2795 
2796 static void
2797 _spdk_bs_update_corrupted_blob(void *cb_arg, int bserrno)
2798 {
2799 	struct spdk_bs_load_ctx *ctx = cb_arg;
2800 
2801 	if (bserrno != 0) {
2802 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
2803 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2804 		return;
2805 	}
2806 
2807 	ctx->blob->md_ro = false;
2808 	_spdk_blob_remove_xattr(ctx->blob, SNAPSHOT_PENDING_REMOVAL, true);
2809 	_spdk_blob_remove_xattr(ctx->blob, SNAPSHOT_IN_PROGRESS, true);
2810 	spdk_blob_set_read_only(ctx->blob);
2811 
2812 	if (ctx->iter_cb_fn) {
2813 		ctx->iter_cb_fn(ctx->iter_cb_arg, ctx->blob, 0);
2814 	}
2815 	_spdk_bs_blob_list_add(ctx->blob);
2816 
2817 	spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2818 }
2819 
2820 static void
2821 _spdk_bs_examine_clone(void *cb_arg, struct spdk_blob *blob, int bserrno)
2822 {
2823 	struct spdk_bs_load_ctx *ctx = cb_arg;
2824 
2825 	if (bserrno != 0) {
2826 		SPDK_ERRLOG("Failed to open clone of a corrupted blob\n");
2827 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2828 		return;
2829 	}
2830 
2831 	if (blob->parent_id == ctx->blob->id) {
2832 		/* Power failure occured before updating clone (snapshot delete case)
2833 		 * or after updating clone (creating snapshot case) - keep snapshot */
2834 		spdk_blob_close(blob, _spdk_bs_update_corrupted_blob, ctx);
2835 	} else {
2836 		/* Power failure occured after updating clone (snapshot delete case)
2837 		 * or before updating clone (creating snapshot case) - remove snapshot */
2838 		spdk_blob_close(blob, _spdk_bs_delete_corrupted_blob, ctx);
2839 	}
2840 }
2841 
2842 static void
2843 _spdk_bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno)
2844 {
2845 	struct spdk_bs_load_ctx *ctx = arg;
2846 	const void *value;
2847 	size_t len;
2848 	int rc = 0;
2849 
2850 	if (bserrno == 0) {
2851 		/* Examine blob if it is corrupted after power failure. Fix
2852 		 * the ones that can be fixed and remove any other corrupted
2853 		 * ones. If it is not corrupted just process it */
2854 		rc = _spdk_blob_get_xattr_value(blob, SNAPSHOT_PENDING_REMOVAL, &value, &len, true);
2855 		if (rc != 0) {
2856 			rc = _spdk_blob_get_xattr_value(blob, SNAPSHOT_IN_PROGRESS, &value, &len, true);
2857 			if (rc != 0) {
2858 				/* Not corrupted - process it and continue with iterating through blobs */
2859 				if (ctx->iter_cb_fn) {
2860 					ctx->iter_cb_fn(ctx->iter_cb_arg, blob, 0);
2861 				}
2862 				_spdk_bs_blob_list_add(blob);
2863 				spdk_bs_iter_next(ctx->bs, blob, _spdk_bs_load_iter, ctx);
2864 				return;
2865 			}
2866 
2867 		}
2868 
2869 		assert(len == sizeof(spdk_blob_id));
2870 
2871 		ctx->blob = blob;
2872 
2873 		/* Open clone to check if we are able to fix this blob or should we remove it */
2874 		spdk_bs_open_blob(ctx->bs, *(spdk_blob_id *)value, _spdk_bs_examine_clone, ctx);
2875 		return;
2876 	} else if (bserrno == -ENOENT) {
2877 		bserrno = 0;
2878 	} else {
2879 		/*
2880 		 * This case needs to be looked at further.  Same problem
2881 		 *  exists with applications that rely on explicit blob
2882 		 *  iteration.  We should just skip the blob that failed
2883 		 *  to load and continue on to the next one.
2884 		 */
2885 		SPDK_ERRLOG("Error in iterating blobs\n");
2886 	}
2887 
2888 	ctx->iter_cb_fn = NULL;
2889 
2890 	spdk_free(ctx->super);
2891 	spdk_free(ctx->mask);
2892 	spdk_bs_sequence_finish(ctx->seq, bserrno);
2893 	free(ctx);
2894 }
2895 
2896 static void
2897 _spdk_bs_load_complete(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2898 {
2899 	ctx->seq = seq;
2900 	spdk_bs_iter_first(ctx->bs, _spdk_bs_load_iter, ctx);
2901 }
2902 
2903 static void
2904 _spdk_bs_load_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2905 {
2906 	struct spdk_bs_load_ctx *ctx = cb_arg;
2907 	int rc;
2908 
2909 	/* The type must be correct */
2910 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_BLOBIDS);
2911 
2912 	/* The length of the mask (in bits) must not be greater than
2913 	 * the length of the buffer (converted to bits) */
2914 	assert(ctx->mask->length <= (ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE * 8));
2915 
2916 	/* The length of the mask must be exactly equal to the size
2917 	 * (in pages) of the metadata region */
2918 	assert(ctx->mask->length == ctx->super->md_len);
2919 
2920 	rc = _spdk_bs_load_mask(&ctx->bs->used_blobids, ctx->mask);
2921 	if (rc < 0) {
2922 		spdk_free(ctx->mask);
2923 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2924 		return;
2925 	}
2926 
2927 	_spdk_bs_load_complete(seq, ctx, bserrno);
2928 }
2929 
2930 static void
2931 _spdk_bs_load_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2932 {
2933 	struct spdk_bs_load_ctx *ctx = cb_arg;
2934 	uint64_t		lba, lba_count, mask_size;
2935 	int			rc;
2936 
2937 	/* The type must be correct */
2938 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
2939 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2940 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
2941 					     struct spdk_blob_md_page) * 8));
2942 	/* The length of the mask must be exactly equal to the total number of clusters */
2943 	assert(ctx->mask->length == ctx->bs->total_clusters);
2944 
2945 	rc = _spdk_bs_load_mask(&ctx->bs->used_clusters, ctx->mask);
2946 	if (rc < 0) {
2947 		spdk_free(ctx->mask);
2948 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2949 		return;
2950 	}
2951 
2952 	ctx->bs->num_free_clusters = spdk_bit_array_count_clear(ctx->bs->used_clusters);
2953 	assert(ctx->bs->num_free_clusters <= ctx->bs->total_clusters);
2954 
2955 	spdk_free(ctx->mask);
2956 
2957 	/* Read the used blobids mask */
2958 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2959 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2960 				 SPDK_MALLOC_DMA);
2961 	if (!ctx->mask) {
2962 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2963 		return;
2964 	}
2965 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2966 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2967 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2968 				  _spdk_bs_load_used_blobids_cpl, ctx);
2969 }
2970 
2971 static void
2972 _spdk_bs_load_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2973 {
2974 	struct spdk_bs_load_ctx *ctx = cb_arg;
2975 	uint64_t		lba, lba_count, mask_size;
2976 	int			rc;
2977 
2978 	/* The type must be correct */
2979 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_PAGES);
2980 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2981 	assert(ctx->mask->length <= (ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE *
2982 				     8));
2983 	/* The length of the mask must be exactly equal to the size (in pages) of the metadata region */
2984 	assert(ctx->mask->length == ctx->super->md_len);
2985 
2986 	rc = _spdk_bs_load_mask(&ctx->bs->used_md_pages, ctx->mask);
2987 	if (rc < 0) {
2988 		spdk_free(ctx->mask);
2989 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2990 		return;
2991 	}
2992 
2993 	spdk_free(ctx->mask);
2994 
2995 	/* Read the used clusters mask */
2996 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2997 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2998 				 SPDK_MALLOC_DMA);
2999 	if (!ctx->mask) {
3000 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3001 		return;
3002 	}
3003 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
3004 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
3005 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
3006 				  _spdk_bs_load_used_clusters_cpl, ctx);
3007 }
3008 
3009 static void
3010 _spdk_bs_load_read_used_pages(spdk_bs_sequence_t *seq, void *cb_arg)
3011 {
3012 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3013 	uint64_t lba, lba_count, mask_size;
3014 
3015 	/* Read the used pages mask */
3016 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
3017 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3018 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3019 	if (!ctx->mask) {
3020 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3021 		return;
3022 	}
3023 
3024 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
3025 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
3026 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
3027 				  _spdk_bs_load_used_pages_cpl, ctx);
3028 }
3029 
3030 static int
3031 _spdk_bs_load_replay_md_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob_store *bs)
3032 {
3033 	struct spdk_blob_md_descriptor *desc;
3034 	size_t	cur_desc = 0;
3035 
3036 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3037 	while (cur_desc < sizeof(page->descriptors)) {
3038 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
3039 			if (desc->length == 0) {
3040 				/* If padding and length are 0, this terminates the page */
3041 				break;
3042 			}
3043 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
3044 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
3045 			unsigned int				i, j;
3046 			unsigned int				cluster_count = 0;
3047 			uint32_t				cluster_idx;
3048 
3049 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
3050 
3051 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
3052 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
3053 					cluster_idx = desc_extent_rle->extents[i].cluster_idx;
3054 					/*
3055 					 * cluster_idx = 0 means an unallocated cluster - don't mark that
3056 					 * in the used cluster map.
3057 					 */
3058 					if (cluster_idx != 0) {
3059 						spdk_bit_array_set(bs->used_clusters, cluster_idx + j);
3060 						if (bs->num_free_clusters == 0) {
3061 							return -ENOSPC;
3062 						}
3063 						bs->num_free_clusters--;
3064 					}
3065 					cluster_count++;
3066 				}
3067 			}
3068 			if (cluster_count == 0) {
3069 				return -EINVAL;
3070 			}
3071 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
3072 			/* Skip this item */
3073 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
3074 			/* Skip this item */
3075 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
3076 			/* Skip this item */
3077 		} else {
3078 			/* Error */
3079 			return -EINVAL;
3080 		}
3081 		/* Advance to the next descriptor */
3082 		cur_desc += sizeof(*desc) + desc->length;
3083 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
3084 			break;
3085 		}
3086 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
3087 	}
3088 	return 0;
3089 }
3090 
3091 static bool _spdk_bs_load_cur_md_page_valid(struct spdk_bs_load_ctx *ctx)
3092 {
3093 	uint32_t crc;
3094 
3095 	crc = _spdk_blob_md_page_calc_crc(ctx->page);
3096 	if (crc != ctx->page->crc) {
3097 		return false;
3098 	}
3099 
3100 	if (ctx->page->sequence_num == 0 &&
3101 	    _spdk_bs_page_to_blobid(ctx->cur_page) != ctx->page->id) {
3102 		return false;
3103 	}
3104 	return true;
3105 }
3106 
3107 static void
3108 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
3109 
3110 static void
3111 _spdk_bs_load_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3112 {
3113 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3114 
3115 	_spdk_bs_load_complete(seq, ctx, bserrno);
3116 }
3117 
3118 static void
3119 _spdk_bs_load_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3120 {
3121 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3122 
3123 	spdk_free(ctx->mask);
3124 	ctx->mask = NULL;
3125 
3126 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_load_write_used_clusters_cpl);
3127 }
3128 
3129 static void
3130 _spdk_bs_load_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3131 {
3132 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3133 
3134 	spdk_free(ctx->mask);
3135 	ctx->mask = NULL;
3136 
3137 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_load_write_used_blobids_cpl);
3138 }
3139 
3140 static void
3141 _spdk_bs_load_write_used_md(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3142 {
3143 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_load_write_used_pages_cpl);
3144 }
3145 
3146 static void
3147 _spdk_bs_load_replay_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3148 {
3149 	struct spdk_bs_load_ctx *ctx = cb_arg;
3150 	uint64_t num_md_clusters;
3151 	uint64_t i;
3152 	uint32_t page_num;
3153 
3154 	if (bserrno != 0) {
3155 		_spdk_bs_load_ctx_fail(seq, ctx, bserrno);
3156 		return;
3157 	}
3158 
3159 	page_num = ctx->cur_page;
3160 	if (_spdk_bs_load_cur_md_page_valid(ctx) == true) {
3161 		if (ctx->page->sequence_num == 0 || ctx->in_page_chain == true) {
3162 			spdk_bit_array_set(ctx->bs->used_md_pages, page_num);
3163 			if (ctx->page->sequence_num == 0) {
3164 				spdk_bit_array_set(ctx->bs->used_blobids, page_num);
3165 			}
3166 			if (_spdk_bs_load_replay_md_parse_page(ctx->page, ctx->bs)) {
3167 				_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3168 				return;
3169 			}
3170 			if (ctx->page->next != SPDK_INVALID_MD_PAGE) {
3171 				ctx->in_page_chain = true;
3172 				ctx->cur_page = ctx->page->next;
3173 				_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3174 				return;
3175 			}
3176 		}
3177 	}
3178 
3179 	ctx->in_page_chain = false;
3180 
3181 	do {
3182 		ctx->page_index++;
3183 	} while (spdk_bit_array_get(ctx->bs->used_md_pages, ctx->page_index) == true);
3184 
3185 	if (ctx->page_index < ctx->super->md_len) {
3186 		ctx->cur_page = ctx->page_index;
3187 		_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3188 	} else {
3189 		/* Claim all of the clusters used by the metadata */
3190 		num_md_clusters = spdk_divide_round_up(ctx->super->md_len, ctx->bs->pages_per_cluster);
3191 		for (i = 0; i < num_md_clusters; i++) {
3192 			_spdk_bs_claim_cluster(ctx->bs, i);
3193 		}
3194 		spdk_free(ctx->page);
3195 		_spdk_bs_load_write_used_md(seq, ctx, bserrno);
3196 	}
3197 }
3198 
3199 static void
3200 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
3201 {
3202 	struct spdk_bs_load_ctx *ctx = cb_arg;
3203 	uint64_t lba;
3204 
3205 	assert(ctx->cur_page < ctx->super->md_len);
3206 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
3207 	spdk_bs_sequence_read_dev(seq, ctx->page, lba,
3208 				  _spdk_bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
3209 				  _spdk_bs_load_replay_md_cpl, ctx);
3210 }
3211 
3212 static void
3213 _spdk_bs_load_replay_md(spdk_bs_sequence_t *seq, void *cb_arg)
3214 {
3215 	struct spdk_bs_load_ctx *ctx = cb_arg;
3216 
3217 	ctx->page_index = 0;
3218 	ctx->cur_page = 0;
3219 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
3220 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3221 	if (!ctx->page) {
3222 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3223 		return;
3224 	}
3225 	_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3226 }
3227 
3228 static void
3229 _spdk_bs_recover(spdk_bs_sequence_t *seq, void *cb_arg)
3230 {
3231 	struct spdk_bs_load_ctx *ctx = cb_arg;
3232 	int		rc;
3233 
3234 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->super->md_len);
3235 	if (rc < 0) {
3236 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3237 		return;
3238 	}
3239 
3240 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->super->md_len);
3241 	if (rc < 0) {
3242 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3243 		return;
3244 	}
3245 
3246 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
3247 	if (rc < 0) {
3248 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3249 		return;
3250 	}
3251 
3252 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
3253 	_spdk_bs_load_replay_md(seq, cb_arg);
3254 }
3255 
3256 static void
3257 _spdk_bs_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3258 {
3259 	struct spdk_bs_load_ctx *ctx = cb_arg;
3260 	uint32_t	crc;
3261 	int		rc;
3262 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
3263 
3264 	if (ctx->super->version > SPDK_BS_VERSION ||
3265 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
3266 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3267 		return;
3268 	}
3269 
3270 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3271 		   sizeof(ctx->super->signature)) != 0) {
3272 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3273 		return;
3274 	}
3275 
3276 	crc = _spdk_blob_md_page_calc_crc(ctx->super);
3277 	if (crc != ctx->super->crc) {
3278 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3279 		return;
3280 	}
3281 
3282 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
3283 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype matched - loading blobstore\n");
3284 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
3285 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype wildcard used - loading blobstore regardless bstype\n");
3286 	} else {
3287 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Unexpected bstype\n");
3288 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
3289 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
3290 		_spdk_bs_load_ctx_fail(seq, ctx, -ENXIO);
3291 		return;
3292 	}
3293 
3294 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
3295 		SPDK_NOTICELOG("Size mismatch, dev size: %lu, blobstore size: %lu\n",
3296 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
3297 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3298 		return;
3299 	}
3300 
3301 	if (ctx->super->size == 0) {
3302 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
3303 	}
3304 
3305 	if (ctx->super->io_unit_size == 0) {
3306 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
3307 	}
3308 
3309 	/* Parse the super block */
3310 	ctx->bs->clean = 1;
3311 	ctx->bs->cluster_sz = ctx->super->cluster_size;
3312 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
3313 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
3314 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
3315 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
3316 	if (rc < 0) {
3317 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3318 		return;
3319 	}
3320 	ctx->bs->md_start = ctx->super->md_start;
3321 	ctx->bs->md_len = ctx->super->md_len;
3322 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
3323 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
3324 	ctx->bs->super_blob = ctx->super->super_blob;
3325 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
3326 
3327 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0) {
3328 		_spdk_bs_recover(seq, ctx);
3329 	} else {
3330 		_spdk_bs_load_read_used_pages(seq, ctx);
3331 	}
3332 }
3333 
3334 void
3335 spdk_bs_load(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
3336 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
3337 {
3338 	struct spdk_blob_store	*bs;
3339 	struct spdk_bs_cpl	cpl;
3340 	spdk_bs_sequence_t	*seq;
3341 	struct spdk_bs_load_ctx *ctx;
3342 	struct spdk_bs_opts	opts = {};
3343 	int err;
3344 
3345 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Loading blobstore from dev %p\n", dev);
3346 
3347 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
3348 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "unsupported dev block length of %d\n", dev->blocklen);
3349 		dev->destroy(dev);
3350 		cb_fn(cb_arg, NULL, -EINVAL);
3351 		return;
3352 	}
3353 
3354 	if (o) {
3355 		opts = *o;
3356 	} else {
3357 		spdk_bs_opts_init(&opts);
3358 	}
3359 
3360 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
3361 		dev->destroy(dev);
3362 		cb_fn(cb_arg, NULL, -EINVAL);
3363 		return;
3364 	}
3365 
3366 	err = _spdk_bs_alloc(dev, &opts, &bs);
3367 	if (err) {
3368 		dev->destroy(dev);
3369 		cb_fn(cb_arg, NULL, err);
3370 		return;
3371 	}
3372 
3373 	ctx = calloc(1, sizeof(*ctx));
3374 	if (!ctx) {
3375 		_spdk_bs_free(bs);
3376 		cb_fn(cb_arg, NULL, -ENOMEM);
3377 		return;
3378 	}
3379 
3380 	ctx->bs = bs;
3381 	ctx->iter_cb_fn = opts.iter_cb_fn;
3382 	ctx->iter_cb_arg = opts.iter_cb_arg;
3383 
3384 	/* Allocate memory for the super block */
3385 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3386 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3387 	if (!ctx->super) {
3388 		free(ctx);
3389 		_spdk_bs_free(bs);
3390 		cb_fn(cb_arg, NULL, -ENOMEM);
3391 		return;
3392 	}
3393 
3394 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
3395 	cpl.u.bs_handle.cb_fn = cb_fn;
3396 	cpl.u.bs_handle.cb_arg = cb_arg;
3397 	cpl.u.bs_handle.bs = bs;
3398 
3399 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3400 	if (!seq) {
3401 		spdk_free(ctx->super);
3402 		free(ctx);
3403 		_spdk_bs_free(bs);
3404 		cb_fn(cb_arg, NULL, -ENOMEM);
3405 		return;
3406 	}
3407 
3408 	/* Read the super block */
3409 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
3410 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
3411 				  _spdk_bs_load_super_cpl, ctx);
3412 }
3413 
3414 /* END spdk_bs_load */
3415 
3416 /* START spdk_bs_dump */
3417 
3418 struct spdk_bs_dump_ctx {
3419 	struct spdk_blob_store		*bs;
3420 	struct spdk_bs_super_block	*super;
3421 	uint32_t			cur_page;
3422 	struct spdk_blob_md_page	*page;
3423 	spdk_bs_sequence_t		*seq;
3424 	FILE				*fp;
3425 	spdk_bs_dump_print_xattr	print_xattr_fn;
3426 	char				xattr_name[4096];
3427 };
3428 
3429 static void
3430 _spdk_bs_dump_finish(spdk_bs_sequence_t *seq, struct spdk_bs_dump_ctx *ctx, int bserrno)
3431 {
3432 	spdk_free(ctx->super);
3433 
3434 	/*
3435 	 * We need to defer calling spdk_bs_call_cpl() until after
3436 	 * dev destruction, so tuck these away for later use.
3437 	 */
3438 	ctx->bs->unload_err = bserrno;
3439 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3440 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3441 
3442 	spdk_bs_sequence_finish(seq, 0);
3443 	_spdk_bs_free(ctx->bs);
3444 	free(ctx);
3445 }
3446 
3447 static void _spdk_bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
3448 
3449 static void
3450 _spdk_bs_dump_print_md_page(struct spdk_bs_dump_ctx *ctx)
3451 {
3452 	uint32_t page_idx = ctx->cur_page;
3453 	struct spdk_blob_md_page *page = ctx->page;
3454 	struct spdk_blob_md_descriptor *desc;
3455 	size_t cur_desc = 0;
3456 	uint32_t crc;
3457 
3458 	fprintf(ctx->fp, "=========\n");
3459 	fprintf(ctx->fp, "Metadata Page Index: %" PRIu32 " (0x%" PRIx32 ")\n", page_idx, page_idx);
3460 	fprintf(ctx->fp, "Blob ID: 0x%" PRIx64 "\n", page->id);
3461 
3462 	crc = _spdk_blob_md_page_calc_crc(page);
3463 	fprintf(ctx->fp, "CRC: 0x%" PRIx32 " (%s)\n", page->crc, crc == page->crc ? "OK" : "Mismatch");
3464 
3465 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3466 	while (cur_desc < sizeof(page->descriptors)) {
3467 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
3468 			if (desc->length == 0) {
3469 				/* If padding and length are 0, this terminates the page */
3470 				break;
3471 			}
3472 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
3473 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
3474 			unsigned int				i;
3475 
3476 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
3477 
3478 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
3479 				if (desc_extent_rle->extents[i].cluster_idx != 0) {
3480 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
3481 						desc_extent_rle->extents[i].cluster_idx);
3482 				} else {
3483 					fprintf(ctx->fp, "Unallocated Extent - ");
3484 				}
3485 				fprintf(ctx->fp, " Length: %" PRIu32, desc_extent_rle->extents[i].length);
3486 				fprintf(ctx->fp, "\n");
3487 			}
3488 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
3489 			struct spdk_blob_md_descriptor_xattr *desc_xattr;
3490 			uint32_t i;
3491 
3492 			desc_xattr = (struct spdk_blob_md_descriptor_xattr *)desc;
3493 
3494 			if (desc_xattr->length !=
3495 			    sizeof(desc_xattr->name_length) + sizeof(desc_xattr->value_length) +
3496 			    desc_xattr->name_length + desc_xattr->value_length) {
3497 			}
3498 
3499 			memcpy(ctx->xattr_name, desc_xattr->name, desc_xattr->name_length);
3500 			ctx->xattr_name[desc_xattr->name_length] = '\0';
3501 			fprintf(ctx->fp, "XATTR: name = \"%s\"\n", ctx->xattr_name);
3502 			fprintf(ctx->fp, "       value = \"");
3503 			ctx->print_xattr_fn(ctx->fp, ctx->super->bstype.bstype, ctx->xattr_name,
3504 					    (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
3505 					    desc_xattr->value_length);
3506 			fprintf(ctx->fp, "\"\n");
3507 			for (i = 0; i < desc_xattr->value_length; i++) {
3508 				if (i % 16 == 0) {
3509 					fprintf(ctx->fp, "               ");
3510 				}
3511 				fprintf(ctx->fp, "%02" PRIx8 " ", *((uint8_t *)desc_xattr->name + desc_xattr->name_length + i));
3512 				if ((i + 1) % 16 == 0) {
3513 					fprintf(ctx->fp, "\n");
3514 				}
3515 			}
3516 			if (i % 16 != 0) {
3517 				fprintf(ctx->fp, "\n");
3518 			}
3519 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
3520 			/* TODO */
3521 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
3522 			/* TODO */
3523 		} else {
3524 			/* Error */
3525 		}
3526 		/* Advance to the next descriptor */
3527 		cur_desc += sizeof(*desc) + desc->length;
3528 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
3529 			break;
3530 		}
3531 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
3532 	}
3533 }
3534 
3535 static void
3536 _spdk_bs_dump_read_md_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3537 {
3538 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3539 
3540 	if (bserrno != 0) {
3541 		_spdk_bs_dump_finish(seq, ctx, bserrno);
3542 		return;
3543 	}
3544 
3545 	if (ctx->page->id != 0) {
3546 		_spdk_bs_dump_print_md_page(ctx);
3547 	}
3548 
3549 	ctx->cur_page++;
3550 
3551 	if (ctx->cur_page < ctx->super->md_len) {
3552 		_spdk_bs_dump_read_md_page(seq, cb_arg);
3553 	} else {
3554 		spdk_free(ctx->page);
3555 		_spdk_bs_dump_finish(seq, ctx, 0);
3556 	}
3557 }
3558 
3559 static void
3560 _spdk_bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
3561 {
3562 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3563 	uint64_t lba;
3564 
3565 	assert(ctx->cur_page < ctx->super->md_len);
3566 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
3567 	spdk_bs_sequence_read_dev(seq, ctx->page, lba,
3568 				  _spdk_bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
3569 				  _spdk_bs_dump_read_md_page_cpl, ctx);
3570 }
3571 
3572 static void
3573 _spdk_bs_dump_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3574 {
3575 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3576 
3577 	fprintf(ctx->fp, "Signature: \"%.8s\" ", ctx->super->signature);
3578 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3579 		   sizeof(ctx->super->signature)) != 0) {
3580 		fprintf(ctx->fp, "(Mismatch)\n");
3581 		_spdk_bs_dump_finish(seq, ctx, bserrno);
3582 		return;
3583 	} else {
3584 		fprintf(ctx->fp, "(OK)\n");
3585 	}
3586 	fprintf(ctx->fp, "Version: %" PRIu32 "\n", ctx->super->version);
3587 	fprintf(ctx->fp, "CRC: 0x%x (%s)\n", ctx->super->crc,
3588 		(ctx->super->crc == _spdk_blob_md_page_calc_crc(ctx->super)) ? "OK" : "Mismatch");
3589 	fprintf(ctx->fp, "Blobstore Type: %.*s\n", SPDK_BLOBSTORE_TYPE_LENGTH, ctx->super->bstype.bstype);
3590 	fprintf(ctx->fp, "Cluster Size: %" PRIu32 "\n", ctx->super->cluster_size);
3591 	fprintf(ctx->fp, "Super Blob ID: ");
3592 	if (ctx->super->super_blob == SPDK_BLOBID_INVALID) {
3593 		fprintf(ctx->fp, "(None)\n");
3594 	} else {
3595 		fprintf(ctx->fp, "%" PRIu64 "\n", ctx->super->super_blob);
3596 	}
3597 	fprintf(ctx->fp, "Clean: %" PRIu32 "\n", ctx->super->clean);
3598 	fprintf(ctx->fp, "Used Metadata Page Mask Start: %" PRIu32 "\n", ctx->super->used_page_mask_start);
3599 	fprintf(ctx->fp, "Used Metadata Page Mask Length: %" PRIu32 "\n", ctx->super->used_page_mask_len);
3600 	fprintf(ctx->fp, "Used Cluster Mask Start: %" PRIu32 "\n", ctx->super->used_cluster_mask_start);
3601 	fprintf(ctx->fp, "Used Cluster Mask Length: %" PRIu32 "\n", ctx->super->used_cluster_mask_len);
3602 	fprintf(ctx->fp, "Used Blob ID Mask Start: %" PRIu32 "\n", ctx->super->used_blobid_mask_start);
3603 	fprintf(ctx->fp, "Used Blob ID Mask Length: %" PRIu32 "\n", ctx->super->used_blobid_mask_len);
3604 	fprintf(ctx->fp, "Metadata Start: %" PRIu32 "\n", ctx->super->md_start);
3605 	fprintf(ctx->fp, "Metadata Length: %" PRIu32 "\n", ctx->super->md_len);
3606 
3607 	ctx->cur_page = 0;
3608 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
3609 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3610 	if (!ctx->page) {
3611 		_spdk_bs_dump_finish(seq, ctx, -ENOMEM);
3612 		return;
3613 	}
3614 	_spdk_bs_dump_read_md_page(seq, cb_arg);
3615 }
3616 
3617 void
3618 spdk_bs_dump(struct spdk_bs_dev *dev, FILE *fp, spdk_bs_dump_print_xattr print_xattr_fn,
3619 	     spdk_bs_op_complete cb_fn, void *cb_arg)
3620 {
3621 	struct spdk_blob_store	*bs;
3622 	struct spdk_bs_cpl	cpl;
3623 	spdk_bs_sequence_t	*seq;
3624 	struct spdk_bs_dump_ctx *ctx;
3625 	struct spdk_bs_opts	opts = {};
3626 	int err;
3627 
3628 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Dumping blobstore from dev %p\n", dev);
3629 
3630 	spdk_bs_opts_init(&opts);
3631 
3632 	err = _spdk_bs_alloc(dev, &opts, &bs);
3633 	if (err) {
3634 		dev->destroy(dev);
3635 		cb_fn(cb_arg, err);
3636 		return;
3637 	}
3638 
3639 	ctx = calloc(1, sizeof(*ctx));
3640 	if (!ctx) {
3641 		_spdk_bs_free(bs);
3642 		cb_fn(cb_arg, -ENOMEM);
3643 		return;
3644 	}
3645 
3646 	ctx->bs = bs;
3647 	ctx->fp = fp;
3648 	ctx->print_xattr_fn = print_xattr_fn;
3649 
3650 	/* Allocate memory for the super block */
3651 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3652 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3653 	if (!ctx->super) {
3654 		free(ctx);
3655 		_spdk_bs_free(bs);
3656 		cb_fn(cb_arg, -ENOMEM);
3657 		return;
3658 	}
3659 
3660 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
3661 	cpl.u.bs_basic.cb_fn = cb_fn;
3662 	cpl.u.bs_basic.cb_arg = cb_arg;
3663 
3664 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3665 	if (!seq) {
3666 		spdk_free(ctx->super);
3667 		free(ctx);
3668 		_spdk_bs_free(bs);
3669 		cb_fn(cb_arg, -ENOMEM);
3670 		return;
3671 	}
3672 
3673 	/* Read the super block */
3674 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
3675 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
3676 				  _spdk_bs_dump_super_cpl, ctx);
3677 }
3678 
3679 /* END spdk_bs_dump */
3680 
3681 /* START spdk_bs_init */
3682 
3683 struct spdk_bs_init_ctx {
3684 	struct spdk_blob_store		*bs;
3685 	struct spdk_bs_super_block	*super;
3686 };
3687 
3688 static void
3689 _spdk_bs_init_persist_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3690 {
3691 	struct spdk_bs_init_ctx *ctx = cb_arg;
3692 
3693 	spdk_free(ctx->super);
3694 	free(ctx);
3695 
3696 	spdk_bs_sequence_finish(seq, bserrno);
3697 }
3698 
3699 static void
3700 _spdk_bs_init_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3701 {
3702 	struct spdk_bs_init_ctx *ctx = cb_arg;
3703 
3704 	/* Write super block */
3705 	spdk_bs_sequence_write_dev(seq, ctx->super, _spdk_bs_page_to_lba(ctx->bs, 0),
3706 				   _spdk_bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
3707 				   _spdk_bs_init_persist_super_cpl, ctx);
3708 }
3709 
3710 void
3711 spdk_bs_init(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
3712 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
3713 {
3714 	struct spdk_bs_init_ctx *ctx;
3715 	struct spdk_blob_store	*bs;
3716 	struct spdk_bs_cpl	cpl;
3717 	spdk_bs_sequence_t	*seq;
3718 	spdk_bs_batch_t		*batch;
3719 	uint64_t		num_md_lba;
3720 	uint64_t		num_md_pages;
3721 	uint64_t		num_md_clusters;
3722 	uint32_t		i;
3723 	struct spdk_bs_opts	opts = {};
3724 	int			rc;
3725 
3726 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Initializing blobstore on dev %p\n", dev);
3727 
3728 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
3729 		SPDK_ERRLOG("unsupported dev block length of %d\n",
3730 			    dev->blocklen);
3731 		dev->destroy(dev);
3732 		cb_fn(cb_arg, NULL, -EINVAL);
3733 		return;
3734 	}
3735 
3736 	if (o) {
3737 		opts = *o;
3738 	} else {
3739 		spdk_bs_opts_init(&opts);
3740 	}
3741 
3742 	if (_spdk_bs_opts_verify(&opts) != 0) {
3743 		dev->destroy(dev);
3744 		cb_fn(cb_arg, NULL, -EINVAL);
3745 		return;
3746 	}
3747 
3748 	rc = _spdk_bs_alloc(dev, &opts, &bs);
3749 	if (rc) {
3750 		dev->destroy(dev);
3751 		cb_fn(cb_arg, NULL, rc);
3752 		return;
3753 	}
3754 
3755 	if (opts.num_md_pages == SPDK_BLOB_OPTS_NUM_MD_PAGES) {
3756 		/* By default, allocate 1 page per cluster.
3757 		 * Technically, this over-allocates metadata
3758 		 * because more metadata will reduce the number
3759 		 * of usable clusters. This can be addressed with
3760 		 * more complex math in the future.
3761 		 */
3762 		bs->md_len = bs->total_clusters;
3763 	} else {
3764 		bs->md_len = opts.num_md_pages;
3765 	}
3766 	rc = spdk_bit_array_resize(&bs->used_md_pages, bs->md_len);
3767 	if (rc < 0) {
3768 		_spdk_bs_free(bs);
3769 		cb_fn(cb_arg, NULL, -ENOMEM);
3770 		return;
3771 	}
3772 
3773 	rc = spdk_bit_array_resize(&bs->used_blobids, bs->md_len);
3774 	if (rc < 0) {
3775 		_spdk_bs_free(bs);
3776 		cb_fn(cb_arg, NULL, -ENOMEM);
3777 		return;
3778 	}
3779 
3780 	ctx = calloc(1, sizeof(*ctx));
3781 	if (!ctx) {
3782 		_spdk_bs_free(bs);
3783 		cb_fn(cb_arg, NULL, -ENOMEM);
3784 		return;
3785 	}
3786 
3787 	ctx->bs = bs;
3788 
3789 	/* Allocate memory for the super block */
3790 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3791 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3792 	if (!ctx->super) {
3793 		free(ctx);
3794 		_spdk_bs_free(bs);
3795 		cb_fn(cb_arg, NULL, -ENOMEM);
3796 		return;
3797 	}
3798 	memcpy(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3799 	       sizeof(ctx->super->signature));
3800 	ctx->super->version = SPDK_BS_VERSION;
3801 	ctx->super->length = sizeof(*ctx->super);
3802 	ctx->super->super_blob = bs->super_blob;
3803 	ctx->super->clean = 0;
3804 	ctx->super->cluster_size = bs->cluster_sz;
3805 	ctx->super->io_unit_size = bs->io_unit_size;
3806 	memcpy(&ctx->super->bstype, &bs->bstype, sizeof(bs->bstype));
3807 
3808 	/* Calculate how many pages the metadata consumes at the front
3809 	 * of the disk.
3810 	 */
3811 
3812 	/* The super block uses 1 page */
3813 	num_md_pages = 1;
3814 
3815 	/* The used_md_pages mask requires 1 bit per metadata page, rounded
3816 	 * up to the nearest page, plus a header.
3817 	 */
3818 	ctx->super->used_page_mask_start = num_md_pages;
3819 	ctx->super->used_page_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3820 					 spdk_divide_round_up(bs->md_len, 8),
3821 					 SPDK_BS_PAGE_SIZE);
3822 	num_md_pages += ctx->super->used_page_mask_len;
3823 
3824 	/* The used_clusters mask requires 1 bit per cluster, rounded
3825 	 * up to the nearest page, plus a header.
3826 	 */
3827 	ctx->super->used_cluster_mask_start = num_md_pages;
3828 	ctx->super->used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3829 					    spdk_divide_round_up(bs->total_clusters, 8),
3830 					    SPDK_BS_PAGE_SIZE);
3831 	num_md_pages += ctx->super->used_cluster_mask_len;
3832 
3833 	/* The used_blobids mask requires 1 bit per metadata page, rounded
3834 	 * up to the nearest page, plus a header.
3835 	 */
3836 	ctx->super->used_blobid_mask_start = num_md_pages;
3837 	ctx->super->used_blobid_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3838 					   spdk_divide_round_up(bs->md_len, 8),
3839 					   SPDK_BS_PAGE_SIZE);
3840 	num_md_pages += ctx->super->used_blobid_mask_len;
3841 
3842 	/* The metadata region size was chosen above */
3843 	ctx->super->md_start = bs->md_start = num_md_pages;
3844 	ctx->super->md_len = bs->md_len;
3845 	num_md_pages += bs->md_len;
3846 
3847 	num_md_lba = _spdk_bs_page_to_lba(bs, num_md_pages);
3848 
3849 	ctx->super->size = dev->blockcnt * dev->blocklen;
3850 
3851 	ctx->super->crc = _spdk_blob_md_page_calc_crc(ctx->super);
3852 
3853 	num_md_clusters = spdk_divide_round_up(num_md_pages, bs->pages_per_cluster);
3854 	if (num_md_clusters > bs->total_clusters) {
3855 		SPDK_ERRLOG("Blobstore metadata cannot use more clusters than is available, "
3856 			    "please decrease number of pages reserved for metadata "
3857 			    "or increase cluster size.\n");
3858 		spdk_free(ctx->super);
3859 		free(ctx);
3860 		_spdk_bs_free(bs);
3861 		cb_fn(cb_arg, NULL, -ENOMEM);
3862 		return;
3863 	}
3864 	/* Claim all of the clusters used by the metadata */
3865 	for (i = 0; i < num_md_clusters; i++) {
3866 		_spdk_bs_claim_cluster(bs, i);
3867 	}
3868 
3869 	bs->total_data_clusters = bs->num_free_clusters;
3870 
3871 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
3872 	cpl.u.bs_handle.cb_fn = cb_fn;
3873 	cpl.u.bs_handle.cb_arg = cb_arg;
3874 	cpl.u.bs_handle.bs = bs;
3875 
3876 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3877 	if (!seq) {
3878 		spdk_free(ctx->super);
3879 		free(ctx);
3880 		_spdk_bs_free(bs);
3881 		cb_fn(cb_arg, NULL, -ENOMEM);
3882 		return;
3883 	}
3884 
3885 	batch = spdk_bs_sequence_to_batch(seq, _spdk_bs_init_trim_cpl, ctx);
3886 
3887 	/* Clear metadata space */
3888 	spdk_bs_batch_write_zeroes_dev(batch, 0, num_md_lba);
3889 
3890 	switch (opts.clear_method) {
3891 	case BS_CLEAR_WITH_UNMAP:
3892 		/* Trim data clusters */
3893 		spdk_bs_batch_unmap_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
3894 		break;
3895 	case BS_CLEAR_WITH_WRITE_ZEROES:
3896 		/* Write_zeroes to data clusters */
3897 		spdk_bs_batch_write_zeroes_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
3898 		break;
3899 	case BS_CLEAR_WITH_NONE:
3900 	default:
3901 		break;
3902 	}
3903 
3904 	spdk_bs_batch_close(batch);
3905 }
3906 
3907 /* END spdk_bs_init */
3908 
3909 /* START spdk_bs_destroy */
3910 
3911 static void
3912 _spdk_bs_destroy_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3913 {
3914 	struct spdk_bs_init_ctx *ctx = cb_arg;
3915 	struct spdk_blob_store *bs = ctx->bs;
3916 
3917 	/*
3918 	 * We need to defer calling spdk_bs_call_cpl() until after
3919 	 * dev destruction, so tuck these away for later use.
3920 	 */
3921 	bs->unload_err = bserrno;
3922 	memcpy(&bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3923 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3924 
3925 	spdk_bs_sequence_finish(seq, bserrno);
3926 
3927 	_spdk_bs_free(bs);
3928 	free(ctx);
3929 }
3930 
3931 void
3932 spdk_bs_destroy(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn,
3933 		void *cb_arg)
3934 {
3935 	struct spdk_bs_cpl	cpl;
3936 	spdk_bs_sequence_t	*seq;
3937 	struct spdk_bs_init_ctx *ctx;
3938 
3939 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Destroying blobstore\n");
3940 
3941 	if (!TAILQ_EMPTY(&bs->blobs)) {
3942 		SPDK_ERRLOG("Blobstore still has open blobs\n");
3943 		cb_fn(cb_arg, -EBUSY);
3944 		return;
3945 	}
3946 
3947 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
3948 	cpl.u.bs_basic.cb_fn = cb_fn;
3949 	cpl.u.bs_basic.cb_arg = cb_arg;
3950 
3951 	ctx = calloc(1, sizeof(*ctx));
3952 	if (!ctx) {
3953 		cb_fn(cb_arg, -ENOMEM);
3954 		return;
3955 	}
3956 
3957 	ctx->bs = bs;
3958 
3959 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3960 	if (!seq) {
3961 		free(ctx);
3962 		cb_fn(cb_arg, -ENOMEM);
3963 		return;
3964 	}
3965 
3966 	/* Write zeroes to the super block */
3967 	spdk_bs_sequence_write_zeroes_dev(seq,
3968 					  _spdk_bs_page_to_lba(bs, 0),
3969 					  _spdk_bs_byte_to_lba(bs, sizeof(struct spdk_bs_super_block)),
3970 					  _spdk_bs_destroy_trim_cpl, ctx);
3971 }
3972 
3973 /* END spdk_bs_destroy */
3974 
3975 /* START spdk_bs_unload */
3976 
3977 static void
3978 _spdk_bs_unload_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3979 {
3980 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3981 
3982 	spdk_free(ctx->super);
3983 
3984 	/*
3985 	 * We need to defer calling spdk_bs_call_cpl() until after
3986 	 * dev destruction, so tuck these away for later use.
3987 	 */
3988 	ctx->bs->unload_err = bserrno;
3989 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3990 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3991 
3992 	spdk_bs_sequence_finish(seq, bserrno);
3993 
3994 	_spdk_bs_free(ctx->bs);
3995 	free(ctx);
3996 }
3997 
3998 static void
3999 _spdk_bs_unload_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4000 {
4001 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4002 
4003 	spdk_free(ctx->mask);
4004 	ctx->super->clean = 1;
4005 
4006 	_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_unload_write_super_cpl, ctx);
4007 }
4008 
4009 static void
4010 _spdk_bs_unload_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4011 {
4012 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4013 
4014 	spdk_free(ctx->mask);
4015 	ctx->mask = NULL;
4016 
4017 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_unload_write_used_clusters_cpl);
4018 }
4019 
4020 static void
4021 _spdk_bs_unload_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4022 {
4023 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4024 
4025 	spdk_free(ctx->mask);
4026 	ctx->mask = NULL;
4027 
4028 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_unload_write_used_blobids_cpl);
4029 }
4030 
4031 static void
4032 _spdk_bs_unload_read_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4033 {
4034 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_unload_write_used_pages_cpl);
4035 }
4036 
4037 void
4038 spdk_bs_unload(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn, void *cb_arg)
4039 {
4040 	struct spdk_bs_cpl	cpl;
4041 	spdk_bs_sequence_t	*seq;
4042 	struct spdk_bs_load_ctx *ctx;
4043 
4044 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blobstore\n");
4045 
4046 	if (!TAILQ_EMPTY(&bs->blobs)) {
4047 		SPDK_ERRLOG("Blobstore still has open blobs\n");
4048 		cb_fn(cb_arg, -EBUSY);
4049 		return;
4050 	}
4051 
4052 	ctx = calloc(1, sizeof(*ctx));
4053 	if (!ctx) {
4054 		cb_fn(cb_arg, -ENOMEM);
4055 		return;
4056 	}
4057 
4058 	ctx->bs = bs;
4059 
4060 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4061 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4062 	if (!ctx->super) {
4063 		free(ctx);
4064 		cb_fn(cb_arg, -ENOMEM);
4065 		return;
4066 	}
4067 
4068 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4069 	cpl.u.bs_basic.cb_fn = cb_fn;
4070 	cpl.u.bs_basic.cb_arg = cb_arg;
4071 
4072 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4073 	if (!seq) {
4074 		spdk_free(ctx->super);
4075 		free(ctx);
4076 		cb_fn(cb_arg, -ENOMEM);
4077 		return;
4078 	}
4079 
4080 	/* Read super block */
4081 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
4082 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
4083 				  _spdk_bs_unload_read_super_cpl, ctx);
4084 }
4085 
4086 /* END spdk_bs_unload */
4087 
4088 /* START spdk_bs_set_super */
4089 
4090 struct spdk_bs_set_super_ctx {
4091 	struct spdk_blob_store		*bs;
4092 	struct spdk_bs_super_block	*super;
4093 };
4094 
4095 static void
4096 _spdk_bs_set_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4097 {
4098 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
4099 
4100 	if (bserrno != 0) {
4101 		SPDK_ERRLOG("Unable to write to super block of blobstore\n");
4102 	}
4103 
4104 	spdk_free(ctx->super);
4105 
4106 	spdk_bs_sequence_finish(seq, bserrno);
4107 
4108 	free(ctx);
4109 }
4110 
4111 static void
4112 _spdk_bs_set_super_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4113 {
4114 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
4115 
4116 	if (bserrno != 0) {
4117 		SPDK_ERRLOG("Unable to read super block of blobstore\n");
4118 		spdk_free(ctx->super);
4119 		spdk_bs_sequence_finish(seq, bserrno);
4120 		free(ctx);
4121 		return;
4122 	}
4123 
4124 	_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_set_super_write_cpl, ctx);
4125 }
4126 
4127 void
4128 spdk_bs_set_super(struct spdk_blob_store *bs, spdk_blob_id blobid,
4129 		  spdk_bs_op_complete cb_fn, void *cb_arg)
4130 {
4131 	struct spdk_bs_cpl		cpl;
4132 	spdk_bs_sequence_t		*seq;
4133 	struct spdk_bs_set_super_ctx	*ctx;
4134 
4135 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Setting super blob id on blobstore\n");
4136 
4137 	ctx = calloc(1, sizeof(*ctx));
4138 	if (!ctx) {
4139 		cb_fn(cb_arg, -ENOMEM);
4140 		return;
4141 	}
4142 
4143 	ctx->bs = bs;
4144 
4145 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4146 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4147 	if (!ctx->super) {
4148 		free(ctx);
4149 		cb_fn(cb_arg, -ENOMEM);
4150 		return;
4151 	}
4152 
4153 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4154 	cpl.u.bs_basic.cb_fn = cb_fn;
4155 	cpl.u.bs_basic.cb_arg = cb_arg;
4156 
4157 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4158 	if (!seq) {
4159 		spdk_free(ctx->super);
4160 		free(ctx);
4161 		cb_fn(cb_arg, -ENOMEM);
4162 		return;
4163 	}
4164 
4165 	bs->super_blob = blobid;
4166 
4167 	/* Read super block */
4168 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
4169 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
4170 				  _spdk_bs_set_super_read_cpl, ctx);
4171 }
4172 
4173 /* END spdk_bs_set_super */
4174 
4175 void
4176 spdk_bs_get_super(struct spdk_blob_store *bs,
4177 		  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4178 {
4179 	if (bs->super_blob == SPDK_BLOBID_INVALID) {
4180 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOENT);
4181 	} else {
4182 		cb_fn(cb_arg, bs->super_blob, 0);
4183 	}
4184 }
4185 
4186 uint64_t
4187 spdk_bs_get_cluster_size(struct spdk_blob_store *bs)
4188 {
4189 	return bs->cluster_sz;
4190 }
4191 
4192 uint64_t
4193 spdk_bs_get_page_size(struct spdk_blob_store *bs)
4194 {
4195 	return SPDK_BS_PAGE_SIZE;
4196 }
4197 
4198 uint64_t
4199 spdk_bs_get_io_unit_size(struct spdk_blob_store *bs)
4200 {
4201 	return bs->io_unit_size;
4202 }
4203 
4204 uint64_t
4205 spdk_bs_free_cluster_count(struct spdk_blob_store *bs)
4206 {
4207 	return bs->num_free_clusters;
4208 }
4209 
4210 uint64_t
4211 spdk_bs_total_data_cluster_count(struct spdk_blob_store *bs)
4212 {
4213 	return bs->total_data_clusters;
4214 }
4215 
4216 static int
4217 spdk_bs_register_md_thread(struct spdk_blob_store *bs)
4218 {
4219 	bs->md_channel = spdk_get_io_channel(bs);
4220 	if (!bs->md_channel) {
4221 		SPDK_ERRLOG("Failed to get IO channel.\n");
4222 		return -1;
4223 	}
4224 
4225 	return 0;
4226 }
4227 
4228 static int
4229 spdk_bs_unregister_md_thread(struct spdk_blob_store *bs)
4230 {
4231 	spdk_put_io_channel(bs->md_channel);
4232 
4233 	return 0;
4234 }
4235 
4236 spdk_blob_id spdk_blob_get_id(struct spdk_blob *blob)
4237 {
4238 	assert(blob != NULL);
4239 
4240 	return blob->id;
4241 }
4242 
4243 uint64_t spdk_blob_get_num_pages(struct spdk_blob *blob)
4244 {
4245 	assert(blob != NULL);
4246 
4247 	return _spdk_bs_cluster_to_page(blob->bs, blob->active.num_clusters);
4248 }
4249 
4250 uint64_t spdk_blob_get_num_io_units(struct spdk_blob *blob)
4251 {
4252 	assert(blob != NULL);
4253 
4254 	return spdk_blob_get_num_pages(blob) * _spdk_bs_io_unit_per_page(blob->bs);
4255 }
4256 
4257 uint64_t spdk_blob_get_num_clusters(struct spdk_blob *blob)
4258 {
4259 	assert(blob != NULL);
4260 
4261 	return blob->active.num_clusters;
4262 }
4263 
4264 /* START spdk_bs_create_blob */
4265 
4266 static void
4267 _spdk_bs_create_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4268 {
4269 	struct spdk_blob *blob = cb_arg;
4270 
4271 	_spdk_blob_free(blob);
4272 
4273 	spdk_bs_sequence_finish(seq, bserrno);
4274 }
4275 
4276 static int
4277 _spdk_blob_set_xattrs(struct spdk_blob *blob, const struct spdk_blob_xattr_opts *xattrs,
4278 		      bool internal)
4279 {
4280 	uint64_t i;
4281 	size_t value_len = 0;
4282 	int rc;
4283 	const void *value = NULL;
4284 	if (xattrs->count > 0 && xattrs->get_value == NULL) {
4285 		return -EINVAL;
4286 	}
4287 	for (i = 0; i < xattrs->count; i++) {
4288 		xattrs->get_value(xattrs->ctx, xattrs->names[i], &value, &value_len);
4289 		if (value == NULL || value_len == 0) {
4290 			return -EINVAL;
4291 		}
4292 		rc = _spdk_blob_set_xattr(blob, xattrs->names[i], value, value_len, internal);
4293 		if (rc < 0) {
4294 			return rc;
4295 		}
4296 	}
4297 	return 0;
4298 }
4299 
4300 static void
4301 _spdk_bs_create_blob(struct spdk_blob_store *bs,
4302 		     const struct spdk_blob_opts *opts,
4303 		     const struct spdk_blob_xattr_opts *internal_xattrs,
4304 		     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4305 {
4306 	struct spdk_blob	*blob;
4307 	uint32_t		page_idx;
4308 	struct spdk_bs_cpl	cpl;
4309 	struct spdk_blob_opts	opts_default;
4310 	struct spdk_blob_xattr_opts internal_xattrs_default;
4311 	spdk_bs_sequence_t	*seq;
4312 	spdk_blob_id		id;
4313 	int rc;
4314 
4315 	assert(spdk_get_thread() == bs->md_thread);
4316 
4317 	page_idx = spdk_bit_array_find_first_clear(bs->used_md_pages, 0);
4318 	if (page_idx == UINT32_MAX) {
4319 		cb_fn(cb_arg, 0, -ENOMEM);
4320 		return;
4321 	}
4322 	spdk_bit_array_set(bs->used_blobids, page_idx);
4323 	spdk_bit_array_set(bs->used_md_pages, page_idx);
4324 
4325 	id = _spdk_bs_page_to_blobid(page_idx);
4326 
4327 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Creating blob with id %lu at page %u\n", id, page_idx);
4328 
4329 	blob = _spdk_blob_alloc(bs, id);
4330 	if (!blob) {
4331 		cb_fn(cb_arg, 0, -ENOMEM);
4332 		return;
4333 	}
4334 
4335 	if (!opts) {
4336 		spdk_blob_opts_init(&opts_default);
4337 		opts = &opts_default;
4338 	}
4339 	if (!internal_xattrs) {
4340 		_spdk_blob_xattrs_init(&internal_xattrs_default);
4341 		internal_xattrs = &internal_xattrs_default;
4342 	}
4343 
4344 	rc = _spdk_blob_set_xattrs(blob, &opts->xattrs, false);
4345 	if (rc < 0) {
4346 		_spdk_blob_free(blob);
4347 		cb_fn(cb_arg, 0, rc);
4348 		return;
4349 	}
4350 
4351 	rc = _spdk_blob_set_xattrs(blob, internal_xattrs, true);
4352 	if (rc < 0) {
4353 		_spdk_blob_free(blob);
4354 		cb_fn(cb_arg, 0, rc);
4355 		return;
4356 	}
4357 
4358 	if (opts->thin_provision) {
4359 		_spdk_blob_set_thin_provision(blob);
4360 	}
4361 
4362 	rc = _spdk_blob_resize(blob, opts->num_clusters);
4363 	if (rc < 0) {
4364 		_spdk_blob_free(blob);
4365 		cb_fn(cb_arg, 0, rc);
4366 		return;
4367 	}
4368 	cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4369 	cpl.u.blobid.cb_fn = cb_fn;
4370 	cpl.u.blobid.cb_arg = cb_arg;
4371 	cpl.u.blobid.blobid = blob->id;
4372 
4373 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4374 	if (!seq) {
4375 		_spdk_blob_free(blob);
4376 		cb_fn(cb_arg, 0, -ENOMEM);
4377 		return;
4378 	}
4379 
4380 	_spdk_blob_persist(seq, blob, _spdk_bs_create_blob_cpl, blob);
4381 }
4382 
4383 void spdk_bs_create_blob(struct spdk_blob_store *bs,
4384 			 spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4385 {
4386 	_spdk_bs_create_blob(bs, NULL, NULL, cb_fn, cb_arg);
4387 }
4388 
4389 void spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
4390 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4391 {
4392 	_spdk_bs_create_blob(bs, opts, NULL, cb_fn, cb_arg);
4393 }
4394 
4395 /* END spdk_bs_create_blob */
4396 
4397 /* START blob_cleanup */
4398 
4399 struct spdk_clone_snapshot_ctx {
4400 	struct spdk_bs_cpl      cpl;
4401 	int bserrno;
4402 	bool frozen;
4403 
4404 	struct spdk_io_channel *channel;
4405 
4406 	/* Current cluster for inflate operation */
4407 	uint64_t cluster;
4408 
4409 	/* For inflation force allocation of all unallocated clusters and remove
4410 	 * thin-provisioning. Otherwise only decouple parent and keep clone thin. */
4411 	bool allocate_all;
4412 
4413 	struct {
4414 		spdk_blob_id id;
4415 		struct spdk_blob *blob;
4416 	} original;
4417 	struct {
4418 		spdk_blob_id id;
4419 		struct spdk_blob *blob;
4420 	} new;
4421 
4422 	/* xattrs specified for snapshot/clones only. They have no impact on
4423 	 * the original blobs xattrs. */
4424 	const struct spdk_blob_xattr_opts *xattrs;
4425 };
4426 
4427 static void
4428 _spdk_bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
4429 {
4430 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
4431 	struct spdk_bs_cpl *cpl = &ctx->cpl;
4432 
4433 	if (bserrno != 0) {
4434 		if (ctx->bserrno != 0) {
4435 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4436 		} else {
4437 			ctx->bserrno = bserrno;
4438 		}
4439 	}
4440 
4441 	switch (cpl->type) {
4442 	case SPDK_BS_CPL_TYPE_BLOBID:
4443 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
4444 		break;
4445 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
4446 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
4447 		break;
4448 	default:
4449 		SPDK_UNREACHABLE();
4450 		break;
4451 	}
4452 
4453 	free(ctx);
4454 }
4455 
4456 static void
4457 _spdk_bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
4458 {
4459 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4460 	struct spdk_blob *origblob = ctx->original.blob;
4461 
4462 	if (bserrno != 0) {
4463 		if (ctx->bserrno != 0) {
4464 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
4465 		} else {
4466 			ctx->bserrno = bserrno;
4467 		}
4468 	}
4469 
4470 	ctx->original.id = origblob->id;
4471 	origblob->locked_operation_in_progress = false;
4472 
4473 	spdk_blob_close(origblob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4474 }
4475 
4476 static void
4477 _spdk_bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
4478 {
4479 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4480 	struct spdk_blob *origblob = ctx->original.blob;
4481 
4482 	if (bserrno != 0) {
4483 		if (ctx->bserrno != 0) {
4484 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4485 		} else {
4486 			ctx->bserrno = bserrno;
4487 		}
4488 	}
4489 
4490 	if (ctx->frozen) {
4491 		/* Unfreeze any outstanding I/O */
4492 		_spdk_blob_unfreeze_io(origblob, _spdk_bs_snapshot_unfreeze_cpl, ctx);
4493 	} else {
4494 		_spdk_bs_snapshot_unfreeze_cpl(ctx, 0);
4495 	}
4496 
4497 }
4498 
4499 static void
4500 _spdk_bs_clone_snapshot_newblob_cleanup(void *cb_arg, int bserrno)
4501 {
4502 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4503 	struct spdk_blob *newblob = ctx->new.blob;
4504 
4505 	if (bserrno != 0) {
4506 		if (ctx->bserrno != 0) {
4507 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4508 		} else {
4509 			ctx->bserrno = bserrno;
4510 		}
4511 	}
4512 
4513 	ctx->new.id = newblob->id;
4514 	spdk_blob_close(newblob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4515 }
4516 
4517 /* END blob_cleanup */
4518 
4519 /* START spdk_bs_create_snapshot */
4520 
4521 static void
4522 _spdk_bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
4523 {
4524 	uint64_t *cluster_temp;
4525 
4526 	cluster_temp = blob1->active.clusters;
4527 	blob1->active.clusters = blob2->active.clusters;
4528 	blob2->active.clusters = cluster_temp;
4529 }
4530 
4531 static void
4532 _spdk_bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
4533 {
4534 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4535 	struct spdk_blob *origblob = ctx->original.blob;
4536 	struct spdk_blob *newblob = ctx->new.blob;
4537 
4538 	if (bserrno != 0) {
4539 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4540 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4541 		return;
4542 	}
4543 
4544 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
4545 	bserrno = _spdk_blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
4546 	if (bserrno != 0) {
4547 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4548 		return;
4549 	}
4550 
4551 	_spdk_bs_blob_list_add(ctx->original.blob);
4552 
4553 	spdk_blob_set_read_only(newblob);
4554 
4555 	/* sync snapshot metadata */
4556 	spdk_blob_sync_md(newblob, _spdk_bs_clone_snapshot_origblob_cleanup, cb_arg);
4557 }
4558 
4559 static void
4560 _spdk_bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
4561 {
4562 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4563 	struct spdk_blob *origblob = ctx->original.blob;
4564 	struct spdk_blob *newblob = ctx->new.blob;
4565 
4566 	if (bserrno != 0) {
4567 		/* return cluster map back to original */
4568 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4569 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4570 		return;
4571 	}
4572 
4573 	/* Set internal xattr for snapshot id */
4574 	bserrno = _spdk_blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
4575 	if (bserrno != 0) {
4576 		/* return cluster map back to original */
4577 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4578 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4579 		return;
4580 	}
4581 
4582 	_spdk_bs_blob_list_remove(origblob);
4583 	origblob->parent_id = newblob->id;
4584 
4585 	/* Create new back_bs_dev for snapshot */
4586 	origblob->back_bs_dev = spdk_bs_create_blob_bs_dev(newblob);
4587 	if (origblob->back_bs_dev == NULL) {
4588 		/* return cluster map back to original */
4589 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4590 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
4591 		return;
4592 	}
4593 
4594 	/* set clone blob as thin provisioned */
4595 	_spdk_blob_set_thin_provision(origblob);
4596 
4597 	_spdk_bs_blob_list_add(newblob);
4598 
4599 	/* sync clone metadata */
4600 	spdk_blob_sync_md(origblob, _spdk_bs_snapshot_origblob_sync_cpl, ctx);
4601 }
4602 
4603 static void
4604 _spdk_bs_snapshot_freeze_cpl(void *cb_arg, int rc)
4605 {
4606 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4607 	struct spdk_blob *origblob = ctx->original.blob;
4608 	struct spdk_blob *newblob = ctx->new.blob;
4609 	int bserrno;
4610 
4611 	if (rc != 0) {
4612 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, rc);
4613 		return;
4614 	}
4615 
4616 	ctx->frozen = true;
4617 
4618 	/* set new back_bs_dev for snapshot */
4619 	newblob->back_bs_dev = origblob->back_bs_dev;
4620 	/* Set invalid flags from origblob */
4621 	newblob->invalid_flags = origblob->invalid_flags;
4622 
4623 	/* inherit parent from original blob if set */
4624 	newblob->parent_id = origblob->parent_id;
4625 	if (origblob->parent_id != SPDK_BLOBID_INVALID) {
4626 		/* Set internal xattr for snapshot id */
4627 		bserrno = _spdk_blob_set_xattr(newblob, BLOB_SNAPSHOT,
4628 					       &origblob->parent_id, sizeof(spdk_blob_id), true);
4629 		if (bserrno != 0) {
4630 			_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4631 			return;
4632 		}
4633 	}
4634 
4635 	/* swap cluster maps */
4636 	_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4637 
4638 	/* sync snapshot metadata */
4639 	spdk_blob_sync_md(newblob, _spdk_bs_snapshot_newblob_sync_cpl, ctx);
4640 }
4641 
4642 static void
4643 _spdk_bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4644 {
4645 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4646 	struct spdk_blob *origblob = ctx->original.blob;
4647 	struct spdk_blob *newblob = _blob;
4648 
4649 	if (bserrno != 0) {
4650 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4651 		return;
4652 	}
4653 
4654 	ctx->new.blob = newblob;
4655 
4656 	/* Zero out newblob cluster map */
4657 	memset(newblob->active.clusters, 0,
4658 	       newblob->active.num_clusters * sizeof(newblob->active.clusters));
4659 
4660 	_spdk_blob_freeze_io(origblob, _spdk_bs_snapshot_freeze_cpl, ctx);
4661 }
4662 
4663 static void
4664 _spdk_bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
4665 {
4666 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4667 	struct spdk_blob *origblob = ctx->original.blob;
4668 
4669 	if (bserrno != 0) {
4670 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4671 		return;
4672 	}
4673 
4674 	ctx->new.id = blobid;
4675 	ctx->cpl.u.blobid.blobid = blobid;
4676 
4677 	spdk_bs_open_blob(origblob->bs, ctx->new.id, _spdk_bs_snapshot_newblob_open_cpl, ctx);
4678 }
4679 
4680 
4681 static void
4682 _spdk_bs_xattr_snapshot(void *arg, const char *name,
4683 			const void **value, size_t *value_len)
4684 {
4685 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
4686 
4687 	struct spdk_blob *blob = (struct spdk_blob *)arg;
4688 	*value = &blob->id;
4689 	*value_len = sizeof(blob->id);
4690 }
4691 
4692 static void
4693 _spdk_bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4694 {
4695 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4696 	struct spdk_blob_opts opts;
4697 	struct spdk_blob_xattr_opts internal_xattrs;
4698 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
4699 
4700 	if (bserrno != 0) {
4701 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
4702 		return;
4703 	}
4704 
4705 	ctx->original.blob = _blob;
4706 
4707 	if (_blob->data_ro || _blob->md_ro) {
4708 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot from read only blob with id %lu\n",
4709 			      _blob->id);
4710 		ctx->bserrno = -EINVAL;
4711 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4712 		return;
4713 	}
4714 
4715 	if (_blob->locked_operation_in_progress) {
4716 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot - another operation in progress\n");
4717 		ctx->bserrno = -EBUSY;
4718 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4719 		return;
4720 	}
4721 
4722 	_blob->locked_operation_in_progress = true;
4723 
4724 	spdk_blob_opts_init(&opts);
4725 	_spdk_blob_xattrs_init(&internal_xattrs);
4726 
4727 	/* Change the size of new blob to the same as in original blob,
4728 	 * but do not allocate clusters */
4729 	opts.thin_provision = true;
4730 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
4731 
4732 	/* If there are any xattrs specified for snapshot, set them now */
4733 	if (ctx->xattrs) {
4734 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
4735 	}
4736 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
4737 	internal_xattrs.count = 1;
4738 	internal_xattrs.ctx = _blob;
4739 	internal_xattrs.names = xattrs_names;
4740 	internal_xattrs.get_value = _spdk_bs_xattr_snapshot;
4741 
4742 	_spdk_bs_create_blob(_blob->bs, &opts, &internal_xattrs,
4743 			     _spdk_bs_snapshot_newblob_create_cpl, ctx);
4744 }
4745 
4746 void spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
4747 			     const struct spdk_blob_xattr_opts *snapshot_xattrs,
4748 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4749 {
4750 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
4751 
4752 	if (!ctx) {
4753 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
4754 		return;
4755 	}
4756 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4757 	ctx->cpl.u.blobid.cb_fn = cb_fn;
4758 	ctx->cpl.u.blobid.cb_arg = cb_arg;
4759 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
4760 	ctx->bserrno = 0;
4761 	ctx->frozen = false;
4762 	ctx->original.id = blobid;
4763 	ctx->xattrs = snapshot_xattrs;
4764 
4765 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_snapshot_origblob_open_cpl, ctx);
4766 }
4767 /* END spdk_bs_create_snapshot */
4768 
4769 /* START spdk_bs_create_clone */
4770 
4771 static void
4772 _spdk_bs_xattr_clone(void *arg, const char *name,
4773 		     const void **value, size_t *value_len)
4774 {
4775 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
4776 
4777 	struct spdk_blob *blob = (struct spdk_blob *)arg;
4778 	*value = &blob->id;
4779 	*value_len = sizeof(blob->id);
4780 }
4781 
4782 static void
4783 _spdk_bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4784 {
4785 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4786 	struct spdk_blob *clone = _blob;
4787 
4788 	ctx->new.blob = clone;
4789 	_spdk_bs_blob_list_add(clone);
4790 
4791 	spdk_blob_close(clone, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4792 }
4793 
4794 static void
4795 _spdk_bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
4796 {
4797 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4798 
4799 	ctx->cpl.u.blobid.blobid = blobid;
4800 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, _spdk_bs_clone_newblob_open_cpl, ctx);
4801 }
4802 
4803 static void
4804 _spdk_bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4805 {
4806 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4807 	struct spdk_blob_opts		opts;
4808 	struct spdk_blob_xattr_opts internal_xattrs;
4809 	char *xattr_names[] = { BLOB_SNAPSHOT };
4810 
4811 	if (bserrno != 0) {
4812 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
4813 		return;
4814 	}
4815 
4816 	ctx->original.blob = _blob;
4817 
4818 	if (!_blob->data_ro || !_blob->md_ro) {
4819 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Clone not from read-only blob\n");
4820 		ctx->bserrno = -EINVAL;
4821 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4822 		return;
4823 	}
4824 
4825 	if (_blob->locked_operation_in_progress) {
4826 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create clone - another operation in progress\n");
4827 		ctx->bserrno = -EBUSY;
4828 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4829 		return;
4830 	}
4831 
4832 	_blob->locked_operation_in_progress = true;
4833 
4834 	spdk_blob_opts_init(&opts);
4835 	_spdk_blob_xattrs_init(&internal_xattrs);
4836 
4837 	opts.thin_provision = true;
4838 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
4839 	if (ctx->xattrs) {
4840 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
4841 	}
4842 
4843 	/* Set internal xattr BLOB_SNAPSHOT */
4844 	internal_xattrs.count = 1;
4845 	internal_xattrs.ctx = _blob;
4846 	internal_xattrs.names = xattr_names;
4847 	internal_xattrs.get_value = _spdk_bs_xattr_clone;
4848 
4849 	_spdk_bs_create_blob(_blob->bs, &opts, &internal_xattrs,
4850 			     _spdk_bs_clone_newblob_create_cpl, ctx);
4851 }
4852 
4853 void spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
4854 			  const struct spdk_blob_xattr_opts *clone_xattrs,
4855 			  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4856 {
4857 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
4858 
4859 	if (!ctx) {
4860 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
4861 		return;
4862 	}
4863 
4864 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4865 	ctx->cpl.u.blobid.cb_fn = cb_fn;
4866 	ctx->cpl.u.blobid.cb_arg = cb_arg;
4867 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
4868 	ctx->bserrno = 0;
4869 	ctx->xattrs = clone_xattrs;
4870 	ctx->original.id = blobid;
4871 
4872 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_clone_origblob_open_cpl, ctx);
4873 }
4874 
4875 /* END spdk_bs_create_clone */
4876 
4877 /* START spdk_bs_inflate_blob */
4878 
4879 static void
4880 _spdk_bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
4881 {
4882 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4883 	struct spdk_blob *_blob = ctx->original.blob;
4884 
4885 	if (bserrno != 0) {
4886 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4887 		return;
4888 	}
4889 
4890 	assert(_parent != NULL);
4891 
4892 	_spdk_bs_blob_list_remove(_blob);
4893 	_blob->parent_id = _parent->id;
4894 	_spdk_blob_set_xattr(_blob, BLOB_SNAPSHOT, &_blob->parent_id,
4895 			     sizeof(spdk_blob_id), true);
4896 
4897 	_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4898 	_blob->back_bs_dev = spdk_bs_create_blob_bs_dev(_parent);
4899 	_spdk_bs_blob_list_add(_blob);
4900 
4901 	spdk_blob_sync_md(_blob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4902 }
4903 
4904 static void
4905 _spdk_bs_inflate_blob_done(void *cb_arg, int bserrno)
4906 {
4907 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4908 	struct spdk_blob *_blob = ctx->original.blob;
4909 	struct spdk_blob *_parent;
4910 
4911 	if (bserrno != 0) {
4912 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4913 		return;
4914 	}
4915 
4916 	if (ctx->allocate_all) {
4917 		/* remove thin provisioning */
4918 		_spdk_bs_blob_list_remove(_blob);
4919 		_spdk_blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
4920 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
4921 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4922 		_blob->back_bs_dev = NULL;
4923 		_blob->parent_id = SPDK_BLOBID_INVALID;
4924 	} else {
4925 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
4926 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
4927 			/* We must change the parent of the inflated blob */
4928 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
4929 					  _spdk_bs_inflate_blob_set_parent_cpl, ctx);
4930 			return;
4931 		}
4932 
4933 		_spdk_bs_blob_list_remove(_blob);
4934 		_spdk_blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
4935 		_blob->parent_id = SPDK_BLOBID_INVALID;
4936 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4937 		_blob->back_bs_dev = spdk_bs_create_zeroes_dev();
4938 	}
4939 
4940 	_blob->state = SPDK_BLOB_STATE_DIRTY;
4941 	spdk_blob_sync_md(_blob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4942 }
4943 
4944 /* Check if cluster needs allocation */
4945 static inline bool
4946 _spdk_bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
4947 {
4948 	struct spdk_blob_bs_dev *b;
4949 
4950 	assert(blob != NULL);
4951 
4952 	if (blob->active.clusters[cluster] != 0) {
4953 		/* Cluster is already allocated */
4954 		return false;
4955 	}
4956 
4957 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
4958 		/* Blob have no parent blob */
4959 		return allocate_all;
4960 	}
4961 
4962 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
4963 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
4964 }
4965 
4966 static void
4967 _spdk_bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
4968 {
4969 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4970 	struct spdk_blob *_blob = ctx->original.blob;
4971 	uint64_t offset;
4972 
4973 	if (bserrno != 0) {
4974 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4975 		return;
4976 	}
4977 
4978 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
4979 		if (_spdk_bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
4980 			break;
4981 		}
4982 	}
4983 
4984 	if (ctx->cluster < _blob->active.num_clusters) {
4985 		offset = _spdk_bs_cluster_to_lba(_blob->bs, ctx->cluster);
4986 
4987 		/* We may safely increment a cluster before write */
4988 		ctx->cluster++;
4989 
4990 		/* Use zero length write to touch a cluster */
4991 		spdk_blob_io_write(_blob, ctx->channel, NULL, offset, 0,
4992 				   _spdk_bs_inflate_blob_touch_next, ctx);
4993 	} else {
4994 		_spdk_bs_inflate_blob_done(cb_arg, bserrno);
4995 	}
4996 }
4997 
4998 static void
4999 _spdk_bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5000 {
5001 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5002 	uint64_t lfc; /* lowest free cluster */
5003 	uint64_t i;
5004 
5005 	if (bserrno != 0) {
5006 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5007 		return;
5008 	}
5009 
5010 	ctx->original.blob = _blob;
5011 
5012 	if (_blob->locked_operation_in_progress) {
5013 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot inflate blob - another operation in progress\n");
5014 		ctx->bserrno = -EBUSY;
5015 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
5016 		return;
5017 	}
5018 
5019 	_blob->locked_operation_in_progress = true;
5020 
5021 	if (!ctx->allocate_all && _blob->parent_id == SPDK_BLOBID_INVALID) {
5022 		/* This blob have no parent, so we cannot decouple it. */
5023 		SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
5024 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
5025 		return;
5026 	}
5027 
5028 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
5029 		/* This is not thin provisioned blob. No need to inflate. */
5030 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, 0);
5031 		return;
5032 	}
5033 
5034 	/* Do two passes - one to verify that we can obtain enough clusters
5035 	 * and another to actually claim them.
5036 	 */
5037 	lfc = 0;
5038 	for (i = 0; i < _blob->active.num_clusters; i++) {
5039 		if (_spdk_bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
5040 			lfc = spdk_bit_array_find_first_clear(_blob->bs->used_clusters, lfc);
5041 			if (lfc == UINT32_MAX) {
5042 				/* No more free clusters. Cannot satisfy the request */
5043 				_spdk_bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
5044 				return;
5045 			}
5046 			lfc++;
5047 		}
5048 	}
5049 
5050 	ctx->cluster = 0;
5051 	_spdk_bs_inflate_blob_touch_next(ctx, 0);
5052 }
5053 
5054 static void
5055 _spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5056 		      spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
5057 {
5058 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
5059 
5060 	if (!ctx) {
5061 		cb_fn(cb_arg, -ENOMEM);
5062 		return;
5063 	}
5064 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5065 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
5066 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
5067 	ctx->bserrno = 0;
5068 	ctx->original.id = blobid;
5069 	ctx->channel = channel;
5070 	ctx->allocate_all = allocate_all;
5071 
5072 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_inflate_blob_open_cpl, ctx);
5073 }
5074 
5075 void
5076 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5077 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
5078 {
5079 	_spdk_bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
5080 }
5081 
5082 void
5083 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5084 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
5085 {
5086 	_spdk_bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
5087 }
5088 /* END spdk_bs_inflate_blob */
5089 
5090 /* START spdk_blob_resize */
5091 struct spdk_bs_resize_ctx {
5092 	spdk_blob_op_complete cb_fn;
5093 	void *cb_arg;
5094 	struct spdk_blob *blob;
5095 	uint64_t sz;
5096 	int rc;
5097 };
5098 
5099 static void
5100 _spdk_bs_resize_unfreeze_cpl(void *cb_arg, int rc)
5101 {
5102 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
5103 
5104 	if (rc != 0) {
5105 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
5106 	}
5107 
5108 	if (ctx->rc != 0) {
5109 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
5110 		rc = ctx->rc;
5111 	}
5112 
5113 	ctx->blob->locked_operation_in_progress = false;
5114 
5115 	ctx->cb_fn(ctx->cb_arg, rc);
5116 	free(ctx);
5117 }
5118 
5119 static void
5120 _spdk_bs_resize_freeze_cpl(void *cb_arg, int rc)
5121 {
5122 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
5123 
5124 	if (rc != 0) {
5125 		ctx->blob->locked_operation_in_progress = false;
5126 		ctx->cb_fn(ctx->cb_arg, rc);
5127 		free(ctx);
5128 		return;
5129 	}
5130 
5131 	ctx->rc = _spdk_blob_resize(ctx->blob, ctx->sz);
5132 
5133 	_spdk_blob_unfreeze_io(ctx->blob, _spdk_bs_resize_unfreeze_cpl, ctx);
5134 }
5135 
5136 void
5137 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
5138 {
5139 	struct spdk_bs_resize_ctx *ctx;
5140 
5141 	_spdk_blob_verify_md_op(blob);
5142 
5143 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Resizing blob %lu to %lu clusters\n", blob->id, sz);
5144 
5145 	if (blob->md_ro) {
5146 		cb_fn(cb_arg, -EPERM);
5147 		return;
5148 	}
5149 
5150 	if (sz == blob->active.num_clusters) {
5151 		cb_fn(cb_arg, 0);
5152 		return;
5153 	}
5154 
5155 	if (blob->locked_operation_in_progress) {
5156 		cb_fn(cb_arg, -EBUSY);
5157 		return;
5158 	}
5159 
5160 	ctx = calloc(1, sizeof(*ctx));
5161 	if (!ctx) {
5162 		cb_fn(cb_arg, -ENOMEM);
5163 		return;
5164 	}
5165 
5166 	blob->locked_operation_in_progress = true;
5167 	ctx->cb_fn = cb_fn;
5168 	ctx->cb_arg = cb_arg;
5169 	ctx->blob = blob;
5170 	ctx->sz = sz;
5171 	_spdk_blob_freeze_io(blob, _spdk_bs_resize_freeze_cpl, ctx);
5172 }
5173 
5174 /* END spdk_blob_resize */
5175 
5176 
5177 /* START spdk_bs_delete_blob */
5178 
5179 static void
5180 _spdk_bs_delete_close_cpl(void *cb_arg, int bserrno)
5181 {
5182 	spdk_bs_sequence_t *seq = cb_arg;
5183 
5184 	spdk_bs_sequence_finish(seq, bserrno);
5185 }
5186 
5187 static void
5188 _spdk_bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5189 {
5190 	struct spdk_blob *blob = cb_arg;
5191 
5192 	if (bserrno != 0) {
5193 		/*
5194 		 * We already removed this blob from the blobstore tailq, so
5195 		 *  we need to free it here since this is the last reference
5196 		 *  to it.
5197 		 */
5198 		_spdk_blob_free(blob);
5199 		_spdk_bs_delete_close_cpl(seq, bserrno);
5200 		return;
5201 	}
5202 
5203 	/*
5204 	 * This will immediately decrement the ref_count and call
5205 	 *  the completion routine since the metadata state is clean.
5206 	 *  By calling spdk_blob_close, we reduce the number of call
5207 	 *  points into code that touches the blob->open_ref count
5208 	 *  and the blobstore's blob list.
5209 	 */
5210 	spdk_blob_close(blob, _spdk_bs_delete_close_cpl, seq);
5211 }
5212 
5213 struct delete_snapshot_ctx {
5214 	struct spdk_blob_list *parent_snapshot_entry;
5215 	struct spdk_blob *snapshot;
5216 	bool snapshot_md_ro;
5217 	struct spdk_blob *clone;
5218 	bool clone_md_ro;
5219 	spdk_blob_op_with_handle_complete cb_fn;
5220 	void *cb_arg;
5221 	int bserrno;
5222 };
5223 
5224 static void
5225 _spdk_delete_blob_cleanup_finish(void *cb_arg, int bserrno)
5226 {
5227 	struct delete_snapshot_ctx *ctx = cb_arg;
5228 
5229 	if (bserrno != 0) {
5230 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
5231 	}
5232 
5233 	assert(ctx != NULL);
5234 
5235 	if (bserrno != 0 && ctx->bserrno == 0) {
5236 		ctx->bserrno = bserrno;
5237 	}
5238 
5239 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
5240 	free(ctx);
5241 }
5242 
5243 static void
5244 _spdk_delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
5245 {
5246 	struct delete_snapshot_ctx *ctx = cb_arg;
5247 
5248 	if (bserrno != 0) {
5249 		ctx->bserrno = bserrno;
5250 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
5251 	}
5252 
5253 	/* open_ref == 1 menas that only deletion context has opened this snapshot
5254 	 * open_ref == 2 menas that clone has opened this snapshot as well,
5255 	 * so we have to add it back to the blobs list */
5256 	if (ctx->snapshot->open_ref == 2) {
5257 		TAILQ_INSERT_HEAD(&ctx->snapshot->bs->blobs, ctx->snapshot, link);
5258 	}
5259 
5260 	ctx->snapshot->locked_operation_in_progress = false;
5261 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
5262 
5263 	spdk_blob_close(ctx->snapshot, _spdk_delete_blob_cleanup_finish, ctx);
5264 }
5265 
5266 static void
5267 _spdk_delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
5268 {
5269 	struct delete_snapshot_ctx *ctx = cb_arg;
5270 
5271 	ctx->clone->locked_operation_in_progress = false;
5272 	ctx->clone->md_ro = ctx->clone_md_ro;
5273 
5274 	spdk_blob_close(ctx->clone, _spdk_delete_snapshot_cleanup_snapshot, ctx);
5275 }
5276 
5277 static void
5278 _spdk_delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
5279 {
5280 	struct delete_snapshot_ctx *ctx = cb_arg;
5281 
5282 	if (bserrno) {
5283 		ctx->bserrno = bserrno;
5284 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5285 		return;
5286 	}
5287 
5288 	ctx->clone->locked_operation_in_progress = false;
5289 	spdk_blob_close(ctx->clone, _spdk_delete_blob_cleanup_finish, ctx);
5290 }
5291 
5292 static void
5293 _spdk_delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
5294 {
5295 	struct delete_snapshot_ctx *ctx = cb_arg;
5296 	struct spdk_blob_list *parent_snapshot_entry = NULL;
5297 	struct spdk_blob_list *snapshot_entry = NULL;
5298 	struct spdk_blob_list *clone_entry = NULL;
5299 	struct spdk_blob_list *snapshot_clone_entry = NULL;
5300 
5301 	if (bserrno) {
5302 		SPDK_ERRLOG("Failed to sync MD on blob\n");
5303 		ctx->bserrno = bserrno;
5304 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5305 		return;
5306 	}
5307 
5308 	/* Get snapshot entry for the snapshot we want to remove */
5309 	snapshot_entry = _spdk_bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
5310 
5311 	assert(snapshot_entry != NULL);
5312 
5313 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
5314 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5315 	assert(clone_entry != NULL);
5316 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
5317 	snapshot_entry->clone_count--;
5318 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
5319 
5320 	if (ctx->snapshot->parent_id != SPDK_BLOBID_INVALID) {
5321 		/* This snapshot is at the same time a clone of another snapshot - we need to
5322 		 * update parent snapshot (remove current clone, add new one inherited from
5323 		 * the snapshot that is being removed) */
5324 
5325 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
5326 		 * snapshot that we are removing */
5327 		_spdk_blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
5328 				&snapshot_clone_entry);
5329 
5330 		/* Switch clone entry in parent snapshot */
5331 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
5332 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
5333 		free(snapshot_clone_entry);
5334 	} else {
5335 		/* No parent snapshot - just remove clone entry */
5336 		free(clone_entry);
5337 	}
5338 
5339 	/* Restore md_ro flags */
5340 	ctx->clone->md_ro = ctx->clone_md_ro;
5341 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
5342 
5343 	_spdk_blob_unfreeze_io(ctx->clone, _spdk_delete_snapshot_unfreeze_cpl, ctx);
5344 }
5345 
5346 static void
5347 _spdk_delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
5348 {
5349 	struct delete_snapshot_ctx *ctx = cb_arg;
5350 	uint64_t i;
5351 
5352 	ctx->snapshot->md_ro = false;
5353 
5354 	if (bserrno) {
5355 		SPDK_ERRLOG("Failed to sync MD on clone\n");
5356 		ctx->bserrno = bserrno;
5357 
5358 		/* Restore snapshot to previous state */
5359 		bserrno = _spdk_blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
5360 		if (bserrno != 0) {
5361 			_spdk_delete_snapshot_cleanup_clone(ctx, bserrno);
5362 			return;
5363 		}
5364 
5365 		spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_cleanup_clone, ctx);
5366 		return;
5367 	}
5368 
5369 	/* Clear cluster map entries for snapshot */
5370 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
5371 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
5372 			ctx->snapshot->active.clusters[i] = 0;
5373 		}
5374 	}
5375 
5376 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
5377 
5378 	if (ctx->parent_snapshot_entry != NULL) {
5379 		ctx->snapshot->back_bs_dev = NULL;
5380 	}
5381 
5382 	spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_sync_snapshot_cpl, ctx);
5383 }
5384 
5385 static void
5386 _spdk_delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
5387 {
5388 	struct delete_snapshot_ctx *ctx = cb_arg;
5389 	uint64_t i;
5390 
5391 	/* Temporarily override md_ro flag for clone for MD modification */
5392 	ctx->clone_md_ro = ctx->clone->md_ro;
5393 	ctx->clone->md_ro = false;
5394 
5395 	if (bserrno) {
5396 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
5397 		ctx->bserrno = bserrno;
5398 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5399 		return;
5400 	}
5401 
5402 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
5403 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
5404 		if (ctx->clone->active.clusters[i] == 0) {
5405 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
5406 		}
5407 	}
5408 
5409 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
5410 	ctx->clone->back_bs_dev->destroy(ctx->clone->back_bs_dev);
5411 
5412 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
5413 	if (ctx->parent_snapshot_entry != NULL) {
5414 		/* ...to parent snapshot */
5415 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
5416 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
5417 		_spdk_blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
5418 				     sizeof(spdk_blob_id),
5419 				     true);
5420 	} else {
5421 		/* ...to blobid invalid and zeroes dev */
5422 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
5423 		ctx->clone->back_bs_dev = spdk_bs_create_zeroes_dev();
5424 		_spdk_blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
5425 	}
5426 
5427 	spdk_blob_sync_md(ctx->clone, _spdk_delete_snapshot_sync_clone_cpl, ctx);
5428 }
5429 
5430 static void
5431 _spdk_delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
5432 {
5433 	struct delete_snapshot_ctx *ctx = cb_arg;
5434 
5435 	if (bserrno) {
5436 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
5437 		ctx->bserrno = bserrno;
5438 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5439 		return;
5440 	}
5441 
5442 	/* Temporarily override md_ro flag for snapshot for MD modification */
5443 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
5444 	ctx->snapshot->md_ro = false;
5445 
5446 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
5447 	ctx->bserrno = _spdk_blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
5448 					    sizeof(spdk_blob_id), true);
5449 	if (ctx->bserrno != 0) {
5450 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5451 		return;
5452 	}
5453 
5454 	spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_sync_snapshot_xattr_cpl, ctx);
5455 }
5456 
5457 static void
5458 _spdk_delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
5459 {
5460 	struct delete_snapshot_ctx *ctx = cb_arg;
5461 
5462 	if (bserrno) {
5463 		SPDK_ERRLOG("Failed to open clone\n");
5464 		ctx->bserrno = bserrno;
5465 		_spdk_delete_snapshot_cleanup_snapshot(ctx, 0);
5466 		return;
5467 	}
5468 
5469 	ctx->clone = clone;
5470 
5471 	if (clone->locked_operation_in_progress) {
5472 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress on its clone\n");
5473 		ctx->bserrno = -EBUSY;
5474 		spdk_blob_close(ctx->clone, _spdk_delete_snapshot_cleanup_snapshot, ctx);
5475 		return;
5476 	}
5477 
5478 	clone->locked_operation_in_progress = true;
5479 
5480 	_spdk_blob_freeze_io(clone, _spdk_delete_snapshot_freeze_io_cb, ctx);
5481 }
5482 
5483 static void
5484 _spdk_update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
5485 {
5486 	struct spdk_blob_list *snapshot_entry = NULL;
5487 	struct spdk_blob_list *clone_entry = NULL;
5488 	struct spdk_blob_list *snapshot_clone_entry = NULL;
5489 
5490 	/* Get snapshot entry for the snapshot we want to remove */
5491 	snapshot_entry = _spdk_bs_get_snapshot_entry(snapshot->bs, snapshot->id);
5492 
5493 	assert(snapshot_entry != NULL);
5494 
5495 	/* Get clone of the snapshot (at this point there can be only one clone) */
5496 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5497 	assert(snapshot_entry->clone_count == 1);
5498 	assert(clone_entry != NULL);
5499 
5500 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
5501 	 * snapshot that we are removing */
5502 	_spdk_blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
5503 			&snapshot_clone_entry);
5504 
5505 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, _spdk_delete_snapshot_open_clone_cb, ctx);
5506 }
5507 
5508 static void
5509 _spdk_bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
5510 {
5511 	spdk_bs_sequence_t *seq = cb_arg;
5512 	struct spdk_blob_list *snapshot_entry = NULL;
5513 	uint32_t page_num;
5514 
5515 	if (bserrno) {
5516 		SPDK_ERRLOG("Failed to remove blob\n");
5517 		spdk_bs_sequence_finish(seq, bserrno);
5518 		return;
5519 	}
5520 
5521 	/* Remove snapshot from the list */
5522 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
5523 	if (snapshot_entry != NULL) {
5524 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
5525 		free(snapshot_entry);
5526 	}
5527 
5528 	page_num = _spdk_bs_blobid_to_page(blob->id);
5529 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
5530 	blob->state = SPDK_BLOB_STATE_DIRTY;
5531 	blob->active.num_pages = 0;
5532 	_spdk_blob_resize(blob, 0);
5533 
5534 	_spdk_blob_persist(seq, blob, _spdk_bs_delete_persist_cpl, blob);
5535 }
5536 
5537 static int
5538 _spdk_bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
5539 {
5540 	struct spdk_blob_list *snapshot_entry = NULL;
5541 	struct spdk_blob_list *clone_entry = NULL;
5542 	struct spdk_blob *clone = NULL;
5543 	bool has_one_clone = false;
5544 
5545 	/* Check if this is a snapshot with clones */
5546 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
5547 	if (snapshot_entry != NULL) {
5548 		if (snapshot_entry->clone_count > 1) {
5549 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
5550 			return -EBUSY;
5551 		} else if (snapshot_entry->clone_count == 1) {
5552 			has_one_clone = true;
5553 		}
5554 	}
5555 
5556 	/* Check if someone has this blob open (besides this delete context):
5557 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
5558 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
5559 	 *	and that is ok, because we will update it accordingly */
5560 	if (blob->open_ref <= 2 && has_one_clone) {
5561 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5562 		assert(clone_entry != NULL);
5563 		clone = _spdk_blob_lookup(blob->bs, clone_entry->id);
5564 
5565 		if (blob->open_ref == 2 && clone == NULL) {
5566 			/* Clone is closed and someone else opened this blob */
5567 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
5568 			return -EBUSY;
5569 		}
5570 
5571 		*update_clone = true;
5572 		return 0;
5573 	}
5574 
5575 	if (blob->open_ref > 1) {
5576 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
5577 		return -EBUSY;
5578 	}
5579 
5580 	assert(has_one_clone == false);
5581 	*update_clone = false;
5582 	return 0;
5583 }
5584 
5585 static void
5586 _spdk_bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
5587 {
5588 	spdk_bs_sequence_t *seq = cb_arg;
5589 
5590 	spdk_bs_sequence_finish(seq, -ENOMEM);
5591 }
5592 
5593 static void
5594 _spdk_bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
5595 {
5596 	spdk_bs_sequence_t *seq = cb_arg;
5597 	struct delete_snapshot_ctx *ctx;
5598 	bool update_clone = false;
5599 
5600 	if (bserrno != 0) {
5601 		spdk_bs_sequence_finish(seq, bserrno);
5602 		return;
5603 	}
5604 
5605 	_spdk_blob_verify_md_op(blob);
5606 
5607 	ctx = calloc(1, sizeof(*ctx));
5608 	if (ctx == NULL) {
5609 		spdk_blob_close(blob, _spdk_bs_delete_enomem_close_cpl, seq);
5610 		return;
5611 	}
5612 
5613 	ctx->snapshot = blob;
5614 	ctx->cb_fn = _spdk_bs_delete_blob_finish;
5615 	ctx->cb_arg = seq;
5616 
5617 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
5618 	ctx->bserrno = _spdk_bs_is_blob_deletable(blob, &update_clone);
5619 	if (ctx->bserrno) {
5620 		spdk_blob_close(blob, _spdk_delete_blob_cleanup_finish, ctx);
5621 		return;
5622 	}
5623 
5624 	if (blob->locked_operation_in_progress) {
5625 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress\n");
5626 		ctx->bserrno = -EBUSY;
5627 		spdk_blob_close(blob, _spdk_delete_blob_cleanup_finish, ctx);
5628 		return;
5629 	}
5630 
5631 	blob->locked_operation_in_progress = true;
5632 
5633 	/*
5634 	 * Remove the blob from the blob_store list now, to ensure it does not
5635 	 *  get returned after this point by _spdk_blob_lookup().
5636 	 */
5637 	TAILQ_REMOVE(&blob->bs->blobs, blob, link);
5638 
5639 	if (update_clone) {
5640 		/* This blob is a snapshot with active clone - update clone first */
5641 		_spdk_update_clone_on_snapshot_deletion(blob, ctx);
5642 	} else {
5643 		/* This blob does not have any clones - just remove it */
5644 		_spdk_bs_blob_list_remove(blob);
5645 		_spdk_bs_delete_blob_finish(seq, blob, 0);
5646 		free(ctx);
5647 	}
5648 }
5649 
5650 void
5651 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5652 		    spdk_blob_op_complete cb_fn, void *cb_arg)
5653 {
5654 	struct spdk_bs_cpl	cpl;
5655 	spdk_bs_sequence_t	*seq;
5656 
5657 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Deleting blob %lu\n", blobid);
5658 
5659 	assert(spdk_get_thread() == bs->md_thread);
5660 
5661 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5662 	cpl.u.blob_basic.cb_fn = cb_fn;
5663 	cpl.u.blob_basic.cb_arg = cb_arg;
5664 
5665 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
5666 	if (!seq) {
5667 		cb_fn(cb_arg, -ENOMEM);
5668 		return;
5669 	}
5670 
5671 	spdk_bs_open_blob(bs, blobid, _spdk_bs_delete_open_cpl, seq);
5672 }
5673 
5674 /* END spdk_bs_delete_blob */
5675 
5676 /* START spdk_bs_open_blob */
5677 
5678 static void
5679 _spdk_bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5680 {
5681 	struct spdk_blob *blob = cb_arg;
5682 
5683 	/* If the blob have crc error, we just return NULL. */
5684 	if (blob == NULL) {
5685 		seq->cpl.u.blob_handle.blob = NULL;
5686 		spdk_bs_sequence_finish(seq, bserrno);
5687 		return;
5688 	}
5689 
5690 	blob->open_ref++;
5691 
5692 	TAILQ_INSERT_HEAD(&blob->bs->blobs, blob, link);
5693 
5694 	spdk_bs_sequence_finish(seq, bserrno);
5695 }
5696 
5697 static void _spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5698 			       struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5699 {
5700 	struct spdk_blob		*blob;
5701 	struct spdk_bs_cpl		cpl;
5702 	struct spdk_blob_open_opts	opts_default;
5703 	spdk_bs_sequence_t		*seq;
5704 	uint32_t			page_num;
5705 
5706 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Opening blob %lu\n", blobid);
5707 	assert(spdk_get_thread() == bs->md_thread);
5708 
5709 	page_num = _spdk_bs_blobid_to_page(blobid);
5710 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
5711 		/* Invalid blobid */
5712 		cb_fn(cb_arg, NULL, -ENOENT);
5713 		return;
5714 	}
5715 
5716 	blob = _spdk_blob_lookup(bs, blobid);
5717 	if (blob) {
5718 		blob->open_ref++;
5719 		cb_fn(cb_arg, blob, 0);
5720 		return;
5721 	}
5722 
5723 	blob = _spdk_blob_alloc(bs, blobid);
5724 	if (!blob) {
5725 		cb_fn(cb_arg, NULL, -ENOMEM);
5726 		return;
5727 	}
5728 
5729 	if (!opts) {
5730 		spdk_blob_open_opts_init(&opts_default);
5731 		opts = &opts_default;
5732 	}
5733 
5734 	blob->clear_method = opts->clear_method;
5735 
5736 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
5737 	cpl.u.blob_handle.cb_fn = cb_fn;
5738 	cpl.u.blob_handle.cb_arg = cb_arg;
5739 	cpl.u.blob_handle.blob = blob;
5740 
5741 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
5742 	if (!seq) {
5743 		_spdk_blob_free(blob);
5744 		cb_fn(cb_arg, NULL, -ENOMEM);
5745 		return;
5746 	}
5747 
5748 	_spdk_blob_load(seq, blob, _spdk_bs_open_blob_cpl, blob);
5749 }
5750 
5751 void spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5752 		       spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5753 {
5754 	_spdk_bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
5755 }
5756 
5757 void spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
5758 			   struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5759 {
5760 	_spdk_bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
5761 }
5762 
5763 /* END spdk_bs_open_blob */
5764 
5765 /* START spdk_blob_set_read_only */
5766 int spdk_blob_set_read_only(struct spdk_blob *blob)
5767 {
5768 	_spdk_blob_verify_md_op(blob);
5769 
5770 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
5771 
5772 	blob->state = SPDK_BLOB_STATE_DIRTY;
5773 	return 0;
5774 }
5775 /* END spdk_blob_set_read_only */
5776 
5777 /* START spdk_blob_sync_md */
5778 
5779 static void
5780 _spdk_blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5781 {
5782 	struct spdk_blob *blob = cb_arg;
5783 
5784 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
5785 		blob->data_ro = true;
5786 		blob->md_ro = true;
5787 	}
5788 
5789 	spdk_bs_sequence_finish(seq, bserrno);
5790 }
5791 
5792 static void
5793 _spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5794 {
5795 	struct spdk_bs_cpl	cpl;
5796 	spdk_bs_sequence_t	*seq;
5797 
5798 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5799 	cpl.u.blob_basic.cb_fn = cb_fn;
5800 	cpl.u.blob_basic.cb_arg = cb_arg;
5801 
5802 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
5803 	if (!seq) {
5804 		cb_fn(cb_arg, -ENOMEM);
5805 		return;
5806 	}
5807 
5808 	_spdk_blob_persist(seq, blob, _spdk_blob_sync_md_cpl, blob);
5809 }
5810 
5811 void
5812 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5813 {
5814 	_spdk_blob_verify_md_op(blob);
5815 
5816 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blob %lu\n", blob->id);
5817 
5818 	if (blob->md_ro) {
5819 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
5820 		cb_fn(cb_arg, 0);
5821 		return;
5822 	}
5823 
5824 	_spdk_blob_sync_md(blob, cb_fn, cb_arg);
5825 }
5826 
5827 /* END spdk_blob_sync_md */
5828 
5829 struct spdk_blob_insert_cluster_ctx {
5830 	struct spdk_thread	*thread;
5831 	struct spdk_blob	*blob;
5832 	uint32_t		cluster_num;	/* cluster index in blob */
5833 	uint32_t		cluster;	/* cluster on disk */
5834 	int			rc;
5835 	spdk_blob_op_complete	cb_fn;
5836 	void			*cb_arg;
5837 };
5838 
5839 static void
5840 _spdk_blob_insert_cluster_msg_cpl(void *arg)
5841 {
5842 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5843 
5844 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
5845 	free(ctx);
5846 }
5847 
5848 static void
5849 _spdk_blob_insert_cluster_msg_cb(void *arg, int bserrno)
5850 {
5851 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5852 
5853 	ctx->rc = bserrno;
5854 	spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
5855 }
5856 
5857 static void
5858 _spdk_blob_insert_cluster_msg(void *arg)
5859 {
5860 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5861 
5862 	ctx->rc = _spdk_blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
5863 	if (ctx->rc != 0) {
5864 		spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
5865 		return;
5866 	}
5867 
5868 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
5869 	_spdk_blob_sync_md(ctx->blob, _spdk_blob_insert_cluster_msg_cb, ctx);
5870 }
5871 
5872 static void
5873 _spdk_blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
5874 				       uint64_t cluster, spdk_blob_op_complete cb_fn, void *cb_arg)
5875 {
5876 	struct spdk_blob_insert_cluster_ctx *ctx;
5877 
5878 	ctx = calloc(1, sizeof(*ctx));
5879 	if (ctx == NULL) {
5880 		cb_fn(cb_arg, -ENOMEM);
5881 		return;
5882 	}
5883 
5884 	ctx->thread = spdk_get_thread();
5885 	ctx->blob = blob;
5886 	ctx->cluster_num = cluster_num;
5887 	ctx->cluster = cluster;
5888 	ctx->cb_fn = cb_fn;
5889 	ctx->cb_arg = cb_arg;
5890 
5891 	spdk_thread_send_msg(blob->bs->md_thread, _spdk_blob_insert_cluster_msg, ctx);
5892 }
5893 
5894 /* START spdk_blob_close */
5895 
5896 static void
5897 _spdk_blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5898 {
5899 	struct spdk_blob *blob = cb_arg;
5900 
5901 	if (bserrno == 0) {
5902 		blob->open_ref--;
5903 		if (blob->open_ref == 0) {
5904 			/*
5905 			 * Blobs with active.num_pages == 0 are deleted blobs.
5906 			 *  these blobs are removed from the blob_store list
5907 			 *  when the deletion process starts - so don't try to
5908 			 *  remove them again.
5909 			 */
5910 			if (blob->active.num_pages > 0) {
5911 				TAILQ_REMOVE(&blob->bs->blobs, blob, link);
5912 			}
5913 			_spdk_blob_free(blob);
5914 		}
5915 	}
5916 
5917 	spdk_bs_sequence_finish(seq, bserrno);
5918 }
5919 
5920 void spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5921 {
5922 	struct spdk_bs_cpl	cpl;
5923 	spdk_bs_sequence_t	*seq;
5924 
5925 	_spdk_blob_verify_md_op(blob);
5926 
5927 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Closing blob %lu\n", blob->id);
5928 
5929 	if (blob->open_ref == 0) {
5930 		cb_fn(cb_arg, -EBADF);
5931 		return;
5932 	}
5933 
5934 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5935 	cpl.u.blob_basic.cb_fn = cb_fn;
5936 	cpl.u.blob_basic.cb_arg = cb_arg;
5937 
5938 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
5939 	if (!seq) {
5940 		cb_fn(cb_arg, -ENOMEM);
5941 		return;
5942 	}
5943 
5944 	/* Sync metadata */
5945 	_spdk_blob_persist(seq, blob, _spdk_blob_close_cpl, blob);
5946 }
5947 
5948 /* END spdk_blob_close */
5949 
5950 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
5951 {
5952 	return spdk_get_io_channel(bs);
5953 }
5954 
5955 void spdk_bs_free_io_channel(struct spdk_io_channel *channel)
5956 {
5957 	spdk_put_io_channel(channel);
5958 }
5959 
5960 void spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
5961 			uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
5962 {
5963 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
5964 				     SPDK_BLOB_UNMAP);
5965 }
5966 
5967 void spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
5968 			       uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
5969 {
5970 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
5971 				     SPDK_BLOB_WRITE_ZEROES);
5972 }
5973 
5974 void spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
5975 			void *payload, uint64_t offset, uint64_t length,
5976 			spdk_blob_op_complete cb_fn, void *cb_arg)
5977 {
5978 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
5979 				     SPDK_BLOB_WRITE);
5980 }
5981 
5982 void spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
5983 		       void *payload, uint64_t offset, uint64_t length,
5984 		       spdk_blob_op_complete cb_fn, void *cb_arg)
5985 {
5986 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
5987 				     SPDK_BLOB_READ);
5988 }
5989 
5990 void spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
5991 			 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
5992 			 spdk_blob_op_complete cb_fn, void *cb_arg)
5993 {
5994 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false);
5995 }
5996 
5997 void spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
5998 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
5999 			spdk_blob_op_complete cb_fn, void *cb_arg)
6000 {
6001 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true);
6002 }
6003 
6004 struct spdk_bs_iter_ctx {
6005 	int64_t page_num;
6006 	struct spdk_blob_store *bs;
6007 
6008 	spdk_blob_op_with_handle_complete cb_fn;
6009 	void *cb_arg;
6010 };
6011 
6012 static void
6013 _spdk_bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6014 {
6015 	struct spdk_bs_iter_ctx *ctx = cb_arg;
6016 	struct spdk_blob_store *bs = ctx->bs;
6017 	spdk_blob_id id;
6018 
6019 	if (bserrno == 0) {
6020 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
6021 		free(ctx);
6022 		return;
6023 	}
6024 
6025 	ctx->page_num++;
6026 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
6027 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
6028 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
6029 		free(ctx);
6030 		return;
6031 	}
6032 
6033 	id = _spdk_bs_page_to_blobid(ctx->page_num);
6034 
6035 	spdk_bs_open_blob(bs, id, _spdk_bs_iter_cpl, ctx);
6036 }
6037 
6038 void
6039 spdk_bs_iter_first(struct spdk_blob_store *bs,
6040 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6041 {
6042 	struct spdk_bs_iter_ctx *ctx;
6043 
6044 	ctx = calloc(1, sizeof(*ctx));
6045 	if (!ctx) {
6046 		cb_fn(cb_arg, NULL, -ENOMEM);
6047 		return;
6048 	}
6049 
6050 	ctx->page_num = -1;
6051 	ctx->bs = bs;
6052 	ctx->cb_fn = cb_fn;
6053 	ctx->cb_arg = cb_arg;
6054 
6055 	_spdk_bs_iter_cpl(ctx, NULL, -1);
6056 }
6057 
6058 static void
6059 _spdk_bs_iter_close_cpl(void *cb_arg, int bserrno)
6060 {
6061 	struct spdk_bs_iter_ctx *ctx = cb_arg;
6062 
6063 	_spdk_bs_iter_cpl(ctx, NULL, -1);
6064 }
6065 
6066 void
6067 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
6068 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6069 {
6070 	struct spdk_bs_iter_ctx *ctx;
6071 
6072 	assert(blob != NULL);
6073 
6074 	ctx = calloc(1, sizeof(*ctx));
6075 	if (!ctx) {
6076 		cb_fn(cb_arg, NULL, -ENOMEM);
6077 		return;
6078 	}
6079 
6080 	ctx->page_num = _spdk_bs_blobid_to_page(blob->id);
6081 	ctx->bs = bs;
6082 	ctx->cb_fn = cb_fn;
6083 	ctx->cb_arg = cb_arg;
6084 
6085 	/* Close the existing blob */
6086 	spdk_blob_close(blob, _spdk_bs_iter_close_cpl, ctx);
6087 }
6088 
6089 static int
6090 _spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
6091 		     uint16_t value_len, bool internal)
6092 {
6093 	struct spdk_xattr_tailq *xattrs;
6094 	struct spdk_xattr	*xattr;
6095 	size_t			desc_size;
6096 
6097 	_spdk_blob_verify_md_op(blob);
6098 
6099 	if (blob->md_ro) {
6100 		return -EPERM;
6101 	}
6102 
6103 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
6104 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
6105 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Xattr '%s' of size %ld does not fix into single page %ld\n", name,
6106 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
6107 		return -ENOMEM;
6108 	}
6109 
6110 	if (internal) {
6111 		xattrs = &blob->xattrs_internal;
6112 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
6113 	} else {
6114 		xattrs = &blob->xattrs;
6115 	}
6116 
6117 	TAILQ_FOREACH(xattr, xattrs, link) {
6118 		if (!strcmp(name, xattr->name)) {
6119 			free(xattr->value);
6120 			xattr->value_len = value_len;
6121 			xattr->value = malloc(value_len);
6122 			memcpy(xattr->value, value, value_len);
6123 
6124 			blob->state = SPDK_BLOB_STATE_DIRTY;
6125 
6126 			return 0;
6127 		}
6128 	}
6129 
6130 	xattr = calloc(1, sizeof(*xattr));
6131 	if (!xattr) {
6132 		return -ENOMEM;
6133 	}
6134 	xattr->name = strdup(name);
6135 	xattr->value_len = value_len;
6136 	xattr->value = malloc(value_len);
6137 	memcpy(xattr->value, value, value_len);
6138 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
6139 
6140 	blob->state = SPDK_BLOB_STATE_DIRTY;
6141 
6142 	return 0;
6143 }
6144 
6145 int
6146 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
6147 		    uint16_t value_len)
6148 {
6149 	return _spdk_blob_set_xattr(blob, name, value, value_len, false);
6150 }
6151 
6152 static int
6153 _spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
6154 {
6155 	struct spdk_xattr_tailq *xattrs;
6156 	struct spdk_xattr	*xattr;
6157 
6158 	_spdk_blob_verify_md_op(blob);
6159 
6160 	if (blob->md_ro) {
6161 		return -EPERM;
6162 	}
6163 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
6164 
6165 	TAILQ_FOREACH(xattr, xattrs, link) {
6166 		if (!strcmp(name, xattr->name)) {
6167 			TAILQ_REMOVE(xattrs, xattr, link);
6168 			free(xattr->value);
6169 			free(xattr->name);
6170 			free(xattr);
6171 
6172 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
6173 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
6174 			}
6175 			blob->state = SPDK_BLOB_STATE_DIRTY;
6176 
6177 			return 0;
6178 		}
6179 	}
6180 
6181 	return -ENOENT;
6182 }
6183 
6184 int
6185 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
6186 {
6187 	return _spdk_blob_remove_xattr(blob, name, false);
6188 }
6189 
6190 static int
6191 _spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
6192 			   const void **value, size_t *value_len, bool internal)
6193 {
6194 	struct spdk_xattr	*xattr;
6195 	struct spdk_xattr_tailq *xattrs;
6196 
6197 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
6198 
6199 	TAILQ_FOREACH(xattr, xattrs, link) {
6200 		if (!strcmp(name, xattr->name)) {
6201 			*value = xattr->value;
6202 			*value_len = xattr->value_len;
6203 			return 0;
6204 		}
6205 	}
6206 	return -ENOENT;
6207 }
6208 
6209 int
6210 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
6211 			  const void **value, size_t *value_len)
6212 {
6213 	_spdk_blob_verify_md_op(blob);
6214 
6215 	return _spdk_blob_get_xattr_value(blob, name, value, value_len, false);
6216 }
6217 
6218 struct spdk_xattr_names {
6219 	uint32_t	count;
6220 	const char	*names[0];
6221 };
6222 
6223 static int
6224 _spdk_blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
6225 {
6226 	struct spdk_xattr	*xattr;
6227 	int			count = 0;
6228 
6229 	TAILQ_FOREACH(xattr, xattrs, link) {
6230 		count++;
6231 	}
6232 
6233 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
6234 	if (*names == NULL) {
6235 		return -ENOMEM;
6236 	}
6237 
6238 	TAILQ_FOREACH(xattr, xattrs, link) {
6239 		(*names)->names[(*names)->count++] = xattr->name;
6240 	}
6241 
6242 	return 0;
6243 }
6244 
6245 int
6246 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
6247 {
6248 	_spdk_blob_verify_md_op(blob);
6249 
6250 	return _spdk_blob_get_xattr_names(&blob->xattrs, names);
6251 }
6252 
6253 uint32_t
6254 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
6255 {
6256 	assert(names != NULL);
6257 
6258 	return names->count;
6259 }
6260 
6261 const char *
6262 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
6263 {
6264 	if (index >= names->count) {
6265 		return NULL;
6266 	}
6267 
6268 	return names->names[index];
6269 }
6270 
6271 void
6272 spdk_xattr_names_free(struct spdk_xattr_names *names)
6273 {
6274 	free(names);
6275 }
6276 
6277 struct spdk_bs_type
6278 spdk_bs_get_bstype(struct spdk_blob_store *bs)
6279 {
6280 	return bs->bstype;
6281 }
6282 
6283 void
6284 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
6285 {
6286 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
6287 }
6288 
6289 bool
6290 spdk_blob_is_read_only(struct spdk_blob *blob)
6291 {
6292 	assert(blob != NULL);
6293 	return (blob->data_ro || blob->md_ro);
6294 }
6295 
6296 bool
6297 spdk_blob_is_snapshot(struct spdk_blob *blob)
6298 {
6299 	struct spdk_blob_list *snapshot_entry;
6300 
6301 	assert(blob != NULL);
6302 
6303 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
6304 	if (snapshot_entry == NULL) {
6305 		return false;
6306 	}
6307 
6308 	return true;
6309 }
6310 
6311 bool
6312 spdk_blob_is_clone(struct spdk_blob *blob)
6313 {
6314 	assert(blob != NULL);
6315 
6316 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
6317 		assert(spdk_blob_is_thin_provisioned(blob));
6318 		return true;
6319 	}
6320 
6321 	return false;
6322 }
6323 
6324 bool
6325 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
6326 {
6327 	assert(blob != NULL);
6328 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
6329 }
6330 
6331 spdk_blob_id
6332 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
6333 {
6334 	struct spdk_blob_list *snapshot_entry = NULL;
6335 	struct spdk_blob_list *clone_entry = NULL;
6336 
6337 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
6338 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
6339 			if (clone_entry->id == blob_id) {
6340 				return snapshot_entry->id;
6341 			}
6342 		}
6343 	}
6344 
6345 	return SPDK_BLOBID_INVALID;
6346 }
6347 
6348 int
6349 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
6350 		     size_t *count)
6351 {
6352 	struct spdk_blob_list *snapshot_entry, *clone_entry;
6353 	size_t n;
6354 
6355 	snapshot_entry = _spdk_bs_get_snapshot_entry(bs, blobid);
6356 	if (snapshot_entry == NULL) {
6357 		*count = 0;
6358 		return 0;
6359 	}
6360 
6361 	if (ids == NULL || *count < snapshot_entry->clone_count) {
6362 		*count = snapshot_entry->clone_count;
6363 		return -ENOMEM;
6364 	}
6365 	*count = snapshot_entry->clone_count;
6366 
6367 	n = 0;
6368 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
6369 		ids[n++] = clone_entry->id;
6370 	}
6371 
6372 	return 0;
6373 }
6374 
6375 SPDK_LOG_REGISTER_COMPONENT("blob", SPDK_LOG_BLOB)
6376