xref: /spdk/lib/blob/blobstore.c (revision 12fbe739a31b09aff0d05f354d4f3bbef99afc55)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2017 Intel Corporation.
3  *   All rights reserved.
4  *   Copyright (c) 2021-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/blob.h"
10 #include "spdk/crc32.h"
11 #include "spdk/env.h"
12 #include "spdk/queue.h"
13 #include "spdk/thread.h"
14 #include "spdk/bit_array.h"
15 #include "spdk/bit_pool.h"
16 #include "spdk/likely.h"
17 #include "spdk/util.h"
18 #include "spdk/string.h"
19 
20 #include "spdk_internal/assert.h"
21 #include "spdk/log.h"
22 
23 #include "blobstore.h"
24 
25 #define BLOB_CRC32C_INITIAL    0xffffffffUL
26 
27 static int bs_register_md_thread(struct spdk_blob_store *bs);
28 static int bs_unregister_md_thread(struct spdk_blob_store *bs);
29 static void blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno);
30 static void blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
31 		uint64_t cluster, uint32_t extent, struct spdk_blob_md_page *page,
32 		spdk_blob_op_complete cb_fn, void *cb_arg);
33 
34 static int blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
35 			  uint16_t value_len, bool internal);
36 static int blob_get_xattr_value(struct spdk_blob *blob, const char *name,
37 				const void **value, size_t *value_len, bool internal);
38 static int blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal);
39 
40 static void blob_write_extent_page(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
41 				   struct spdk_blob_md_page *page, spdk_blob_op_complete cb_fn, void *cb_arg);
42 
43 /*
44  * External snapshots require a channel per thread per esnap bdev.  The tree
45  * is populated lazily as blob IOs are handled by the back_bs_dev. When this
46  * channel is destroyed, all the channels in the tree are destroyed.
47  */
48 
49 struct blob_esnap_channel {
50 	RB_ENTRY(blob_esnap_channel)	node;
51 	spdk_blob_id			blob_id;
52 	struct spdk_io_channel		*channel;
53 };
54 
55 static int blob_esnap_channel_compare(struct blob_esnap_channel *c1, struct blob_esnap_channel *c2);
56 static void blob_esnap_destroy_bs_dev_channels(struct spdk_blob *blob, bool abort_io,
57 		spdk_blob_op_with_handle_complete cb_fn, void *cb_arg);
58 static void blob_esnap_destroy_bs_channel(struct spdk_bs_channel *ch);
59 RB_GENERATE_STATIC(blob_esnap_channel_tree, blob_esnap_channel, node, blob_esnap_channel_compare)
60 
61 static inline bool
62 blob_is_esnap_clone(const struct spdk_blob *blob)
63 {
64 	assert(blob != NULL);
65 	return !!(blob->invalid_flags & SPDK_BLOB_EXTERNAL_SNAPSHOT);
66 }
67 
68 static int
69 blob_id_cmp(struct spdk_blob *blob1, struct spdk_blob *blob2)
70 {
71 	assert(blob1 != NULL && blob2 != NULL);
72 	return (blob1->id < blob2->id ? -1 : blob1->id > blob2->id);
73 }
74 
75 RB_GENERATE_STATIC(spdk_blob_tree, spdk_blob, link, blob_id_cmp);
76 
77 static void
78 blob_verify_md_op(struct spdk_blob *blob)
79 {
80 	assert(blob != NULL);
81 	assert(spdk_get_thread() == blob->bs->md_thread);
82 	assert(blob->state != SPDK_BLOB_STATE_LOADING);
83 }
84 
85 static struct spdk_blob_list *
86 bs_get_snapshot_entry(struct spdk_blob_store *bs, spdk_blob_id blobid)
87 {
88 	struct spdk_blob_list *snapshot_entry = NULL;
89 
90 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
91 		if (snapshot_entry->id == blobid) {
92 			break;
93 		}
94 	}
95 
96 	return snapshot_entry;
97 }
98 
99 static void
100 bs_claim_md_page(struct spdk_blob_store *bs, uint32_t page)
101 {
102 	assert(spdk_spin_held(&bs->used_lock));
103 	assert(page < spdk_bit_array_capacity(bs->used_md_pages));
104 	assert(spdk_bit_array_get(bs->used_md_pages, page) == false);
105 
106 	spdk_bit_array_set(bs->used_md_pages, page);
107 }
108 
109 static void
110 bs_release_md_page(struct spdk_blob_store *bs, uint32_t page)
111 {
112 	assert(spdk_spin_held(&bs->used_lock));
113 	assert(page < spdk_bit_array_capacity(bs->used_md_pages));
114 	assert(spdk_bit_array_get(bs->used_md_pages, page) == true);
115 
116 	spdk_bit_array_clear(bs->used_md_pages, page);
117 }
118 
119 static uint32_t
120 bs_claim_cluster(struct spdk_blob_store *bs)
121 {
122 	uint32_t cluster_num;
123 
124 	assert(spdk_spin_held(&bs->used_lock));
125 
126 	cluster_num = spdk_bit_pool_allocate_bit(bs->used_clusters);
127 	if (cluster_num == UINT32_MAX) {
128 		return UINT32_MAX;
129 	}
130 
131 	SPDK_DEBUGLOG(blob, "Claiming cluster %u\n", cluster_num);
132 	bs->num_free_clusters--;
133 
134 	return cluster_num;
135 }
136 
137 static void
138 bs_release_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
139 {
140 	assert(spdk_spin_held(&bs->used_lock));
141 	assert(cluster_num < spdk_bit_pool_capacity(bs->used_clusters));
142 	assert(spdk_bit_pool_is_allocated(bs->used_clusters, cluster_num) == true);
143 	assert(bs->num_free_clusters < bs->total_clusters);
144 
145 	SPDK_DEBUGLOG(blob, "Releasing cluster %u\n", cluster_num);
146 
147 	spdk_bit_pool_free_bit(bs->used_clusters, cluster_num);
148 	bs->num_free_clusters++;
149 }
150 
151 static int
152 blob_insert_cluster(struct spdk_blob *blob, uint32_t cluster_num, uint64_t cluster)
153 {
154 	uint64_t *cluster_lba = &blob->active.clusters[cluster_num];
155 
156 	blob_verify_md_op(blob);
157 
158 	if (*cluster_lba != 0) {
159 		return -EEXIST;
160 	}
161 
162 	*cluster_lba = bs_cluster_to_lba(blob->bs, cluster);
163 	return 0;
164 }
165 
166 static int
167 bs_allocate_cluster(struct spdk_blob *blob, uint32_t cluster_num,
168 		    uint64_t *cluster, uint32_t *lowest_free_md_page, bool update_map)
169 {
170 	uint32_t *extent_page = 0;
171 
172 	assert(spdk_spin_held(&blob->bs->used_lock));
173 
174 	*cluster = bs_claim_cluster(blob->bs);
175 	if (*cluster == UINT32_MAX) {
176 		/* No more free clusters. Cannot satisfy the request */
177 		return -ENOSPC;
178 	}
179 
180 	if (blob->use_extent_table) {
181 		extent_page = bs_cluster_to_extent_page(blob, cluster_num);
182 		if (*extent_page == 0) {
183 			/* Extent page shall never occupy md_page so start the search from 1 */
184 			if (*lowest_free_md_page == 0) {
185 				*lowest_free_md_page = 1;
186 			}
187 			/* No extent_page is allocated for the cluster */
188 			*lowest_free_md_page = spdk_bit_array_find_first_clear(blob->bs->used_md_pages,
189 					       *lowest_free_md_page);
190 			if (*lowest_free_md_page == UINT32_MAX) {
191 				/* No more free md pages. Cannot satisfy the request */
192 				bs_release_cluster(blob->bs, *cluster);
193 				return -ENOSPC;
194 			}
195 			bs_claim_md_page(blob->bs, *lowest_free_md_page);
196 		}
197 	}
198 
199 	SPDK_DEBUGLOG(blob, "Claiming cluster %" PRIu64 " for blob 0x%" PRIx64 "\n", *cluster,
200 		      blob->id);
201 
202 	if (update_map) {
203 		blob_insert_cluster(blob, cluster_num, *cluster);
204 		if (blob->use_extent_table && *extent_page == 0) {
205 			*extent_page = *lowest_free_md_page;
206 		}
207 	}
208 
209 	return 0;
210 }
211 
212 static void
213 blob_xattrs_init(struct spdk_blob_xattr_opts *xattrs)
214 {
215 	xattrs->count = 0;
216 	xattrs->names = NULL;
217 	xattrs->ctx = NULL;
218 	xattrs->get_value = NULL;
219 }
220 
221 void
222 spdk_blob_opts_init(struct spdk_blob_opts *opts, size_t opts_size)
223 {
224 	if (!opts) {
225 		SPDK_ERRLOG("opts should not be NULL\n");
226 		return;
227 	}
228 
229 	if (!opts_size) {
230 		SPDK_ERRLOG("opts_size should not be zero value\n");
231 		return;
232 	}
233 
234 	memset(opts, 0, opts_size);
235 	opts->opts_size = opts_size;
236 
237 #define FIELD_OK(field) \
238         offsetof(struct spdk_blob_opts, field) + sizeof(opts->field) <= opts_size
239 
240 #define SET_FIELD(field, value) \
241         if (FIELD_OK(field)) { \
242                 opts->field = value; \
243         } \
244 
245 	SET_FIELD(num_clusters, 0);
246 	SET_FIELD(thin_provision, false);
247 	SET_FIELD(clear_method, BLOB_CLEAR_WITH_DEFAULT);
248 
249 	if (FIELD_OK(xattrs)) {
250 		blob_xattrs_init(&opts->xattrs);
251 	}
252 
253 	SET_FIELD(use_extent_table, true);
254 
255 #undef FIELD_OK
256 #undef SET_FIELD
257 }
258 
259 void
260 spdk_blob_open_opts_init(struct spdk_blob_open_opts *opts, size_t opts_size)
261 {
262 	if (!opts) {
263 		SPDK_ERRLOG("opts should not be NULL\n");
264 		return;
265 	}
266 
267 	if (!opts_size) {
268 		SPDK_ERRLOG("opts_size should not be zero value\n");
269 		return;
270 	}
271 
272 	memset(opts, 0, opts_size);
273 	opts->opts_size = opts_size;
274 
275 #define FIELD_OK(field) \
276         offsetof(struct spdk_blob_open_opts, field) + sizeof(opts->field) <= opts_size
277 
278 #define SET_FIELD(field, value) \
279         if (FIELD_OK(field)) { \
280                 opts->field = value; \
281         } \
282 
283 	SET_FIELD(clear_method, BLOB_CLEAR_WITH_DEFAULT);
284 
285 #undef FIELD_OK
286 #undef SET_FILED
287 }
288 
289 static struct spdk_blob *
290 blob_alloc(struct spdk_blob_store *bs, spdk_blob_id id)
291 {
292 	struct spdk_blob *blob;
293 
294 	blob = calloc(1, sizeof(*blob));
295 	if (!blob) {
296 		return NULL;
297 	}
298 
299 	blob->id = id;
300 	blob->bs = bs;
301 
302 	blob->parent_id = SPDK_BLOBID_INVALID;
303 
304 	blob->state = SPDK_BLOB_STATE_DIRTY;
305 	blob->extent_rle_found = false;
306 	blob->extent_table_found = false;
307 	blob->active.num_pages = 1;
308 	blob->active.pages = calloc(1, sizeof(*blob->active.pages));
309 	if (!blob->active.pages) {
310 		free(blob);
311 		return NULL;
312 	}
313 
314 	blob->active.pages[0] = bs_blobid_to_page(id);
315 
316 	TAILQ_INIT(&blob->xattrs);
317 	TAILQ_INIT(&blob->xattrs_internal);
318 	TAILQ_INIT(&blob->pending_persists);
319 	TAILQ_INIT(&blob->persists_to_complete);
320 
321 	return blob;
322 }
323 
324 static void
325 xattrs_free(struct spdk_xattr_tailq *xattrs)
326 {
327 	struct spdk_xattr	*xattr, *xattr_tmp;
328 
329 	TAILQ_FOREACH_SAFE(xattr, xattrs, link, xattr_tmp) {
330 		TAILQ_REMOVE(xattrs, xattr, link);
331 		free(xattr->name);
332 		free(xattr->value);
333 		free(xattr);
334 	}
335 }
336 
337 static void
338 blob_free(struct spdk_blob *blob)
339 {
340 	assert(blob != NULL);
341 	assert(TAILQ_EMPTY(&blob->pending_persists));
342 	assert(TAILQ_EMPTY(&blob->persists_to_complete));
343 
344 	free(blob->active.extent_pages);
345 	free(blob->clean.extent_pages);
346 	free(blob->active.clusters);
347 	free(blob->clean.clusters);
348 	free(blob->active.pages);
349 	free(blob->clean.pages);
350 
351 	xattrs_free(&blob->xattrs);
352 	xattrs_free(&blob->xattrs_internal);
353 
354 	if (blob->back_bs_dev) {
355 		blob->back_bs_dev->destroy(blob->back_bs_dev);
356 	}
357 
358 	free(blob);
359 }
360 
361 static void
362 blob_back_bs_destroy_esnap_done(void *ctx, struct spdk_blob *blob, int bserrno)
363 {
364 	struct spdk_bs_dev	*bs_dev = ctx;
365 
366 	if (bserrno != 0) {
367 		/*
368 		 * This is probably due to a memory allocation failure when creating the
369 		 * blob_esnap_destroy_ctx before iterating threads.
370 		 */
371 		SPDK_ERRLOG("blob 0x%" PRIx64 ": Unable to destroy bs dev channels: error %d\n",
372 			    blob->id, bserrno);
373 		assert(false);
374 	}
375 
376 	if (bs_dev == NULL) {
377 		/*
378 		 * This check exists to make scanbuild happy.
379 		 *
380 		 * blob->back_bs_dev for an esnap is NULL during the first iteration of blobs while
381 		 * the blobstore is being loaded. It could also be NULL if there was an error
382 		 * opening the esnap device. In each of these cases, no channels could have been
383 		 * created because back_bs_dev->create_channel() would have led to a NULL pointer
384 		 * deref.
385 		 */
386 		assert(false);
387 		return;
388 	}
389 
390 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": calling destroy on back_bs_dev\n", blob->id);
391 	bs_dev->destroy(bs_dev);
392 }
393 
394 static void
395 blob_back_bs_destroy(struct spdk_blob *blob)
396 {
397 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": preparing to destroy back_bs_dev\n",
398 		      blob->id);
399 
400 	blob_esnap_destroy_bs_dev_channels(blob, false, blob_back_bs_destroy_esnap_done,
401 					   blob->back_bs_dev);
402 	blob->back_bs_dev = NULL;
403 }
404 
405 struct freeze_io_ctx {
406 	struct spdk_bs_cpl cpl;
407 	struct spdk_blob *blob;
408 };
409 
410 static void
411 blob_io_sync(struct spdk_io_channel_iter *i)
412 {
413 	spdk_for_each_channel_continue(i, 0);
414 }
415 
416 static void
417 blob_execute_queued_io(struct spdk_io_channel_iter *i)
418 {
419 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
420 	struct spdk_bs_channel *ch = spdk_io_channel_get_ctx(_ch);
421 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
422 	struct spdk_bs_request_set	*set;
423 	struct spdk_bs_user_op_args	*args;
424 	spdk_bs_user_op_t *op, *tmp;
425 
426 	TAILQ_FOREACH_SAFE(op, &ch->queued_io, link, tmp) {
427 		set = (struct spdk_bs_request_set *)op;
428 		args = &set->u.user_op;
429 
430 		if (args->blob == ctx->blob) {
431 			TAILQ_REMOVE(&ch->queued_io, op, link);
432 			bs_user_op_execute(op);
433 		}
434 	}
435 
436 	spdk_for_each_channel_continue(i, 0);
437 }
438 
439 static void
440 blob_io_cpl(struct spdk_io_channel_iter *i, int status)
441 {
442 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
443 
444 	ctx->cpl.u.blob_basic.cb_fn(ctx->cpl.u.blob_basic.cb_arg, 0);
445 
446 	free(ctx);
447 }
448 
449 static void
450 blob_freeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
451 {
452 	struct freeze_io_ctx *ctx;
453 
454 	blob_verify_md_op(blob);
455 
456 	ctx = calloc(1, sizeof(*ctx));
457 	if (!ctx) {
458 		cb_fn(cb_arg, -ENOMEM);
459 		return;
460 	}
461 
462 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
463 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
464 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
465 	ctx->blob = blob;
466 
467 	/* Freeze I/O on blob */
468 	blob->frozen_refcnt++;
469 
470 	spdk_for_each_channel(blob->bs, blob_io_sync, ctx, blob_io_cpl);
471 }
472 
473 static void
474 blob_unfreeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
475 {
476 	struct freeze_io_ctx *ctx;
477 
478 	blob_verify_md_op(blob);
479 
480 	ctx = calloc(1, sizeof(*ctx));
481 	if (!ctx) {
482 		cb_fn(cb_arg, -ENOMEM);
483 		return;
484 	}
485 
486 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
487 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
488 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
489 	ctx->blob = blob;
490 
491 	assert(blob->frozen_refcnt > 0);
492 
493 	blob->frozen_refcnt--;
494 
495 	spdk_for_each_channel(blob->bs, blob_execute_queued_io, ctx, blob_io_cpl);
496 }
497 
498 static int
499 blob_mark_clean(struct spdk_blob *blob)
500 {
501 	uint32_t *extent_pages = NULL;
502 	uint64_t *clusters = NULL;
503 	uint32_t *pages = NULL;
504 
505 	assert(blob != NULL);
506 
507 	if (blob->active.num_extent_pages) {
508 		assert(blob->active.extent_pages);
509 		extent_pages = calloc(blob->active.num_extent_pages, sizeof(*blob->active.extent_pages));
510 		if (!extent_pages) {
511 			return -ENOMEM;
512 		}
513 		memcpy(extent_pages, blob->active.extent_pages,
514 		       blob->active.num_extent_pages * sizeof(*extent_pages));
515 	}
516 
517 	if (blob->active.num_clusters) {
518 		assert(blob->active.clusters);
519 		clusters = calloc(blob->active.num_clusters, sizeof(*blob->active.clusters));
520 		if (!clusters) {
521 			free(extent_pages);
522 			return -ENOMEM;
523 		}
524 		memcpy(clusters, blob->active.clusters, blob->active.num_clusters * sizeof(*blob->active.clusters));
525 	}
526 
527 	if (blob->active.num_pages) {
528 		assert(blob->active.pages);
529 		pages = calloc(blob->active.num_pages, sizeof(*blob->active.pages));
530 		if (!pages) {
531 			free(extent_pages);
532 			free(clusters);
533 			return -ENOMEM;
534 		}
535 		memcpy(pages, blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
536 	}
537 
538 	free(blob->clean.extent_pages);
539 	free(blob->clean.clusters);
540 	free(blob->clean.pages);
541 
542 	blob->clean.num_extent_pages = blob->active.num_extent_pages;
543 	blob->clean.extent_pages = blob->active.extent_pages;
544 	blob->clean.num_clusters = blob->active.num_clusters;
545 	blob->clean.clusters = blob->active.clusters;
546 	blob->clean.num_pages = blob->active.num_pages;
547 	blob->clean.pages = blob->active.pages;
548 
549 	blob->active.extent_pages = extent_pages;
550 	blob->active.clusters = clusters;
551 	blob->active.pages = pages;
552 
553 	/* If the metadata was dirtied again while the metadata was being written to disk,
554 	 *  we do not want to revert the DIRTY state back to CLEAN here.
555 	 */
556 	if (blob->state == SPDK_BLOB_STATE_LOADING) {
557 		blob->state = SPDK_BLOB_STATE_CLEAN;
558 	}
559 
560 	return 0;
561 }
562 
563 static int
564 blob_deserialize_xattr(struct spdk_blob *blob,
565 		       struct spdk_blob_md_descriptor_xattr *desc_xattr, bool internal)
566 {
567 	struct spdk_xattr                       *xattr;
568 
569 	if (desc_xattr->length != sizeof(desc_xattr->name_length) +
570 	    sizeof(desc_xattr->value_length) +
571 	    desc_xattr->name_length + desc_xattr->value_length) {
572 		return -EINVAL;
573 	}
574 
575 	xattr = calloc(1, sizeof(*xattr));
576 	if (xattr == NULL) {
577 		return -ENOMEM;
578 	}
579 
580 	xattr->name = malloc(desc_xattr->name_length + 1);
581 	if (xattr->name == NULL) {
582 		free(xattr);
583 		return -ENOMEM;
584 	}
585 
586 	xattr->value = malloc(desc_xattr->value_length);
587 	if (xattr->value == NULL) {
588 		free(xattr->name);
589 		free(xattr);
590 		return -ENOMEM;
591 	}
592 
593 	memcpy(xattr->name, desc_xattr->name, desc_xattr->name_length);
594 	xattr->name[desc_xattr->name_length] = '\0';
595 	xattr->value_len = desc_xattr->value_length;
596 	memcpy(xattr->value,
597 	       (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
598 	       desc_xattr->value_length);
599 
600 	TAILQ_INSERT_TAIL(internal ? &blob->xattrs_internal : &blob->xattrs, xattr, link);
601 
602 	return 0;
603 }
604 
605 
606 static int
607 blob_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob *blob)
608 {
609 	struct spdk_blob_md_descriptor *desc;
610 	size_t	cur_desc = 0;
611 	void *tmp;
612 
613 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
614 	while (cur_desc < sizeof(page->descriptors)) {
615 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
616 			if (desc->length == 0) {
617 				/* If padding and length are 0, this terminates the page */
618 				break;
619 			}
620 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
621 			struct spdk_blob_md_descriptor_flags	*desc_flags;
622 
623 			desc_flags = (struct spdk_blob_md_descriptor_flags *)desc;
624 
625 			if (desc_flags->length != sizeof(*desc_flags) - sizeof(*desc)) {
626 				return -EINVAL;
627 			}
628 
629 			if ((desc_flags->invalid_flags | SPDK_BLOB_INVALID_FLAGS_MASK) !=
630 			    SPDK_BLOB_INVALID_FLAGS_MASK) {
631 				return -EINVAL;
632 			}
633 
634 			if ((desc_flags->data_ro_flags | SPDK_BLOB_DATA_RO_FLAGS_MASK) !=
635 			    SPDK_BLOB_DATA_RO_FLAGS_MASK) {
636 				blob->data_ro = true;
637 				blob->md_ro = true;
638 			}
639 
640 			if ((desc_flags->md_ro_flags | SPDK_BLOB_MD_RO_FLAGS_MASK) !=
641 			    SPDK_BLOB_MD_RO_FLAGS_MASK) {
642 				blob->md_ro = true;
643 			}
644 
645 			if ((desc_flags->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
646 				blob->data_ro = true;
647 				blob->md_ro = true;
648 			}
649 
650 			blob->invalid_flags = desc_flags->invalid_flags;
651 			blob->data_ro_flags = desc_flags->data_ro_flags;
652 			blob->md_ro_flags = desc_flags->md_ro_flags;
653 
654 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
655 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
656 			unsigned int				i, j;
657 			unsigned int				cluster_count = blob->active.num_clusters;
658 
659 			if (blob->extent_table_found) {
660 				/* Extent Table already present in the md,
661 				 * both descriptors should never be at the same time. */
662 				return -EINVAL;
663 			}
664 			blob->extent_rle_found = true;
665 
666 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
667 
668 			if (desc_extent_rle->length == 0 ||
669 			    (desc_extent_rle->length % sizeof(desc_extent_rle->extents[0]) != 0)) {
670 				return -EINVAL;
671 			}
672 
673 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
674 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
675 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
676 						if (!spdk_bit_pool_is_allocated(blob->bs->used_clusters,
677 										desc_extent_rle->extents[i].cluster_idx + j)) {
678 							return -EINVAL;
679 						}
680 					}
681 					cluster_count++;
682 				}
683 			}
684 
685 			if (cluster_count == 0) {
686 				return -EINVAL;
687 			}
688 			tmp = realloc(blob->active.clusters, cluster_count * sizeof(*blob->active.clusters));
689 			if (tmp == NULL) {
690 				return -ENOMEM;
691 			}
692 			blob->active.clusters = tmp;
693 			blob->active.cluster_array_size = cluster_count;
694 
695 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
696 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
697 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
698 						blob->active.clusters[blob->active.num_clusters++] = bs_cluster_to_lba(blob->bs,
699 								desc_extent_rle->extents[i].cluster_idx + j);
700 					} else if (spdk_blob_is_thin_provisioned(blob)) {
701 						blob->active.clusters[blob->active.num_clusters++] = 0;
702 					} else {
703 						return -EINVAL;
704 					}
705 				}
706 			}
707 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE) {
708 			struct spdk_blob_md_descriptor_extent_table *desc_extent_table;
709 			uint32_t num_extent_pages = blob->active.num_extent_pages;
710 			uint32_t i, j;
711 			size_t extent_pages_length;
712 
713 			desc_extent_table = (struct spdk_blob_md_descriptor_extent_table *)desc;
714 			extent_pages_length = desc_extent_table->length - sizeof(desc_extent_table->num_clusters);
715 
716 			if (blob->extent_rle_found) {
717 				/* This means that Extent RLE is present in MD,
718 				 * both should never be at the same time. */
719 				return -EINVAL;
720 			} else if (blob->extent_table_found &&
721 				   desc_extent_table->num_clusters != blob->remaining_clusters_in_et) {
722 				/* Number of clusters in this ET does not match number
723 				 * from previously read EXTENT_TABLE. */
724 				return -EINVAL;
725 			}
726 
727 			if (desc_extent_table->length == 0 ||
728 			    (extent_pages_length % sizeof(desc_extent_table->extent_page[0]) != 0)) {
729 				return -EINVAL;
730 			}
731 
732 			blob->extent_table_found = true;
733 
734 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
735 				num_extent_pages += desc_extent_table->extent_page[i].num_pages;
736 			}
737 
738 			if (num_extent_pages > 0) {
739 				tmp = realloc(blob->active.extent_pages, num_extent_pages * sizeof(uint32_t));
740 				if (tmp == NULL) {
741 					return -ENOMEM;
742 				}
743 				blob->active.extent_pages = tmp;
744 			}
745 			blob->active.extent_pages_array_size = num_extent_pages;
746 
747 			blob->remaining_clusters_in_et = desc_extent_table->num_clusters;
748 
749 			/* Extent table entries contain md page numbers for extent pages.
750 			 * Zeroes represent unallocated extent pages, those are run-length-encoded.
751 			 */
752 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
753 				if (desc_extent_table->extent_page[i].page_idx != 0) {
754 					assert(desc_extent_table->extent_page[i].num_pages == 1);
755 					blob->active.extent_pages[blob->active.num_extent_pages++] =
756 						desc_extent_table->extent_page[i].page_idx;
757 				} else if (spdk_blob_is_thin_provisioned(blob)) {
758 					for (j = 0; j < desc_extent_table->extent_page[i].num_pages; j++) {
759 						blob->active.extent_pages[blob->active.num_extent_pages++] = 0;
760 					}
761 				} else {
762 					return -EINVAL;
763 				}
764 			}
765 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
766 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
767 			unsigned int					i;
768 			unsigned int					cluster_count = 0;
769 			size_t						cluster_idx_length;
770 
771 			if (blob->extent_rle_found) {
772 				/* This means that Extent RLE is present in MD,
773 				 * both should never be at the same time. */
774 				return -EINVAL;
775 			}
776 
777 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
778 			cluster_idx_length = desc_extent->length - sizeof(desc_extent->start_cluster_idx);
779 
780 			if (desc_extent->length <= sizeof(desc_extent->start_cluster_idx) ||
781 			    (cluster_idx_length % sizeof(desc_extent->cluster_idx[0]) != 0)) {
782 				return -EINVAL;
783 			}
784 
785 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
786 				if (desc_extent->cluster_idx[i] != 0) {
787 					if (!spdk_bit_pool_is_allocated(blob->bs->used_clusters, desc_extent->cluster_idx[i])) {
788 						return -EINVAL;
789 					}
790 				}
791 				cluster_count++;
792 			}
793 
794 			if (cluster_count == 0) {
795 				return -EINVAL;
796 			}
797 
798 			/* When reading extent pages sequentially starting cluster idx should match
799 			 * current size of a blob.
800 			 * If changed to batch reading, this check shall be removed. */
801 			if (desc_extent->start_cluster_idx != blob->active.num_clusters) {
802 				return -EINVAL;
803 			}
804 
805 			tmp = realloc(blob->active.clusters,
806 				      (cluster_count + blob->active.num_clusters) * sizeof(*blob->active.clusters));
807 			if (tmp == NULL) {
808 				return -ENOMEM;
809 			}
810 			blob->active.clusters = tmp;
811 			blob->active.cluster_array_size = (cluster_count + blob->active.num_clusters);
812 
813 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
814 				if (desc_extent->cluster_idx[i] != 0) {
815 					blob->active.clusters[blob->active.num_clusters++] = bs_cluster_to_lba(blob->bs,
816 							desc_extent->cluster_idx[i]);
817 				} else if (spdk_blob_is_thin_provisioned(blob)) {
818 					blob->active.clusters[blob->active.num_clusters++] = 0;
819 				} else {
820 					return -EINVAL;
821 				}
822 			}
823 			assert(desc_extent->start_cluster_idx + cluster_count == blob->active.num_clusters);
824 			assert(blob->remaining_clusters_in_et >= cluster_count);
825 			blob->remaining_clusters_in_et -= cluster_count;
826 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
827 			int rc;
828 
829 			rc = blob_deserialize_xattr(blob,
830 						    (struct spdk_blob_md_descriptor_xattr *) desc, false);
831 			if (rc != 0) {
832 				return rc;
833 			}
834 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
835 			int rc;
836 
837 			rc = blob_deserialize_xattr(blob,
838 						    (struct spdk_blob_md_descriptor_xattr *) desc, true);
839 			if (rc != 0) {
840 				return rc;
841 			}
842 		} else {
843 			/* Unrecognized descriptor type.  Do not fail - just continue to the
844 			 *  next descriptor.  If this descriptor is associated with some feature
845 			 *  defined in a newer version of blobstore, that version of blobstore
846 			 *  should create and set an associated feature flag to specify if this
847 			 *  blob can be loaded or not.
848 			 */
849 		}
850 
851 		/* Advance to the next descriptor */
852 		cur_desc += sizeof(*desc) + desc->length;
853 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
854 			break;
855 		}
856 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
857 	}
858 
859 	return 0;
860 }
861 
862 static bool bs_load_cur_extent_page_valid(struct spdk_blob_md_page *page);
863 
864 static int
865 blob_parse_extent_page(struct spdk_blob_md_page *extent_page, struct spdk_blob *blob)
866 {
867 	assert(blob != NULL);
868 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
869 
870 	if (bs_load_cur_extent_page_valid(extent_page) == false) {
871 		return -ENOENT;
872 	}
873 
874 	return blob_parse_page(extent_page, blob);
875 }
876 
877 static int
878 blob_parse(const struct spdk_blob_md_page *pages, uint32_t page_count,
879 	   struct spdk_blob *blob)
880 {
881 	const struct spdk_blob_md_page *page;
882 	uint32_t i;
883 	int rc;
884 	void *tmp;
885 
886 	assert(page_count > 0);
887 	assert(pages[0].sequence_num == 0);
888 	assert(blob != NULL);
889 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
890 	assert(blob->active.clusters == NULL);
891 
892 	/* The blobid provided doesn't match what's in the MD, this can
893 	 * happen for example if a bogus blobid is passed in through open.
894 	 */
895 	if (blob->id != pages[0].id) {
896 		SPDK_ERRLOG("Blobid (0x%" PRIx64 ") doesn't match what's in metadata "
897 			    "(0x%" PRIx64 ")\n", blob->id, pages[0].id);
898 		return -ENOENT;
899 	}
900 
901 	tmp = realloc(blob->active.pages, page_count * sizeof(*blob->active.pages));
902 	if (!tmp) {
903 		return -ENOMEM;
904 	}
905 	blob->active.pages = tmp;
906 
907 	blob->active.pages[0] = pages[0].id;
908 
909 	for (i = 1; i < page_count; i++) {
910 		assert(spdk_bit_array_get(blob->bs->used_md_pages, pages[i - 1].next));
911 		blob->active.pages[i] = pages[i - 1].next;
912 	}
913 	blob->active.num_pages = page_count;
914 
915 	for (i = 0; i < page_count; i++) {
916 		page = &pages[i];
917 
918 		assert(page->id == blob->id);
919 		assert(page->sequence_num == i);
920 
921 		rc = blob_parse_page(page, blob);
922 		if (rc != 0) {
923 			return rc;
924 		}
925 	}
926 
927 	return 0;
928 }
929 
930 static int
931 blob_serialize_add_page(const struct spdk_blob *blob,
932 			struct spdk_blob_md_page **pages,
933 			uint32_t *page_count,
934 			struct spdk_blob_md_page **last_page)
935 {
936 	struct spdk_blob_md_page *page, *tmp_pages;
937 
938 	assert(pages != NULL);
939 	assert(page_count != NULL);
940 
941 	*last_page = NULL;
942 	if (*page_count == 0) {
943 		assert(*pages == NULL);
944 		*pages = spdk_malloc(SPDK_BS_PAGE_SIZE, 0,
945 				     NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
946 		if (*pages == NULL) {
947 			return -ENOMEM;
948 		}
949 		*page_count = 1;
950 	} else {
951 		assert(*pages != NULL);
952 		tmp_pages = spdk_realloc(*pages, SPDK_BS_PAGE_SIZE * (*page_count + 1), 0);
953 		if (tmp_pages == NULL) {
954 			return -ENOMEM;
955 		}
956 		(*page_count)++;
957 		*pages = tmp_pages;
958 	}
959 
960 	page = &(*pages)[*page_count - 1];
961 	memset(page, 0, sizeof(*page));
962 	page->id = blob->id;
963 	page->sequence_num = *page_count - 1;
964 	page->next = SPDK_INVALID_MD_PAGE;
965 	*last_page = page;
966 
967 	return 0;
968 }
969 
970 /* Transform the in-memory representation 'xattr' into an on-disk xattr descriptor.
971  * Update required_sz on both success and failure.
972  *
973  */
974 static int
975 blob_serialize_xattr(const struct spdk_xattr *xattr,
976 		     uint8_t *buf, size_t buf_sz,
977 		     size_t *required_sz, bool internal)
978 {
979 	struct spdk_blob_md_descriptor_xattr	*desc;
980 
981 	*required_sz = sizeof(struct spdk_blob_md_descriptor_xattr) +
982 		       strlen(xattr->name) +
983 		       xattr->value_len;
984 
985 	if (buf_sz < *required_sz) {
986 		return -1;
987 	}
988 
989 	desc = (struct spdk_blob_md_descriptor_xattr *)buf;
990 
991 	desc->type = internal ? SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL : SPDK_MD_DESCRIPTOR_TYPE_XATTR;
992 	desc->length = sizeof(desc->name_length) +
993 		       sizeof(desc->value_length) +
994 		       strlen(xattr->name) +
995 		       xattr->value_len;
996 	desc->name_length = strlen(xattr->name);
997 	desc->value_length = xattr->value_len;
998 
999 	memcpy(desc->name, xattr->name, desc->name_length);
1000 	memcpy((void *)((uintptr_t)desc->name + desc->name_length),
1001 	       xattr->value,
1002 	       desc->value_length);
1003 
1004 	return 0;
1005 }
1006 
1007 static void
1008 blob_serialize_extent_table_entry(const struct spdk_blob *blob,
1009 				  uint64_t start_ep, uint64_t *next_ep,
1010 				  uint8_t **buf, size_t *remaining_sz)
1011 {
1012 	struct spdk_blob_md_descriptor_extent_table *desc;
1013 	size_t cur_sz;
1014 	uint64_t i, et_idx;
1015 	uint32_t extent_page, ep_len;
1016 
1017 	/* The buffer must have room for at least num_clusters entry */
1018 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc->num_clusters);
1019 	if (*remaining_sz < cur_sz) {
1020 		*next_ep = start_ep;
1021 		return;
1022 	}
1023 
1024 	desc = (struct spdk_blob_md_descriptor_extent_table *)*buf;
1025 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE;
1026 
1027 	desc->num_clusters = blob->active.num_clusters;
1028 
1029 	ep_len = 1;
1030 	et_idx = 0;
1031 	for (i = start_ep; i < blob->active.num_extent_pages; i++) {
1032 		if (*remaining_sz < cur_sz  + sizeof(desc->extent_page[0])) {
1033 			/* If we ran out of buffer space, return */
1034 			break;
1035 		}
1036 
1037 		extent_page = blob->active.extent_pages[i];
1038 		/* Verify that next extent_page is unallocated */
1039 		if (extent_page == 0 &&
1040 		    (i + 1 < blob->active.num_extent_pages && blob->active.extent_pages[i + 1] == 0)) {
1041 			ep_len++;
1042 			continue;
1043 		}
1044 		desc->extent_page[et_idx].page_idx = extent_page;
1045 		desc->extent_page[et_idx].num_pages = ep_len;
1046 		et_idx++;
1047 
1048 		ep_len = 1;
1049 		cur_sz += sizeof(desc->extent_page[et_idx]);
1050 	}
1051 	*next_ep = i;
1052 
1053 	desc->length = sizeof(desc->num_clusters) + sizeof(desc->extent_page[0]) * et_idx;
1054 	*remaining_sz -= sizeof(struct spdk_blob_md_descriptor) + desc->length;
1055 	*buf += sizeof(struct spdk_blob_md_descriptor) + desc->length;
1056 }
1057 
1058 static int
1059 blob_serialize_extent_table(const struct spdk_blob *blob,
1060 			    struct spdk_blob_md_page **pages,
1061 			    struct spdk_blob_md_page *cur_page,
1062 			    uint32_t *page_count, uint8_t **buf,
1063 			    size_t *remaining_sz)
1064 {
1065 	uint64_t				last_extent_page;
1066 	int					rc;
1067 
1068 	last_extent_page = 0;
1069 	/* At least single extent table entry has to be always persisted.
1070 	 * Such case occurs with num_extent_pages == 0. */
1071 	while (last_extent_page <= blob->active.num_extent_pages) {
1072 		blob_serialize_extent_table_entry(blob, last_extent_page, &last_extent_page, buf,
1073 						  remaining_sz);
1074 
1075 		if (last_extent_page == blob->active.num_extent_pages) {
1076 			break;
1077 		}
1078 
1079 		rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
1080 		if (rc < 0) {
1081 			return rc;
1082 		}
1083 
1084 		*buf = (uint8_t *)cur_page->descriptors;
1085 		*remaining_sz = sizeof(cur_page->descriptors);
1086 	}
1087 
1088 	return 0;
1089 }
1090 
1091 static void
1092 blob_serialize_extent_rle(const struct spdk_blob *blob,
1093 			  uint64_t start_cluster, uint64_t *next_cluster,
1094 			  uint8_t **buf, size_t *buf_sz)
1095 {
1096 	struct spdk_blob_md_descriptor_extent_rle *desc_extent_rle;
1097 	size_t cur_sz;
1098 	uint64_t i, extent_idx;
1099 	uint64_t lba, lba_per_cluster, lba_count;
1100 
1101 	/* The buffer must have room for at least one extent */
1102 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc_extent_rle->extents[0]);
1103 	if (*buf_sz < cur_sz) {
1104 		*next_cluster = start_cluster;
1105 		return;
1106 	}
1107 
1108 	desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)*buf;
1109 	desc_extent_rle->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE;
1110 
1111 	lba_per_cluster = bs_cluster_to_lba(blob->bs, 1);
1112 	/* Assert for scan-build false positive */
1113 	assert(lba_per_cluster > 0);
1114 
1115 	lba = blob->active.clusters[start_cluster];
1116 	lba_count = lba_per_cluster;
1117 	extent_idx = 0;
1118 	for (i = start_cluster + 1; i < blob->active.num_clusters; i++) {
1119 		if ((lba + lba_count) == blob->active.clusters[i] && lba != 0) {
1120 			/* Run-length encode sequential non-zero LBA */
1121 			lba_count += lba_per_cluster;
1122 			continue;
1123 		} else if (lba == 0 && blob->active.clusters[i] == 0) {
1124 			/* Run-length encode unallocated clusters */
1125 			lba_count += lba_per_cluster;
1126 			continue;
1127 		}
1128 		desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
1129 		desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
1130 		extent_idx++;
1131 
1132 		cur_sz += sizeof(desc_extent_rle->extents[extent_idx]);
1133 
1134 		if (*buf_sz < cur_sz) {
1135 			/* If we ran out of buffer space, return */
1136 			*next_cluster = i;
1137 			break;
1138 		}
1139 
1140 		lba = blob->active.clusters[i];
1141 		lba_count = lba_per_cluster;
1142 	}
1143 
1144 	if (*buf_sz >= cur_sz) {
1145 		desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
1146 		desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
1147 		extent_idx++;
1148 
1149 		*next_cluster = blob->active.num_clusters;
1150 	}
1151 
1152 	desc_extent_rle->length = sizeof(desc_extent_rle->extents[0]) * extent_idx;
1153 	*buf_sz -= sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
1154 	*buf += sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
1155 }
1156 
1157 static int
1158 blob_serialize_extents_rle(const struct spdk_blob *blob,
1159 			   struct spdk_blob_md_page **pages,
1160 			   struct spdk_blob_md_page *cur_page,
1161 			   uint32_t *page_count, uint8_t **buf,
1162 			   size_t *remaining_sz)
1163 {
1164 	uint64_t				last_cluster;
1165 	int					rc;
1166 
1167 	last_cluster = 0;
1168 	while (last_cluster < blob->active.num_clusters) {
1169 		blob_serialize_extent_rle(blob, last_cluster, &last_cluster, buf, remaining_sz);
1170 
1171 		if (last_cluster == blob->active.num_clusters) {
1172 			break;
1173 		}
1174 
1175 		rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
1176 		if (rc < 0) {
1177 			return rc;
1178 		}
1179 
1180 		*buf = (uint8_t *)cur_page->descriptors;
1181 		*remaining_sz = sizeof(cur_page->descriptors);
1182 	}
1183 
1184 	return 0;
1185 }
1186 
1187 static void
1188 blob_serialize_extent_page(const struct spdk_blob *blob,
1189 			   uint64_t cluster, struct spdk_blob_md_page *page)
1190 {
1191 	struct spdk_blob_md_descriptor_extent_page *desc_extent;
1192 	uint64_t i, extent_idx;
1193 	uint64_t lba, lba_per_cluster;
1194 	uint64_t start_cluster_idx = (cluster / SPDK_EXTENTS_PER_EP) * SPDK_EXTENTS_PER_EP;
1195 
1196 	desc_extent = (struct spdk_blob_md_descriptor_extent_page *) page->descriptors;
1197 	desc_extent->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE;
1198 
1199 	lba_per_cluster = bs_cluster_to_lba(blob->bs, 1);
1200 
1201 	desc_extent->start_cluster_idx = start_cluster_idx;
1202 	extent_idx = 0;
1203 	for (i = start_cluster_idx; i < blob->active.num_clusters; i++) {
1204 		lba = blob->active.clusters[i];
1205 		desc_extent->cluster_idx[extent_idx++] = lba / lba_per_cluster;
1206 		if (extent_idx >= SPDK_EXTENTS_PER_EP) {
1207 			break;
1208 		}
1209 	}
1210 	desc_extent->length = sizeof(desc_extent->start_cluster_idx) +
1211 			      sizeof(desc_extent->cluster_idx[0]) * extent_idx;
1212 }
1213 
1214 static void
1215 blob_serialize_flags(const struct spdk_blob *blob,
1216 		     uint8_t *buf, size_t *buf_sz)
1217 {
1218 	struct spdk_blob_md_descriptor_flags *desc;
1219 
1220 	/*
1221 	 * Flags get serialized first, so we should always have room for the flags
1222 	 *  descriptor.
1223 	 */
1224 	assert(*buf_sz >= sizeof(*desc));
1225 
1226 	desc = (struct spdk_blob_md_descriptor_flags *)buf;
1227 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_FLAGS;
1228 	desc->length = sizeof(*desc) - sizeof(struct spdk_blob_md_descriptor);
1229 	desc->invalid_flags = blob->invalid_flags;
1230 	desc->data_ro_flags = blob->data_ro_flags;
1231 	desc->md_ro_flags = blob->md_ro_flags;
1232 
1233 	*buf_sz -= sizeof(*desc);
1234 }
1235 
1236 static int
1237 blob_serialize_xattrs(const struct spdk_blob *blob,
1238 		      const struct spdk_xattr_tailq *xattrs, bool internal,
1239 		      struct spdk_blob_md_page **pages,
1240 		      struct spdk_blob_md_page *cur_page,
1241 		      uint32_t *page_count, uint8_t **buf,
1242 		      size_t *remaining_sz)
1243 {
1244 	const struct spdk_xattr	*xattr;
1245 	int	rc;
1246 
1247 	TAILQ_FOREACH(xattr, xattrs, link) {
1248 		size_t required_sz = 0;
1249 
1250 		rc = blob_serialize_xattr(xattr,
1251 					  *buf, *remaining_sz,
1252 					  &required_sz, internal);
1253 		if (rc < 0) {
1254 			/* Need to add a new page to the chain */
1255 			rc = blob_serialize_add_page(blob, pages, page_count,
1256 						     &cur_page);
1257 			if (rc < 0) {
1258 				spdk_free(*pages);
1259 				*pages = NULL;
1260 				*page_count = 0;
1261 				return rc;
1262 			}
1263 
1264 			*buf = (uint8_t *)cur_page->descriptors;
1265 			*remaining_sz = sizeof(cur_page->descriptors);
1266 
1267 			/* Try again */
1268 			required_sz = 0;
1269 			rc = blob_serialize_xattr(xattr,
1270 						  *buf, *remaining_sz,
1271 						  &required_sz, internal);
1272 
1273 			if (rc < 0) {
1274 				spdk_free(*pages);
1275 				*pages = NULL;
1276 				*page_count = 0;
1277 				return rc;
1278 			}
1279 		}
1280 
1281 		*remaining_sz -= required_sz;
1282 		*buf += required_sz;
1283 	}
1284 
1285 	return 0;
1286 }
1287 
1288 static int
1289 blob_serialize(const struct spdk_blob *blob, struct spdk_blob_md_page **pages,
1290 	       uint32_t *page_count)
1291 {
1292 	struct spdk_blob_md_page		*cur_page;
1293 	int					rc;
1294 	uint8_t					*buf;
1295 	size_t					remaining_sz;
1296 
1297 	assert(pages != NULL);
1298 	assert(page_count != NULL);
1299 	assert(blob != NULL);
1300 	assert(blob->state == SPDK_BLOB_STATE_DIRTY);
1301 
1302 	*pages = NULL;
1303 	*page_count = 0;
1304 
1305 	/* A blob always has at least 1 page, even if it has no descriptors */
1306 	rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
1307 	if (rc < 0) {
1308 		return rc;
1309 	}
1310 
1311 	buf = (uint8_t *)cur_page->descriptors;
1312 	remaining_sz = sizeof(cur_page->descriptors);
1313 
1314 	/* Serialize flags */
1315 	blob_serialize_flags(blob, buf, &remaining_sz);
1316 	buf += sizeof(struct spdk_blob_md_descriptor_flags);
1317 
1318 	/* Serialize xattrs */
1319 	rc = blob_serialize_xattrs(blob, &blob->xattrs, false,
1320 				   pages, cur_page, page_count, &buf, &remaining_sz);
1321 	if (rc < 0) {
1322 		return rc;
1323 	}
1324 
1325 	/* Serialize internal xattrs */
1326 	rc = blob_serialize_xattrs(blob, &blob->xattrs_internal, true,
1327 				   pages, cur_page, page_count, &buf, &remaining_sz);
1328 	if (rc < 0) {
1329 		return rc;
1330 	}
1331 
1332 	if (blob->use_extent_table) {
1333 		/* Serialize extent table */
1334 		rc = blob_serialize_extent_table(blob, pages, cur_page, page_count, &buf, &remaining_sz);
1335 	} else {
1336 		/* Serialize extents */
1337 		rc = blob_serialize_extents_rle(blob, pages, cur_page, page_count, &buf, &remaining_sz);
1338 	}
1339 
1340 	return rc;
1341 }
1342 
1343 struct spdk_blob_load_ctx {
1344 	struct spdk_blob		*blob;
1345 
1346 	struct spdk_blob_md_page	*pages;
1347 	uint32_t			num_pages;
1348 	uint32_t			next_extent_page;
1349 	spdk_bs_sequence_t	        *seq;
1350 
1351 	spdk_bs_sequence_cpl		cb_fn;
1352 	void				*cb_arg;
1353 };
1354 
1355 static uint32_t
1356 blob_md_page_calc_crc(void *page)
1357 {
1358 	uint32_t		crc;
1359 
1360 	crc = BLOB_CRC32C_INITIAL;
1361 	crc = spdk_crc32c_update(page, SPDK_BS_PAGE_SIZE - 4, crc);
1362 	crc ^= BLOB_CRC32C_INITIAL;
1363 
1364 	return crc;
1365 
1366 }
1367 
1368 static void
1369 blob_load_final(struct spdk_blob_load_ctx *ctx, int bserrno)
1370 {
1371 	struct spdk_blob		*blob = ctx->blob;
1372 
1373 	if (bserrno == 0) {
1374 		blob_mark_clean(blob);
1375 	}
1376 
1377 	ctx->cb_fn(ctx->seq, ctx->cb_arg, bserrno);
1378 
1379 	/* Free the memory */
1380 	spdk_free(ctx->pages);
1381 	free(ctx);
1382 }
1383 
1384 static void
1385 blob_load_snapshot_cpl(void *cb_arg, struct spdk_blob *snapshot, int bserrno)
1386 {
1387 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1388 	struct spdk_blob		*blob = ctx->blob;
1389 
1390 	if (bserrno == 0) {
1391 		blob->back_bs_dev = bs_create_blob_bs_dev(snapshot);
1392 		if (blob->back_bs_dev == NULL) {
1393 			bserrno = -ENOMEM;
1394 		}
1395 	}
1396 	if (bserrno != 0) {
1397 		SPDK_ERRLOG("Snapshot fail\n");
1398 	}
1399 
1400 	blob_load_final(ctx, bserrno);
1401 }
1402 
1403 static void blob_update_clear_method(struct spdk_blob *blob);
1404 
1405 static int
1406 blob_load_esnap(struct spdk_blob *blob, void *blob_ctx)
1407 {
1408 	struct spdk_blob_store *bs = blob->bs;
1409 	struct spdk_bs_dev *bs_dev = NULL;
1410 	const void *esnap_id = NULL;
1411 	size_t id_len = 0;
1412 	int rc;
1413 
1414 	if (bs->esnap_bs_dev_create == NULL) {
1415 		SPDK_NOTICELOG("blob 0x%" PRIx64 " is an esnap clone but the blobstore was opened "
1416 			       "without support for esnap clones\n", blob->id);
1417 		return -ENOTSUP;
1418 	}
1419 	assert(blob->back_bs_dev == NULL);
1420 
1421 	rc = blob_get_xattr_value(blob, BLOB_EXTERNAL_SNAPSHOT_ID, &esnap_id, &id_len, true);
1422 	if (rc != 0) {
1423 		SPDK_ERRLOG("blob 0x%" PRIx64 " is an esnap clone but has no esnap ID\n", blob->id);
1424 		return -EINVAL;
1425 	}
1426 	assert(id_len > 0 && id_len < UINT32_MAX);
1427 
1428 	SPDK_INFOLOG(blob, "Creating external snapshot device\n");
1429 
1430 	rc = bs->esnap_bs_dev_create(bs->esnap_ctx, blob_ctx, blob, esnap_id, (uint32_t)id_len,
1431 				     &bs_dev);
1432 	if (rc != 0) {
1433 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": failed to load back_bs_dev "
1434 			      "with error %d\n", blob->id, rc);
1435 		return rc;
1436 	}
1437 
1438 	/*
1439 	 * Note: bs_dev might be NULL if the consumer chose to not open the external snapshot.
1440 	 * This especially might happen during spdk_bs_load() iteration.
1441 	 */
1442 	if (bs_dev != NULL) {
1443 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": loaded back_bs_dev\n", blob->id);
1444 		if ((bs->io_unit_size % bs_dev->blocklen) != 0) {
1445 			SPDK_NOTICELOG("blob 0x%" PRIx64 " external snapshot device block size %u "
1446 				       "is not compatible with blobstore block size %u\n",
1447 				       blob->id, bs_dev->blocklen, bs->io_unit_size);
1448 			bs_dev->destroy(bs_dev);
1449 			return -EINVAL;
1450 		}
1451 	}
1452 
1453 	blob->back_bs_dev = bs_dev;
1454 	blob->parent_id = SPDK_BLOBID_EXTERNAL_SNAPSHOT;
1455 
1456 	return 0;
1457 }
1458 
1459 static void
1460 blob_load_backing_dev(spdk_bs_sequence_t *seq, void *cb_arg)
1461 {
1462 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1463 	struct spdk_blob		*blob = ctx->blob;
1464 	const void			*value;
1465 	size_t				len;
1466 	int				rc;
1467 
1468 	if (blob_is_esnap_clone(blob)) {
1469 		rc = blob_load_esnap(blob, seq->cpl.u.blob_handle.esnap_ctx);
1470 		blob_load_final(ctx, rc);
1471 		return;
1472 	}
1473 
1474 	if (spdk_blob_is_thin_provisioned(blob)) {
1475 		rc = blob_get_xattr_value(blob, BLOB_SNAPSHOT, &value, &len, true);
1476 		if (rc == 0) {
1477 			if (len != sizeof(spdk_blob_id)) {
1478 				blob_load_final(ctx, -EINVAL);
1479 				return;
1480 			}
1481 			/* open snapshot blob and continue in the callback function */
1482 			blob->parent_id = *(spdk_blob_id *)value;
1483 			spdk_bs_open_blob(blob->bs, blob->parent_id,
1484 					  blob_load_snapshot_cpl, ctx);
1485 			return;
1486 		} else {
1487 			/* add zeroes_dev for thin provisioned blob */
1488 			blob->back_bs_dev = bs_create_zeroes_dev();
1489 		}
1490 	} else {
1491 		/* standard blob */
1492 		blob->back_bs_dev = NULL;
1493 	}
1494 	blob_load_final(ctx, 0);
1495 }
1496 
1497 static void
1498 blob_load_cpl_extents_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1499 {
1500 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1501 	struct spdk_blob		*blob = ctx->blob;
1502 	struct spdk_blob_md_page	*page;
1503 	uint64_t			i;
1504 	uint32_t			crc;
1505 	uint64_t			lba;
1506 	void				*tmp;
1507 	uint64_t			sz;
1508 
1509 	if (bserrno) {
1510 		SPDK_ERRLOG("Extent page read failed: %d\n", bserrno);
1511 		blob_load_final(ctx, bserrno);
1512 		return;
1513 	}
1514 
1515 	if (ctx->pages == NULL) {
1516 		/* First iteration of this function, allocate buffer for single EXTENT_PAGE */
1517 		ctx->pages = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0,
1518 					  NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1519 		if (!ctx->pages) {
1520 			blob_load_final(ctx, -ENOMEM);
1521 			return;
1522 		}
1523 		ctx->num_pages = 1;
1524 		ctx->next_extent_page = 0;
1525 	} else {
1526 		page = &ctx->pages[0];
1527 		crc = blob_md_page_calc_crc(page);
1528 		if (crc != page->crc) {
1529 			blob_load_final(ctx, -EINVAL);
1530 			return;
1531 		}
1532 
1533 		if (page->next != SPDK_INVALID_MD_PAGE) {
1534 			blob_load_final(ctx, -EINVAL);
1535 			return;
1536 		}
1537 
1538 		bserrno = blob_parse_extent_page(page, blob);
1539 		if (bserrno) {
1540 			blob_load_final(ctx, bserrno);
1541 			return;
1542 		}
1543 	}
1544 
1545 	for (i = ctx->next_extent_page; i < blob->active.num_extent_pages; i++) {
1546 		if (blob->active.extent_pages[i] != 0) {
1547 			/* Extent page was allocated, read and parse it. */
1548 			lba = bs_md_page_to_lba(blob->bs, blob->active.extent_pages[i]);
1549 			ctx->next_extent_page = i + 1;
1550 
1551 			bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1552 					     bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
1553 					     blob_load_cpl_extents_cpl, ctx);
1554 			return;
1555 		} else {
1556 			/* Thin provisioned blobs can point to unallocated extent pages.
1557 			 * In this case blob size should be increased by up to the amount left in remaining_clusters_in_et. */
1558 
1559 			sz = spdk_min(blob->remaining_clusters_in_et, SPDK_EXTENTS_PER_EP);
1560 			blob->active.num_clusters += sz;
1561 			blob->remaining_clusters_in_et -= sz;
1562 
1563 			assert(spdk_blob_is_thin_provisioned(blob));
1564 			assert(i + 1 < blob->active.num_extent_pages || blob->remaining_clusters_in_et == 0);
1565 
1566 			tmp = realloc(blob->active.clusters, blob->active.num_clusters * sizeof(*blob->active.clusters));
1567 			if (tmp == NULL) {
1568 				blob_load_final(ctx, -ENOMEM);
1569 				return;
1570 			}
1571 			memset(tmp + sizeof(*blob->active.clusters) * blob->active.cluster_array_size, 0,
1572 			       sizeof(*blob->active.clusters) * (blob->active.num_clusters - blob->active.cluster_array_size));
1573 			blob->active.clusters = tmp;
1574 			blob->active.cluster_array_size = blob->active.num_clusters;
1575 		}
1576 	}
1577 
1578 	blob_load_backing_dev(seq, ctx);
1579 }
1580 
1581 static void
1582 blob_load_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1583 {
1584 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1585 	struct spdk_blob		*blob = ctx->blob;
1586 	struct spdk_blob_md_page	*page;
1587 	int				rc;
1588 	uint32_t			crc;
1589 	uint32_t			current_page;
1590 
1591 	if (ctx->num_pages == 1) {
1592 		current_page = bs_blobid_to_page(blob->id);
1593 	} else {
1594 		assert(ctx->num_pages != 0);
1595 		page = &ctx->pages[ctx->num_pages - 2];
1596 		current_page = page->next;
1597 	}
1598 
1599 	if (bserrno) {
1600 		SPDK_ERRLOG("Metadata page %d read failed for blobid 0x%" PRIx64 ": %d\n",
1601 			    current_page, blob->id, bserrno);
1602 		blob_load_final(ctx, bserrno);
1603 		return;
1604 	}
1605 
1606 	page = &ctx->pages[ctx->num_pages - 1];
1607 	crc = blob_md_page_calc_crc(page);
1608 	if (crc != page->crc) {
1609 		SPDK_ERRLOG("Metadata page %d crc mismatch for blobid 0x%" PRIx64 "\n",
1610 			    current_page, blob->id);
1611 		blob_load_final(ctx, -EINVAL);
1612 		return;
1613 	}
1614 
1615 	if (page->next != SPDK_INVALID_MD_PAGE) {
1616 		struct spdk_blob_md_page *tmp_pages;
1617 		uint32_t next_page = page->next;
1618 		uint64_t next_lba = bs_md_page_to_lba(blob->bs, next_page);
1619 
1620 		/* Read the next page */
1621 		tmp_pages = spdk_realloc(ctx->pages, (sizeof(*page) * (ctx->num_pages + 1)), 0);
1622 		if (tmp_pages == NULL) {
1623 			blob_load_final(ctx, -ENOMEM);
1624 			return;
1625 		}
1626 		ctx->num_pages++;
1627 		ctx->pages = tmp_pages;
1628 
1629 		bs_sequence_read_dev(seq, &ctx->pages[ctx->num_pages - 1],
1630 				     next_lba,
1631 				     bs_byte_to_lba(blob->bs, sizeof(*page)),
1632 				     blob_load_cpl, ctx);
1633 		return;
1634 	}
1635 
1636 	/* Parse the pages */
1637 	rc = blob_parse(ctx->pages, ctx->num_pages, blob);
1638 	if (rc) {
1639 		blob_load_final(ctx, rc);
1640 		return;
1641 	}
1642 
1643 	if (blob->extent_table_found == true) {
1644 		/* If EXTENT_TABLE was found, that means support for it should be enabled. */
1645 		assert(blob->extent_rle_found == false);
1646 		blob->use_extent_table = true;
1647 	} else {
1648 		/* If EXTENT_RLE or no extent_* descriptor was found disable support
1649 		 * for extent table. No extent_* descriptors means that blob has length of 0
1650 		 * and no extent_rle descriptors were persisted for it.
1651 		 * EXTENT_TABLE if used, is always present in metadata regardless of length. */
1652 		blob->use_extent_table = false;
1653 	}
1654 
1655 	/* Check the clear_method stored in metadata vs what may have been passed
1656 	 * via spdk_bs_open_blob_ext() and update accordingly.
1657 	 */
1658 	blob_update_clear_method(blob);
1659 
1660 	spdk_free(ctx->pages);
1661 	ctx->pages = NULL;
1662 
1663 	if (blob->extent_table_found) {
1664 		blob_load_cpl_extents_cpl(seq, ctx, 0);
1665 	} else {
1666 		blob_load_backing_dev(seq, ctx);
1667 	}
1668 }
1669 
1670 /* Load a blob from disk given a blobid */
1671 static void
1672 blob_load(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1673 	  spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1674 {
1675 	struct spdk_blob_load_ctx *ctx;
1676 	struct spdk_blob_store *bs;
1677 	uint32_t page_num;
1678 	uint64_t lba;
1679 
1680 	blob_verify_md_op(blob);
1681 
1682 	bs = blob->bs;
1683 
1684 	ctx = calloc(1, sizeof(*ctx));
1685 	if (!ctx) {
1686 		cb_fn(seq, cb_arg, -ENOMEM);
1687 		return;
1688 	}
1689 
1690 	ctx->blob = blob;
1691 	ctx->pages = spdk_realloc(ctx->pages, SPDK_BS_PAGE_SIZE, 0);
1692 	if (!ctx->pages) {
1693 		free(ctx);
1694 		cb_fn(seq, cb_arg, -ENOMEM);
1695 		return;
1696 	}
1697 	ctx->num_pages = 1;
1698 	ctx->cb_fn = cb_fn;
1699 	ctx->cb_arg = cb_arg;
1700 	ctx->seq = seq;
1701 
1702 	page_num = bs_blobid_to_page(blob->id);
1703 	lba = bs_md_page_to_lba(blob->bs, page_num);
1704 
1705 	blob->state = SPDK_BLOB_STATE_LOADING;
1706 
1707 	bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1708 			     bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE),
1709 			     blob_load_cpl, ctx);
1710 }
1711 
1712 struct spdk_blob_persist_ctx {
1713 	struct spdk_blob		*blob;
1714 
1715 	struct spdk_blob_md_page	*pages;
1716 	uint32_t			next_extent_page;
1717 	struct spdk_blob_md_page	*extent_page;
1718 
1719 	spdk_bs_sequence_t		*seq;
1720 	spdk_bs_sequence_cpl		cb_fn;
1721 	void				*cb_arg;
1722 	TAILQ_ENTRY(spdk_blob_persist_ctx) link;
1723 };
1724 
1725 static void
1726 bs_batch_clear_dev(struct spdk_blob_persist_ctx *ctx, spdk_bs_batch_t *batch, uint64_t lba,
1727 		   uint64_t lba_count)
1728 {
1729 	switch (ctx->blob->clear_method) {
1730 	case BLOB_CLEAR_WITH_DEFAULT:
1731 	case BLOB_CLEAR_WITH_UNMAP:
1732 		bs_batch_unmap_dev(batch, lba, lba_count);
1733 		break;
1734 	case BLOB_CLEAR_WITH_WRITE_ZEROES:
1735 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
1736 		break;
1737 	case BLOB_CLEAR_WITH_NONE:
1738 	default:
1739 		break;
1740 	}
1741 }
1742 
1743 static void bs_mark_dirty(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
1744 			  spdk_bs_sequence_cpl cb_fn, void *cb_arg);
1745 
1746 static void
1747 blob_persist_complete_cb(void *arg)
1748 {
1749 	struct spdk_blob_persist_ctx *ctx = arg;
1750 
1751 	/* Call user callback */
1752 	ctx->cb_fn(ctx->seq, ctx->cb_arg, 0);
1753 
1754 	/* Free the memory */
1755 	spdk_free(ctx->pages);
1756 	free(ctx);
1757 }
1758 
1759 static void blob_persist_start(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno);
1760 
1761 static void
1762 blob_persist_complete(spdk_bs_sequence_t *seq, struct spdk_blob_persist_ctx *ctx, int bserrno)
1763 {
1764 	struct spdk_blob_persist_ctx	*next_persist, *tmp;
1765 	struct spdk_blob		*blob = ctx->blob;
1766 
1767 	if (bserrno == 0) {
1768 		blob_mark_clean(blob);
1769 	}
1770 
1771 	assert(ctx == TAILQ_FIRST(&blob->persists_to_complete));
1772 
1773 	/* Complete all persists that were pending when the current persist started */
1774 	TAILQ_FOREACH_SAFE(next_persist, &blob->persists_to_complete, link, tmp) {
1775 		TAILQ_REMOVE(&blob->persists_to_complete, next_persist, link);
1776 		spdk_thread_send_msg(spdk_get_thread(), blob_persist_complete_cb, next_persist);
1777 	}
1778 
1779 	if (TAILQ_EMPTY(&blob->pending_persists)) {
1780 		return;
1781 	}
1782 
1783 	/* Queue up all pending persists for completion and start blob persist with first one */
1784 	TAILQ_SWAP(&blob->persists_to_complete, &blob->pending_persists, spdk_blob_persist_ctx, link);
1785 	next_persist = TAILQ_FIRST(&blob->persists_to_complete);
1786 
1787 	blob->state = SPDK_BLOB_STATE_DIRTY;
1788 	bs_mark_dirty(seq, blob->bs, blob_persist_start, next_persist);
1789 }
1790 
1791 static void
1792 blob_persist_clear_extents_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1793 {
1794 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1795 	struct spdk_blob		*blob = ctx->blob;
1796 	struct spdk_blob_store		*bs = blob->bs;
1797 	size_t				i;
1798 
1799 	if (bserrno != 0) {
1800 		blob_persist_complete(seq, ctx, bserrno);
1801 		return;
1802 	}
1803 
1804 	spdk_spin_lock(&bs->used_lock);
1805 
1806 	/* Release all extent_pages that were truncated */
1807 	for (i = blob->active.num_extent_pages; i < blob->active.extent_pages_array_size; i++) {
1808 		/* Nothing to release if it was not allocated */
1809 		if (blob->active.extent_pages[i] != 0) {
1810 			bs_release_md_page(bs, blob->active.extent_pages[i]);
1811 		}
1812 	}
1813 
1814 	spdk_spin_unlock(&bs->used_lock);
1815 
1816 	if (blob->active.num_extent_pages == 0) {
1817 		free(blob->active.extent_pages);
1818 		blob->active.extent_pages = NULL;
1819 		blob->active.extent_pages_array_size = 0;
1820 	} else if (blob->active.num_extent_pages != blob->active.extent_pages_array_size) {
1821 #ifndef __clang_analyzer__
1822 		void *tmp;
1823 
1824 		/* scan-build really can't figure reallocs, workaround it */
1825 		tmp = realloc(blob->active.extent_pages, sizeof(uint32_t) * blob->active.num_extent_pages);
1826 		assert(tmp != NULL);
1827 		blob->active.extent_pages = tmp;
1828 #endif
1829 		blob->active.extent_pages_array_size = blob->active.num_extent_pages;
1830 	}
1831 
1832 	blob_persist_complete(seq, ctx, bserrno);
1833 }
1834 
1835 static void
1836 blob_persist_clear_extents(spdk_bs_sequence_t *seq, struct spdk_blob_persist_ctx *ctx)
1837 {
1838 	struct spdk_blob		*blob = ctx->blob;
1839 	struct spdk_blob_store		*bs = blob->bs;
1840 	size_t				i;
1841 	uint64_t                        lba;
1842 	uint64_t                        lba_count;
1843 	spdk_bs_batch_t                 *batch;
1844 
1845 	batch = bs_sequence_to_batch(seq, blob_persist_clear_extents_cpl, ctx);
1846 	lba_count = bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE);
1847 
1848 	/* Clear all extent_pages that were truncated */
1849 	for (i = blob->active.num_extent_pages; i < blob->active.extent_pages_array_size; i++) {
1850 		/* Nothing to clear if it was not allocated */
1851 		if (blob->active.extent_pages[i] != 0) {
1852 			lba = bs_md_page_to_lba(bs, blob->active.extent_pages[i]);
1853 			bs_batch_write_zeroes_dev(batch, lba, lba_count);
1854 		}
1855 	}
1856 
1857 	bs_batch_close(batch);
1858 }
1859 
1860 static void
1861 blob_persist_clear_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1862 {
1863 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1864 	struct spdk_blob		*blob = ctx->blob;
1865 	struct spdk_blob_store		*bs = blob->bs;
1866 	size_t				i;
1867 
1868 	if (bserrno != 0) {
1869 		blob_persist_complete(seq, ctx, bserrno);
1870 		return;
1871 	}
1872 
1873 	spdk_spin_lock(&bs->used_lock);
1874 	/* Release all clusters that were truncated */
1875 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1876 		uint32_t cluster_num = bs_lba_to_cluster(bs, blob->active.clusters[i]);
1877 
1878 		/* Nothing to release if it was not allocated */
1879 		if (blob->active.clusters[i] != 0) {
1880 			bs_release_cluster(bs, cluster_num);
1881 		}
1882 	}
1883 	spdk_spin_unlock(&bs->used_lock);
1884 
1885 	if (blob->active.num_clusters == 0) {
1886 		free(blob->active.clusters);
1887 		blob->active.clusters = NULL;
1888 		blob->active.cluster_array_size = 0;
1889 	} else if (blob->active.num_clusters != blob->active.cluster_array_size) {
1890 #ifndef __clang_analyzer__
1891 		void *tmp;
1892 
1893 		/* scan-build really can't figure reallocs, workaround it */
1894 		tmp = realloc(blob->active.clusters, sizeof(*blob->active.clusters) * blob->active.num_clusters);
1895 		assert(tmp != NULL);
1896 		blob->active.clusters = tmp;
1897 
1898 #endif
1899 		blob->active.cluster_array_size = blob->active.num_clusters;
1900 	}
1901 
1902 	/* Move on to clearing extent pages */
1903 	blob_persist_clear_extents(seq, ctx);
1904 }
1905 
1906 static void
1907 blob_persist_clear_clusters(spdk_bs_sequence_t *seq, struct spdk_blob_persist_ctx *ctx)
1908 {
1909 	struct spdk_blob		*blob = ctx->blob;
1910 	struct spdk_blob_store		*bs = blob->bs;
1911 	spdk_bs_batch_t			*batch;
1912 	size_t				i;
1913 	uint64_t			lba;
1914 	uint64_t			lba_count;
1915 
1916 	/* Clusters don't move around in blobs. The list shrinks or grows
1917 	 * at the end, but no changes ever occur in the middle of the list.
1918 	 */
1919 
1920 	batch = bs_sequence_to_batch(seq, blob_persist_clear_clusters_cpl, ctx);
1921 
1922 	/* Clear all clusters that were truncated */
1923 	lba = 0;
1924 	lba_count = 0;
1925 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1926 		uint64_t next_lba = blob->active.clusters[i];
1927 		uint64_t next_lba_count = bs_cluster_to_lba(bs, 1);
1928 
1929 		if (next_lba > 0 && (lba + lba_count) == next_lba) {
1930 			/* This cluster is contiguous with the previous one. */
1931 			lba_count += next_lba_count;
1932 			continue;
1933 		} else if (next_lba == 0) {
1934 			continue;
1935 		}
1936 
1937 		/* This cluster is not contiguous with the previous one. */
1938 
1939 		/* If a run of LBAs previously existing, clear them now */
1940 		if (lba_count > 0) {
1941 			bs_batch_clear_dev(ctx, batch, lba, lba_count);
1942 		}
1943 
1944 		/* Start building the next batch */
1945 		lba = next_lba;
1946 		if (next_lba > 0) {
1947 			lba_count = next_lba_count;
1948 		} else {
1949 			lba_count = 0;
1950 		}
1951 	}
1952 
1953 	/* If we ended with a contiguous set of LBAs, clear them now */
1954 	if (lba_count > 0) {
1955 		bs_batch_clear_dev(ctx, batch, lba, lba_count);
1956 	}
1957 
1958 	bs_batch_close(batch);
1959 }
1960 
1961 static void
1962 blob_persist_zero_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1963 {
1964 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1965 	struct spdk_blob		*blob = ctx->blob;
1966 	struct spdk_blob_store		*bs = blob->bs;
1967 	size_t				i;
1968 
1969 	if (bserrno != 0) {
1970 		blob_persist_complete(seq, ctx, bserrno);
1971 		return;
1972 	}
1973 
1974 	spdk_spin_lock(&bs->used_lock);
1975 
1976 	/* This loop starts at 1 because the first page is special and handled
1977 	 * below. The pages (except the first) are never written in place,
1978 	 * so any pages in the clean list must be zeroed.
1979 	 */
1980 	for (i = 1; i < blob->clean.num_pages; i++) {
1981 		bs_release_md_page(bs, blob->clean.pages[i]);
1982 	}
1983 
1984 	if (blob->active.num_pages == 0) {
1985 		uint32_t page_num;
1986 
1987 		page_num = bs_blobid_to_page(blob->id);
1988 		bs_release_md_page(bs, page_num);
1989 	}
1990 
1991 	spdk_spin_unlock(&bs->used_lock);
1992 
1993 	/* Move on to clearing clusters */
1994 	blob_persist_clear_clusters(seq, ctx);
1995 }
1996 
1997 static void
1998 blob_persist_zero_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1999 {
2000 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
2001 	struct spdk_blob		*blob = ctx->blob;
2002 	struct spdk_blob_store		*bs = blob->bs;
2003 	uint64_t			lba;
2004 	uint64_t			lba_count;
2005 	spdk_bs_batch_t			*batch;
2006 	size_t				i;
2007 
2008 	if (bserrno != 0) {
2009 		blob_persist_complete(seq, ctx, bserrno);
2010 		return;
2011 	}
2012 
2013 	batch = bs_sequence_to_batch(seq, blob_persist_zero_pages_cpl, ctx);
2014 
2015 	lba_count = bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE);
2016 
2017 	/* This loop starts at 1 because the first page is special and handled
2018 	 * below. The pages (except the first) are never written in place,
2019 	 * so any pages in the clean list must be zeroed.
2020 	 */
2021 	for (i = 1; i < blob->clean.num_pages; i++) {
2022 		lba = bs_md_page_to_lba(bs, blob->clean.pages[i]);
2023 
2024 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
2025 	}
2026 
2027 	/* The first page will only be zeroed if this is a delete. */
2028 	if (blob->active.num_pages == 0) {
2029 		uint32_t page_num;
2030 
2031 		/* The first page in the metadata goes where the blobid indicates */
2032 		page_num = bs_blobid_to_page(blob->id);
2033 		lba = bs_md_page_to_lba(bs, page_num);
2034 
2035 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
2036 	}
2037 
2038 	bs_batch_close(batch);
2039 }
2040 
2041 static void
2042 blob_persist_write_page_root(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2043 {
2044 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
2045 	struct spdk_blob		*blob = ctx->blob;
2046 	struct spdk_blob_store		*bs = blob->bs;
2047 	uint64_t			lba;
2048 	uint32_t			lba_count;
2049 	struct spdk_blob_md_page	*page;
2050 
2051 	if (bserrno != 0) {
2052 		blob_persist_complete(seq, ctx, bserrno);
2053 		return;
2054 	}
2055 
2056 	if (blob->active.num_pages == 0) {
2057 		/* Move on to the next step */
2058 		blob_persist_zero_pages(seq, ctx, 0);
2059 		return;
2060 	}
2061 
2062 	lba_count = bs_byte_to_lba(bs, sizeof(*page));
2063 
2064 	page = &ctx->pages[0];
2065 	/* The first page in the metadata goes where the blobid indicates */
2066 	lba = bs_md_page_to_lba(bs, bs_blobid_to_page(blob->id));
2067 
2068 	bs_sequence_write_dev(seq, page, lba, lba_count,
2069 			      blob_persist_zero_pages, ctx);
2070 }
2071 
2072 static void
2073 blob_persist_write_page_chain(spdk_bs_sequence_t *seq, struct spdk_blob_persist_ctx *ctx)
2074 {
2075 	struct spdk_blob		*blob = ctx->blob;
2076 	struct spdk_blob_store		*bs = blob->bs;
2077 	uint64_t			lba;
2078 	uint32_t			lba_count;
2079 	struct spdk_blob_md_page	*page;
2080 	spdk_bs_batch_t			*batch;
2081 	size_t				i;
2082 
2083 	/* Clusters don't move around in blobs. The list shrinks or grows
2084 	 * at the end, but no changes ever occur in the middle of the list.
2085 	 */
2086 
2087 	lba_count = bs_byte_to_lba(bs, sizeof(*page));
2088 
2089 	batch = bs_sequence_to_batch(seq, blob_persist_write_page_root, ctx);
2090 
2091 	/* This starts at 1. The root page is not written until
2092 	 * all of the others are finished
2093 	 */
2094 	for (i = 1; i < blob->active.num_pages; i++) {
2095 		page = &ctx->pages[i];
2096 		assert(page->sequence_num == i);
2097 
2098 		lba = bs_md_page_to_lba(bs, blob->active.pages[i]);
2099 
2100 		bs_batch_write_dev(batch, page, lba, lba_count);
2101 	}
2102 
2103 	bs_batch_close(batch);
2104 }
2105 
2106 static int
2107 blob_resize(struct spdk_blob *blob, uint64_t sz)
2108 {
2109 	uint64_t	i;
2110 	uint64_t	*tmp;
2111 	uint64_t	cluster;
2112 	uint32_t	lfmd; /*  lowest free md page */
2113 	uint64_t	num_clusters;
2114 	uint32_t	*ep_tmp;
2115 	uint64_t	new_num_ep = 0, current_num_ep = 0;
2116 	struct spdk_blob_store *bs;
2117 	int		rc;
2118 
2119 	bs = blob->bs;
2120 
2121 	blob_verify_md_op(blob);
2122 
2123 	if (blob->active.num_clusters == sz) {
2124 		return 0;
2125 	}
2126 
2127 	if (blob->active.num_clusters < blob->active.cluster_array_size) {
2128 		/* If this blob was resized to be larger, then smaller, then
2129 		 * larger without syncing, then the cluster array already
2130 		 * contains spare assigned clusters we can use.
2131 		 */
2132 		num_clusters = spdk_min(blob->active.cluster_array_size,
2133 					sz);
2134 	} else {
2135 		num_clusters = blob->active.num_clusters;
2136 	}
2137 
2138 	if (blob->use_extent_table) {
2139 		/* Round up since every cluster beyond current Extent Table size,
2140 		 * requires new extent page. */
2141 		new_num_ep = spdk_divide_round_up(sz, SPDK_EXTENTS_PER_EP);
2142 		current_num_ep = spdk_divide_round_up(num_clusters, SPDK_EXTENTS_PER_EP);
2143 	}
2144 
2145 	assert(!spdk_spin_held(&bs->used_lock));
2146 
2147 	/* Check first that we have enough clusters and md pages before we start claiming them.
2148 	 * bs->used_lock is held to ensure that clusters we think are free are still free when we go
2149 	 * to claim them later in this function.
2150 	 */
2151 	if (sz > num_clusters && spdk_blob_is_thin_provisioned(blob) == false) {
2152 		spdk_spin_lock(&bs->used_lock);
2153 		if ((sz - num_clusters) > bs->num_free_clusters) {
2154 			rc = -ENOSPC;
2155 			goto out;
2156 		}
2157 		lfmd = 0;
2158 		for (i = current_num_ep; i < new_num_ep ; i++) {
2159 			lfmd = spdk_bit_array_find_first_clear(blob->bs->used_md_pages, lfmd);
2160 			if (lfmd == UINT32_MAX) {
2161 				/* No more free md pages. Cannot satisfy the request */
2162 				rc = -ENOSPC;
2163 				goto out;
2164 			}
2165 		}
2166 	}
2167 
2168 	if (sz > num_clusters) {
2169 		/* Expand the cluster array if necessary.
2170 		 * We only shrink the array when persisting.
2171 		 */
2172 		tmp = realloc(blob->active.clusters, sizeof(*blob->active.clusters) * sz);
2173 		if (sz > 0 && tmp == NULL) {
2174 			rc = -ENOMEM;
2175 			goto out;
2176 		}
2177 		memset(tmp + blob->active.cluster_array_size, 0,
2178 		       sizeof(*blob->active.clusters) * (sz - blob->active.cluster_array_size));
2179 		blob->active.clusters = tmp;
2180 		blob->active.cluster_array_size = sz;
2181 
2182 		/* Expand the extents table, only if enough clusters were added */
2183 		if (new_num_ep > current_num_ep && blob->use_extent_table) {
2184 			ep_tmp = realloc(blob->active.extent_pages, sizeof(*blob->active.extent_pages) * new_num_ep);
2185 			if (new_num_ep > 0 && ep_tmp == NULL) {
2186 				rc = -ENOMEM;
2187 				goto out;
2188 			}
2189 			memset(ep_tmp + blob->active.extent_pages_array_size, 0,
2190 			       sizeof(*blob->active.extent_pages) * (new_num_ep - blob->active.extent_pages_array_size));
2191 			blob->active.extent_pages = ep_tmp;
2192 			blob->active.extent_pages_array_size = new_num_ep;
2193 		}
2194 	}
2195 
2196 	blob->state = SPDK_BLOB_STATE_DIRTY;
2197 
2198 	if (spdk_blob_is_thin_provisioned(blob) == false) {
2199 		cluster = 0;
2200 		lfmd = 0;
2201 		for (i = num_clusters; i < sz; i++) {
2202 			bs_allocate_cluster(blob, i, &cluster, &lfmd, true);
2203 			/* Do not increment lfmd here.  lfmd will get updated
2204 			 * to the md_page allocated (if any) when a new extent
2205 			 * page is needed.  Just pass that value again,
2206 			 * bs_allocate_cluster will just start at that index
2207 			 * to find the next free md_page when needed.
2208 			 */
2209 		}
2210 	}
2211 
2212 	blob->active.num_clusters = sz;
2213 	blob->active.num_extent_pages = new_num_ep;
2214 
2215 	rc = 0;
2216 out:
2217 	if (spdk_spin_held(&bs->used_lock)) {
2218 		spdk_spin_unlock(&bs->used_lock);
2219 	}
2220 
2221 	return rc;
2222 }
2223 
2224 static void
2225 blob_persist_generate_new_md(struct spdk_blob_persist_ctx *ctx)
2226 {
2227 	spdk_bs_sequence_t *seq = ctx->seq;
2228 	struct spdk_blob *blob = ctx->blob;
2229 	struct spdk_blob_store *bs = blob->bs;
2230 	uint64_t i;
2231 	uint32_t page_num;
2232 	void *tmp;
2233 	int rc;
2234 
2235 	/* Generate the new metadata */
2236 	rc = blob_serialize(blob, &ctx->pages, &blob->active.num_pages);
2237 	if (rc < 0) {
2238 		blob_persist_complete(seq, ctx, rc);
2239 		return;
2240 	}
2241 
2242 	assert(blob->active.num_pages >= 1);
2243 
2244 	/* Resize the cache of page indices */
2245 	tmp = realloc(blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
2246 	if (!tmp) {
2247 		blob_persist_complete(seq, ctx, -ENOMEM);
2248 		return;
2249 	}
2250 	blob->active.pages = tmp;
2251 
2252 	/* Assign this metadata to pages. This requires two passes - one to verify that there are
2253 	 * enough pages and a second to actually claim them. The used_lock is held across
2254 	 * both passes to ensure things don't change in the middle.
2255 	 */
2256 	spdk_spin_lock(&bs->used_lock);
2257 	page_num = 0;
2258 	/* Note that this loop starts at one. The first page location is fixed by the blobid. */
2259 	for (i = 1; i < blob->active.num_pages; i++) {
2260 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
2261 		if (page_num == UINT32_MAX) {
2262 			spdk_spin_unlock(&bs->used_lock);
2263 			blob_persist_complete(seq, ctx, -ENOMEM);
2264 			return;
2265 		}
2266 		page_num++;
2267 	}
2268 
2269 	page_num = 0;
2270 	blob->active.pages[0] = bs_blobid_to_page(blob->id);
2271 	for (i = 1; i < blob->active.num_pages; i++) {
2272 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
2273 		ctx->pages[i - 1].next = page_num;
2274 		/* Now that previous metadata page is complete, calculate the crc for it. */
2275 		ctx->pages[i - 1].crc = blob_md_page_calc_crc(&ctx->pages[i - 1]);
2276 		blob->active.pages[i] = page_num;
2277 		bs_claim_md_page(bs, page_num);
2278 		SPDK_DEBUGLOG(blob, "Claiming page %u for blob 0x%" PRIx64 "\n", page_num,
2279 			      blob->id);
2280 		page_num++;
2281 	}
2282 	spdk_spin_unlock(&bs->used_lock);
2283 	ctx->pages[i - 1].crc = blob_md_page_calc_crc(&ctx->pages[i - 1]);
2284 	/* Start writing the metadata from last page to first */
2285 	blob->state = SPDK_BLOB_STATE_CLEAN;
2286 	blob_persist_write_page_chain(seq, ctx);
2287 }
2288 
2289 static void
2290 blob_persist_write_extent_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2291 {
2292 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
2293 	struct spdk_blob		*blob = ctx->blob;
2294 	size_t				i;
2295 	uint32_t			extent_page_id;
2296 	uint32_t                        page_count = 0;
2297 	int				rc;
2298 
2299 	if (ctx->extent_page != NULL) {
2300 		spdk_free(ctx->extent_page);
2301 		ctx->extent_page = NULL;
2302 	}
2303 
2304 	if (bserrno != 0) {
2305 		blob_persist_complete(seq, ctx, bserrno);
2306 		return;
2307 	}
2308 
2309 	/* Only write out Extent Pages when blob was resized. */
2310 	for (i = ctx->next_extent_page; i < blob->active.extent_pages_array_size; i++) {
2311 		extent_page_id = blob->active.extent_pages[i];
2312 		if (extent_page_id == 0) {
2313 			/* No Extent Page to persist */
2314 			assert(spdk_blob_is_thin_provisioned(blob));
2315 			continue;
2316 		}
2317 		assert(spdk_bit_array_get(blob->bs->used_md_pages, extent_page_id));
2318 		ctx->next_extent_page = i + 1;
2319 		rc = blob_serialize_add_page(ctx->blob, &ctx->extent_page, &page_count, &ctx->extent_page);
2320 		if (rc < 0) {
2321 			blob_persist_complete(seq, ctx, rc);
2322 			return;
2323 		}
2324 
2325 		blob->state = SPDK_BLOB_STATE_DIRTY;
2326 		blob_serialize_extent_page(blob, i * SPDK_EXTENTS_PER_EP, ctx->extent_page);
2327 
2328 		ctx->extent_page->crc = blob_md_page_calc_crc(ctx->extent_page);
2329 
2330 		bs_sequence_write_dev(seq, ctx->extent_page, bs_md_page_to_lba(blob->bs, extent_page_id),
2331 				      bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
2332 				      blob_persist_write_extent_pages, ctx);
2333 		return;
2334 	}
2335 
2336 	blob_persist_generate_new_md(ctx);
2337 }
2338 
2339 static void
2340 blob_persist_start(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2341 {
2342 	struct spdk_blob_persist_ctx *ctx = cb_arg;
2343 	struct spdk_blob *blob = ctx->blob;
2344 
2345 	if (bserrno != 0) {
2346 		blob_persist_complete(seq, ctx, bserrno);
2347 		return;
2348 	}
2349 
2350 	if (blob->active.num_pages == 0) {
2351 		/* This is the signal that the blob should be deleted.
2352 		 * Immediately jump to the clean up routine. */
2353 		assert(blob->clean.num_pages > 0);
2354 		blob->state = SPDK_BLOB_STATE_CLEAN;
2355 		blob_persist_zero_pages(seq, ctx, 0);
2356 		return;
2357 
2358 	}
2359 
2360 	if (blob->clean.num_clusters < blob->active.num_clusters) {
2361 		/* Blob was resized up */
2362 		assert(blob->clean.num_extent_pages <= blob->active.num_extent_pages);
2363 		ctx->next_extent_page = spdk_max(1, blob->clean.num_extent_pages) - 1;
2364 	} else if (blob->active.num_clusters < blob->active.cluster_array_size) {
2365 		/* Blob was resized down */
2366 		assert(blob->clean.num_extent_pages >= blob->active.num_extent_pages);
2367 		ctx->next_extent_page = spdk_max(1, blob->active.num_extent_pages) - 1;
2368 	} else {
2369 		/* No change in size occurred */
2370 		blob_persist_generate_new_md(ctx);
2371 		return;
2372 	}
2373 
2374 	blob_persist_write_extent_pages(seq, ctx, 0);
2375 }
2376 
2377 struct spdk_bs_mark_dirty {
2378 	struct spdk_blob_store		*bs;
2379 	struct spdk_bs_super_block	*super;
2380 	spdk_bs_sequence_cpl		cb_fn;
2381 	void				*cb_arg;
2382 };
2383 
2384 static void
2385 bs_mark_dirty_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2386 {
2387 	struct spdk_bs_mark_dirty *ctx = cb_arg;
2388 
2389 	if (bserrno == 0) {
2390 		ctx->bs->clean = 0;
2391 	}
2392 
2393 	ctx->cb_fn(seq, ctx->cb_arg, bserrno);
2394 
2395 	spdk_free(ctx->super);
2396 	free(ctx);
2397 }
2398 
2399 static void bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2400 			   struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg);
2401 
2402 
2403 static void
2404 bs_mark_dirty_write(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2405 {
2406 	struct spdk_bs_mark_dirty *ctx = cb_arg;
2407 
2408 	if (bserrno != 0) {
2409 		bs_mark_dirty_write_cpl(seq, ctx, bserrno);
2410 		return;
2411 	}
2412 
2413 	ctx->super->clean = 0;
2414 	if (ctx->super->size == 0) {
2415 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
2416 	}
2417 
2418 	bs_write_super(seq, ctx->bs, ctx->super, bs_mark_dirty_write_cpl, ctx);
2419 }
2420 
2421 static void
2422 bs_mark_dirty(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2423 	      spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2424 {
2425 	struct spdk_bs_mark_dirty *ctx;
2426 
2427 	/* Blobstore is already marked dirty */
2428 	if (bs->clean == 0) {
2429 		cb_fn(seq, cb_arg, 0);
2430 		return;
2431 	}
2432 
2433 	ctx = calloc(1, sizeof(*ctx));
2434 	if (!ctx) {
2435 		cb_fn(seq, cb_arg, -ENOMEM);
2436 		return;
2437 	}
2438 	ctx->bs = bs;
2439 	ctx->cb_fn = cb_fn;
2440 	ctx->cb_arg = cb_arg;
2441 
2442 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
2443 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2444 	if (!ctx->super) {
2445 		free(ctx);
2446 		cb_fn(seq, cb_arg, -ENOMEM);
2447 		return;
2448 	}
2449 
2450 	bs_sequence_read_dev(seq, ctx->super, bs_page_to_lba(bs, 0),
2451 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
2452 			     bs_mark_dirty_write, ctx);
2453 }
2454 
2455 /* Write a blob to disk */
2456 static void
2457 blob_persist(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
2458 	     spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2459 {
2460 	struct spdk_blob_persist_ctx *ctx;
2461 
2462 	blob_verify_md_op(blob);
2463 
2464 	if (blob->state == SPDK_BLOB_STATE_CLEAN && TAILQ_EMPTY(&blob->persists_to_complete)) {
2465 		cb_fn(seq, cb_arg, 0);
2466 		return;
2467 	}
2468 
2469 	ctx = calloc(1, sizeof(*ctx));
2470 	if (!ctx) {
2471 		cb_fn(seq, cb_arg, -ENOMEM);
2472 		return;
2473 	}
2474 	ctx->blob = blob;
2475 	ctx->seq = seq;
2476 	ctx->cb_fn = cb_fn;
2477 	ctx->cb_arg = cb_arg;
2478 
2479 	/* Multiple blob persists can affect one another, via blob->state or
2480 	 * blob mutable data changes. To prevent it, queue up the persists. */
2481 	if (!TAILQ_EMPTY(&blob->persists_to_complete)) {
2482 		TAILQ_INSERT_TAIL(&blob->pending_persists, ctx, link);
2483 		return;
2484 	}
2485 	TAILQ_INSERT_HEAD(&blob->persists_to_complete, ctx, link);
2486 
2487 	bs_mark_dirty(seq, blob->bs, blob_persist_start, ctx);
2488 }
2489 
2490 struct spdk_blob_copy_cluster_ctx {
2491 	struct spdk_blob *blob;
2492 	uint8_t *buf;
2493 	uint64_t page;
2494 	uint64_t new_cluster;
2495 	uint32_t new_extent_page;
2496 	spdk_bs_sequence_t *seq;
2497 	struct spdk_blob_md_page *new_cluster_page;
2498 };
2499 
2500 static void
2501 blob_allocate_and_copy_cluster_cpl(void *cb_arg, int bserrno)
2502 {
2503 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2504 	struct spdk_bs_request_set *set = (struct spdk_bs_request_set *)ctx->seq;
2505 	TAILQ_HEAD(, spdk_bs_request_set) requests;
2506 	spdk_bs_user_op_t *op;
2507 
2508 	TAILQ_INIT(&requests);
2509 	TAILQ_SWAP(&set->channel->need_cluster_alloc, &requests, spdk_bs_request_set, link);
2510 
2511 	while (!TAILQ_EMPTY(&requests)) {
2512 		op = TAILQ_FIRST(&requests);
2513 		TAILQ_REMOVE(&requests, op, link);
2514 		if (bserrno == 0) {
2515 			bs_user_op_execute(op);
2516 		} else {
2517 			bs_user_op_abort(op, bserrno);
2518 		}
2519 	}
2520 
2521 	spdk_free(ctx->buf);
2522 	free(ctx);
2523 }
2524 
2525 static void
2526 blob_insert_cluster_cpl(void *cb_arg, int bserrno)
2527 {
2528 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2529 
2530 	if (bserrno) {
2531 		if (bserrno == -EEXIST) {
2532 			/* The metadata insert failed because another thread
2533 			 * allocated the cluster first. Free our cluster
2534 			 * but continue without error. */
2535 			bserrno = 0;
2536 		}
2537 		spdk_spin_lock(&ctx->blob->bs->used_lock);
2538 		bs_release_cluster(ctx->blob->bs, ctx->new_cluster);
2539 		if (ctx->new_extent_page != 0) {
2540 			bs_release_md_page(ctx->blob->bs, ctx->new_extent_page);
2541 		}
2542 		spdk_spin_unlock(&ctx->blob->bs->used_lock);
2543 	}
2544 
2545 	bs_sequence_finish(ctx->seq, bserrno);
2546 }
2547 
2548 static void
2549 blob_write_copy_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2550 {
2551 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2552 	uint32_t cluster_number;
2553 
2554 	if (bserrno) {
2555 		/* The write failed, so jump to the final completion handler */
2556 		bs_sequence_finish(seq, bserrno);
2557 		return;
2558 	}
2559 
2560 	cluster_number = bs_page_to_cluster(ctx->blob->bs, ctx->page);
2561 
2562 	blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
2563 					 ctx->new_extent_page, ctx->new_cluster_page, blob_insert_cluster_cpl, ctx);
2564 }
2565 
2566 static void
2567 blob_write_copy(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2568 {
2569 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2570 
2571 	if (bserrno != 0) {
2572 		/* The read failed, so jump to the final completion handler */
2573 		bs_sequence_finish(seq, bserrno);
2574 		return;
2575 	}
2576 
2577 	/* Write whole cluster */
2578 	bs_sequence_write_dev(seq, ctx->buf,
2579 			      bs_cluster_to_lba(ctx->blob->bs, ctx->new_cluster),
2580 			      bs_cluster_to_lba(ctx->blob->bs, 1),
2581 			      blob_write_copy_cpl, ctx);
2582 }
2583 
2584 static bool
2585 blob_can_copy(struct spdk_blob *blob, uint32_t cluster_start_page, uint64_t *base_lba)
2586 {
2587 	uint64_t lba = bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page);
2588 
2589 	return (!blob_is_esnap_clone(blob) && blob->bs->dev->copy != NULL) &&
2590 	       blob->back_bs_dev->translate_lba(blob->back_bs_dev, lba, base_lba);
2591 }
2592 
2593 static void
2594 blob_copy(struct spdk_blob_copy_cluster_ctx *ctx, spdk_bs_user_op_t *op, uint64_t src_lba)
2595 {
2596 	struct spdk_blob *blob = ctx->blob;
2597 	uint64_t lba_count = bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz);
2598 
2599 	bs_sequence_copy_dev(ctx->seq,
2600 			     bs_cluster_to_lba(blob->bs, ctx->new_cluster),
2601 			     src_lba,
2602 			     lba_count,
2603 			     blob_write_copy_cpl, ctx);
2604 }
2605 
2606 static void
2607 bs_allocate_and_copy_cluster(struct spdk_blob *blob,
2608 			     struct spdk_io_channel *_ch,
2609 			     uint64_t io_unit, spdk_bs_user_op_t *op)
2610 {
2611 	struct spdk_bs_cpl cpl;
2612 	struct spdk_bs_channel *ch;
2613 	struct spdk_blob_copy_cluster_ctx *ctx;
2614 	uint32_t cluster_start_page;
2615 	uint32_t cluster_number;
2616 	bool is_zeroes;
2617 	bool can_copy;
2618 	uint64_t copy_src_lba;
2619 	int rc;
2620 
2621 	ch = spdk_io_channel_get_ctx(_ch);
2622 
2623 	if (!TAILQ_EMPTY(&ch->need_cluster_alloc)) {
2624 		/* There are already operations pending. Queue this user op
2625 		 * and return because it will be re-executed when the outstanding
2626 		 * cluster allocation completes. */
2627 		TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
2628 		return;
2629 	}
2630 
2631 	/* Round the io_unit offset down to the first page in the cluster */
2632 	cluster_start_page = bs_io_unit_to_cluster_start(blob, io_unit);
2633 
2634 	/* Calculate which index in the metadata cluster array the corresponding
2635 	 * cluster is supposed to be at. */
2636 	cluster_number = bs_io_unit_to_cluster_number(blob, io_unit);
2637 
2638 	ctx = calloc(1, sizeof(*ctx));
2639 	if (!ctx) {
2640 		bs_user_op_abort(op, -ENOMEM);
2641 		return;
2642 	}
2643 
2644 	assert(blob->bs->cluster_sz % blob->back_bs_dev->blocklen == 0);
2645 
2646 	ctx->blob = blob;
2647 	ctx->page = cluster_start_page;
2648 	ctx->new_cluster_page = ch->new_cluster_page;
2649 	memset(ctx->new_cluster_page, 0, SPDK_BS_PAGE_SIZE);
2650 	can_copy = blob_can_copy(blob, cluster_start_page, &copy_src_lba);
2651 
2652 	is_zeroes = blob->back_bs_dev->is_zeroes(blob->back_bs_dev,
2653 			bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page),
2654 			bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz));
2655 	if (blob->parent_id != SPDK_BLOBID_INVALID && !is_zeroes && !can_copy) {
2656 		ctx->buf = spdk_malloc(blob->bs->cluster_sz, blob->back_bs_dev->blocklen,
2657 				       NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2658 		if (!ctx->buf) {
2659 			SPDK_ERRLOG("DMA allocation for cluster of size = %" PRIu32 " failed.\n",
2660 				    blob->bs->cluster_sz);
2661 			free(ctx);
2662 			bs_user_op_abort(op, -ENOMEM);
2663 			return;
2664 		}
2665 	}
2666 
2667 	spdk_spin_lock(&blob->bs->used_lock);
2668 	rc = bs_allocate_cluster(blob, cluster_number, &ctx->new_cluster, &ctx->new_extent_page,
2669 				 false);
2670 	spdk_spin_unlock(&blob->bs->used_lock);
2671 	if (rc != 0) {
2672 		spdk_free(ctx->buf);
2673 		free(ctx);
2674 		bs_user_op_abort(op, rc);
2675 		return;
2676 	}
2677 
2678 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2679 	cpl.u.blob_basic.cb_fn = blob_allocate_and_copy_cluster_cpl;
2680 	cpl.u.blob_basic.cb_arg = ctx;
2681 
2682 	ctx->seq = bs_sequence_start_blob(_ch, &cpl, blob);
2683 	if (!ctx->seq) {
2684 		spdk_spin_lock(&blob->bs->used_lock);
2685 		bs_release_cluster(blob->bs, ctx->new_cluster);
2686 		spdk_spin_unlock(&blob->bs->used_lock);
2687 		spdk_free(ctx->buf);
2688 		free(ctx);
2689 		bs_user_op_abort(op, -ENOMEM);
2690 		return;
2691 	}
2692 
2693 	/* Queue the user op to block other incoming operations */
2694 	TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
2695 
2696 	if (blob->parent_id != SPDK_BLOBID_INVALID && !is_zeroes) {
2697 		if (can_copy) {
2698 			blob_copy(ctx, op, copy_src_lba);
2699 		} else {
2700 			/* Read cluster from backing device */
2701 			bs_sequence_read_bs_dev(ctx->seq, blob->back_bs_dev, ctx->buf,
2702 						bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page),
2703 						bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz),
2704 						blob_write_copy, ctx);
2705 		}
2706 
2707 	} else {
2708 		blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
2709 						 ctx->new_extent_page, ctx->new_cluster_page, blob_insert_cluster_cpl, ctx);
2710 	}
2711 }
2712 
2713 static inline bool
2714 blob_calculate_lba_and_lba_count(struct spdk_blob *blob, uint64_t io_unit, uint64_t length,
2715 				 uint64_t *lba,	uint64_t *lba_count)
2716 {
2717 	*lba_count = length;
2718 
2719 	if (!bs_io_unit_is_allocated(blob, io_unit)) {
2720 		assert(blob->back_bs_dev != NULL);
2721 		*lba = bs_io_unit_to_back_dev_lba(blob, io_unit);
2722 		*lba_count = bs_io_unit_to_back_dev_lba(blob, *lba_count);
2723 		return false;
2724 	} else {
2725 		*lba = bs_blob_io_unit_to_lba(blob, io_unit);
2726 		return true;
2727 	}
2728 }
2729 
2730 struct op_split_ctx {
2731 	struct spdk_blob *blob;
2732 	struct spdk_io_channel *channel;
2733 	uint64_t io_unit_offset;
2734 	uint64_t io_units_remaining;
2735 	void *curr_payload;
2736 	enum spdk_blob_op_type op_type;
2737 	spdk_bs_sequence_t *seq;
2738 	bool in_submit_ctx;
2739 	bool completed_in_submit_ctx;
2740 	bool done;
2741 };
2742 
2743 static void
2744 blob_request_submit_op_split_next(void *cb_arg, int bserrno)
2745 {
2746 	struct op_split_ctx	*ctx = cb_arg;
2747 	struct spdk_blob	*blob = ctx->blob;
2748 	struct spdk_io_channel	*ch = ctx->channel;
2749 	enum spdk_blob_op_type	op_type = ctx->op_type;
2750 	uint8_t			*buf;
2751 	uint64_t		offset;
2752 	uint64_t		length;
2753 	uint64_t		op_length;
2754 
2755 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
2756 		bs_sequence_finish(ctx->seq, bserrno);
2757 		if (ctx->in_submit_ctx) {
2758 			/* Defer freeing of the ctx object, since it will be
2759 			 * accessed when this unwinds back to the submisison
2760 			 * context.
2761 			 */
2762 			ctx->done = true;
2763 		} else {
2764 			free(ctx);
2765 		}
2766 		return;
2767 	}
2768 
2769 	if (ctx->in_submit_ctx) {
2770 		/* If this split operation completed in the context
2771 		 * of its submission, mark the flag and return immediately
2772 		 * to avoid recursion.
2773 		 */
2774 		ctx->completed_in_submit_ctx = true;
2775 		return;
2776 	}
2777 
2778 	while (true) {
2779 		ctx->completed_in_submit_ctx = false;
2780 
2781 		offset = ctx->io_unit_offset;
2782 		length = ctx->io_units_remaining;
2783 		buf = ctx->curr_payload;
2784 		op_length = spdk_min(length, bs_num_io_units_to_cluster_boundary(blob,
2785 				     offset));
2786 
2787 		/* Update length and payload for next operation */
2788 		ctx->io_units_remaining -= op_length;
2789 		ctx->io_unit_offset += op_length;
2790 		if (op_type == SPDK_BLOB_WRITE || op_type == SPDK_BLOB_READ) {
2791 			ctx->curr_payload += op_length * blob->bs->io_unit_size;
2792 		}
2793 
2794 		assert(!ctx->in_submit_ctx);
2795 		ctx->in_submit_ctx = true;
2796 
2797 		switch (op_type) {
2798 		case SPDK_BLOB_READ:
2799 			spdk_blob_io_read(blob, ch, buf, offset, op_length,
2800 					  blob_request_submit_op_split_next, ctx);
2801 			break;
2802 		case SPDK_BLOB_WRITE:
2803 			spdk_blob_io_write(blob, ch, buf, offset, op_length,
2804 					   blob_request_submit_op_split_next, ctx);
2805 			break;
2806 		case SPDK_BLOB_UNMAP:
2807 			spdk_blob_io_unmap(blob, ch, offset, op_length,
2808 					   blob_request_submit_op_split_next, ctx);
2809 			break;
2810 		case SPDK_BLOB_WRITE_ZEROES:
2811 			spdk_blob_io_write_zeroes(blob, ch, offset, op_length,
2812 						  blob_request_submit_op_split_next, ctx);
2813 			break;
2814 		case SPDK_BLOB_READV:
2815 		case SPDK_BLOB_WRITEV:
2816 			SPDK_ERRLOG("readv/write not valid\n");
2817 			bs_sequence_finish(ctx->seq, -EINVAL);
2818 			free(ctx);
2819 			return;
2820 		}
2821 
2822 #ifndef __clang_analyzer__
2823 		/* scan-build reports a false positive around accessing the ctx here. It
2824 		 * forms a path that recursively calls this function, but then says
2825 		 * "assuming ctx->in_submit_ctx is false", when that isn't possible.
2826 		 * This path does free(ctx), returns to here, and reports a use-after-free
2827 		 * bug.  Wrapping this bit of code so that scan-build doesn't see it
2828 		 * works around the scan-build bug.
2829 		 */
2830 		assert(ctx->in_submit_ctx);
2831 		ctx->in_submit_ctx = false;
2832 
2833 		/* If the operation completed immediately, loop back and submit the
2834 		 * next operation.  Otherwise we can return and the next split
2835 		 * operation will get submitted when this current operation is
2836 		 * later completed asynchronously.
2837 		 */
2838 		if (ctx->completed_in_submit_ctx) {
2839 			continue;
2840 		} else if (ctx->done) {
2841 			free(ctx);
2842 		}
2843 #endif
2844 		break;
2845 	}
2846 }
2847 
2848 static void
2849 blob_request_submit_op_split(struct spdk_io_channel *ch, struct spdk_blob *blob,
2850 			     void *payload, uint64_t offset, uint64_t length,
2851 			     spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
2852 {
2853 	struct op_split_ctx *ctx;
2854 	spdk_bs_sequence_t *seq;
2855 	struct spdk_bs_cpl cpl;
2856 
2857 	assert(blob != NULL);
2858 
2859 	ctx = calloc(1, sizeof(struct op_split_ctx));
2860 	if (ctx == NULL) {
2861 		cb_fn(cb_arg, -ENOMEM);
2862 		return;
2863 	}
2864 
2865 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2866 	cpl.u.blob_basic.cb_fn = cb_fn;
2867 	cpl.u.blob_basic.cb_arg = cb_arg;
2868 
2869 	seq = bs_sequence_start_blob(ch, &cpl, blob);
2870 	if (!seq) {
2871 		free(ctx);
2872 		cb_fn(cb_arg, -ENOMEM);
2873 		return;
2874 	}
2875 
2876 	ctx->blob = blob;
2877 	ctx->channel = ch;
2878 	ctx->curr_payload = payload;
2879 	ctx->io_unit_offset = offset;
2880 	ctx->io_units_remaining = length;
2881 	ctx->op_type = op_type;
2882 	ctx->seq = seq;
2883 
2884 	blob_request_submit_op_split_next(ctx, 0);
2885 }
2886 
2887 static void
2888 blob_request_submit_op_single(struct spdk_io_channel *_ch, struct spdk_blob *blob,
2889 			      void *payload, uint64_t offset, uint64_t length,
2890 			      spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
2891 {
2892 	struct spdk_bs_cpl cpl;
2893 	uint64_t lba;
2894 	uint64_t lba_count;
2895 	bool is_allocated;
2896 
2897 	assert(blob != NULL);
2898 
2899 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2900 	cpl.u.blob_basic.cb_fn = cb_fn;
2901 	cpl.u.blob_basic.cb_arg = cb_arg;
2902 
2903 	if (blob->frozen_refcnt) {
2904 		/* This blob I/O is frozen */
2905 		spdk_bs_user_op_t *op;
2906 		struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_ch);
2907 
2908 		op = bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
2909 		if (!op) {
2910 			cb_fn(cb_arg, -ENOMEM);
2911 			return;
2912 		}
2913 
2914 		TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
2915 
2916 		return;
2917 	}
2918 
2919 	is_allocated = blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
2920 
2921 	switch (op_type) {
2922 	case SPDK_BLOB_READ: {
2923 		spdk_bs_batch_t *batch;
2924 
2925 		batch = bs_batch_open(_ch, &cpl, blob);
2926 		if (!batch) {
2927 			cb_fn(cb_arg, -ENOMEM);
2928 			return;
2929 		}
2930 
2931 		if (is_allocated) {
2932 			/* Read from the blob */
2933 			bs_batch_read_dev(batch, payload, lba, lba_count);
2934 		} else {
2935 			/* Read from the backing block device */
2936 			bs_batch_read_bs_dev(batch, blob->back_bs_dev, payload, lba, lba_count);
2937 		}
2938 
2939 		bs_batch_close(batch);
2940 		break;
2941 	}
2942 	case SPDK_BLOB_WRITE:
2943 	case SPDK_BLOB_WRITE_ZEROES: {
2944 		if (is_allocated) {
2945 			/* Write to the blob */
2946 			spdk_bs_batch_t *batch;
2947 
2948 			if (lba_count == 0) {
2949 				cb_fn(cb_arg, 0);
2950 				return;
2951 			}
2952 
2953 			batch = bs_batch_open(_ch, &cpl, blob);
2954 			if (!batch) {
2955 				cb_fn(cb_arg, -ENOMEM);
2956 				return;
2957 			}
2958 
2959 			if (op_type == SPDK_BLOB_WRITE) {
2960 				bs_batch_write_dev(batch, payload, lba, lba_count);
2961 			} else {
2962 				bs_batch_write_zeroes_dev(batch, lba, lba_count);
2963 			}
2964 
2965 			bs_batch_close(batch);
2966 		} else {
2967 			/* Queue this operation and allocate the cluster */
2968 			spdk_bs_user_op_t *op;
2969 
2970 			op = bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
2971 			if (!op) {
2972 				cb_fn(cb_arg, -ENOMEM);
2973 				return;
2974 			}
2975 
2976 			bs_allocate_and_copy_cluster(blob, _ch, offset, op);
2977 		}
2978 		break;
2979 	}
2980 	case SPDK_BLOB_UNMAP: {
2981 		spdk_bs_batch_t *batch;
2982 
2983 		batch = bs_batch_open(_ch, &cpl, blob);
2984 		if (!batch) {
2985 			cb_fn(cb_arg, -ENOMEM);
2986 			return;
2987 		}
2988 
2989 		if (is_allocated) {
2990 			bs_batch_unmap_dev(batch, lba, lba_count);
2991 		}
2992 
2993 		bs_batch_close(batch);
2994 		break;
2995 	}
2996 	case SPDK_BLOB_READV:
2997 	case SPDK_BLOB_WRITEV:
2998 		SPDK_ERRLOG("readv/write not valid\n");
2999 		cb_fn(cb_arg, -EINVAL);
3000 		break;
3001 	}
3002 }
3003 
3004 static void
3005 blob_request_submit_op(struct spdk_blob *blob, struct spdk_io_channel *_channel,
3006 		       void *payload, uint64_t offset, uint64_t length,
3007 		       spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
3008 {
3009 	assert(blob != NULL);
3010 
3011 	if (blob->data_ro && op_type != SPDK_BLOB_READ) {
3012 		cb_fn(cb_arg, -EPERM);
3013 		return;
3014 	}
3015 
3016 	if (length == 0) {
3017 		cb_fn(cb_arg, 0);
3018 		return;
3019 	}
3020 
3021 	if (offset + length > bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
3022 		cb_fn(cb_arg, -EINVAL);
3023 		return;
3024 	}
3025 	if (length <= bs_num_io_units_to_cluster_boundary(blob, offset)) {
3026 		blob_request_submit_op_single(_channel, blob, payload, offset, length,
3027 					      cb_fn, cb_arg, op_type);
3028 	} else {
3029 		blob_request_submit_op_split(_channel, blob, payload, offset, length,
3030 					     cb_fn, cb_arg, op_type);
3031 	}
3032 }
3033 
3034 struct rw_iov_ctx {
3035 	struct spdk_blob *blob;
3036 	struct spdk_io_channel *channel;
3037 	spdk_blob_op_complete cb_fn;
3038 	void *cb_arg;
3039 	bool read;
3040 	int iovcnt;
3041 	struct iovec *orig_iov;
3042 	uint64_t io_unit_offset;
3043 	uint64_t io_units_remaining;
3044 	uint64_t io_units_done;
3045 	struct spdk_blob_ext_io_opts *ext_io_opts;
3046 	struct iovec iov[0];
3047 };
3048 
3049 static void
3050 rw_iov_done(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3051 {
3052 	assert(cb_arg == NULL);
3053 	bs_sequence_finish(seq, bserrno);
3054 }
3055 
3056 static void
3057 rw_iov_split_next(void *cb_arg, int bserrno)
3058 {
3059 	struct rw_iov_ctx *ctx = cb_arg;
3060 	struct spdk_blob *blob = ctx->blob;
3061 	struct iovec *iov, *orig_iov;
3062 	int iovcnt;
3063 	size_t orig_iovoff;
3064 	uint64_t io_units_count, io_units_to_boundary, io_unit_offset;
3065 	uint64_t byte_count;
3066 
3067 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
3068 		ctx->cb_fn(ctx->cb_arg, bserrno);
3069 		free(ctx);
3070 		return;
3071 	}
3072 
3073 	io_unit_offset = ctx->io_unit_offset;
3074 	io_units_to_boundary = bs_num_io_units_to_cluster_boundary(blob, io_unit_offset);
3075 	io_units_count = spdk_min(ctx->io_units_remaining, io_units_to_boundary);
3076 	/*
3077 	 * Get index and offset into the original iov array for our current position in the I/O sequence.
3078 	 *  byte_count will keep track of how many bytes remaining until orig_iov and orig_iovoff will
3079 	 *  point to the current position in the I/O sequence.
3080 	 */
3081 	byte_count = ctx->io_units_done * blob->bs->io_unit_size;
3082 	orig_iov = &ctx->orig_iov[0];
3083 	orig_iovoff = 0;
3084 	while (byte_count > 0) {
3085 		if (byte_count >= orig_iov->iov_len) {
3086 			byte_count -= orig_iov->iov_len;
3087 			orig_iov++;
3088 		} else {
3089 			orig_iovoff = byte_count;
3090 			byte_count = 0;
3091 		}
3092 	}
3093 
3094 	/*
3095 	 * Build an iov array for the next I/O in the sequence.  byte_count will keep track of how many
3096 	 *  bytes of this next I/O remain to be accounted for in the new iov array.
3097 	 */
3098 	byte_count = io_units_count * blob->bs->io_unit_size;
3099 	iov = &ctx->iov[0];
3100 	iovcnt = 0;
3101 	while (byte_count > 0) {
3102 		assert(iovcnt < ctx->iovcnt);
3103 		iov->iov_len = spdk_min(byte_count, orig_iov->iov_len - orig_iovoff);
3104 		iov->iov_base = orig_iov->iov_base + orig_iovoff;
3105 		byte_count -= iov->iov_len;
3106 		orig_iovoff = 0;
3107 		orig_iov++;
3108 		iov++;
3109 		iovcnt++;
3110 	}
3111 
3112 	ctx->io_unit_offset += io_units_count;
3113 	ctx->io_units_remaining -= io_units_count;
3114 	ctx->io_units_done += io_units_count;
3115 	iov = &ctx->iov[0];
3116 
3117 	if (ctx->read) {
3118 		spdk_blob_io_readv_ext(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
3119 				       io_units_count, rw_iov_split_next, ctx, ctx->ext_io_opts);
3120 	} else {
3121 		spdk_blob_io_writev_ext(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
3122 					io_units_count, rw_iov_split_next, ctx, ctx->ext_io_opts);
3123 	}
3124 }
3125 
3126 static void
3127 blob_request_submit_rw_iov(struct spdk_blob *blob, struct spdk_io_channel *_channel,
3128 			   struct iovec *iov, int iovcnt,
3129 			   uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg, bool read,
3130 			   struct spdk_blob_ext_io_opts *ext_io_opts)
3131 {
3132 	struct spdk_bs_cpl	cpl;
3133 
3134 	assert(blob != NULL);
3135 
3136 	if (!read && blob->data_ro) {
3137 		cb_fn(cb_arg, -EPERM);
3138 		return;
3139 	}
3140 
3141 	if (length == 0) {
3142 		cb_fn(cb_arg, 0);
3143 		return;
3144 	}
3145 
3146 	if (offset + length > bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
3147 		cb_fn(cb_arg, -EINVAL);
3148 		return;
3149 	}
3150 
3151 	/*
3152 	 * For now, we implement readv/writev using a sequence (instead of a batch) to account for having
3153 	 *  to split a request that spans a cluster boundary.  For I/O that do not span a cluster boundary,
3154 	 *  there will be no noticeable difference compared to using a batch.  For I/O that do span a cluster
3155 	 *  boundary, the target LBAs (after blob offset to LBA translation) may not be contiguous, so we need
3156 	 *  to allocate a separate iov array and split the I/O such that none of the resulting
3157 	 *  smaller I/O cross a cluster boundary.  These smaller I/O will be issued in sequence (not in parallel)
3158 	 *  but since this case happens very infrequently, any performance impact will be negligible.
3159 	 *
3160 	 * This could be optimized in the future to allocate a big enough iov array to account for all of the iovs
3161 	 *  for all of the smaller I/Os, pre-build all of the iov arrays for the smaller I/Os, then issue them
3162 	 *  in a batch.  That would also require creating an intermediate spdk_bs_cpl that would get called
3163 	 *  when the batch was completed, to allow for freeing the memory for the iov arrays.
3164 	 */
3165 	if (spdk_likely(length <= bs_num_io_units_to_cluster_boundary(blob, offset))) {
3166 		uint64_t lba_count;
3167 		uint64_t lba;
3168 		bool is_allocated;
3169 
3170 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
3171 		cpl.u.blob_basic.cb_fn = cb_fn;
3172 		cpl.u.blob_basic.cb_arg = cb_arg;
3173 
3174 		if (blob->frozen_refcnt) {
3175 			/* This blob I/O is frozen */
3176 			enum spdk_blob_op_type op_type;
3177 			spdk_bs_user_op_t *op;
3178 			struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_channel);
3179 
3180 			op_type = read ? SPDK_BLOB_READV : SPDK_BLOB_WRITEV;
3181 			op = bs_user_op_alloc(_channel, &cpl, op_type, blob, iov, iovcnt, offset, length);
3182 			if (!op) {
3183 				cb_fn(cb_arg, -ENOMEM);
3184 				return;
3185 			}
3186 
3187 			TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
3188 
3189 			return;
3190 		}
3191 
3192 		is_allocated = blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
3193 
3194 		if (read) {
3195 			spdk_bs_sequence_t *seq;
3196 
3197 			seq = bs_sequence_start_blob(_channel, &cpl, blob);
3198 			if (!seq) {
3199 				cb_fn(cb_arg, -ENOMEM);
3200 				return;
3201 			}
3202 
3203 			seq->ext_io_opts = ext_io_opts;
3204 
3205 			if (is_allocated) {
3206 				bs_sequence_readv_dev(seq, iov, iovcnt, lba, lba_count, rw_iov_done, NULL);
3207 			} else {
3208 				bs_sequence_readv_bs_dev(seq, blob->back_bs_dev, iov, iovcnt, lba, lba_count,
3209 							 rw_iov_done, NULL);
3210 			}
3211 		} else {
3212 			if (is_allocated) {
3213 				spdk_bs_sequence_t *seq;
3214 
3215 				seq = bs_sequence_start_blob(_channel, &cpl, blob);
3216 				if (!seq) {
3217 					cb_fn(cb_arg, -ENOMEM);
3218 					return;
3219 				}
3220 
3221 				seq->ext_io_opts = ext_io_opts;
3222 
3223 				bs_sequence_writev_dev(seq, iov, iovcnt, lba, lba_count, rw_iov_done, NULL);
3224 			} else {
3225 				/* Queue this operation and allocate the cluster */
3226 				spdk_bs_user_op_t *op;
3227 
3228 				op = bs_user_op_alloc(_channel, &cpl, SPDK_BLOB_WRITEV, blob, iov, iovcnt, offset,
3229 						      length);
3230 				if (!op) {
3231 					cb_fn(cb_arg, -ENOMEM);
3232 					return;
3233 				}
3234 
3235 				op->ext_io_opts = ext_io_opts;
3236 
3237 				bs_allocate_and_copy_cluster(blob, _channel, offset, op);
3238 			}
3239 		}
3240 	} else {
3241 		struct rw_iov_ctx *ctx;
3242 
3243 		ctx = calloc(1, sizeof(struct rw_iov_ctx) + iovcnt * sizeof(struct iovec));
3244 		if (ctx == NULL) {
3245 			cb_fn(cb_arg, -ENOMEM);
3246 			return;
3247 		}
3248 
3249 		ctx->blob = blob;
3250 		ctx->channel = _channel;
3251 		ctx->cb_fn = cb_fn;
3252 		ctx->cb_arg = cb_arg;
3253 		ctx->read = read;
3254 		ctx->orig_iov = iov;
3255 		ctx->iovcnt = iovcnt;
3256 		ctx->io_unit_offset = offset;
3257 		ctx->io_units_remaining = length;
3258 		ctx->io_units_done = 0;
3259 		ctx->ext_io_opts = ext_io_opts;
3260 
3261 		rw_iov_split_next(ctx, 0);
3262 	}
3263 }
3264 
3265 static struct spdk_blob *
3266 blob_lookup(struct spdk_blob_store *bs, spdk_blob_id blobid)
3267 {
3268 	struct spdk_blob find;
3269 
3270 	if (spdk_bit_array_get(bs->open_blobids, blobid) == 0) {
3271 		return NULL;
3272 	}
3273 
3274 	find.id = blobid;
3275 	return RB_FIND(spdk_blob_tree, &bs->open_blobs, &find);
3276 }
3277 
3278 static void
3279 blob_get_snapshot_and_clone_entries(struct spdk_blob *blob,
3280 				    struct spdk_blob_list **snapshot_entry, struct spdk_blob_list **clone_entry)
3281 {
3282 	assert(blob != NULL);
3283 	*snapshot_entry = NULL;
3284 	*clone_entry = NULL;
3285 
3286 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
3287 		return;
3288 	}
3289 
3290 	TAILQ_FOREACH(*snapshot_entry, &blob->bs->snapshots, link) {
3291 		if ((*snapshot_entry)->id == blob->parent_id) {
3292 			break;
3293 		}
3294 	}
3295 
3296 	if (*snapshot_entry != NULL) {
3297 		TAILQ_FOREACH(*clone_entry, &(*snapshot_entry)->clones, link) {
3298 			if ((*clone_entry)->id == blob->id) {
3299 				break;
3300 			}
3301 		}
3302 
3303 		assert(*clone_entry != NULL);
3304 	}
3305 }
3306 
3307 static int
3308 bs_channel_create(void *io_device, void *ctx_buf)
3309 {
3310 	struct spdk_blob_store		*bs = io_device;
3311 	struct spdk_bs_channel		*channel = ctx_buf;
3312 	struct spdk_bs_dev		*dev;
3313 	uint32_t			max_ops = bs->max_channel_ops;
3314 	uint32_t			i;
3315 
3316 	dev = bs->dev;
3317 
3318 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_bs_request_set));
3319 	if (!channel->req_mem) {
3320 		return -1;
3321 	}
3322 
3323 	TAILQ_INIT(&channel->reqs);
3324 
3325 	for (i = 0; i < max_ops; i++) {
3326 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
3327 	}
3328 
3329 	channel->bs = bs;
3330 	channel->dev = dev;
3331 	channel->dev_channel = dev->create_channel(dev);
3332 
3333 	if (!channel->dev_channel) {
3334 		SPDK_ERRLOG("Failed to create device channel.\n");
3335 		free(channel->req_mem);
3336 		return -1;
3337 	}
3338 
3339 	channel->new_cluster_page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0, NULL, SPDK_ENV_SOCKET_ID_ANY,
3340 				    SPDK_MALLOC_DMA);
3341 	if (!channel->new_cluster_page) {
3342 		SPDK_ERRLOG("Failed to allocate new cluster page\n");
3343 		free(channel->req_mem);
3344 		channel->dev->destroy_channel(channel->dev, channel->dev_channel);
3345 		return -1;
3346 	}
3347 
3348 	TAILQ_INIT(&channel->need_cluster_alloc);
3349 	TAILQ_INIT(&channel->queued_io);
3350 	RB_INIT(&channel->esnap_channels);
3351 
3352 	return 0;
3353 }
3354 
3355 static void
3356 bs_channel_destroy(void *io_device, void *ctx_buf)
3357 {
3358 	struct spdk_bs_channel *channel = ctx_buf;
3359 	spdk_bs_user_op_t *op;
3360 
3361 	while (!TAILQ_EMPTY(&channel->need_cluster_alloc)) {
3362 		op = TAILQ_FIRST(&channel->need_cluster_alloc);
3363 		TAILQ_REMOVE(&channel->need_cluster_alloc, op, link);
3364 		bs_user_op_abort(op, -EIO);
3365 	}
3366 
3367 	while (!TAILQ_EMPTY(&channel->queued_io)) {
3368 		op = TAILQ_FIRST(&channel->queued_io);
3369 		TAILQ_REMOVE(&channel->queued_io, op, link);
3370 		bs_user_op_abort(op, -EIO);
3371 	}
3372 
3373 	blob_esnap_destroy_bs_channel(channel);
3374 
3375 	free(channel->req_mem);
3376 	spdk_free(channel->new_cluster_page);
3377 	channel->dev->destroy_channel(channel->dev, channel->dev_channel);
3378 }
3379 
3380 static void
3381 bs_dev_destroy(void *io_device)
3382 {
3383 	struct spdk_blob_store *bs = io_device;
3384 	struct spdk_blob	*blob, *blob_tmp;
3385 
3386 	bs->dev->destroy(bs->dev);
3387 
3388 	RB_FOREACH_SAFE(blob, spdk_blob_tree, &bs->open_blobs, blob_tmp) {
3389 		RB_REMOVE(spdk_blob_tree, &bs->open_blobs, blob);
3390 		spdk_bit_array_clear(bs->open_blobids, blob->id);
3391 		blob_free(blob);
3392 	}
3393 
3394 	spdk_spin_destroy(&bs->used_lock);
3395 
3396 	spdk_bit_array_free(&bs->open_blobids);
3397 	spdk_bit_array_free(&bs->used_blobids);
3398 	spdk_bit_array_free(&bs->used_md_pages);
3399 	spdk_bit_pool_free(&bs->used_clusters);
3400 	/*
3401 	 * If this function is called for any reason except a successful unload,
3402 	 * the unload_cpl type will be NONE and this will be a nop.
3403 	 */
3404 	bs_call_cpl(&bs->unload_cpl, bs->unload_err);
3405 
3406 	free(bs);
3407 }
3408 
3409 static int
3410 bs_blob_list_add(struct spdk_blob *blob)
3411 {
3412 	spdk_blob_id snapshot_id;
3413 	struct spdk_blob_list *snapshot_entry = NULL;
3414 	struct spdk_blob_list *clone_entry = NULL;
3415 
3416 	assert(blob != NULL);
3417 
3418 	snapshot_id = blob->parent_id;
3419 	if (snapshot_id == SPDK_BLOBID_INVALID ||
3420 	    snapshot_id == SPDK_BLOBID_EXTERNAL_SNAPSHOT) {
3421 		return 0;
3422 	}
3423 
3424 	snapshot_entry = bs_get_snapshot_entry(blob->bs, snapshot_id);
3425 	if (snapshot_entry == NULL) {
3426 		/* Snapshot not found */
3427 		snapshot_entry = calloc(1, sizeof(struct spdk_blob_list));
3428 		if (snapshot_entry == NULL) {
3429 			return -ENOMEM;
3430 		}
3431 		snapshot_entry->id = snapshot_id;
3432 		TAILQ_INIT(&snapshot_entry->clones);
3433 		TAILQ_INSERT_TAIL(&blob->bs->snapshots, snapshot_entry, link);
3434 	} else {
3435 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
3436 			if (clone_entry->id == blob->id) {
3437 				break;
3438 			}
3439 		}
3440 	}
3441 
3442 	if (clone_entry == NULL) {
3443 		/* Clone not found */
3444 		clone_entry = calloc(1, sizeof(struct spdk_blob_list));
3445 		if (clone_entry == NULL) {
3446 			return -ENOMEM;
3447 		}
3448 		clone_entry->id = blob->id;
3449 		TAILQ_INIT(&clone_entry->clones);
3450 		TAILQ_INSERT_TAIL(&snapshot_entry->clones, clone_entry, link);
3451 		snapshot_entry->clone_count++;
3452 	}
3453 
3454 	return 0;
3455 }
3456 
3457 static void
3458 bs_blob_list_remove(struct spdk_blob *blob)
3459 {
3460 	struct spdk_blob_list *snapshot_entry = NULL;
3461 	struct spdk_blob_list *clone_entry = NULL;
3462 
3463 	blob_get_snapshot_and_clone_entries(blob, &snapshot_entry, &clone_entry);
3464 
3465 	if (snapshot_entry == NULL) {
3466 		return;
3467 	}
3468 
3469 	blob->parent_id = SPDK_BLOBID_INVALID;
3470 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
3471 	free(clone_entry);
3472 
3473 	snapshot_entry->clone_count--;
3474 }
3475 
3476 static int
3477 bs_blob_list_free(struct spdk_blob_store *bs)
3478 {
3479 	struct spdk_blob_list *snapshot_entry;
3480 	struct spdk_blob_list *snapshot_entry_tmp;
3481 	struct spdk_blob_list *clone_entry;
3482 	struct spdk_blob_list *clone_entry_tmp;
3483 
3484 	TAILQ_FOREACH_SAFE(snapshot_entry, &bs->snapshots, link, snapshot_entry_tmp) {
3485 		TAILQ_FOREACH_SAFE(clone_entry, &snapshot_entry->clones, link, clone_entry_tmp) {
3486 			TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
3487 			free(clone_entry);
3488 		}
3489 		TAILQ_REMOVE(&bs->snapshots, snapshot_entry, link);
3490 		free(snapshot_entry);
3491 	}
3492 
3493 	return 0;
3494 }
3495 
3496 static void
3497 bs_free(struct spdk_blob_store *bs)
3498 {
3499 	bs_blob_list_free(bs);
3500 
3501 	bs_unregister_md_thread(bs);
3502 	spdk_io_device_unregister(bs, bs_dev_destroy);
3503 }
3504 
3505 void
3506 spdk_bs_opts_init(struct spdk_bs_opts *opts, size_t opts_size)
3507 {
3508 
3509 	if (!opts) {
3510 		SPDK_ERRLOG("opts should not be NULL\n");
3511 		return;
3512 	}
3513 
3514 	if (!opts_size) {
3515 		SPDK_ERRLOG("opts_size should not be zero value\n");
3516 		return;
3517 	}
3518 
3519 	memset(opts, 0, opts_size);
3520 	opts->opts_size = opts_size;
3521 
3522 #define FIELD_OK(field) \
3523 	offsetof(struct spdk_bs_opts, field) + sizeof(opts->field) <= opts_size
3524 
3525 #define SET_FIELD(field, value) \
3526 	if (FIELD_OK(field)) { \
3527 		opts->field = value; \
3528 	} \
3529 
3530 	SET_FIELD(cluster_sz, SPDK_BLOB_OPTS_CLUSTER_SZ);
3531 	SET_FIELD(num_md_pages, SPDK_BLOB_OPTS_NUM_MD_PAGES);
3532 	SET_FIELD(max_md_ops, SPDK_BLOB_OPTS_NUM_MD_PAGES);
3533 	SET_FIELD(max_channel_ops, SPDK_BLOB_OPTS_DEFAULT_CHANNEL_OPS);
3534 	SET_FIELD(clear_method,  BS_CLEAR_WITH_UNMAP);
3535 
3536 	if (FIELD_OK(bstype)) {
3537 		memset(&opts->bstype, 0, sizeof(opts->bstype));
3538 	}
3539 
3540 	SET_FIELD(iter_cb_fn, NULL);
3541 	SET_FIELD(iter_cb_arg, NULL);
3542 	SET_FIELD(force_recover, false);
3543 	SET_FIELD(esnap_bs_dev_create, NULL);
3544 	SET_FIELD(esnap_ctx, NULL);
3545 
3546 #undef FIELD_OK
3547 #undef SET_FIELD
3548 }
3549 
3550 static int
3551 bs_opts_verify(struct spdk_bs_opts *opts)
3552 {
3553 	if (opts->cluster_sz == 0 || opts->num_md_pages == 0 || opts->max_md_ops == 0 ||
3554 	    opts->max_channel_ops == 0) {
3555 		SPDK_ERRLOG("Blobstore options cannot be set to 0\n");
3556 		return -1;
3557 	}
3558 
3559 	return 0;
3560 }
3561 
3562 /* START spdk_bs_load */
3563 
3564 /* spdk_bs_load_ctx is used for init, load, unload and dump code paths. */
3565 
3566 struct spdk_bs_load_ctx {
3567 	struct spdk_blob_store		*bs;
3568 	struct spdk_bs_super_block	*super;
3569 
3570 	struct spdk_bs_md_mask		*mask;
3571 	bool				in_page_chain;
3572 	uint32_t			page_index;
3573 	uint32_t			cur_page;
3574 	struct spdk_blob_md_page	*page;
3575 
3576 	uint64_t			num_extent_pages;
3577 	uint32_t			*extent_page_num;
3578 	struct spdk_blob_md_page	*extent_pages;
3579 	struct spdk_bit_array		*used_clusters;
3580 
3581 	spdk_bs_sequence_t			*seq;
3582 	spdk_blob_op_with_handle_complete	iter_cb_fn;
3583 	void					*iter_cb_arg;
3584 	struct spdk_blob			*blob;
3585 	spdk_blob_id				blobid;
3586 
3587 	bool					force_recover;
3588 
3589 	/* These fields are used in the spdk_bs_dump path. */
3590 	bool					dumping;
3591 	FILE					*fp;
3592 	spdk_bs_dump_print_xattr		print_xattr_fn;
3593 	char					xattr_name[4096];
3594 };
3595 
3596 static int
3597 bs_alloc(struct spdk_bs_dev *dev, struct spdk_bs_opts *opts, struct spdk_blob_store **_bs,
3598 	 struct spdk_bs_load_ctx **_ctx)
3599 {
3600 	struct spdk_blob_store	*bs;
3601 	struct spdk_bs_load_ctx	*ctx;
3602 	uint64_t dev_size;
3603 	int rc;
3604 
3605 	dev_size = dev->blocklen * dev->blockcnt;
3606 	if (dev_size < opts->cluster_sz) {
3607 		/* Device size cannot be smaller than cluster size of blobstore */
3608 		SPDK_INFOLOG(blob, "Device size %" PRIu64 " is smaller than cluster size %" PRIu32 "\n",
3609 			     dev_size, opts->cluster_sz);
3610 		return -ENOSPC;
3611 	}
3612 	if (opts->cluster_sz < SPDK_BS_PAGE_SIZE) {
3613 		/* Cluster size cannot be smaller than page size */
3614 		SPDK_ERRLOG("Cluster size %" PRIu32 " is smaller than page size %d\n",
3615 			    opts->cluster_sz, SPDK_BS_PAGE_SIZE);
3616 		return -EINVAL;
3617 	}
3618 	bs = calloc(1, sizeof(struct spdk_blob_store));
3619 	if (!bs) {
3620 		return -ENOMEM;
3621 	}
3622 
3623 	ctx = calloc(1, sizeof(struct spdk_bs_load_ctx));
3624 	if (!ctx) {
3625 		free(bs);
3626 		return -ENOMEM;
3627 	}
3628 
3629 	ctx->bs = bs;
3630 	ctx->iter_cb_fn = opts->iter_cb_fn;
3631 	ctx->iter_cb_arg = opts->iter_cb_arg;
3632 	ctx->force_recover = opts->force_recover;
3633 
3634 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3635 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3636 	if (!ctx->super) {
3637 		free(ctx);
3638 		free(bs);
3639 		return -ENOMEM;
3640 	}
3641 
3642 	RB_INIT(&bs->open_blobs);
3643 	TAILQ_INIT(&bs->snapshots);
3644 	bs->dev = dev;
3645 	bs->md_thread = spdk_get_thread();
3646 	assert(bs->md_thread != NULL);
3647 
3648 	/*
3649 	 * Do not use bs_lba_to_cluster() here since blockcnt may not be an
3650 	 *  even multiple of the cluster size.
3651 	 */
3652 	bs->cluster_sz = opts->cluster_sz;
3653 	bs->total_clusters = dev->blockcnt / (bs->cluster_sz / dev->blocklen);
3654 	ctx->used_clusters = spdk_bit_array_create(bs->total_clusters);
3655 	if (!ctx->used_clusters) {
3656 		spdk_free(ctx->super);
3657 		free(ctx);
3658 		free(bs);
3659 		return -ENOMEM;
3660 	}
3661 
3662 	bs->pages_per_cluster = bs->cluster_sz / SPDK_BS_PAGE_SIZE;
3663 	if (spdk_u32_is_pow2(bs->pages_per_cluster)) {
3664 		bs->pages_per_cluster_shift = spdk_u32log2(bs->pages_per_cluster);
3665 	}
3666 	bs->num_free_clusters = bs->total_clusters;
3667 	bs->io_unit_size = dev->blocklen;
3668 
3669 	bs->max_channel_ops = opts->max_channel_ops;
3670 	bs->super_blob = SPDK_BLOBID_INVALID;
3671 	memcpy(&bs->bstype, &opts->bstype, sizeof(opts->bstype));
3672 	bs->esnap_bs_dev_create = opts->esnap_bs_dev_create;
3673 	bs->esnap_ctx = opts->esnap_ctx;
3674 
3675 	/* The metadata is assumed to be at least 1 page */
3676 	bs->used_md_pages = spdk_bit_array_create(1);
3677 	bs->used_blobids = spdk_bit_array_create(0);
3678 	bs->open_blobids = spdk_bit_array_create(0);
3679 
3680 	spdk_spin_init(&bs->used_lock);
3681 
3682 	spdk_io_device_register(bs, bs_channel_create, bs_channel_destroy,
3683 				sizeof(struct spdk_bs_channel), "blobstore");
3684 	rc = bs_register_md_thread(bs);
3685 	if (rc == -1) {
3686 		spdk_io_device_unregister(bs, NULL);
3687 		spdk_spin_destroy(&bs->used_lock);
3688 		spdk_bit_array_free(&bs->open_blobids);
3689 		spdk_bit_array_free(&bs->used_blobids);
3690 		spdk_bit_array_free(&bs->used_md_pages);
3691 		spdk_bit_array_free(&ctx->used_clusters);
3692 		spdk_free(ctx->super);
3693 		free(ctx);
3694 		free(bs);
3695 		/* FIXME: this is a lie but don't know how to get a proper error code here */
3696 		return -ENOMEM;
3697 	}
3698 
3699 	*_ctx = ctx;
3700 	*_bs = bs;
3701 	return 0;
3702 }
3703 
3704 static void
3705 bs_load_ctx_fail(struct spdk_bs_load_ctx *ctx, int bserrno)
3706 {
3707 	assert(bserrno != 0);
3708 
3709 	spdk_free(ctx->super);
3710 	bs_sequence_finish(ctx->seq, bserrno);
3711 	bs_free(ctx->bs);
3712 	spdk_bit_array_free(&ctx->used_clusters);
3713 	free(ctx);
3714 }
3715 
3716 static void
3717 bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
3718 	       struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg)
3719 {
3720 	/* Update the values in the super block */
3721 	super->super_blob = bs->super_blob;
3722 	memcpy(&super->bstype, &bs->bstype, sizeof(bs->bstype));
3723 	super->crc = blob_md_page_calc_crc(super);
3724 	bs_sequence_write_dev(seq, super, bs_page_to_lba(bs, 0),
3725 			      bs_byte_to_lba(bs, sizeof(*super)),
3726 			      cb_fn, cb_arg);
3727 }
3728 
3729 static void
3730 bs_write_used_clusters(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3731 {
3732 	struct spdk_bs_load_ctx	*ctx = arg;
3733 	uint64_t	mask_size, lba, lba_count;
3734 
3735 	/* Write out the used clusters mask */
3736 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
3737 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3738 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3739 	if (!ctx->mask) {
3740 		bs_load_ctx_fail(ctx, -ENOMEM);
3741 		return;
3742 	}
3743 
3744 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_CLUSTERS;
3745 	ctx->mask->length = ctx->bs->total_clusters;
3746 	/* We could get here through the normal unload path, or through dirty
3747 	 * shutdown recovery.  For the normal unload path, we use the mask from
3748 	 * the bit pool.  For dirty shutdown recovery, we don't have a bit pool yet -
3749 	 * only the bit array from the load ctx.
3750 	 */
3751 	if (ctx->bs->used_clusters) {
3752 		assert(ctx->mask->length == spdk_bit_pool_capacity(ctx->bs->used_clusters));
3753 		spdk_bit_pool_store_mask(ctx->bs->used_clusters, ctx->mask->mask);
3754 	} else {
3755 		assert(ctx->mask->length == spdk_bit_array_capacity(ctx->used_clusters));
3756 		spdk_bit_array_store_mask(ctx->used_clusters, ctx->mask->mask);
3757 	}
3758 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
3759 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
3760 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3761 }
3762 
3763 static void
3764 bs_write_used_md(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3765 {
3766 	struct spdk_bs_load_ctx	*ctx = arg;
3767 	uint64_t	mask_size, lba, lba_count;
3768 
3769 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
3770 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3771 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3772 	if (!ctx->mask) {
3773 		bs_load_ctx_fail(ctx, -ENOMEM);
3774 		return;
3775 	}
3776 
3777 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_PAGES;
3778 	ctx->mask->length = ctx->super->md_len;
3779 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_md_pages));
3780 
3781 	spdk_bit_array_store_mask(ctx->bs->used_md_pages, ctx->mask->mask);
3782 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
3783 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
3784 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3785 }
3786 
3787 static void
3788 bs_write_used_blobids(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3789 {
3790 	struct spdk_bs_load_ctx	*ctx = arg;
3791 	uint64_t	mask_size, lba, lba_count;
3792 
3793 	if (ctx->super->used_blobid_mask_len == 0) {
3794 		/*
3795 		 * This is a pre-v3 on-disk format where the blobid mask does not get
3796 		 *  written to disk.
3797 		 */
3798 		cb_fn(seq, arg, 0);
3799 		return;
3800 	}
3801 
3802 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
3803 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
3804 				 SPDK_MALLOC_DMA);
3805 	if (!ctx->mask) {
3806 		bs_load_ctx_fail(ctx, -ENOMEM);
3807 		return;
3808 	}
3809 
3810 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_BLOBIDS;
3811 	ctx->mask->length = ctx->super->md_len;
3812 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_blobids));
3813 
3814 	spdk_bit_array_store_mask(ctx->bs->used_blobids, ctx->mask->mask);
3815 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
3816 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
3817 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3818 }
3819 
3820 static void
3821 blob_set_thin_provision(struct spdk_blob *blob)
3822 {
3823 	blob_verify_md_op(blob);
3824 	blob->invalid_flags |= SPDK_BLOB_THIN_PROV;
3825 	blob->state = SPDK_BLOB_STATE_DIRTY;
3826 }
3827 
3828 static void
3829 blob_set_clear_method(struct spdk_blob *blob, enum blob_clear_method clear_method)
3830 {
3831 	blob_verify_md_op(blob);
3832 	blob->clear_method = clear_method;
3833 	blob->md_ro_flags |= (clear_method << SPDK_BLOB_CLEAR_METHOD_SHIFT);
3834 	blob->state = SPDK_BLOB_STATE_DIRTY;
3835 }
3836 
3837 static void bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno);
3838 
3839 static void
3840 bs_delete_corrupted_blob_cpl(void *cb_arg, int bserrno)
3841 {
3842 	struct spdk_bs_load_ctx *ctx = cb_arg;
3843 	spdk_blob_id id;
3844 	int64_t page_num;
3845 
3846 	/* Iterate to next blob (we can't use spdk_bs_iter_next function as our
3847 	 * last blob has been removed */
3848 	page_num = bs_blobid_to_page(ctx->blobid);
3849 	page_num++;
3850 	page_num = spdk_bit_array_find_first_set(ctx->bs->used_blobids, page_num);
3851 	if (page_num >= spdk_bit_array_capacity(ctx->bs->used_blobids)) {
3852 		bs_load_iter(ctx, NULL, -ENOENT);
3853 		return;
3854 	}
3855 
3856 	id = bs_page_to_blobid(page_num);
3857 
3858 	spdk_bs_open_blob(ctx->bs, id, bs_load_iter, ctx);
3859 }
3860 
3861 static void
3862 bs_delete_corrupted_close_cb(void *cb_arg, int bserrno)
3863 {
3864 	struct spdk_bs_load_ctx *ctx = cb_arg;
3865 
3866 	if (bserrno != 0) {
3867 		SPDK_ERRLOG("Failed to close corrupted blob\n");
3868 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3869 		return;
3870 	}
3871 
3872 	spdk_bs_delete_blob(ctx->bs, ctx->blobid, bs_delete_corrupted_blob_cpl, ctx);
3873 }
3874 
3875 static void
3876 bs_delete_corrupted_blob(void *cb_arg, int bserrno)
3877 {
3878 	struct spdk_bs_load_ctx *ctx = cb_arg;
3879 	uint64_t i;
3880 
3881 	if (bserrno != 0) {
3882 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
3883 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3884 		return;
3885 	}
3886 
3887 	/* Snapshot and clone have the same copy of cluster map and extent pages
3888 	 * at this point. Let's clear both for snapshot now,
3889 	 * so that it won't be cleared for clone later when we remove snapshot.
3890 	 * Also set thin provision to pass data corruption check */
3891 	for (i = 0; i < ctx->blob->active.num_clusters; i++) {
3892 		ctx->blob->active.clusters[i] = 0;
3893 	}
3894 	for (i = 0; i < ctx->blob->active.num_extent_pages; i++) {
3895 		ctx->blob->active.extent_pages[i] = 0;
3896 	}
3897 
3898 	ctx->blob->md_ro = false;
3899 
3900 	blob_set_thin_provision(ctx->blob);
3901 
3902 	ctx->blobid = ctx->blob->id;
3903 
3904 	spdk_blob_close(ctx->blob, bs_delete_corrupted_close_cb, ctx);
3905 }
3906 
3907 static void
3908 bs_update_corrupted_blob(void *cb_arg, int bserrno)
3909 {
3910 	struct spdk_bs_load_ctx *ctx = cb_arg;
3911 
3912 	if (bserrno != 0) {
3913 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
3914 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3915 		return;
3916 	}
3917 
3918 	ctx->blob->md_ro = false;
3919 	blob_remove_xattr(ctx->blob, SNAPSHOT_PENDING_REMOVAL, true);
3920 	blob_remove_xattr(ctx->blob, SNAPSHOT_IN_PROGRESS, true);
3921 	spdk_blob_set_read_only(ctx->blob);
3922 
3923 	if (ctx->iter_cb_fn) {
3924 		ctx->iter_cb_fn(ctx->iter_cb_arg, ctx->blob, 0);
3925 	}
3926 	bs_blob_list_add(ctx->blob);
3927 
3928 	spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3929 }
3930 
3931 static void
3932 bs_examine_clone(void *cb_arg, struct spdk_blob *blob, int bserrno)
3933 {
3934 	struct spdk_bs_load_ctx *ctx = cb_arg;
3935 
3936 	if (bserrno != 0) {
3937 		SPDK_ERRLOG("Failed to open clone of a corrupted blob\n");
3938 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3939 		return;
3940 	}
3941 
3942 	if (blob->parent_id == ctx->blob->id) {
3943 		/* Power failure occurred before updating clone (snapshot delete case)
3944 		 * or after updating clone (creating snapshot case) - keep snapshot */
3945 		spdk_blob_close(blob, bs_update_corrupted_blob, ctx);
3946 	} else {
3947 		/* Power failure occurred after updating clone (snapshot delete case)
3948 		 * or before updating clone (creating snapshot case) - remove snapshot */
3949 		spdk_blob_close(blob, bs_delete_corrupted_blob, ctx);
3950 	}
3951 }
3952 
3953 static void
3954 bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno)
3955 {
3956 	struct spdk_bs_load_ctx *ctx = arg;
3957 	const void *value;
3958 	size_t len;
3959 	int rc = 0;
3960 
3961 	if (bserrno == 0) {
3962 		/* Examine blob if it is corrupted after power failure. Fix
3963 		 * the ones that can be fixed and remove any other corrupted
3964 		 * ones. If it is not corrupted just process it */
3965 		rc = blob_get_xattr_value(blob, SNAPSHOT_PENDING_REMOVAL, &value, &len, true);
3966 		if (rc != 0) {
3967 			rc = blob_get_xattr_value(blob, SNAPSHOT_IN_PROGRESS, &value, &len, true);
3968 			if (rc != 0) {
3969 				/* Not corrupted - process it and continue with iterating through blobs */
3970 				if (ctx->iter_cb_fn) {
3971 					ctx->iter_cb_fn(ctx->iter_cb_arg, blob, 0);
3972 				}
3973 				bs_blob_list_add(blob);
3974 				spdk_bs_iter_next(ctx->bs, blob, bs_load_iter, ctx);
3975 				return;
3976 			}
3977 
3978 		}
3979 
3980 		assert(len == sizeof(spdk_blob_id));
3981 
3982 		ctx->blob = blob;
3983 
3984 		/* Open clone to check if we are able to fix this blob or should we remove it */
3985 		spdk_bs_open_blob(ctx->bs, *(spdk_blob_id *)value, bs_examine_clone, ctx);
3986 		return;
3987 	} else if (bserrno == -ENOENT) {
3988 		bserrno = 0;
3989 	} else {
3990 		/*
3991 		 * This case needs to be looked at further.  Same problem
3992 		 *  exists with applications that rely on explicit blob
3993 		 *  iteration.  We should just skip the blob that failed
3994 		 *  to load and continue on to the next one.
3995 		 */
3996 		SPDK_ERRLOG("Error in iterating blobs\n");
3997 	}
3998 
3999 	ctx->iter_cb_fn = NULL;
4000 
4001 	spdk_free(ctx->super);
4002 	spdk_free(ctx->mask);
4003 	bs_sequence_finish(ctx->seq, bserrno);
4004 	free(ctx);
4005 }
4006 
4007 static void bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
4008 
4009 static void
4010 bs_load_complete(struct spdk_bs_load_ctx *ctx)
4011 {
4012 	ctx->bs->used_clusters = spdk_bit_pool_create_from_array(ctx->used_clusters);
4013 	if (ctx->dumping) {
4014 		bs_dump_read_md_page(ctx->seq, ctx);
4015 		return;
4016 	}
4017 	spdk_bs_iter_first(ctx->bs, bs_load_iter, ctx);
4018 }
4019 
4020 static void
4021 bs_load_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4022 {
4023 	struct spdk_bs_load_ctx *ctx = cb_arg;
4024 	int rc;
4025 
4026 	/* The type must be correct */
4027 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_BLOBIDS);
4028 
4029 	/* The length of the mask (in bits) must not be greater than
4030 	 * the length of the buffer (converted to bits) */
4031 	assert(ctx->mask->length <= (ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE * 8));
4032 
4033 	/* The length of the mask must be exactly equal to the size
4034 	 * (in pages) of the metadata region */
4035 	assert(ctx->mask->length == ctx->super->md_len);
4036 
4037 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->mask->length);
4038 	if (rc < 0) {
4039 		spdk_free(ctx->mask);
4040 		bs_load_ctx_fail(ctx, rc);
4041 		return;
4042 	}
4043 
4044 	spdk_bit_array_load_mask(ctx->bs->used_blobids, ctx->mask->mask);
4045 	bs_load_complete(ctx);
4046 }
4047 
4048 static void
4049 bs_load_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4050 {
4051 	struct spdk_bs_load_ctx *ctx = cb_arg;
4052 	uint64_t		lba, lba_count, mask_size;
4053 	int			rc;
4054 
4055 	if (bserrno != 0) {
4056 		bs_load_ctx_fail(ctx, bserrno);
4057 		return;
4058 	}
4059 
4060 	/* The type must be correct */
4061 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
4062 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
4063 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
4064 					     struct spdk_blob_md_page) * 8));
4065 	/*
4066 	 * The length of the mask must be equal to or larger than the total number of clusters. It may be
4067 	 * larger than the total number of clusters due to a failure spdk_bs_grow.
4068 	 */
4069 	assert(ctx->mask->length >= ctx->bs->total_clusters);
4070 	if (ctx->mask->length > ctx->bs->total_clusters) {
4071 		SPDK_WARNLOG("Shrink the used_custers mask length to total_clusters");
4072 		ctx->mask->length = ctx->bs->total_clusters;
4073 	}
4074 
4075 	rc = spdk_bit_array_resize(&ctx->used_clusters, ctx->mask->length);
4076 	if (rc < 0) {
4077 		spdk_free(ctx->mask);
4078 		bs_load_ctx_fail(ctx, rc);
4079 		return;
4080 	}
4081 
4082 	spdk_bit_array_load_mask(ctx->used_clusters, ctx->mask->mask);
4083 	ctx->bs->num_free_clusters = spdk_bit_array_count_clear(ctx->used_clusters);
4084 	assert(ctx->bs->num_free_clusters <= ctx->bs->total_clusters);
4085 
4086 	spdk_free(ctx->mask);
4087 
4088 	/* Read the used blobids mask */
4089 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
4090 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
4091 				 SPDK_MALLOC_DMA);
4092 	if (!ctx->mask) {
4093 		bs_load_ctx_fail(ctx, -ENOMEM);
4094 		return;
4095 	}
4096 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
4097 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
4098 	bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
4099 			     bs_load_used_blobids_cpl, ctx);
4100 }
4101 
4102 static void
4103 bs_load_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4104 {
4105 	struct spdk_bs_load_ctx *ctx = cb_arg;
4106 	uint64_t		lba, lba_count, mask_size;
4107 	int			rc;
4108 
4109 	if (bserrno != 0) {
4110 		bs_load_ctx_fail(ctx, bserrno);
4111 		return;
4112 	}
4113 
4114 	/* The type must be correct */
4115 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_PAGES);
4116 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
4117 	assert(ctx->mask->length <= (ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE *
4118 				     8));
4119 	/* The length of the mask must be exactly equal to the size (in pages) of the metadata region */
4120 	if (ctx->mask->length != ctx->super->md_len) {
4121 		SPDK_ERRLOG("mismatched md_len in used_pages mask: "
4122 			    "mask->length=%" PRIu32 " super->md_len=%" PRIu32 "\n",
4123 			    ctx->mask->length, ctx->super->md_len);
4124 		assert(false);
4125 	}
4126 
4127 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->mask->length);
4128 	if (rc < 0) {
4129 		spdk_free(ctx->mask);
4130 		bs_load_ctx_fail(ctx, rc);
4131 		return;
4132 	}
4133 
4134 	spdk_bit_array_load_mask(ctx->bs->used_md_pages, ctx->mask->mask);
4135 	spdk_free(ctx->mask);
4136 
4137 	/* Read the used clusters mask */
4138 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
4139 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
4140 				 SPDK_MALLOC_DMA);
4141 	if (!ctx->mask) {
4142 		bs_load_ctx_fail(ctx, -ENOMEM);
4143 		return;
4144 	}
4145 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
4146 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
4147 	bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
4148 			     bs_load_used_clusters_cpl, ctx);
4149 }
4150 
4151 static void
4152 bs_load_read_used_pages(struct spdk_bs_load_ctx *ctx)
4153 {
4154 	uint64_t lba, lba_count, mask_size;
4155 
4156 	/* Read the used pages mask */
4157 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
4158 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
4159 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4160 	if (!ctx->mask) {
4161 		bs_load_ctx_fail(ctx, -ENOMEM);
4162 		return;
4163 	}
4164 
4165 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
4166 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
4167 	bs_sequence_read_dev(ctx->seq, ctx->mask, lba, lba_count,
4168 			     bs_load_used_pages_cpl, ctx);
4169 }
4170 
4171 static int
4172 bs_load_replay_md_parse_page(struct spdk_bs_load_ctx *ctx, struct spdk_blob_md_page *page)
4173 {
4174 	struct spdk_blob_store *bs = ctx->bs;
4175 	struct spdk_blob_md_descriptor *desc;
4176 	size_t	cur_desc = 0;
4177 
4178 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
4179 	while (cur_desc < sizeof(page->descriptors)) {
4180 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
4181 			if (desc->length == 0) {
4182 				/* If padding and length are 0, this terminates the page */
4183 				break;
4184 			}
4185 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
4186 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
4187 			unsigned int				i, j;
4188 			unsigned int				cluster_count = 0;
4189 			uint32_t				cluster_idx;
4190 
4191 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
4192 
4193 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
4194 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
4195 					cluster_idx = desc_extent_rle->extents[i].cluster_idx;
4196 					/*
4197 					 * cluster_idx = 0 means an unallocated cluster - don't mark that
4198 					 * in the used cluster map.
4199 					 */
4200 					if (cluster_idx != 0) {
4201 						SPDK_NOTICELOG("Recover: cluster %" PRIu32 "\n", cluster_idx + j);
4202 						spdk_bit_array_set(ctx->used_clusters, cluster_idx + j);
4203 						if (bs->num_free_clusters == 0) {
4204 							return -ENOSPC;
4205 						}
4206 						bs->num_free_clusters--;
4207 					}
4208 					cluster_count++;
4209 				}
4210 			}
4211 			if (cluster_count == 0) {
4212 				return -EINVAL;
4213 			}
4214 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
4215 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
4216 			uint32_t					i;
4217 			uint32_t					cluster_count = 0;
4218 			uint32_t					cluster_idx;
4219 			size_t						cluster_idx_length;
4220 
4221 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
4222 			cluster_idx_length = desc_extent->length - sizeof(desc_extent->start_cluster_idx);
4223 
4224 			if (desc_extent->length <= sizeof(desc_extent->start_cluster_idx) ||
4225 			    (cluster_idx_length % sizeof(desc_extent->cluster_idx[0]) != 0)) {
4226 				return -EINVAL;
4227 			}
4228 
4229 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
4230 				cluster_idx = desc_extent->cluster_idx[i];
4231 				/*
4232 				 * cluster_idx = 0 means an unallocated cluster - don't mark that
4233 				 * in the used cluster map.
4234 				 */
4235 				if (cluster_idx != 0) {
4236 					if (cluster_idx < desc_extent->start_cluster_idx &&
4237 					    cluster_idx >= desc_extent->start_cluster_idx + cluster_count) {
4238 						return -EINVAL;
4239 					}
4240 					spdk_bit_array_set(ctx->used_clusters, cluster_idx);
4241 					if (bs->num_free_clusters == 0) {
4242 						return -ENOSPC;
4243 					}
4244 					bs->num_free_clusters--;
4245 				}
4246 				cluster_count++;
4247 			}
4248 
4249 			if (cluster_count == 0) {
4250 				return -EINVAL;
4251 			}
4252 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
4253 			/* Skip this item */
4254 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
4255 			/* Skip this item */
4256 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
4257 			/* Skip this item */
4258 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE) {
4259 			struct spdk_blob_md_descriptor_extent_table *desc_extent_table;
4260 			uint32_t num_extent_pages = ctx->num_extent_pages;
4261 			uint32_t i;
4262 			size_t extent_pages_length;
4263 			void *tmp;
4264 
4265 			desc_extent_table = (struct spdk_blob_md_descriptor_extent_table *)desc;
4266 			extent_pages_length = desc_extent_table->length - sizeof(desc_extent_table->num_clusters);
4267 
4268 			if (desc_extent_table->length == 0 ||
4269 			    (extent_pages_length % sizeof(desc_extent_table->extent_page[0]) != 0)) {
4270 				return -EINVAL;
4271 			}
4272 
4273 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
4274 				if (desc_extent_table->extent_page[i].page_idx != 0) {
4275 					if (desc_extent_table->extent_page[i].num_pages != 1) {
4276 						return -EINVAL;
4277 					}
4278 					num_extent_pages += 1;
4279 				}
4280 			}
4281 
4282 			if (num_extent_pages > 0) {
4283 				tmp = realloc(ctx->extent_page_num, num_extent_pages * sizeof(uint32_t));
4284 				if (tmp == NULL) {
4285 					return -ENOMEM;
4286 				}
4287 				ctx->extent_page_num = tmp;
4288 
4289 				/* Extent table entries contain md page numbers for extent pages.
4290 				 * Zeroes represent unallocated extent pages, those are run-length-encoded.
4291 				 */
4292 				for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
4293 					if (desc_extent_table->extent_page[i].page_idx != 0) {
4294 						ctx->extent_page_num[ctx->num_extent_pages] = desc_extent_table->extent_page[i].page_idx;
4295 						ctx->num_extent_pages += 1;
4296 					}
4297 				}
4298 			}
4299 		} else {
4300 			/* Error */
4301 			return -EINVAL;
4302 		}
4303 		/* Advance to the next descriptor */
4304 		cur_desc += sizeof(*desc) + desc->length;
4305 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
4306 			break;
4307 		}
4308 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
4309 	}
4310 	return 0;
4311 }
4312 
4313 static bool
4314 bs_load_cur_extent_page_valid(struct spdk_blob_md_page *page)
4315 {
4316 	uint32_t crc;
4317 	struct spdk_blob_md_descriptor *desc = (struct spdk_blob_md_descriptor *)page->descriptors;
4318 	size_t desc_len;
4319 
4320 	crc = blob_md_page_calc_crc(page);
4321 	if (crc != page->crc) {
4322 		return false;
4323 	}
4324 
4325 	/* Extent page should always be of sequence num 0. */
4326 	if (page->sequence_num != 0) {
4327 		return false;
4328 	}
4329 
4330 	/* Descriptor type must be EXTENT_PAGE. */
4331 	if (desc->type != SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
4332 		return false;
4333 	}
4334 
4335 	/* Descriptor length cannot exceed the page. */
4336 	desc_len = sizeof(*desc) + desc->length;
4337 	if (desc_len > sizeof(page->descriptors)) {
4338 		return false;
4339 	}
4340 
4341 	/* It has to be the only descriptor in the page. */
4342 	if (desc_len + sizeof(*desc) <= sizeof(page->descriptors)) {
4343 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + desc_len);
4344 		if (desc->length != 0) {
4345 			return false;
4346 		}
4347 	}
4348 
4349 	return true;
4350 }
4351 
4352 static bool
4353 bs_load_cur_md_page_valid(struct spdk_bs_load_ctx *ctx)
4354 {
4355 	uint32_t crc;
4356 	struct spdk_blob_md_page *page = ctx->page;
4357 
4358 	crc = blob_md_page_calc_crc(page);
4359 	if (crc != page->crc) {
4360 		return false;
4361 	}
4362 
4363 	/* First page of a sequence should match the blobid. */
4364 	if (page->sequence_num == 0 &&
4365 	    bs_page_to_blobid(ctx->cur_page) != page->id) {
4366 		return false;
4367 	}
4368 	assert(bs_load_cur_extent_page_valid(page) == false);
4369 
4370 	return true;
4371 }
4372 
4373 static void bs_load_replay_cur_md_page(struct spdk_bs_load_ctx *ctx);
4374 
4375 static void
4376 bs_load_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4377 {
4378 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4379 
4380 	if (bserrno != 0) {
4381 		bs_load_ctx_fail(ctx, bserrno);
4382 		return;
4383 	}
4384 
4385 	bs_load_complete(ctx);
4386 }
4387 
4388 static void
4389 bs_load_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4390 {
4391 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4392 
4393 	spdk_free(ctx->mask);
4394 	ctx->mask = NULL;
4395 
4396 	if (bserrno != 0) {
4397 		bs_load_ctx_fail(ctx, bserrno);
4398 		return;
4399 	}
4400 
4401 	bs_write_used_clusters(seq, ctx, bs_load_write_used_clusters_cpl);
4402 }
4403 
4404 static void
4405 bs_load_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4406 {
4407 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4408 
4409 	spdk_free(ctx->mask);
4410 	ctx->mask = NULL;
4411 
4412 	if (bserrno != 0) {
4413 		bs_load_ctx_fail(ctx, bserrno);
4414 		return;
4415 	}
4416 
4417 	bs_write_used_blobids(seq, ctx, bs_load_write_used_blobids_cpl);
4418 }
4419 
4420 static void
4421 bs_load_write_used_md(struct spdk_bs_load_ctx *ctx)
4422 {
4423 	bs_write_used_md(ctx->seq, ctx, bs_load_write_used_pages_cpl);
4424 }
4425 
4426 static void
4427 bs_load_replay_md_chain_cpl(struct spdk_bs_load_ctx *ctx)
4428 {
4429 	uint64_t num_md_clusters;
4430 	uint64_t i;
4431 
4432 	ctx->in_page_chain = false;
4433 
4434 	do {
4435 		ctx->page_index++;
4436 	} while (spdk_bit_array_get(ctx->bs->used_md_pages, ctx->page_index) == true);
4437 
4438 	if (ctx->page_index < ctx->super->md_len) {
4439 		ctx->cur_page = ctx->page_index;
4440 		bs_load_replay_cur_md_page(ctx);
4441 	} else {
4442 		/* Claim all of the clusters used by the metadata */
4443 		num_md_clusters = spdk_divide_round_up(
4444 					  ctx->super->md_start + ctx->super->md_len, ctx->bs->pages_per_cluster);
4445 		for (i = 0; i < num_md_clusters; i++) {
4446 			spdk_bit_array_set(ctx->used_clusters, i);
4447 		}
4448 		ctx->bs->num_free_clusters -= num_md_clusters;
4449 		spdk_free(ctx->page);
4450 		bs_load_write_used_md(ctx);
4451 	}
4452 }
4453 
4454 static void
4455 bs_load_replay_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4456 {
4457 	struct spdk_bs_load_ctx *ctx = cb_arg;
4458 	uint32_t page_num;
4459 	uint64_t i;
4460 
4461 	if (bserrno != 0) {
4462 		spdk_free(ctx->extent_pages);
4463 		bs_load_ctx_fail(ctx, bserrno);
4464 		return;
4465 	}
4466 
4467 	for (i = 0; i < ctx->num_extent_pages; i++) {
4468 		/* Extent pages are only read when present within in chain md.
4469 		 * Integrity of md is not right if that page was not a valid extent page. */
4470 		if (bs_load_cur_extent_page_valid(&ctx->extent_pages[i]) != true) {
4471 			spdk_free(ctx->extent_pages);
4472 			bs_load_ctx_fail(ctx, -EILSEQ);
4473 			return;
4474 		}
4475 
4476 		page_num = ctx->extent_page_num[i];
4477 		spdk_bit_array_set(ctx->bs->used_md_pages, page_num);
4478 		if (bs_load_replay_md_parse_page(ctx, &ctx->extent_pages[i])) {
4479 			spdk_free(ctx->extent_pages);
4480 			bs_load_ctx_fail(ctx, -EILSEQ);
4481 			return;
4482 		}
4483 	}
4484 
4485 	spdk_free(ctx->extent_pages);
4486 	free(ctx->extent_page_num);
4487 	ctx->extent_page_num = NULL;
4488 	ctx->num_extent_pages = 0;
4489 
4490 	bs_load_replay_md_chain_cpl(ctx);
4491 }
4492 
4493 static void
4494 bs_load_replay_extent_pages(struct spdk_bs_load_ctx *ctx)
4495 {
4496 	spdk_bs_batch_t *batch;
4497 	uint32_t page;
4498 	uint64_t lba;
4499 	uint64_t i;
4500 
4501 	ctx->extent_pages = spdk_zmalloc(SPDK_BS_PAGE_SIZE * ctx->num_extent_pages, 0,
4502 					 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4503 	if (!ctx->extent_pages) {
4504 		bs_load_ctx_fail(ctx, -ENOMEM);
4505 		return;
4506 	}
4507 
4508 	batch = bs_sequence_to_batch(ctx->seq, bs_load_replay_extent_page_cpl, ctx);
4509 
4510 	for (i = 0; i < ctx->num_extent_pages; i++) {
4511 		page = ctx->extent_page_num[i];
4512 		assert(page < ctx->super->md_len);
4513 		lba = bs_md_page_to_lba(ctx->bs, page);
4514 		bs_batch_read_dev(batch, &ctx->extent_pages[i], lba,
4515 				  bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE));
4516 	}
4517 
4518 	bs_batch_close(batch);
4519 }
4520 
4521 static void
4522 bs_load_replay_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4523 {
4524 	struct spdk_bs_load_ctx *ctx = cb_arg;
4525 	uint32_t page_num;
4526 	struct spdk_blob_md_page *page;
4527 
4528 	if (bserrno != 0) {
4529 		bs_load_ctx_fail(ctx, bserrno);
4530 		return;
4531 	}
4532 
4533 	page_num = ctx->cur_page;
4534 	page = ctx->page;
4535 	if (bs_load_cur_md_page_valid(ctx) == true) {
4536 		if (page->sequence_num == 0 || ctx->in_page_chain == true) {
4537 			spdk_spin_lock(&ctx->bs->used_lock);
4538 			bs_claim_md_page(ctx->bs, page_num);
4539 			spdk_spin_unlock(&ctx->bs->used_lock);
4540 			if (page->sequence_num == 0) {
4541 				SPDK_NOTICELOG("Recover: blob 0x%" PRIx32 "\n", page_num);
4542 				spdk_bit_array_set(ctx->bs->used_blobids, page_num);
4543 			}
4544 			if (bs_load_replay_md_parse_page(ctx, page)) {
4545 				bs_load_ctx_fail(ctx, -EILSEQ);
4546 				return;
4547 			}
4548 			if (page->next != SPDK_INVALID_MD_PAGE) {
4549 				ctx->in_page_chain = true;
4550 				ctx->cur_page = page->next;
4551 				bs_load_replay_cur_md_page(ctx);
4552 				return;
4553 			}
4554 			if (ctx->num_extent_pages != 0) {
4555 				bs_load_replay_extent_pages(ctx);
4556 				return;
4557 			}
4558 		}
4559 	}
4560 	bs_load_replay_md_chain_cpl(ctx);
4561 }
4562 
4563 static void
4564 bs_load_replay_cur_md_page(struct spdk_bs_load_ctx *ctx)
4565 {
4566 	uint64_t lba;
4567 
4568 	assert(ctx->cur_page < ctx->super->md_len);
4569 	lba = bs_md_page_to_lba(ctx->bs, ctx->cur_page);
4570 	bs_sequence_read_dev(ctx->seq, ctx->page, lba,
4571 			     bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
4572 			     bs_load_replay_md_cpl, ctx);
4573 }
4574 
4575 static void
4576 bs_load_replay_md(struct spdk_bs_load_ctx *ctx)
4577 {
4578 	ctx->page_index = 0;
4579 	ctx->cur_page = 0;
4580 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0,
4581 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4582 	if (!ctx->page) {
4583 		bs_load_ctx_fail(ctx, -ENOMEM);
4584 		return;
4585 	}
4586 	bs_load_replay_cur_md_page(ctx);
4587 }
4588 
4589 static void
4590 bs_recover(struct spdk_bs_load_ctx *ctx)
4591 {
4592 	int		rc;
4593 
4594 	SPDK_NOTICELOG("Performing recovery on blobstore\n");
4595 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->super->md_len);
4596 	if (rc < 0) {
4597 		bs_load_ctx_fail(ctx, -ENOMEM);
4598 		return;
4599 	}
4600 
4601 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->super->md_len);
4602 	if (rc < 0) {
4603 		bs_load_ctx_fail(ctx, -ENOMEM);
4604 		return;
4605 	}
4606 
4607 	rc = spdk_bit_array_resize(&ctx->used_clusters, ctx->bs->total_clusters);
4608 	if (rc < 0) {
4609 		bs_load_ctx_fail(ctx, -ENOMEM);
4610 		return;
4611 	}
4612 
4613 	rc = spdk_bit_array_resize(&ctx->bs->open_blobids, ctx->super->md_len);
4614 	if (rc < 0) {
4615 		bs_load_ctx_fail(ctx, -ENOMEM);
4616 		return;
4617 	}
4618 
4619 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
4620 	bs_load_replay_md(ctx);
4621 }
4622 
4623 static int
4624 bs_parse_super(struct spdk_bs_load_ctx *ctx)
4625 {
4626 	int rc;
4627 
4628 	if (ctx->super->size == 0) {
4629 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
4630 	}
4631 
4632 	if (ctx->super->io_unit_size == 0) {
4633 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
4634 	}
4635 
4636 	ctx->bs->clean = 1;
4637 	ctx->bs->cluster_sz = ctx->super->cluster_size;
4638 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
4639 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
4640 	if (spdk_u32_is_pow2(ctx->bs->pages_per_cluster)) {
4641 		ctx->bs->pages_per_cluster_shift = spdk_u32log2(ctx->bs->pages_per_cluster);
4642 	}
4643 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
4644 	rc = spdk_bit_array_resize(&ctx->used_clusters, ctx->bs->total_clusters);
4645 	if (rc < 0) {
4646 		return -ENOMEM;
4647 	}
4648 	ctx->bs->md_start = ctx->super->md_start;
4649 	ctx->bs->md_len = ctx->super->md_len;
4650 	rc = spdk_bit_array_resize(&ctx->bs->open_blobids, ctx->bs->md_len);
4651 	if (rc < 0) {
4652 		return -ENOMEM;
4653 	}
4654 
4655 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
4656 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
4657 	ctx->bs->super_blob = ctx->super->super_blob;
4658 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
4659 
4660 	return 0;
4661 }
4662 
4663 static void
4664 bs_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4665 {
4666 	struct spdk_bs_load_ctx *ctx = cb_arg;
4667 	uint32_t	crc;
4668 	int		rc;
4669 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
4670 
4671 	if (ctx->super->version > SPDK_BS_VERSION ||
4672 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
4673 		bs_load_ctx_fail(ctx, -EILSEQ);
4674 		return;
4675 	}
4676 
4677 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
4678 		   sizeof(ctx->super->signature)) != 0) {
4679 		bs_load_ctx_fail(ctx, -EILSEQ);
4680 		return;
4681 	}
4682 
4683 	crc = blob_md_page_calc_crc(ctx->super);
4684 	if (crc != ctx->super->crc) {
4685 		bs_load_ctx_fail(ctx, -EILSEQ);
4686 		return;
4687 	}
4688 
4689 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
4690 		SPDK_DEBUGLOG(blob, "Bstype matched - loading blobstore\n");
4691 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
4692 		SPDK_DEBUGLOG(blob, "Bstype wildcard used - loading blobstore regardless bstype\n");
4693 	} else {
4694 		SPDK_DEBUGLOG(blob, "Unexpected bstype\n");
4695 		SPDK_LOGDUMP(blob, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
4696 		SPDK_LOGDUMP(blob, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
4697 		bs_load_ctx_fail(ctx, -ENXIO);
4698 		return;
4699 	}
4700 
4701 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
4702 		SPDK_NOTICELOG("Size mismatch, dev size: %" PRIu64 ", blobstore size: %" PRIu64 "\n",
4703 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
4704 		bs_load_ctx_fail(ctx, -EILSEQ);
4705 		return;
4706 	}
4707 
4708 	rc = bs_parse_super(ctx);
4709 	if (rc < 0) {
4710 		bs_load_ctx_fail(ctx, rc);
4711 		return;
4712 	}
4713 
4714 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0 || ctx->force_recover) {
4715 		bs_recover(ctx);
4716 	} else {
4717 		bs_load_read_used_pages(ctx);
4718 	}
4719 }
4720 
4721 static inline int
4722 bs_opts_copy(struct spdk_bs_opts *src, struct spdk_bs_opts *dst)
4723 {
4724 
4725 	if (!src->opts_size) {
4726 		SPDK_ERRLOG("opts_size should not be zero value\n");
4727 		return -1;
4728 	}
4729 
4730 #define FIELD_OK(field) \
4731         offsetof(struct spdk_bs_opts, field) + sizeof(src->field) <= src->opts_size
4732 
4733 #define SET_FIELD(field) \
4734         if (FIELD_OK(field)) { \
4735                 dst->field = src->field; \
4736         } \
4737 
4738 	SET_FIELD(cluster_sz);
4739 	SET_FIELD(num_md_pages);
4740 	SET_FIELD(max_md_ops);
4741 	SET_FIELD(max_channel_ops);
4742 	SET_FIELD(clear_method);
4743 
4744 	if (FIELD_OK(bstype)) {
4745 		memcpy(&dst->bstype, &src->bstype, sizeof(dst->bstype));
4746 	}
4747 	SET_FIELD(iter_cb_fn);
4748 	SET_FIELD(iter_cb_arg);
4749 	SET_FIELD(force_recover);
4750 	SET_FIELD(esnap_bs_dev_create);
4751 	SET_FIELD(esnap_ctx);
4752 
4753 	dst->opts_size = src->opts_size;
4754 
4755 	/* You should not remove this statement, but need to update the assert statement
4756 	 * if you add a new field, and also add a corresponding SET_FIELD statement */
4757 	SPDK_STATIC_ASSERT(sizeof(struct spdk_bs_opts) == 88, "Incorrect size");
4758 
4759 #undef FIELD_OK
4760 #undef SET_FIELD
4761 
4762 	return 0;
4763 }
4764 
4765 void
4766 spdk_bs_load(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
4767 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
4768 {
4769 	struct spdk_blob_store	*bs;
4770 	struct spdk_bs_cpl	cpl;
4771 	struct spdk_bs_load_ctx *ctx;
4772 	struct spdk_bs_opts	opts = {};
4773 	int err;
4774 
4775 	SPDK_DEBUGLOG(blob, "Loading blobstore from dev %p\n", dev);
4776 
4777 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
4778 		SPDK_DEBUGLOG(blob, "unsupported dev block length of %d\n", dev->blocklen);
4779 		dev->destroy(dev);
4780 		cb_fn(cb_arg, NULL, -EINVAL);
4781 		return;
4782 	}
4783 
4784 	spdk_bs_opts_init(&opts, sizeof(opts));
4785 	if (o) {
4786 		if (bs_opts_copy(o, &opts)) {
4787 			return;
4788 		}
4789 	}
4790 
4791 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
4792 		dev->destroy(dev);
4793 		cb_fn(cb_arg, NULL, -EINVAL);
4794 		return;
4795 	}
4796 
4797 	err = bs_alloc(dev, &opts, &bs, &ctx);
4798 	if (err) {
4799 		dev->destroy(dev);
4800 		cb_fn(cb_arg, NULL, err);
4801 		return;
4802 	}
4803 
4804 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
4805 	cpl.u.bs_handle.cb_fn = cb_fn;
4806 	cpl.u.bs_handle.cb_arg = cb_arg;
4807 	cpl.u.bs_handle.bs = bs;
4808 
4809 	ctx->seq = bs_sequence_start_bs(bs->md_channel, &cpl);
4810 	if (!ctx->seq) {
4811 		spdk_free(ctx->super);
4812 		free(ctx);
4813 		bs_free(bs);
4814 		cb_fn(cb_arg, NULL, -ENOMEM);
4815 		return;
4816 	}
4817 
4818 	/* Read the super block */
4819 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
4820 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
4821 			     bs_load_super_cpl, ctx);
4822 }
4823 
4824 /* END spdk_bs_load */
4825 
4826 /* START spdk_bs_dump */
4827 
4828 static void
4829 bs_dump_finish(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
4830 {
4831 	spdk_free(ctx->super);
4832 
4833 	/*
4834 	 * We need to defer calling bs_call_cpl() until after
4835 	 * dev destruction, so tuck these away for later use.
4836 	 */
4837 	ctx->bs->unload_err = bserrno;
4838 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
4839 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
4840 
4841 	bs_sequence_finish(seq, 0);
4842 	bs_free(ctx->bs);
4843 	free(ctx);
4844 }
4845 
4846 static void
4847 bs_dump_print_xattr(struct spdk_bs_load_ctx *ctx, struct spdk_blob_md_descriptor *desc)
4848 {
4849 	struct spdk_blob_md_descriptor_xattr *desc_xattr;
4850 	uint32_t i;
4851 	const char *type;
4852 
4853 	desc_xattr = (struct spdk_blob_md_descriptor_xattr *)desc;
4854 
4855 	if (desc_xattr->length !=
4856 	    sizeof(desc_xattr->name_length) + sizeof(desc_xattr->value_length) +
4857 	    desc_xattr->name_length + desc_xattr->value_length) {
4858 	}
4859 
4860 	memcpy(ctx->xattr_name, desc_xattr->name, desc_xattr->name_length);
4861 	ctx->xattr_name[desc_xattr->name_length] = '\0';
4862 	if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
4863 		type = "XATTR";
4864 	} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
4865 		type = "XATTR_INTERNAL";
4866 	} else {
4867 		assert(false);
4868 		type = "XATTR_?";
4869 	}
4870 	fprintf(ctx->fp, "%s: name = \"%s\"\n", type, ctx->xattr_name);
4871 	fprintf(ctx->fp, "       value = \"");
4872 	ctx->print_xattr_fn(ctx->fp, ctx->super->bstype.bstype, ctx->xattr_name,
4873 			    (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
4874 			    desc_xattr->value_length);
4875 	fprintf(ctx->fp, "\"\n");
4876 	for (i = 0; i < desc_xattr->value_length; i++) {
4877 		if (i % 16 == 0) {
4878 			fprintf(ctx->fp, "               ");
4879 		}
4880 		fprintf(ctx->fp, "%02" PRIx8 " ", *((uint8_t *)desc_xattr->name + desc_xattr->name_length + i));
4881 		if ((i + 1) % 16 == 0) {
4882 			fprintf(ctx->fp, "\n");
4883 		}
4884 	}
4885 	if (i % 16 != 0) {
4886 		fprintf(ctx->fp, "\n");
4887 	}
4888 }
4889 
4890 struct type_flag_desc {
4891 	uint64_t mask;
4892 	uint64_t val;
4893 	const char *name;
4894 };
4895 
4896 static void
4897 bs_dump_print_type_bits(struct spdk_bs_load_ctx *ctx, uint64_t flags,
4898 			struct type_flag_desc *desc, size_t numflags)
4899 {
4900 	uint64_t covered = 0;
4901 	size_t i;
4902 
4903 	for (i = 0; i < numflags; i++) {
4904 		if ((desc[i].mask & flags) != desc[i].val) {
4905 			continue;
4906 		}
4907 		fprintf(ctx->fp, "\t\t 0x%016" PRIx64 " %s", desc[i].val, desc[i].name);
4908 		if (desc[i].mask != desc[i].val) {
4909 			fprintf(ctx->fp, " (mask 0x%" PRIx64 " value 0x%" PRIx64 ")",
4910 				desc[i].mask, desc[i].val);
4911 		}
4912 		fprintf(ctx->fp, "\n");
4913 		covered |= desc[i].mask;
4914 	}
4915 	if ((flags & ~covered) != 0) {
4916 		fprintf(ctx->fp, "\t\t 0x%016" PRIx64 " Unknown\n", flags & ~covered);
4917 	}
4918 }
4919 
4920 static void
4921 bs_dump_print_type_flags(struct spdk_bs_load_ctx *ctx, struct spdk_blob_md_descriptor *desc)
4922 {
4923 	struct spdk_blob_md_descriptor_flags *type_desc;
4924 #define ADD_FLAG(f) { f, f, #f }
4925 #define ADD_MASK_VAL(m, v) { m, v, #v }
4926 	static struct type_flag_desc invalid[] = {
4927 		ADD_FLAG(SPDK_BLOB_THIN_PROV),
4928 		ADD_FLAG(SPDK_BLOB_INTERNAL_XATTR),
4929 		ADD_FLAG(SPDK_BLOB_EXTENT_TABLE),
4930 	};
4931 	static struct type_flag_desc data_ro[] = {
4932 		ADD_FLAG(SPDK_BLOB_READ_ONLY),
4933 	};
4934 	static struct type_flag_desc md_ro[] = {
4935 		ADD_MASK_VAL(SPDK_BLOB_MD_RO_FLAGS_MASK, BLOB_CLEAR_WITH_DEFAULT),
4936 		ADD_MASK_VAL(SPDK_BLOB_MD_RO_FLAGS_MASK, BLOB_CLEAR_WITH_NONE),
4937 		ADD_MASK_VAL(SPDK_BLOB_MD_RO_FLAGS_MASK, BLOB_CLEAR_WITH_UNMAP),
4938 		ADD_MASK_VAL(SPDK_BLOB_MD_RO_FLAGS_MASK, BLOB_CLEAR_WITH_WRITE_ZEROES),
4939 	};
4940 #undef ADD_FLAG
4941 #undef ADD_MASK_VAL
4942 
4943 	type_desc = (struct spdk_blob_md_descriptor_flags *)desc;
4944 	fprintf(ctx->fp, "Flags:\n");
4945 	fprintf(ctx->fp, "\tinvalid: 0x%016" PRIx64 "\n", type_desc->invalid_flags);
4946 	bs_dump_print_type_bits(ctx, type_desc->invalid_flags, invalid,
4947 				SPDK_COUNTOF(invalid));
4948 	fprintf(ctx->fp, "\tdata_ro: 0x%016" PRIx64 "\n", type_desc->data_ro_flags);
4949 	bs_dump_print_type_bits(ctx, type_desc->data_ro_flags, data_ro,
4950 				SPDK_COUNTOF(data_ro));
4951 	fprintf(ctx->fp, "\t  md_ro: 0x%016" PRIx64 "\n", type_desc->md_ro_flags);
4952 	bs_dump_print_type_bits(ctx, type_desc->md_ro_flags, md_ro,
4953 				SPDK_COUNTOF(md_ro));
4954 }
4955 
4956 static void
4957 bs_dump_print_extent_table(struct spdk_bs_load_ctx *ctx, struct spdk_blob_md_descriptor *desc)
4958 {
4959 	struct spdk_blob_md_descriptor_extent_table *et_desc;
4960 	uint64_t num_extent_pages;
4961 	uint32_t et_idx;
4962 
4963 	et_desc = (struct spdk_blob_md_descriptor_extent_table *)desc;
4964 	num_extent_pages = (et_desc->length - sizeof(et_desc->num_clusters)) /
4965 			   sizeof(et_desc->extent_page[0]);
4966 
4967 	fprintf(ctx->fp, "Extent table:\n");
4968 	for (et_idx = 0; et_idx < num_extent_pages; et_idx++) {
4969 		if (et_desc->extent_page[et_idx].page_idx == 0) {
4970 			/* Zeroes represent unallocated extent pages. */
4971 			continue;
4972 		}
4973 		fprintf(ctx->fp, "\tExtent page: %5" PRIu32 " length %3" PRIu32
4974 			" at LBA %" PRIu64 "\n", et_desc->extent_page[et_idx].page_idx,
4975 			et_desc->extent_page[et_idx].num_pages,
4976 			bs_md_page_to_lba(ctx->bs, et_desc->extent_page[et_idx].page_idx));
4977 	}
4978 }
4979 
4980 static void
4981 bs_dump_print_md_page(struct spdk_bs_load_ctx *ctx)
4982 {
4983 	uint32_t page_idx = ctx->cur_page;
4984 	struct spdk_blob_md_page *page = ctx->page;
4985 	struct spdk_blob_md_descriptor *desc;
4986 	size_t cur_desc = 0;
4987 	uint32_t crc;
4988 
4989 	fprintf(ctx->fp, "=========\n");
4990 	fprintf(ctx->fp, "Metadata Page Index: %" PRIu32 " (0x%" PRIx32 ")\n", page_idx, page_idx);
4991 	fprintf(ctx->fp, "Start LBA: %" PRIu64 "\n", bs_md_page_to_lba(ctx->bs, page_idx));
4992 	fprintf(ctx->fp, "Blob ID: 0x%" PRIx64 "\n", page->id);
4993 	fprintf(ctx->fp, "Sequence: %" PRIu32 "\n", page->sequence_num);
4994 	if (page->next == SPDK_INVALID_MD_PAGE) {
4995 		fprintf(ctx->fp, "Next: None\n");
4996 	} else {
4997 		fprintf(ctx->fp, "Next: %" PRIu32 "\n", page->next);
4998 	}
4999 	fprintf(ctx->fp, "In used bit array%s:", ctx->super->clean ? "" : " (not clean: dubious)");
5000 	if (spdk_bit_array_get(ctx->bs->used_md_pages, page_idx)) {
5001 		fprintf(ctx->fp, " md");
5002 	}
5003 	if (spdk_bit_array_get(ctx->bs->used_blobids, page_idx)) {
5004 		fprintf(ctx->fp, " blob");
5005 	}
5006 	fprintf(ctx->fp, "\n");
5007 
5008 	crc = blob_md_page_calc_crc(page);
5009 	fprintf(ctx->fp, "CRC: 0x%" PRIx32 " (%s)\n", page->crc, crc == page->crc ? "OK" : "Mismatch");
5010 
5011 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
5012 	while (cur_desc < sizeof(page->descriptors)) {
5013 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
5014 			if (desc->length == 0) {
5015 				/* If padding and length are 0, this terminates the page */
5016 				break;
5017 			}
5018 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
5019 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
5020 			unsigned int				i;
5021 
5022 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
5023 
5024 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
5025 				if (desc_extent_rle->extents[i].cluster_idx != 0) {
5026 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
5027 						desc_extent_rle->extents[i].cluster_idx);
5028 				} else {
5029 					fprintf(ctx->fp, "Unallocated Extent - ");
5030 				}
5031 				fprintf(ctx->fp, " Length: %" PRIu32, desc_extent_rle->extents[i].length);
5032 				fprintf(ctx->fp, "\n");
5033 			}
5034 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
5035 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
5036 			unsigned int					i;
5037 
5038 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
5039 
5040 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->cluster_idx[0]); i++) {
5041 				if (desc_extent->cluster_idx[i] != 0) {
5042 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
5043 						desc_extent->cluster_idx[i]);
5044 				} else {
5045 					fprintf(ctx->fp, "Unallocated Extent");
5046 				}
5047 				fprintf(ctx->fp, "\n");
5048 			}
5049 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
5050 			bs_dump_print_xattr(ctx, desc);
5051 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
5052 			bs_dump_print_xattr(ctx, desc);
5053 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
5054 			bs_dump_print_type_flags(ctx, desc);
5055 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE) {
5056 			bs_dump_print_extent_table(ctx, desc);
5057 		} else {
5058 			/* Error */
5059 			fprintf(ctx->fp, "Unknown descriptor type %" PRIu8 "\n", desc->type);
5060 		}
5061 		/* Advance to the next descriptor */
5062 		cur_desc += sizeof(*desc) + desc->length;
5063 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
5064 			break;
5065 		}
5066 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
5067 	}
5068 }
5069 
5070 static void
5071 bs_dump_read_md_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5072 {
5073 	struct spdk_bs_load_ctx *ctx = cb_arg;
5074 
5075 	if (bserrno != 0) {
5076 		bs_dump_finish(seq, ctx, bserrno);
5077 		return;
5078 	}
5079 
5080 	if (ctx->page->id != 0) {
5081 		bs_dump_print_md_page(ctx);
5082 	}
5083 
5084 	ctx->cur_page++;
5085 
5086 	if (ctx->cur_page < ctx->super->md_len) {
5087 		bs_dump_read_md_page(seq, ctx);
5088 	} else {
5089 		spdk_free(ctx->page);
5090 		bs_dump_finish(seq, ctx, 0);
5091 	}
5092 }
5093 
5094 static void
5095 bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
5096 {
5097 	struct spdk_bs_load_ctx *ctx = cb_arg;
5098 	uint64_t lba;
5099 
5100 	assert(ctx->cur_page < ctx->super->md_len);
5101 	lba = bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
5102 	bs_sequence_read_dev(seq, ctx->page, lba,
5103 			     bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
5104 			     bs_dump_read_md_page_cpl, ctx);
5105 }
5106 
5107 static void
5108 bs_dump_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5109 {
5110 	struct spdk_bs_load_ctx *ctx = cb_arg;
5111 	int rc;
5112 
5113 	fprintf(ctx->fp, "Signature: \"%.8s\" ", ctx->super->signature);
5114 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
5115 		   sizeof(ctx->super->signature)) != 0) {
5116 		fprintf(ctx->fp, "(Mismatch)\n");
5117 		bs_dump_finish(seq, ctx, bserrno);
5118 		return;
5119 	} else {
5120 		fprintf(ctx->fp, "(OK)\n");
5121 	}
5122 	fprintf(ctx->fp, "Version: %" PRIu32 "\n", ctx->super->version);
5123 	fprintf(ctx->fp, "CRC: 0x%x (%s)\n", ctx->super->crc,
5124 		(ctx->super->crc == blob_md_page_calc_crc(ctx->super)) ? "OK" : "Mismatch");
5125 	fprintf(ctx->fp, "Blobstore Type: %.*s\n", SPDK_BLOBSTORE_TYPE_LENGTH, ctx->super->bstype.bstype);
5126 	fprintf(ctx->fp, "Cluster Size: %" PRIu32 "\n", ctx->super->cluster_size);
5127 	fprintf(ctx->fp, "Super Blob ID: ");
5128 	if (ctx->super->super_blob == SPDK_BLOBID_INVALID) {
5129 		fprintf(ctx->fp, "(None)\n");
5130 	} else {
5131 		fprintf(ctx->fp, "0x%" PRIx64 "\n", ctx->super->super_blob);
5132 	}
5133 	fprintf(ctx->fp, "Clean: %" PRIu32 "\n", ctx->super->clean);
5134 	fprintf(ctx->fp, "Used Metadata Page Mask Start: %" PRIu32 "\n", ctx->super->used_page_mask_start);
5135 	fprintf(ctx->fp, "Used Metadata Page Mask Length: %" PRIu32 "\n", ctx->super->used_page_mask_len);
5136 	fprintf(ctx->fp, "Used Cluster Mask Start: %" PRIu32 "\n", ctx->super->used_cluster_mask_start);
5137 	fprintf(ctx->fp, "Used Cluster Mask Length: %" PRIu32 "\n", ctx->super->used_cluster_mask_len);
5138 	fprintf(ctx->fp, "Used Blob ID Mask Start: %" PRIu32 "\n", ctx->super->used_blobid_mask_start);
5139 	fprintf(ctx->fp, "Used Blob ID Mask Length: %" PRIu32 "\n", ctx->super->used_blobid_mask_len);
5140 	fprintf(ctx->fp, "Metadata Start: %" PRIu32 "\n", ctx->super->md_start);
5141 	fprintf(ctx->fp, "Metadata Length: %" PRIu32 "\n", ctx->super->md_len);
5142 
5143 	ctx->cur_page = 0;
5144 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0,
5145 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
5146 	if (!ctx->page) {
5147 		bs_dump_finish(seq, ctx, -ENOMEM);
5148 		return;
5149 	}
5150 
5151 	rc = bs_parse_super(ctx);
5152 	if (rc < 0) {
5153 		bs_load_ctx_fail(ctx, rc);
5154 		return;
5155 	}
5156 
5157 	bs_load_read_used_pages(ctx);
5158 }
5159 
5160 void
5161 spdk_bs_dump(struct spdk_bs_dev *dev, FILE *fp, spdk_bs_dump_print_xattr print_xattr_fn,
5162 	     spdk_bs_op_complete cb_fn, void *cb_arg)
5163 {
5164 	struct spdk_blob_store	*bs;
5165 	struct spdk_bs_cpl	cpl;
5166 	struct spdk_bs_load_ctx *ctx;
5167 	struct spdk_bs_opts	opts = {};
5168 	int err;
5169 
5170 	SPDK_DEBUGLOG(blob, "Dumping blobstore from dev %p\n", dev);
5171 
5172 	spdk_bs_opts_init(&opts, sizeof(opts));
5173 
5174 	err = bs_alloc(dev, &opts, &bs, &ctx);
5175 	if (err) {
5176 		dev->destroy(dev);
5177 		cb_fn(cb_arg, err);
5178 		return;
5179 	}
5180 
5181 	ctx->dumping = true;
5182 	ctx->fp = fp;
5183 	ctx->print_xattr_fn = print_xattr_fn;
5184 
5185 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
5186 	cpl.u.bs_basic.cb_fn = cb_fn;
5187 	cpl.u.bs_basic.cb_arg = cb_arg;
5188 
5189 	ctx->seq = bs_sequence_start_bs(bs->md_channel, &cpl);
5190 	if (!ctx->seq) {
5191 		spdk_free(ctx->super);
5192 		free(ctx);
5193 		bs_free(bs);
5194 		cb_fn(cb_arg, -ENOMEM);
5195 		return;
5196 	}
5197 
5198 	/* Read the super block */
5199 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
5200 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
5201 			     bs_dump_super_cpl, ctx);
5202 }
5203 
5204 /* END spdk_bs_dump */
5205 
5206 /* START spdk_bs_init */
5207 
5208 static void
5209 bs_init_persist_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5210 {
5211 	struct spdk_bs_load_ctx *ctx = cb_arg;
5212 
5213 	ctx->bs->used_clusters = spdk_bit_pool_create_from_array(ctx->used_clusters);
5214 	spdk_free(ctx->super);
5215 	free(ctx);
5216 
5217 	bs_sequence_finish(seq, bserrno);
5218 }
5219 
5220 static void
5221 bs_init_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5222 {
5223 	struct spdk_bs_load_ctx *ctx = cb_arg;
5224 
5225 	/* Write super block */
5226 	bs_sequence_write_dev(seq, ctx->super, bs_page_to_lba(ctx->bs, 0),
5227 			      bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
5228 			      bs_init_persist_super_cpl, ctx);
5229 }
5230 
5231 void
5232 spdk_bs_init(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
5233 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
5234 {
5235 	struct spdk_bs_load_ctx *ctx;
5236 	struct spdk_blob_store	*bs;
5237 	struct spdk_bs_cpl	cpl;
5238 	spdk_bs_sequence_t	*seq;
5239 	spdk_bs_batch_t		*batch;
5240 	uint64_t		num_md_lba;
5241 	uint64_t		num_md_pages;
5242 	uint64_t		num_md_clusters;
5243 	uint64_t		max_used_cluster_mask_len;
5244 	uint32_t		i;
5245 	struct spdk_bs_opts	opts = {};
5246 	int			rc;
5247 	uint64_t		lba, lba_count;
5248 
5249 	SPDK_DEBUGLOG(blob, "Initializing blobstore on dev %p\n", dev);
5250 
5251 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
5252 		SPDK_ERRLOG("unsupported dev block length of %d\n",
5253 			    dev->blocklen);
5254 		dev->destroy(dev);
5255 		cb_fn(cb_arg, NULL, -EINVAL);
5256 		return;
5257 	}
5258 
5259 	spdk_bs_opts_init(&opts, sizeof(opts));
5260 	if (o) {
5261 		if (bs_opts_copy(o, &opts)) {
5262 			return;
5263 		}
5264 	}
5265 
5266 	if (bs_opts_verify(&opts) != 0) {
5267 		dev->destroy(dev);
5268 		cb_fn(cb_arg, NULL, -EINVAL);
5269 		return;
5270 	}
5271 
5272 	rc = bs_alloc(dev, &opts, &bs, &ctx);
5273 	if (rc) {
5274 		dev->destroy(dev);
5275 		cb_fn(cb_arg, NULL, rc);
5276 		return;
5277 	}
5278 
5279 	if (opts.num_md_pages == SPDK_BLOB_OPTS_NUM_MD_PAGES) {
5280 		/* By default, allocate 1 page per cluster.
5281 		 * Technically, this over-allocates metadata
5282 		 * because more metadata will reduce the number
5283 		 * of usable clusters. This can be addressed with
5284 		 * more complex math in the future.
5285 		 */
5286 		bs->md_len = bs->total_clusters;
5287 	} else {
5288 		bs->md_len = opts.num_md_pages;
5289 	}
5290 	rc = spdk_bit_array_resize(&bs->used_md_pages, bs->md_len);
5291 	if (rc < 0) {
5292 		spdk_free(ctx->super);
5293 		free(ctx);
5294 		bs_free(bs);
5295 		cb_fn(cb_arg, NULL, -ENOMEM);
5296 		return;
5297 	}
5298 
5299 	rc = spdk_bit_array_resize(&bs->used_blobids, bs->md_len);
5300 	if (rc < 0) {
5301 		spdk_free(ctx->super);
5302 		free(ctx);
5303 		bs_free(bs);
5304 		cb_fn(cb_arg, NULL, -ENOMEM);
5305 		return;
5306 	}
5307 
5308 	rc = spdk_bit_array_resize(&bs->open_blobids, bs->md_len);
5309 	if (rc < 0) {
5310 		spdk_free(ctx->super);
5311 		free(ctx);
5312 		bs_free(bs);
5313 		cb_fn(cb_arg, NULL, -ENOMEM);
5314 		return;
5315 	}
5316 
5317 	memcpy(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
5318 	       sizeof(ctx->super->signature));
5319 	ctx->super->version = SPDK_BS_VERSION;
5320 	ctx->super->length = sizeof(*ctx->super);
5321 	ctx->super->super_blob = bs->super_blob;
5322 	ctx->super->clean = 0;
5323 	ctx->super->cluster_size = bs->cluster_sz;
5324 	ctx->super->io_unit_size = bs->io_unit_size;
5325 	memcpy(&ctx->super->bstype, &bs->bstype, sizeof(bs->bstype));
5326 
5327 	/* Calculate how many pages the metadata consumes at the front
5328 	 * of the disk.
5329 	 */
5330 
5331 	/* The super block uses 1 page */
5332 	num_md_pages = 1;
5333 
5334 	/* The used_md_pages mask requires 1 bit per metadata page, rounded
5335 	 * up to the nearest page, plus a header.
5336 	 */
5337 	ctx->super->used_page_mask_start = num_md_pages;
5338 	ctx->super->used_page_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
5339 					 spdk_divide_round_up(bs->md_len, 8),
5340 					 SPDK_BS_PAGE_SIZE);
5341 	num_md_pages += ctx->super->used_page_mask_len;
5342 
5343 	/* The used_clusters mask requires 1 bit per cluster, rounded
5344 	 * up to the nearest page, plus a header.
5345 	 */
5346 	ctx->super->used_cluster_mask_start = num_md_pages;
5347 	ctx->super->used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
5348 					    spdk_divide_round_up(bs->total_clusters, 8),
5349 					    SPDK_BS_PAGE_SIZE);
5350 	/* The blobstore might be extended, then the used_cluster bitmap will need more space.
5351 	 * Here we calculate the max clusters we can support according to the
5352 	 * num_md_pages (bs->md_len).
5353 	 */
5354 	max_used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
5355 				    spdk_divide_round_up(bs->md_len, 8),
5356 				    SPDK_BS_PAGE_SIZE);
5357 	max_used_cluster_mask_len = spdk_max(max_used_cluster_mask_len,
5358 					     ctx->super->used_cluster_mask_len);
5359 	num_md_pages += max_used_cluster_mask_len;
5360 
5361 	/* The used_blobids mask requires 1 bit per metadata page, rounded
5362 	 * up to the nearest page, plus a header.
5363 	 */
5364 	ctx->super->used_blobid_mask_start = num_md_pages;
5365 	ctx->super->used_blobid_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
5366 					   spdk_divide_round_up(bs->md_len, 8),
5367 					   SPDK_BS_PAGE_SIZE);
5368 	num_md_pages += ctx->super->used_blobid_mask_len;
5369 
5370 	/* The metadata region size was chosen above */
5371 	ctx->super->md_start = bs->md_start = num_md_pages;
5372 	ctx->super->md_len = bs->md_len;
5373 	num_md_pages += bs->md_len;
5374 
5375 	num_md_lba = bs_page_to_lba(bs, num_md_pages);
5376 
5377 	ctx->super->size = dev->blockcnt * dev->blocklen;
5378 
5379 	ctx->super->crc = blob_md_page_calc_crc(ctx->super);
5380 
5381 	num_md_clusters = spdk_divide_round_up(num_md_pages, bs->pages_per_cluster);
5382 	if (num_md_clusters > bs->total_clusters) {
5383 		SPDK_ERRLOG("Blobstore metadata cannot use more clusters than is available, "
5384 			    "please decrease number of pages reserved for metadata "
5385 			    "or increase cluster size.\n");
5386 		spdk_free(ctx->super);
5387 		spdk_bit_array_free(&ctx->used_clusters);
5388 		free(ctx);
5389 		bs_free(bs);
5390 		cb_fn(cb_arg, NULL, -ENOMEM);
5391 		return;
5392 	}
5393 	/* Claim all of the clusters used by the metadata */
5394 	for (i = 0; i < num_md_clusters; i++) {
5395 		spdk_bit_array_set(ctx->used_clusters, i);
5396 	}
5397 
5398 	bs->num_free_clusters -= num_md_clusters;
5399 	bs->total_data_clusters = bs->num_free_clusters;
5400 
5401 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
5402 	cpl.u.bs_handle.cb_fn = cb_fn;
5403 	cpl.u.bs_handle.cb_arg = cb_arg;
5404 	cpl.u.bs_handle.bs = bs;
5405 
5406 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
5407 	if (!seq) {
5408 		spdk_free(ctx->super);
5409 		free(ctx);
5410 		bs_free(bs);
5411 		cb_fn(cb_arg, NULL, -ENOMEM);
5412 		return;
5413 	}
5414 
5415 	batch = bs_sequence_to_batch(seq, bs_init_trim_cpl, ctx);
5416 
5417 	/* Clear metadata space */
5418 	bs_batch_write_zeroes_dev(batch, 0, num_md_lba);
5419 
5420 	lba = num_md_lba;
5421 	lba_count = ctx->bs->dev->blockcnt - lba;
5422 	switch (opts.clear_method) {
5423 	case BS_CLEAR_WITH_UNMAP:
5424 		/* Trim data clusters */
5425 		bs_batch_unmap_dev(batch, lba, lba_count);
5426 		break;
5427 	case BS_CLEAR_WITH_WRITE_ZEROES:
5428 		/* Write_zeroes to data clusters */
5429 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
5430 		break;
5431 	case BS_CLEAR_WITH_NONE:
5432 	default:
5433 		break;
5434 	}
5435 
5436 	bs_batch_close(batch);
5437 }
5438 
5439 /* END spdk_bs_init */
5440 
5441 /* START spdk_bs_destroy */
5442 
5443 static void
5444 bs_destroy_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5445 {
5446 	struct spdk_bs_load_ctx *ctx = cb_arg;
5447 	struct spdk_blob_store *bs = ctx->bs;
5448 
5449 	/*
5450 	 * We need to defer calling bs_call_cpl() until after
5451 	 * dev destruction, so tuck these away for later use.
5452 	 */
5453 	bs->unload_err = bserrno;
5454 	memcpy(&bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
5455 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
5456 
5457 	bs_sequence_finish(seq, bserrno);
5458 
5459 	bs_free(bs);
5460 	free(ctx);
5461 }
5462 
5463 void
5464 spdk_bs_destroy(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn,
5465 		void *cb_arg)
5466 {
5467 	struct spdk_bs_cpl	cpl;
5468 	spdk_bs_sequence_t	*seq;
5469 	struct spdk_bs_load_ctx *ctx;
5470 
5471 	SPDK_DEBUGLOG(blob, "Destroying blobstore\n");
5472 
5473 	if (!RB_EMPTY(&bs->open_blobs)) {
5474 		SPDK_ERRLOG("Blobstore still has open blobs\n");
5475 		cb_fn(cb_arg, -EBUSY);
5476 		return;
5477 	}
5478 
5479 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
5480 	cpl.u.bs_basic.cb_fn = cb_fn;
5481 	cpl.u.bs_basic.cb_arg = cb_arg;
5482 
5483 	ctx = calloc(1, sizeof(*ctx));
5484 	if (!ctx) {
5485 		cb_fn(cb_arg, -ENOMEM);
5486 		return;
5487 	}
5488 
5489 	ctx->bs = bs;
5490 
5491 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
5492 	if (!seq) {
5493 		free(ctx);
5494 		cb_fn(cb_arg, -ENOMEM);
5495 		return;
5496 	}
5497 
5498 	/* Write zeroes to the super block */
5499 	bs_sequence_write_zeroes_dev(seq,
5500 				     bs_page_to_lba(bs, 0),
5501 				     bs_byte_to_lba(bs, sizeof(struct spdk_bs_super_block)),
5502 				     bs_destroy_trim_cpl, ctx);
5503 }
5504 
5505 /* END spdk_bs_destroy */
5506 
5507 /* START spdk_bs_unload */
5508 
5509 static void
5510 bs_unload_finish(struct spdk_bs_load_ctx *ctx, int bserrno)
5511 {
5512 	spdk_bs_sequence_t *seq = ctx->seq;
5513 
5514 	spdk_free(ctx->super);
5515 
5516 	/*
5517 	 * We need to defer calling bs_call_cpl() until after
5518 	 * dev destruction, so tuck these away for later use.
5519 	 */
5520 	ctx->bs->unload_err = bserrno;
5521 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
5522 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
5523 
5524 	bs_sequence_finish(seq, bserrno);
5525 
5526 	bs_free(ctx->bs);
5527 	free(ctx);
5528 }
5529 
5530 static void
5531 bs_unload_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5532 {
5533 	struct spdk_bs_load_ctx	*ctx = cb_arg;
5534 
5535 	bs_unload_finish(ctx, bserrno);
5536 }
5537 
5538 static void
5539 bs_unload_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5540 {
5541 	struct spdk_bs_load_ctx	*ctx = cb_arg;
5542 
5543 	spdk_free(ctx->mask);
5544 
5545 	if (bserrno != 0) {
5546 		bs_unload_finish(ctx, bserrno);
5547 		return;
5548 	}
5549 
5550 	ctx->super->clean = 1;
5551 
5552 	bs_write_super(seq, ctx->bs, ctx->super, bs_unload_write_super_cpl, ctx);
5553 }
5554 
5555 static void
5556 bs_unload_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5557 {
5558 	struct spdk_bs_load_ctx	*ctx = cb_arg;
5559 
5560 	spdk_free(ctx->mask);
5561 	ctx->mask = NULL;
5562 
5563 	if (bserrno != 0) {
5564 		bs_unload_finish(ctx, bserrno);
5565 		return;
5566 	}
5567 
5568 	bs_write_used_clusters(seq, ctx, bs_unload_write_used_clusters_cpl);
5569 }
5570 
5571 static void
5572 bs_unload_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5573 {
5574 	struct spdk_bs_load_ctx	*ctx = cb_arg;
5575 
5576 	spdk_free(ctx->mask);
5577 	ctx->mask = NULL;
5578 
5579 	if (bserrno != 0) {
5580 		bs_unload_finish(ctx, bserrno);
5581 		return;
5582 	}
5583 
5584 	bs_write_used_blobids(seq, ctx, bs_unload_write_used_blobids_cpl);
5585 }
5586 
5587 static void
5588 bs_unload_read_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5589 {
5590 	struct spdk_bs_load_ctx	*ctx = cb_arg;
5591 
5592 	if (bserrno != 0) {
5593 		bs_unload_finish(ctx, bserrno);
5594 		return;
5595 	}
5596 
5597 	bs_write_used_md(seq, cb_arg, bs_unload_write_used_pages_cpl);
5598 }
5599 
5600 void
5601 spdk_bs_unload(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn, void *cb_arg)
5602 {
5603 	struct spdk_bs_cpl	cpl;
5604 	struct spdk_bs_load_ctx *ctx;
5605 
5606 	SPDK_DEBUGLOG(blob, "Syncing blobstore\n");
5607 
5608 	/*
5609 	 * If external snapshot channels are being destroyed while the blobstore is unloaded, the
5610 	 * unload is deferred until after the channel destruction completes.
5611 	 */
5612 	if (bs->esnap_channels_unloading != 0) {
5613 		if (bs->esnap_unload_cb_fn != NULL) {
5614 			SPDK_ERRLOG("Blobstore unload in progress\n");
5615 			cb_fn(cb_arg, -EBUSY);
5616 			return;
5617 		}
5618 		SPDK_DEBUGLOG(blob_esnap, "Blobstore unload deferred: %" PRIu32
5619 			      " esnap clones are unloading\n", bs->esnap_channels_unloading);
5620 		bs->esnap_unload_cb_fn = cb_fn;
5621 		bs->esnap_unload_cb_arg = cb_arg;
5622 		return;
5623 	}
5624 	if (bs->esnap_unload_cb_fn != NULL) {
5625 		SPDK_DEBUGLOG(blob_esnap, "Blobstore deferred unload progressing\n");
5626 		assert(bs->esnap_unload_cb_fn == cb_fn);
5627 		assert(bs->esnap_unload_cb_arg == cb_arg);
5628 		bs->esnap_unload_cb_fn = NULL;
5629 		bs->esnap_unload_cb_arg = NULL;
5630 	}
5631 
5632 	if (!RB_EMPTY(&bs->open_blobs)) {
5633 		SPDK_ERRLOG("Blobstore still has open blobs\n");
5634 		cb_fn(cb_arg, -EBUSY);
5635 		return;
5636 	}
5637 
5638 	ctx = calloc(1, sizeof(*ctx));
5639 	if (!ctx) {
5640 		cb_fn(cb_arg, -ENOMEM);
5641 		return;
5642 	}
5643 
5644 	ctx->bs = bs;
5645 
5646 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
5647 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
5648 	if (!ctx->super) {
5649 		free(ctx);
5650 		cb_fn(cb_arg, -ENOMEM);
5651 		return;
5652 	}
5653 
5654 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
5655 	cpl.u.bs_basic.cb_fn = cb_fn;
5656 	cpl.u.bs_basic.cb_arg = cb_arg;
5657 
5658 	ctx->seq = bs_sequence_start_bs(bs->md_channel, &cpl);
5659 	if (!ctx->seq) {
5660 		spdk_free(ctx->super);
5661 		free(ctx);
5662 		cb_fn(cb_arg, -ENOMEM);
5663 		return;
5664 	}
5665 
5666 	/* Read super block */
5667 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
5668 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
5669 			     bs_unload_read_super_cpl, ctx);
5670 }
5671 
5672 /* END spdk_bs_unload */
5673 
5674 /* START spdk_bs_set_super */
5675 
5676 struct spdk_bs_set_super_ctx {
5677 	struct spdk_blob_store		*bs;
5678 	struct spdk_bs_super_block	*super;
5679 };
5680 
5681 static void
5682 bs_set_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5683 {
5684 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
5685 
5686 	if (bserrno != 0) {
5687 		SPDK_ERRLOG("Unable to write to super block of blobstore\n");
5688 	}
5689 
5690 	spdk_free(ctx->super);
5691 
5692 	bs_sequence_finish(seq, bserrno);
5693 
5694 	free(ctx);
5695 }
5696 
5697 static void
5698 bs_set_super_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5699 {
5700 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
5701 
5702 	if (bserrno != 0) {
5703 		SPDK_ERRLOG("Unable to read super block of blobstore\n");
5704 		spdk_free(ctx->super);
5705 		bs_sequence_finish(seq, bserrno);
5706 		free(ctx);
5707 		return;
5708 	}
5709 
5710 	bs_write_super(seq, ctx->bs, ctx->super, bs_set_super_write_cpl, ctx);
5711 }
5712 
5713 void
5714 spdk_bs_set_super(struct spdk_blob_store *bs, spdk_blob_id blobid,
5715 		  spdk_bs_op_complete cb_fn, void *cb_arg)
5716 {
5717 	struct spdk_bs_cpl		cpl;
5718 	spdk_bs_sequence_t		*seq;
5719 	struct spdk_bs_set_super_ctx	*ctx;
5720 
5721 	SPDK_DEBUGLOG(blob, "Setting super blob id on blobstore\n");
5722 
5723 	ctx = calloc(1, sizeof(*ctx));
5724 	if (!ctx) {
5725 		cb_fn(cb_arg, -ENOMEM);
5726 		return;
5727 	}
5728 
5729 	ctx->bs = bs;
5730 
5731 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
5732 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
5733 	if (!ctx->super) {
5734 		free(ctx);
5735 		cb_fn(cb_arg, -ENOMEM);
5736 		return;
5737 	}
5738 
5739 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
5740 	cpl.u.bs_basic.cb_fn = cb_fn;
5741 	cpl.u.bs_basic.cb_arg = cb_arg;
5742 
5743 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
5744 	if (!seq) {
5745 		spdk_free(ctx->super);
5746 		free(ctx);
5747 		cb_fn(cb_arg, -ENOMEM);
5748 		return;
5749 	}
5750 
5751 	bs->super_blob = blobid;
5752 
5753 	/* Read super block */
5754 	bs_sequence_read_dev(seq, ctx->super, bs_page_to_lba(bs, 0),
5755 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
5756 			     bs_set_super_read_cpl, ctx);
5757 }
5758 
5759 /* END spdk_bs_set_super */
5760 
5761 void
5762 spdk_bs_get_super(struct spdk_blob_store *bs,
5763 		  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5764 {
5765 	if (bs->super_blob == SPDK_BLOBID_INVALID) {
5766 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOENT);
5767 	} else {
5768 		cb_fn(cb_arg, bs->super_blob, 0);
5769 	}
5770 }
5771 
5772 uint64_t
5773 spdk_bs_get_cluster_size(struct spdk_blob_store *bs)
5774 {
5775 	return bs->cluster_sz;
5776 }
5777 
5778 uint64_t
5779 spdk_bs_get_page_size(struct spdk_blob_store *bs)
5780 {
5781 	return SPDK_BS_PAGE_SIZE;
5782 }
5783 
5784 uint64_t
5785 spdk_bs_get_io_unit_size(struct spdk_blob_store *bs)
5786 {
5787 	return bs->io_unit_size;
5788 }
5789 
5790 uint64_t
5791 spdk_bs_free_cluster_count(struct spdk_blob_store *bs)
5792 {
5793 	return bs->num_free_clusters;
5794 }
5795 
5796 uint64_t
5797 spdk_bs_total_data_cluster_count(struct spdk_blob_store *bs)
5798 {
5799 	return bs->total_data_clusters;
5800 }
5801 
5802 static int
5803 bs_register_md_thread(struct spdk_blob_store *bs)
5804 {
5805 	bs->md_channel = spdk_get_io_channel(bs);
5806 	if (!bs->md_channel) {
5807 		SPDK_ERRLOG("Failed to get IO channel.\n");
5808 		return -1;
5809 	}
5810 
5811 	return 0;
5812 }
5813 
5814 static int
5815 bs_unregister_md_thread(struct spdk_blob_store *bs)
5816 {
5817 	spdk_put_io_channel(bs->md_channel);
5818 
5819 	return 0;
5820 }
5821 
5822 spdk_blob_id
5823 spdk_blob_get_id(struct spdk_blob *blob)
5824 {
5825 	assert(blob != NULL);
5826 
5827 	return blob->id;
5828 }
5829 
5830 uint64_t
5831 spdk_blob_get_num_pages(struct spdk_blob *blob)
5832 {
5833 	assert(blob != NULL);
5834 
5835 	return bs_cluster_to_page(blob->bs, blob->active.num_clusters);
5836 }
5837 
5838 uint64_t
5839 spdk_blob_get_num_io_units(struct spdk_blob *blob)
5840 {
5841 	assert(blob != NULL);
5842 
5843 	return spdk_blob_get_num_pages(blob) * bs_io_unit_per_page(blob->bs);
5844 }
5845 
5846 uint64_t
5847 spdk_blob_get_num_clusters(struct spdk_blob *blob)
5848 {
5849 	assert(blob != NULL);
5850 
5851 	return blob->active.num_clusters;
5852 }
5853 
5854 static uint64_t
5855 blob_find_io_unit(struct spdk_blob *blob, uint64_t offset, bool is_allocated)
5856 {
5857 	uint64_t blob_io_unit_num = spdk_blob_get_num_io_units(blob);
5858 
5859 	while (offset < blob_io_unit_num) {
5860 		if (bs_io_unit_is_allocated(blob, offset) == is_allocated) {
5861 			return offset;
5862 		}
5863 
5864 		offset += bs_num_io_units_to_cluster_boundary(blob, offset);
5865 	}
5866 
5867 	return UINT64_MAX;
5868 }
5869 
5870 uint64_t
5871 spdk_blob_get_next_allocated_io_unit(struct spdk_blob *blob, uint64_t offset)
5872 {
5873 	return blob_find_io_unit(blob, offset, true);
5874 }
5875 
5876 uint64_t
5877 spdk_blob_get_next_unallocated_io_unit(struct spdk_blob *blob, uint64_t offset)
5878 {
5879 	return blob_find_io_unit(blob, offset, false);
5880 }
5881 
5882 /* START spdk_bs_create_blob */
5883 
5884 static void
5885 bs_create_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5886 {
5887 	struct spdk_blob *blob = cb_arg;
5888 	uint32_t page_idx = bs_blobid_to_page(blob->id);
5889 
5890 	if (bserrno != 0) {
5891 		spdk_spin_lock(&blob->bs->used_lock);
5892 		spdk_bit_array_clear(blob->bs->used_blobids, page_idx);
5893 		bs_release_md_page(blob->bs, page_idx);
5894 		spdk_spin_unlock(&blob->bs->used_lock);
5895 	}
5896 
5897 	blob_free(blob);
5898 
5899 	bs_sequence_finish(seq, bserrno);
5900 }
5901 
5902 static int
5903 blob_set_xattrs(struct spdk_blob *blob, const struct spdk_blob_xattr_opts *xattrs,
5904 		bool internal)
5905 {
5906 	uint64_t i;
5907 	size_t value_len = 0;
5908 	int rc;
5909 	const void *value = NULL;
5910 	if (xattrs->count > 0 && xattrs->get_value == NULL) {
5911 		return -EINVAL;
5912 	}
5913 	for (i = 0; i < xattrs->count; i++) {
5914 		xattrs->get_value(xattrs->ctx, xattrs->names[i], &value, &value_len);
5915 		if (value == NULL || value_len == 0) {
5916 			return -EINVAL;
5917 		}
5918 		rc = blob_set_xattr(blob, xattrs->names[i], value, value_len, internal);
5919 		if (rc < 0) {
5920 			return rc;
5921 		}
5922 	}
5923 	return 0;
5924 }
5925 
5926 static void
5927 blob_opts_copy(const struct spdk_blob_opts *src, struct spdk_blob_opts *dst)
5928 {
5929 #define FIELD_OK(field) \
5930         offsetof(struct spdk_blob_opts, field) + sizeof(src->field) <= src->opts_size
5931 
5932 #define SET_FIELD(field) \
5933         if (FIELD_OK(field)) { \
5934                 dst->field = src->field; \
5935         } \
5936 
5937 	SET_FIELD(num_clusters);
5938 	SET_FIELD(thin_provision);
5939 	SET_FIELD(clear_method);
5940 
5941 	if (FIELD_OK(xattrs)) {
5942 		memcpy(&dst->xattrs, &src->xattrs, sizeof(src->xattrs));
5943 	}
5944 
5945 	SET_FIELD(use_extent_table);
5946 	SET_FIELD(esnap_id);
5947 	SET_FIELD(esnap_id_len);
5948 
5949 	dst->opts_size = src->opts_size;
5950 
5951 	/* You should not remove this statement, but need to update the assert statement
5952 	 * if you add a new field, and also add a corresponding SET_FIELD statement */
5953 	SPDK_STATIC_ASSERT(sizeof(struct spdk_blob_opts) == 80, "Incorrect size");
5954 
5955 #undef FIELD_OK
5956 #undef SET_FIELD
5957 }
5958 
5959 static void
5960 bs_create_blob(struct spdk_blob_store *bs,
5961 	       const struct spdk_blob_opts *opts,
5962 	       const struct spdk_blob_xattr_opts *internal_xattrs,
5963 	       spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5964 {
5965 	struct spdk_blob	*blob;
5966 	uint32_t		page_idx;
5967 	struct spdk_bs_cpl	cpl;
5968 	struct spdk_blob_opts	opts_local;
5969 	struct spdk_blob_xattr_opts internal_xattrs_default;
5970 	spdk_bs_sequence_t	*seq;
5971 	spdk_blob_id		id;
5972 	int rc;
5973 
5974 	assert(spdk_get_thread() == bs->md_thread);
5975 
5976 	spdk_spin_lock(&bs->used_lock);
5977 	page_idx = spdk_bit_array_find_first_clear(bs->used_md_pages, 0);
5978 	if (page_idx == UINT32_MAX) {
5979 		spdk_spin_unlock(&bs->used_lock);
5980 		cb_fn(cb_arg, 0, -ENOMEM);
5981 		return;
5982 	}
5983 	spdk_bit_array_set(bs->used_blobids, page_idx);
5984 	bs_claim_md_page(bs, page_idx);
5985 	spdk_spin_unlock(&bs->used_lock);
5986 
5987 	id = bs_page_to_blobid(page_idx);
5988 
5989 	SPDK_DEBUGLOG(blob, "Creating blob with id 0x%" PRIx64 " at page %u\n", id, page_idx);
5990 
5991 	spdk_blob_opts_init(&opts_local, sizeof(opts_local));
5992 	if (opts) {
5993 		blob_opts_copy(opts, &opts_local);
5994 	}
5995 
5996 	blob = blob_alloc(bs, id);
5997 	if (!blob) {
5998 		rc = -ENOMEM;
5999 		goto error;
6000 	}
6001 
6002 	blob->use_extent_table = opts_local.use_extent_table;
6003 	if (blob->use_extent_table) {
6004 		blob->invalid_flags |= SPDK_BLOB_EXTENT_TABLE;
6005 	}
6006 
6007 	if (!internal_xattrs) {
6008 		blob_xattrs_init(&internal_xattrs_default);
6009 		internal_xattrs = &internal_xattrs_default;
6010 	}
6011 
6012 	rc = blob_set_xattrs(blob, &opts_local.xattrs, false);
6013 	if (rc < 0) {
6014 		goto error;
6015 	}
6016 
6017 	rc = blob_set_xattrs(blob, internal_xattrs, true);
6018 	if (rc < 0) {
6019 		goto error;
6020 	}
6021 
6022 	if (opts_local.thin_provision) {
6023 		blob_set_thin_provision(blob);
6024 	}
6025 
6026 	blob_set_clear_method(blob, opts_local.clear_method);
6027 
6028 	if (opts_local.esnap_id != NULL) {
6029 		if (opts_local.esnap_id_len > UINT16_MAX) {
6030 			SPDK_ERRLOG("esnap id length %" PRIu64 "is too long\n",
6031 				    opts_local.esnap_id_len);
6032 			rc = -EINVAL;
6033 			goto error;
6034 
6035 		}
6036 		blob_set_thin_provision(blob);
6037 		blob->invalid_flags |= SPDK_BLOB_EXTERNAL_SNAPSHOT;
6038 		rc = blob_set_xattr(blob, BLOB_EXTERNAL_SNAPSHOT_ID,
6039 				    opts_local.esnap_id, opts_local.esnap_id_len, true);
6040 		if (rc != 0) {
6041 			goto error;
6042 		}
6043 	}
6044 
6045 	rc = blob_resize(blob, opts_local.num_clusters);
6046 	if (rc < 0) {
6047 		goto error;
6048 	}
6049 	cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6050 	cpl.u.blobid.cb_fn = cb_fn;
6051 	cpl.u.blobid.cb_arg = cb_arg;
6052 	cpl.u.blobid.blobid = blob->id;
6053 
6054 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
6055 	if (!seq) {
6056 		rc = -ENOMEM;
6057 		goto error;
6058 	}
6059 
6060 	blob_persist(seq, blob, bs_create_blob_cpl, blob);
6061 	return;
6062 
6063 error:
6064 	SPDK_ERRLOG("Failed to create blob: %s, size in clusters/size: %lu (clusters)\n",
6065 		    spdk_strerror(rc), opts_local.num_clusters);
6066 	if (blob != NULL) {
6067 		blob_free(blob);
6068 	}
6069 	spdk_spin_lock(&bs->used_lock);
6070 	spdk_bit_array_clear(bs->used_blobids, page_idx);
6071 	bs_release_md_page(bs, page_idx);
6072 	spdk_spin_unlock(&bs->used_lock);
6073 	cb_fn(cb_arg, 0, rc);
6074 }
6075 
6076 void
6077 spdk_bs_create_blob(struct spdk_blob_store *bs,
6078 		    spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6079 {
6080 	bs_create_blob(bs, NULL, NULL, cb_fn, cb_arg);
6081 }
6082 
6083 void
6084 spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
6085 			spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6086 {
6087 	bs_create_blob(bs, opts, NULL, cb_fn, cb_arg);
6088 }
6089 
6090 /* END spdk_bs_create_blob */
6091 
6092 /* START blob_cleanup */
6093 
6094 struct spdk_clone_snapshot_ctx {
6095 	struct spdk_bs_cpl      cpl;
6096 	int bserrno;
6097 	bool frozen;
6098 
6099 	struct spdk_io_channel *channel;
6100 
6101 	/* Current cluster for inflate operation */
6102 	uint64_t cluster;
6103 
6104 	/* For inflation force allocation of all unallocated clusters and remove
6105 	 * thin-provisioning. Otherwise only decouple parent and keep clone thin. */
6106 	bool allocate_all;
6107 
6108 	struct {
6109 		spdk_blob_id id;
6110 		struct spdk_blob *blob;
6111 		bool md_ro;
6112 	} original;
6113 	struct {
6114 		spdk_blob_id id;
6115 		struct spdk_blob *blob;
6116 	} new;
6117 
6118 	/* xattrs specified for snapshot/clones only. They have no impact on
6119 	 * the original blobs xattrs. */
6120 	const struct spdk_blob_xattr_opts *xattrs;
6121 };
6122 
6123 static void
6124 bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
6125 {
6126 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
6127 	struct spdk_bs_cpl *cpl = &ctx->cpl;
6128 
6129 	if (bserrno != 0) {
6130 		if (ctx->bserrno != 0) {
6131 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
6132 		} else {
6133 			ctx->bserrno = bserrno;
6134 		}
6135 	}
6136 
6137 	switch (cpl->type) {
6138 	case SPDK_BS_CPL_TYPE_BLOBID:
6139 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
6140 		break;
6141 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
6142 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
6143 		break;
6144 	default:
6145 		SPDK_UNREACHABLE();
6146 		break;
6147 	}
6148 
6149 	free(ctx);
6150 }
6151 
6152 static void
6153 bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
6154 {
6155 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6156 	struct spdk_blob *origblob = ctx->original.blob;
6157 
6158 	if (bserrno != 0) {
6159 		if (ctx->bserrno != 0) {
6160 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
6161 		} else {
6162 			ctx->bserrno = bserrno;
6163 		}
6164 	}
6165 
6166 	ctx->original.id = origblob->id;
6167 	origblob->locked_operation_in_progress = false;
6168 
6169 	/* Revert md_ro to original state */
6170 	origblob->md_ro = ctx->original.md_ro;
6171 
6172 	spdk_blob_close(origblob, bs_clone_snapshot_cleanup_finish, ctx);
6173 }
6174 
6175 static void
6176 bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
6177 {
6178 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6179 	struct spdk_blob *origblob = ctx->original.blob;
6180 
6181 	if (bserrno != 0) {
6182 		if (ctx->bserrno != 0) {
6183 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
6184 		} else {
6185 			ctx->bserrno = bserrno;
6186 		}
6187 	}
6188 
6189 	if (ctx->frozen) {
6190 		/* Unfreeze any outstanding I/O */
6191 		blob_unfreeze_io(origblob, bs_snapshot_unfreeze_cpl, ctx);
6192 	} else {
6193 		bs_snapshot_unfreeze_cpl(ctx, 0);
6194 	}
6195 
6196 }
6197 
6198 static void
6199 bs_clone_snapshot_newblob_cleanup(struct spdk_clone_snapshot_ctx *ctx, int bserrno)
6200 {
6201 	struct spdk_blob *newblob = ctx->new.blob;
6202 
6203 	if (bserrno != 0) {
6204 		if (ctx->bserrno != 0) {
6205 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
6206 		} else {
6207 			ctx->bserrno = bserrno;
6208 		}
6209 	}
6210 
6211 	ctx->new.id = newblob->id;
6212 	spdk_blob_close(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
6213 }
6214 
6215 /* END blob_cleanup */
6216 
6217 /* START spdk_bs_create_snapshot */
6218 
6219 static void
6220 bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
6221 {
6222 	uint64_t *cluster_temp;
6223 	uint32_t *extent_page_temp;
6224 
6225 	cluster_temp = blob1->active.clusters;
6226 	blob1->active.clusters = blob2->active.clusters;
6227 	blob2->active.clusters = cluster_temp;
6228 
6229 	extent_page_temp = blob1->active.extent_pages;
6230 	blob1->active.extent_pages = blob2->active.extent_pages;
6231 	blob2->active.extent_pages = extent_page_temp;
6232 }
6233 
6234 /* Copies an internal xattr */
6235 static int
6236 bs_snapshot_copy_xattr(struct spdk_blob *toblob, struct spdk_blob *fromblob, const char *name)
6237 {
6238 	const void	*val = NULL;
6239 	size_t		len;
6240 	int		bserrno;
6241 
6242 	bserrno = blob_get_xattr_value(fromblob, name, &val, &len, true);
6243 	if (bserrno != 0) {
6244 		SPDK_ERRLOG("blob 0x%" PRIx64 " missing %s XATTR\n", fromblob->id, name);
6245 		return bserrno;
6246 	}
6247 
6248 	bserrno = blob_set_xattr(toblob, name, val, len, true);
6249 	if (bserrno != 0) {
6250 		SPDK_ERRLOG("could not set %s XATTR on blob 0x%" PRIx64 "\n",
6251 			    name, toblob->id);
6252 		return bserrno;
6253 	}
6254 	return 0;
6255 }
6256 
6257 static void
6258 bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
6259 {
6260 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6261 	struct spdk_blob *origblob = ctx->original.blob;
6262 	struct spdk_blob *newblob = ctx->new.blob;
6263 
6264 	if (bserrno != 0) {
6265 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6266 		if (blob_is_esnap_clone(newblob)) {
6267 			bs_snapshot_copy_xattr(origblob, newblob, BLOB_EXTERNAL_SNAPSHOT_ID);
6268 			origblob->invalid_flags |= SPDK_BLOB_EXTERNAL_SNAPSHOT;
6269 		}
6270 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6271 		return;
6272 	}
6273 
6274 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
6275 	bserrno = blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
6276 	if (bserrno != 0) {
6277 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6278 		return;
6279 	}
6280 
6281 	bs_blob_list_add(ctx->original.blob);
6282 
6283 	spdk_blob_set_read_only(newblob);
6284 
6285 	/* sync snapshot metadata */
6286 	spdk_blob_sync_md(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
6287 }
6288 
6289 static void
6290 bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
6291 {
6292 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6293 	struct spdk_blob *origblob = ctx->original.blob;
6294 	struct spdk_blob *newblob = ctx->new.blob;
6295 
6296 	if (bserrno != 0) {
6297 		/* return cluster map back to original */
6298 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6299 
6300 		/* Newblob md sync failed. Valid clusters are only present in origblob.
6301 		 * Since I/O is frozen on origblob, not changes to zeroed out cluster map should have occurred.
6302 		 * Newblob needs to be reverted to thin_provisioned state at creation to properly close. */
6303 		blob_set_thin_provision(newblob);
6304 		assert(spdk_mem_all_zero(newblob->active.clusters,
6305 					 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
6306 		assert(spdk_mem_all_zero(newblob->active.extent_pages,
6307 					 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
6308 
6309 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6310 		return;
6311 	}
6312 
6313 	/* Set internal xattr for snapshot id */
6314 	bserrno = blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
6315 	if (bserrno != 0) {
6316 		/* return cluster map back to original */
6317 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6318 		blob_set_thin_provision(newblob);
6319 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6320 		return;
6321 	}
6322 
6323 	/* Create new back_bs_dev for snapshot */
6324 	origblob->back_bs_dev = bs_create_blob_bs_dev(newblob);
6325 	if (origblob->back_bs_dev == NULL) {
6326 		/* return cluster map back to original */
6327 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6328 		blob_set_thin_provision(newblob);
6329 		bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
6330 		return;
6331 	}
6332 
6333 	/* Remove the xattr that references an external snapshot */
6334 	if (blob_is_esnap_clone(origblob)) {
6335 		origblob->invalid_flags &= ~SPDK_BLOB_EXTERNAL_SNAPSHOT;
6336 		bserrno = blob_remove_xattr(origblob, BLOB_EXTERNAL_SNAPSHOT_ID, true);
6337 		if (bserrno != 0) {
6338 			if (bserrno == -ENOENT) {
6339 				SPDK_ERRLOG("blob 0x%" PRIx64 " has no " BLOB_EXTERNAL_SNAPSHOT_ID
6340 					    " xattr to remove\n", origblob->id);
6341 				assert(false);
6342 			} else {
6343 				/* return cluster map back to original */
6344 				bs_snapshot_swap_cluster_maps(newblob, origblob);
6345 				blob_set_thin_provision(newblob);
6346 				bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6347 				return;
6348 			}
6349 		}
6350 	}
6351 
6352 	bs_blob_list_remove(origblob);
6353 	origblob->parent_id = newblob->id;
6354 	/* set clone blob as thin provisioned */
6355 	blob_set_thin_provision(origblob);
6356 
6357 	bs_blob_list_add(newblob);
6358 
6359 	/* sync clone metadata */
6360 	spdk_blob_sync_md(origblob, bs_snapshot_origblob_sync_cpl, ctx);
6361 }
6362 
6363 static void
6364 bs_snapshot_freeze_cpl(void *cb_arg, int rc)
6365 {
6366 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6367 	struct spdk_blob *origblob = ctx->original.blob;
6368 	struct spdk_blob *newblob = ctx->new.blob;
6369 	int bserrno;
6370 
6371 	if (rc != 0) {
6372 		bs_clone_snapshot_newblob_cleanup(ctx, rc);
6373 		return;
6374 	}
6375 
6376 	ctx->frozen = true;
6377 
6378 	if (blob_is_esnap_clone(origblob)) {
6379 		/* Clean up any channels associated with the original blob id because future IO will
6380 		 * perform IO using the snapshot blob_id.
6381 		 */
6382 		blob_esnap_destroy_bs_dev_channels(origblob, false, NULL, NULL);
6383 	}
6384 	if (newblob->back_bs_dev) {
6385 		blob_back_bs_destroy(newblob);
6386 	}
6387 	/* set new back_bs_dev for snapshot */
6388 	newblob->back_bs_dev = origblob->back_bs_dev;
6389 	/* Set invalid flags from origblob */
6390 	newblob->invalid_flags = origblob->invalid_flags;
6391 
6392 	/* inherit parent from original blob if set */
6393 	newblob->parent_id = origblob->parent_id;
6394 	switch (origblob->parent_id) {
6395 	case SPDK_BLOBID_EXTERNAL_SNAPSHOT:
6396 		bserrno = bs_snapshot_copy_xattr(newblob, origblob, BLOB_EXTERNAL_SNAPSHOT_ID);
6397 		if (bserrno != 0) {
6398 			bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6399 			return;
6400 		}
6401 		break;
6402 	case SPDK_BLOBID_INVALID:
6403 		break;
6404 	default:
6405 		/* Set internal xattr for snapshot id */
6406 		bserrno = blob_set_xattr(newblob, BLOB_SNAPSHOT,
6407 					 &origblob->parent_id, sizeof(spdk_blob_id), true);
6408 		if (bserrno != 0) {
6409 			bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6410 			return;
6411 		}
6412 	}
6413 
6414 	/* swap cluster maps */
6415 	bs_snapshot_swap_cluster_maps(newblob, origblob);
6416 
6417 	/* Set the clear method on the new blob to match the original. */
6418 	blob_set_clear_method(newblob, origblob->clear_method);
6419 
6420 	/* sync snapshot metadata */
6421 	spdk_blob_sync_md(newblob, bs_snapshot_newblob_sync_cpl, ctx);
6422 }
6423 
6424 static void
6425 bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6426 {
6427 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6428 	struct spdk_blob *origblob = ctx->original.blob;
6429 	struct spdk_blob *newblob = _blob;
6430 
6431 	if (bserrno != 0) {
6432 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6433 		return;
6434 	}
6435 
6436 	ctx->new.blob = newblob;
6437 	assert(spdk_blob_is_thin_provisioned(newblob));
6438 	assert(spdk_mem_all_zero(newblob->active.clusters,
6439 				 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
6440 	assert(spdk_mem_all_zero(newblob->active.extent_pages,
6441 				 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
6442 
6443 	blob_freeze_io(origblob, bs_snapshot_freeze_cpl, ctx);
6444 }
6445 
6446 static void
6447 bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
6448 {
6449 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6450 	struct spdk_blob *origblob = ctx->original.blob;
6451 
6452 	if (bserrno != 0) {
6453 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6454 		return;
6455 	}
6456 
6457 	ctx->new.id = blobid;
6458 	ctx->cpl.u.blobid.blobid = blobid;
6459 
6460 	spdk_bs_open_blob(origblob->bs, ctx->new.id, bs_snapshot_newblob_open_cpl, ctx);
6461 }
6462 
6463 
6464 static void
6465 bs_xattr_snapshot(void *arg, const char *name,
6466 		  const void **value, size_t *value_len)
6467 {
6468 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
6469 
6470 	struct spdk_blob *blob = (struct spdk_blob *)arg;
6471 	*value = &blob->id;
6472 	*value_len = sizeof(blob->id);
6473 }
6474 
6475 static void
6476 bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6477 {
6478 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6479 	struct spdk_blob_opts opts;
6480 	struct spdk_blob_xattr_opts internal_xattrs;
6481 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
6482 
6483 	if (bserrno != 0) {
6484 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6485 		return;
6486 	}
6487 
6488 	ctx->original.blob = _blob;
6489 
6490 	if (_blob->data_ro || _blob->md_ro) {
6491 		SPDK_DEBUGLOG(blob, "Cannot create snapshot from read only blob with id 0x%"
6492 			      PRIx64 "\n", _blob->id);
6493 		ctx->bserrno = -EINVAL;
6494 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6495 		return;
6496 	}
6497 
6498 	if (_blob->locked_operation_in_progress) {
6499 		SPDK_DEBUGLOG(blob, "Cannot create snapshot - another operation in progress\n");
6500 		ctx->bserrno = -EBUSY;
6501 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6502 		return;
6503 	}
6504 
6505 	_blob->locked_operation_in_progress = true;
6506 
6507 	spdk_blob_opts_init(&opts, sizeof(opts));
6508 	blob_xattrs_init(&internal_xattrs);
6509 
6510 	/* Change the size of new blob to the same as in original blob,
6511 	 * but do not allocate clusters */
6512 	opts.thin_provision = true;
6513 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
6514 	opts.use_extent_table = _blob->use_extent_table;
6515 
6516 	/* If there are any xattrs specified for snapshot, set them now */
6517 	if (ctx->xattrs) {
6518 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
6519 	}
6520 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
6521 	internal_xattrs.count = 1;
6522 	internal_xattrs.ctx = _blob;
6523 	internal_xattrs.names = xattrs_names;
6524 	internal_xattrs.get_value = bs_xattr_snapshot;
6525 
6526 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
6527 		       bs_snapshot_newblob_create_cpl, ctx);
6528 }
6529 
6530 void
6531 spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
6532 			const struct spdk_blob_xattr_opts *snapshot_xattrs,
6533 			spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6534 {
6535 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6536 
6537 	if (!ctx) {
6538 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
6539 		return;
6540 	}
6541 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6542 	ctx->cpl.u.blobid.cb_fn = cb_fn;
6543 	ctx->cpl.u.blobid.cb_arg = cb_arg;
6544 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
6545 	ctx->bserrno = 0;
6546 	ctx->frozen = false;
6547 	ctx->original.id = blobid;
6548 	ctx->xattrs = snapshot_xattrs;
6549 
6550 	spdk_bs_open_blob(bs, ctx->original.id, bs_snapshot_origblob_open_cpl, ctx);
6551 }
6552 /* END spdk_bs_create_snapshot */
6553 
6554 /* START spdk_bs_create_clone */
6555 
6556 static void
6557 bs_xattr_clone(void *arg, const char *name,
6558 	       const void **value, size_t *value_len)
6559 {
6560 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
6561 
6562 	struct spdk_blob *blob = (struct spdk_blob *)arg;
6563 	*value = &blob->id;
6564 	*value_len = sizeof(blob->id);
6565 }
6566 
6567 static void
6568 bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6569 {
6570 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6571 	struct spdk_blob *clone = _blob;
6572 
6573 	ctx->new.blob = clone;
6574 	bs_blob_list_add(clone);
6575 
6576 	spdk_blob_close(clone, bs_clone_snapshot_origblob_cleanup, ctx);
6577 }
6578 
6579 static void
6580 bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
6581 {
6582 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6583 
6584 	ctx->cpl.u.blobid.blobid = blobid;
6585 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, bs_clone_newblob_open_cpl, ctx);
6586 }
6587 
6588 static void
6589 bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6590 {
6591 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6592 	struct spdk_blob_opts		opts;
6593 	struct spdk_blob_xattr_opts internal_xattrs;
6594 	char *xattr_names[] = { BLOB_SNAPSHOT };
6595 
6596 	if (bserrno != 0) {
6597 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6598 		return;
6599 	}
6600 
6601 	ctx->original.blob = _blob;
6602 	ctx->original.md_ro = _blob->md_ro;
6603 
6604 	if (!_blob->data_ro || !_blob->md_ro) {
6605 		SPDK_DEBUGLOG(blob, "Clone not from read-only blob\n");
6606 		ctx->bserrno = -EINVAL;
6607 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6608 		return;
6609 	}
6610 
6611 	if (_blob->locked_operation_in_progress) {
6612 		SPDK_DEBUGLOG(blob, "Cannot create clone - another operation in progress\n");
6613 		ctx->bserrno = -EBUSY;
6614 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6615 		return;
6616 	}
6617 
6618 	_blob->locked_operation_in_progress = true;
6619 
6620 	spdk_blob_opts_init(&opts, sizeof(opts));
6621 	blob_xattrs_init(&internal_xattrs);
6622 
6623 	opts.thin_provision = true;
6624 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
6625 	opts.use_extent_table = _blob->use_extent_table;
6626 	if (ctx->xattrs) {
6627 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
6628 	}
6629 
6630 	/* Set internal xattr BLOB_SNAPSHOT */
6631 	internal_xattrs.count = 1;
6632 	internal_xattrs.ctx = _blob;
6633 	internal_xattrs.names = xattr_names;
6634 	internal_xattrs.get_value = bs_xattr_clone;
6635 
6636 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
6637 		       bs_clone_newblob_create_cpl, ctx);
6638 }
6639 
6640 void
6641 spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
6642 		     const struct spdk_blob_xattr_opts *clone_xattrs,
6643 		     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6644 {
6645 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
6646 
6647 	if (!ctx) {
6648 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
6649 		return;
6650 	}
6651 
6652 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6653 	ctx->cpl.u.blobid.cb_fn = cb_fn;
6654 	ctx->cpl.u.blobid.cb_arg = cb_arg;
6655 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
6656 	ctx->bserrno = 0;
6657 	ctx->xattrs = clone_xattrs;
6658 	ctx->original.id = blobid;
6659 
6660 	spdk_bs_open_blob(bs, ctx->original.id, bs_clone_origblob_open_cpl, ctx);
6661 }
6662 
6663 /* END spdk_bs_create_clone */
6664 
6665 /* START spdk_bs_inflate_blob */
6666 
6667 static void
6668 bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
6669 {
6670 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6671 	struct spdk_blob *_blob = ctx->original.blob;
6672 
6673 	if (bserrno != 0) {
6674 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6675 		return;
6676 	}
6677 
6678 	/* Temporarily override md_ro flag for MD modification */
6679 	_blob->md_ro = false;
6680 
6681 	bserrno = blob_set_xattr(_blob, BLOB_SNAPSHOT, &_parent->id, sizeof(spdk_blob_id), true);
6682 	if (bserrno != 0) {
6683 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6684 		return;
6685 	}
6686 
6687 	assert(_parent != NULL);
6688 
6689 	bs_blob_list_remove(_blob);
6690 	_blob->parent_id = _parent->id;
6691 
6692 	blob_back_bs_destroy(_blob);
6693 	_blob->back_bs_dev = bs_create_blob_bs_dev(_parent);
6694 	bs_blob_list_add(_blob);
6695 
6696 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6697 }
6698 
6699 static void
6700 bs_inflate_blob_done(struct spdk_clone_snapshot_ctx *ctx)
6701 {
6702 	struct spdk_blob *_blob = ctx->original.blob;
6703 	struct spdk_blob *_parent;
6704 
6705 	if (ctx->allocate_all) {
6706 		/* remove thin provisioning */
6707 		bs_blob_list_remove(_blob);
6708 		if (_blob->parent_id == SPDK_BLOBID_EXTERNAL_SNAPSHOT) {
6709 			blob_remove_xattr(_blob, BLOB_EXTERNAL_SNAPSHOT_ID, true);
6710 			_blob->invalid_flags &= ~SPDK_BLOB_EXTERNAL_SNAPSHOT;
6711 		} else {
6712 			blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
6713 		}
6714 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
6715 		blob_back_bs_destroy(_blob);
6716 		_blob->parent_id = SPDK_BLOBID_INVALID;
6717 	} else {
6718 		/* For now, esnap clones always have allocate_all set. */
6719 		assert(!blob_is_esnap_clone(_blob));
6720 
6721 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
6722 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
6723 			/* We must change the parent of the inflated blob */
6724 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
6725 					  bs_inflate_blob_set_parent_cpl, ctx);
6726 			return;
6727 		}
6728 
6729 		bs_blob_list_remove(_blob);
6730 		_blob->parent_id = SPDK_BLOBID_INVALID;
6731 		blob_back_bs_destroy(_blob);
6732 		_blob->back_bs_dev = bs_create_zeroes_dev();
6733 	}
6734 
6735 	/* Temporarily override md_ro flag for MD modification */
6736 	_blob->md_ro = false;
6737 	blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
6738 	_blob->state = SPDK_BLOB_STATE_DIRTY;
6739 
6740 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6741 }
6742 
6743 /* Check if cluster needs allocation */
6744 static inline bool
6745 bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
6746 {
6747 	struct spdk_blob_bs_dev *b;
6748 
6749 	assert(blob != NULL);
6750 
6751 	if (blob->active.clusters[cluster] != 0) {
6752 		/* Cluster is already allocated */
6753 		return false;
6754 	}
6755 
6756 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
6757 		/* Blob have no parent blob */
6758 		return allocate_all;
6759 	}
6760 
6761 	if (blob->parent_id == SPDK_BLOBID_EXTERNAL_SNAPSHOT) {
6762 		return true;
6763 	}
6764 
6765 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
6766 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
6767 }
6768 
6769 static void
6770 bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
6771 {
6772 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6773 	struct spdk_blob *_blob = ctx->original.blob;
6774 	struct spdk_bs_cpl cpl;
6775 	spdk_bs_user_op_t *op;
6776 	uint64_t offset;
6777 
6778 	if (bserrno != 0) {
6779 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6780 		return;
6781 	}
6782 
6783 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
6784 		if (bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
6785 			break;
6786 		}
6787 	}
6788 
6789 	if (ctx->cluster < _blob->active.num_clusters) {
6790 		offset = bs_cluster_to_lba(_blob->bs, ctx->cluster);
6791 
6792 		/* We may safely increment a cluster before copying */
6793 		ctx->cluster++;
6794 
6795 		/* Use a dummy 0B read as a context for cluster copy */
6796 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6797 		cpl.u.blob_basic.cb_fn = bs_inflate_blob_touch_next;
6798 		cpl.u.blob_basic.cb_arg = ctx;
6799 
6800 		op = bs_user_op_alloc(ctx->channel, &cpl, SPDK_BLOB_READ, _blob,
6801 				      NULL, 0, offset, 0);
6802 		if (!op) {
6803 			bs_clone_snapshot_origblob_cleanup(ctx, -ENOMEM);
6804 			return;
6805 		}
6806 
6807 		bs_allocate_and_copy_cluster(_blob, ctx->channel, offset, op);
6808 	} else {
6809 		bs_inflate_blob_done(ctx);
6810 	}
6811 }
6812 
6813 static void
6814 bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6815 {
6816 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6817 	uint64_t clusters_needed;
6818 	uint64_t i;
6819 
6820 	if (bserrno != 0) {
6821 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6822 		return;
6823 	}
6824 
6825 	ctx->original.blob = _blob;
6826 	ctx->original.md_ro = _blob->md_ro;
6827 
6828 	if (_blob->locked_operation_in_progress) {
6829 		SPDK_DEBUGLOG(blob, "Cannot inflate blob - another operation in progress\n");
6830 		ctx->bserrno = -EBUSY;
6831 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6832 		return;
6833 	}
6834 
6835 	_blob->locked_operation_in_progress = true;
6836 
6837 	switch (_blob->parent_id) {
6838 	case SPDK_BLOBID_INVALID:
6839 		if (!ctx->allocate_all) {
6840 			/* This blob has no parent, so we cannot decouple it. */
6841 			SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
6842 			bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
6843 			return;
6844 		}
6845 		break;
6846 	case SPDK_BLOBID_EXTERNAL_SNAPSHOT:
6847 		/*
6848 		 * It would be better to rely on back_bs_dev->is_zeroes(), to determine which
6849 		 * clusters require allocation. Until there is a blobstore consumer that
6850 		 * uses esnaps with an spdk_bs_dev that implements a useful is_zeroes() it is not
6851 		 * worth the effort.
6852 		 */
6853 		ctx->allocate_all = true;
6854 		break;
6855 	default:
6856 		break;
6857 	}
6858 
6859 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
6860 		/* This is not thin provisioned blob. No need to inflate. */
6861 		bs_clone_snapshot_origblob_cleanup(ctx, 0);
6862 		return;
6863 	}
6864 
6865 	/* Do two passes - one to verify that we can obtain enough clusters
6866 	 * and another to actually claim them.
6867 	 */
6868 	clusters_needed = 0;
6869 	for (i = 0; i < _blob->active.num_clusters; i++) {
6870 		if (bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
6871 			clusters_needed++;
6872 		}
6873 	}
6874 
6875 	if (clusters_needed > _blob->bs->num_free_clusters) {
6876 		/* Not enough free clusters. Cannot satisfy the request. */
6877 		bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
6878 		return;
6879 	}
6880 
6881 	ctx->cluster = 0;
6882 	bs_inflate_blob_touch_next(ctx, 0);
6883 }
6884 
6885 static void
6886 bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6887 		spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
6888 {
6889 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6890 
6891 	if (!ctx) {
6892 		cb_fn(cb_arg, -ENOMEM);
6893 		return;
6894 	}
6895 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6896 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
6897 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
6898 	ctx->bserrno = 0;
6899 	ctx->original.id = blobid;
6900 	ctx->channel = channel;
6901 	ctx->allocate_all = allocate_all;
6902 
6903 	spdk_bs_open_blob(bs, ctx->original.id, bs_inflate_blob_open_cpl, ctx);
6904 }
6905 
6906 void
6907 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6908 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6909 {
6910 	bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
6911 }
6912 
6913 void
6914 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6915 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6916 {
6917 	bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
6918 }
6919 /* END spdk_bs_inflate_blob */
6920 
6921 /* START spdk_blob_resize */
6922 struct spdk_bs_resize_ctx {
6923 	spdk_blob_op_complete cb_fn;
6924 	void *cb_arg;
6925 	struct spdk_blob *blob;
6926 	uint64_t sz;
6927 	int rc;
6928 };
6929 
6930 static void
6931 bs_resize_unfreeze_cpl(void *cb_arg, int rc)
6932 {
6933 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6934 
6935 	if (rc != 0) {
6936 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
6937 	}
6938 
6939 	if (ctx->rc != 0) {
6940 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
6941 		rc = ctx->rc;
6942 	}
6943 
6944 	ctx->blob->locked_operation_in_progress = false;
6945 
6946 	ctx->cb_fn(ctx->cb_arg, rc);
6947 	free(ctx);
6948 }
6949 
6950 static void
6951 bs_resize_freeze_cpl(void *cb_arg, int rc)
6952 {
6953 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6954 
6955 	if (rc != 0) {
6956 		ctx->blob->locked_operation_in_progress = false;
6957 		ctx->cb_fn(ctx->cb_arg, rc);
6958 		free(ctx);
6959 		return;
6960 	}
6961 
6962 	ctx->rc = blob_resize(ctx->blob, ctx->sz);
6963 
6964 	blob_unfreeze_io(ctx->blob, bs_resize_unfreeze_cpl, ctx);
6965 }
6966 
6967 void
6968 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
6969 {
6970 	struct spdk_bs_resize_ctx *ctx;
6971 
6972 	blob_verify_md_op(blob);
6973 
6974 	SPDK_DEBUGLOG(blob, "Resizing blob 0x%" PRIx64 " to %" PRIu64 " clusters\n", blob->id, sz);
6975 
6976 	if (blob->md_ro) {
6977 		cb_fn(cb_arg, -EPERM);
6978 		return;
6979 	}
6980 
6981 	if (sz == blob->active.num_clusters) {
6982 		cb_fn(cb_arg, 0);
6983 		return;
6984 	}
6985 
6986 	if (blob->locked_operation_in_progress) {
6987 		cb_fn(cb_arg, -EBUSY);
6988 		return;
6989 	}
6990 
6991 	ctx = calloc(1, sizeof(*ctx));
6992 	if (!ctx) {
6993 		cb_fn(cb_arg, -ENOMEM);
6994 		return;
6995 	}
6996 
6997 	blob->locked_operation_in_progress = true;
6998 	ctx->cb_fn = cb_fn;
6999 	ctx->cb_arg = cb_arg;
7000 	ctx->blob = blob;
7001 	ctx->sz = sz;
7002 	blob_freeze_io(blob, bs_resize_freeze_cpl, ctx);
7003 }
7004 
7005 /* END spdk_blob_resize */
7006 
7007 
7008 /* START spdk_bs_delete_blob */
7009 
7010 static void
7011 bs_delete_close_cpl(void *cb_arg, int bserrno)
7012 {
7013 	spdk_bs_sequence_t *seq = cb_arg;
7014 
7015 	bs_sequence_finish(seq, bserrno);
7016 }
7017 
7018 static void
7019 bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7020 {
7021 	struct spdk_blob *blob = cb_arg;
7022 
7023 	if (bserrno != 0) {
7024 		/*
7025 		 * We already removed this blob from the blobstore tailq, so
7026 		 *  we need to free it here since this is the last reference
7027 		 *  to it.
7028 		 */
7029 		blob_free(blob);
7030 		bs_delete_close_cpl(seq, bserrno);
7031 		return;
7032 	}
7033 
7034 	/*
7035 	 * This will immediately decrement the ref_count and call
7036 	 *  the completion routine since the metadata state is clean.
7037 	 *  By calling spdk_blob_close, we reduce the number of call
7038 	 *  points into code that touches the blob->open_ref count
7039 	 *  and the blobstore's blob list.
7040 	 */
7041 	spdk_blob_close(blob, bs_delete_close_cpl, seq);
7042 }
7043 
7044 struct delete_snapshot_ctx {
7045 	struct spdk_blob_list *parent_snapshot_entry;
7046 	struct spdk_blob *snapshot;
7047 	struct spdk_blob_md_page *page;
7048 	bool snapshot_md_ro;
7049 	struct spdk_blob *clone;
7050 	bool clone_md_ro;
7051 	spdk_blob_op_with_handle_complete cb_fn;
7052 	void *cb_arg;
7053 	int bserrno;
7054 	uint32_t next_extent_page;
7055 };
7056 
7057 static void
7058 delete_blob_cleanup_finish(void *cb_arg, int bserrno)
7059 {
7060 	struct delete_snapshot_ctx *ctx = cb_arg;
7061 
7062 	if (bserrno != 0) {
7063 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
7064 	}
7065 
7066 	assert(ctx != NULL);
7067 
7068 	if (bserrno != 0 && ctx->bserrno == 0) {
7069 		ctx->bserrno = bserrno;
7070 	}
7071 
7072 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
7073 	spdk_free(ctx->page);
7074 	free(ctx);
7075 }
7076 
7077 static void
7078 delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
7079 {
7080 	struct delete_snapshot_ctx *ctx = cb_arg;
7081 
7082 	if (bserrno != 0) {
7083 		ctx->bserrno = bserrno;
7084 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
7085 	}
7086 
7087 	if (ctx->bserrno != 0) {
7088 		assert(blob_lookup(ctx->snapshot->bs, ctx->snapshot->id) == NULL);
7089 		RB_INSERT(spdk_blob_tree, &ctx->snapshot->bs->open_blobs, ctx->snapshot);
7090 		spdk_bit_array_set(ctx->snapshot->bs->open_blobids, ctx->snapshot->id);
7091 	}
7092 
7093 	ctx->snapshot->locked_operation_in_progress = false;
7094 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
7095 
7096 	spdk_blob_close(ctx->snapshot, delete_blob_cleanup_finish, ctx);
7097 }
7098 
7099 static void
7100 delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
7101 {
7102 	struct delete_snapshot_ctx *ctx = cb_arg;
7103 
7104 	ctx->clone->locked_operation_in_progress = false;
7105 	ctx->clone->md_ro = ctx->clone_md_ro;
7106 
7107 	spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
7108 }
7109 
7110 static void
7111 delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
7112 {
7113 	struct delete_snapshot_ctx *ctx = cb_arg;
7114 
7115 	if (bserrno) {
7116 		ctx->bserrno = bserrno;
7117 		delete_snapshot_cleanup_clone(ctx, 0);
7118 		return;
7119 	}
7120 
7121 	ctx->clone->locked_operation_in_progress = false;
7122 	spdk_blob_close(ctx->clone, delete_blob_cleanup_finish, ctx);
7123 }
7124 
7125 static void
7126 delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
7127 {
7128 	struct delete_snapshot_ctx *ctx = cb_arg;
7129 	struct spdk_blob_list *parent_snapshot_entry = NULL;
7130 	struct spdk_blob_list *snapshot_entry = NULL;
7131 	struct spdk_blob_list *clone_entry = NULL;
7132 	struct spdk_blob_list *snapshot_clone_entry = NULL;
7133 
7134 	if (bserrno) {
7135 		SPDK_ERRLOG("Failed to sync MD on blob\n");
7136 		ctx->bserrno = bserrno;
7137 		delete_snapshot_cleanup_clone(ctx, 0);
7138 		return;
7139 	}
7140 
7141 	/* Get snapshot entry for the snapshot we want to remove */
7142 	snapshot_entry = bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
7143 
7144 	assert(snapshot_entry != NULL);
7145 
7146 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
7147 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
7148 	assert(clone_entry != NULL);
7149 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
7150 	snapshot_entry->clone_count--;
7151 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
7152 
7153 	switch (ctx->snapshot->parent_id) {
7154 	case SPDK_BLOBID_INVALID:
7155 	case SPDK_BLOBID_EXTERNAL_SNAPSHOT:
7156 		/* No parent snapshot - just remove clone entry */
7157 		free(clone_entry);
7158 		break;
7159 	default:
7160 		/* This snapshot is at the same time a clone of another snapshot - we need to
7161 		 * update parent snapshot (remove current clone, add new one inherited from
7162 		 * the snapshot that is being removed) */
7163 
7164 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
7165 		 * snapshot that we are removing */
7166 		blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
7167 						    &snapshot_clone_entry);
7168 
7169 		/* Switch clone entry in parent snapshot */
7170 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
7171 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
7172 		free(snapshot_clone_entry);
7173 	}
7174 
7175 	/* Restore md_ro flags */
7176 	ctx->clone->md_ro = ctx->clone_md_ro;
7177 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
7178 
7179 	blob_unfreeze_io(ctx->clone, delete_snapshot_unfreeze_cpl, ctx);
7180 }
7181 
7182 static void
7183 delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
7184 {
7185 	struct delete_snapshot_ctx *ctx = cb_arg;
7186 	uint64_t i;
7187 
7188 	ctx->snapshot->md_ro = false;
7189 
7190 	if (bserrno) {
7191 		SPDK_ERRLOG("Failed to sync MD on clone\n");
7192 		ctx->bserrno = bserrno;
7193 
7194 		/* Restore snapshot to previous state */
7195 		bserrno = blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
7196 		if (bserrno != 0) {
7197 			delete_snapshot_cleanup_clone(ctx, bserrno);
7198 			return;
7199 		}
7200 
7201 		spdk_blob_sync_md(ctx->snapshot, delete_snapshot_cleanup_clone, ctx);
7202 		return;
7203 	}
7204 
7205 	/* Clear cluster map entries for snapshot */
7206 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
7207 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
7208 			ctx->snapshot->active.clusters[i] = 0;
7209 		}
7210 	}
7211 	for (i = 0; i < ctx->snapshot->active.num_extent_pages &&
7212 	     i < ctx->clone->active.num_extent_pages; i++) {
7213 		if (ctx->clone->active.extent_pages[i] == ctx->snapshot->active.extent_pages[i]) {
7214 			ctx->snapshot->active.extent_pages[i] = 0;
7215 		}
7216 	}
7217 
7218 	blob_set_thin_provision(ctx->snapshot);
7219 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
7220 
7221 	if (ctx->parent_snapshot_entry != NULL) {
7222 		ctx->snapshot->back_bs_dev = NULL;
7223 	}
7224 
7225 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_cpl, ctx);
7226 }
7227 
7228 static void
7229 delete_snapshot_update_extent_pages_cpl(struct delete_snapshot_ctx *ctx)
7230 {
7231 	int bserrno;
7232 
7233 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
7234 	blob_back_bs_destroy(ctx->clone);
7235 
7236 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
7237 	if (ctx->snapshot->parent_id == SPDK_BLOBID_EXTERNAL_SNAPSHOT) {
7238 		bserrno = bs_snapshot_copy_xattr(ctx->clone, ctx->snapshot,
7239 						 BLOB_EXTERNAL_SNAPSHOT_ID);
7240 		if (bserrno != 0) {
7241 			ctx->bserrno = bserrno;
7242 
7243 			/* Restore snapshot to previous state */
7244 			bserrno = blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
7245 			if (bserrno != 0) {
7246 				delete_snapshot_cleanup_clone(ctx, bserrno);
7247 				return;
7248 			}
7249 
7250 			spdk_blob_sync_md(ctx->snapshot, delete_snapshot_cleanup_clone, ctx);
7251 			return;
7252 		}
7253 		ctx->clone->parent_id = SPDK_BLOBID_EXTERNAL_SNAPSHOT;
7254 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
7255 		/* Do not delete the external snapshot along with this snapshot */
7256 		ctx->snapshot->back_bs_dev = NULL;
7257 		ctx->clone->invalid_flags |= SPDK_BLOB_EXTERNAL_SNAPSHOT;
7258 	} else if (ctx->parent_snapshot_entry != NULL) {
7259 		/* ...to parent snapshot */
7260 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
7261 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
7262 		blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
7263 			       sizeof(spdk_blob_id),
7264 			       true);
7265 	} else {
7266 		/* ...to blobid invalid and zeroes dev */
7267 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
7268 		ctx->clone->back_bs_dev = bs_create_zeroes_dev();
7269 		blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
7270 	}
7271 
7272 	spdk_blob_sync_md(ctx->clone, delete_snapshot_sync_clone_cpl, ctx);
7273 }
7274 
7275 static void
7276 delete_snapshot_update_extent_pages(void *cb_arg, int bserrno)
7277 {
7278 	struct delete_snapshot_ctx *ctx = cb_arg;
7279 	uint32_t *extent_page;
7280 	uint64_t i;
7281 
7282 	for (i = ctx->next_extent_page; i < ctx->snapshot->active.num_extent_pages &&
7283 	     i < ctx->clone->active.num_extent_pages; i++) {
7284 		if (ctx->snapshot->active.extent_pages[i] == 0) {
7285 			/* No extent page to use from snapshot */
7286 			continue;
7287 		}
7288 
7289 		extent_page = &ctx->clone->active.extent_pages[i];
7290 		if (*extent_page == 0) {
7291 			/* Copy extent page from snapshot when clone did not have a matching one */
7292 			*extent_page = ctx->snapshot->active.extent_pages[i];
7293 			continue;
7294 		}
7295 
7296 		/* Clone and snapshot both contain partially filled matching extent pages.
7297 		 * Update the clone extent page in place with cluster map containing the mix of both. */
7298 		ctx->next_extent_page = i + 1;
7299 		memset(ctx->page, 0, SPDK_BS_PAGE_SIZE);
7300 
7301 		blob_write_extent_page(ctx->clone, *extent_page, i * SPDK_EXTENTS_PER_EP, ctx->page,
7302 				       delete_snapshot_update_extent_pages, ctx);
7303 		return;
7304 	}
7305 	delete_snapshot_update_extent_pages_cpl(ctx);
7306 }
7307 
7308 static void
7309 delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
7310 {
7311 	struct delete_snapshot_ctx *ctx = cb_arg;
7312 	uint64_t i;
7313 
7314 	/* Temporarily override md_ro flag for clone for MD modification */
7315 	ctx->clone_md_ro = ctx->clone->md_ro;
7316 	ctx->clone->md_ro = false;
7317 
7318 	if (bserrno) {
7319 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
7320 		ctx->bserrno = bserrno;
7321 		delete_snapshot_cleanup_clone(ctx, 0);
7322 		return;
7323 	}
7324 
7325 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
7326 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
7327 		if (ctx->clone->active.clusters[i] == 0) {
7328 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
7329 		}
7330 	}
7331 	ctx->next_extent_page = 0;
7332 	delete_snapshot_update_extent_pages(ctx, 0);
7333 }
7334 
7335 static void
7336 delete_snapshot_esnap_channels_destroyed_cb(void *cb_arg, struct spdk_blob *blob, int bserrno)
7337 {
7338 	struct delete_snapshot_ctx *ctx = cb_arg;
7339 
7340 	if (bserrno != 0) {
7341 		SPDK_ERRLOG("blob 0x%" PRIx64 ": failed to destroy esnap channels: %d\n",
7342 			    blob->id, bserrno);
7343 		/* That error should not stop us from syncing metadata. */
7344 	}
7345 
7346 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_xattr_cpl, ctx);
7347 }
7348 
7349 static void
7350 delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
7351 {
7352 	struct delete_snapshot_ctx *ctx = cb_arg;
7353 
7354 	if (bserrno) {
7355 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
7356 		ctx->bserrno = bserrno;
7357 		delete_snapshot_cleanup_clone(ctx, 0);
7358 		return;
7359 	}
7360 
7361 	/* Temporarily override md_ro flag for snapshot for MD modification */
7362 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
7363 	ctx->snapshot->md_ro = false;
7364 
7365 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
7366 	ctx->bserrno = blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
7367 				      sizeof(spdk_blob_id), true);
7368 	if (ctx->bserrno != 0) {
7369 		delete_snapshot_cleanup_clone(ctx, 0);
7370 		return;
7371 	}
7372 
7373 	if (blob_is_esnap_clone(ctx->snapshot)) {
7374 		blob_esnap_destroy_bs_dev_channels(ctx->snapshot, false,
7375 						   delete_snapshot_esnap_channels_destroyed_cb,
7376 						   ctx);
7377 		return;
7378 	}
7379 
7380 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_xattr_cpl, ctx);
7381 }
7382 
7383 static void
7384 delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
7385 {
7386 	struct delete_snapshot_ctx *ctx = cb_arg;
7387 
7388 	if (bserrno) {
7389 		SPDK_ERRLOG("Failed to open clone\n");
7390 		ctx->bserrno = bserrno;
7391 		delete_snapshot_cleanup_snapshot(ctx, 0);
7392 		return;
7393 	}
7394 
7395 	ctx->clone = clone;
7396 
7397 	if (clone->locked_operation_in_progress) {
7398 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress on its clone\n");
7399 		ctx->bserrno = -EBUSY;
7400 		spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
7401 		return;
7402 	}
7403 
7404 	clone->locked_operation_in_progress = true;
7405 
7406 	blob_freeze_io(clone, delete_snapshot_freeze_io_cb, ctx);
7407 }
7408 
7409 static void
7410 update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
7411 {
7412 	struct spdk_blob_list *snapshot_entry = NULL;
7413 	struct spdk_blob_list *clone_entry = NULL;
7414 	struct spdk_blob_list *snapshot_clone_entry = NULL;
7415 
7416 	/* Get snapshot entry for the snapshot we want to remove */
7417 	snapshot_entry = bs_get_snapshot_entry(snapshot->bs, snapshot->id);
7418 
7419 	assert(snapshot_entry != NULL);
7420 
7421 	/* Get clone of the snapshot (at this point there can be only one clone) */
7422 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
7423 	assert(snapshot_entry->clone_count == 1);
7424 	assert(clone_entry != NULL);
7425 
7426 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
7427 	 * snapshot that we are removing */
7428 	blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
7429 					    &snapshot_clone_entry);
7430 
7431 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, delete_snapshot_open_clone_cb, ctx);
7432 }
7433 
7434 static void
7435 bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
7436 {
7437 	spdk_bs_sequence_t *seq = cb_arg;
7438 	struct spdk_blob_list *snapshot_entry = NULL;
7439 	uint32_t page_num;
7440 
7441 	if (bserrno) {
7442 		SPDK_ERRLOG("Failed to remove blob\n");
7443 		bs_sequence_finish(seq, bserrno);
7444 		return;
7445 	}
7446 
7447 	/* Remove snapshot from the list */
7448 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7449 	if (snapshot_entry != NULL) {
7450 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
7451 		free(snapshot_entry);
7452 	}
7453 
7454 	page_num = bs_blobid_to_page(blob->id);
7455 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
7456 	blob->state = SPDK_BLOB_STATE_DIRTY;
7457 	blob->active.num_pages = 0;
7458 	blob_resize(blob, 0);
7459 
7460 	blob_persist(seq, blob, bs_delete_persist_cpl, blob);
7461 }
7462 
7463 static int
7464 bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
7465 {
7466 	struct spdk_blob_list *snapshot_entry = NULL;
7467 	struct spdk_blob_list *clone_entry = NULL;
7468 	struct spdk_blob *clone = NULL;
7469 	bool has_one_clone = false;
7470 
7471 	/* Check if this is a snapshot with clones */
7472 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7473 	if (snapshot_entry != NULL) {
7474 		if (snapshot_entry->clone_count > 1) {
7475 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
7476 			return -EBUSY;
7477 		} else if (snapshot_entry->clone_count == 1) {
7478 			has_one_clone = true;
7479 		}
7480 	}
7481 
7482 	/* Check if someone has this blob open (besides this delete context):
7483 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
7484 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
7485 	 *	and that is ok, because we will update it accordingly */
7486 	if (blob->open_ref <= 2 && has_one_clone) {
7487 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
7488 		assert(clone_entry != NULL);
7489 		clone = blob_lookup(blob->bs, clone_entry->id);
7490 
7491 		if (blob->open_ref == 2 && clone == NULL) {
7492 			/* Clone is closed and someone else opened this blob */
7493 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
7494 			return -EBUSY;
7495 		}
7496 
7497 		*update_clone = true;
7498 		return 0;
7499 	}
7500 
7501 	if (blob->open_ref > 1) {
7502 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
7503 		return -EBUSY;
7504 	}
7505 
7506 	assert(has_one_clone == false);
7507 	*update_clone = false;
7508 	return 0;
7509 }
7510 
7511 static void
7512 bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
7513 {
7514 	spdk_bs_sequence_t *seq = cb_arg;
7515 
7516 	bs_sequence_finish(seq, -ENOMEM);
7517 }
7518 
7519 static void
7520 bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
7521 {
7522 	spdk_bs_sequence_t *seq = cb_arg;
7523 	struct delete_snapshot_ctx *ctx;
7524 	bool update_clone = false;
7525 
7526 	if (bserrno != 0) {
7527 		bs_sequence_finish(seq, bserrno);
7528 		return;
7529 	}
7530 
7531 	blob_verify_md_op(blob);
7532 
7533 	ctx = calloc(1, sizeof(*ctx));
7534 	if (ctx == NULL) {
7535 		spdk_blob_close(blob, bs_delete_enomem_close_cpl, seq);
7536 		return;
7537 	}
7538 
7539 	ctx->snapshot = blob;
7540 	ctx->cb_fn = bs_delete_blob_finish;
7541 	ctx->cb_arg = seq;
7542 
7543 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
7544 	ctx->bserrno = bs_is_blob_deletable(blob, &update_clone);
7545 	if (ctx->bserrno) {
7546 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7547 		return;
7548 	}
7549 
7550 	if (blob->locked_operation_in_progress) {
7551 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress\n");
7552 		ctx->bserrno = -EBUSY;
7553 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7554 		return;
7555 	}
7556 
7557 	blob->locked_operation_in_progress = true;
7558 
7559 	/*
7560 	 * Remove the blob from the blob_store list now, to ensure it does not
7561 	 *  get returned after this point by blob_lookup().
7562 	 */
7563 	spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
7564 	RB_REMOVE(spdk_blob_tree, &blob->bs->open_blobs, blob);
7565 
7566 	if (update_clone) {
7567 		ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0, NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
7568 		if (!ctx->page) {
7569 			ctx->bserrno = -ENOMEM;
7570 			spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7571 			return;
7572 		}
7573 		/* This blob is a snapshot with active clone - update clone first */
7574 		update_clone_on_snapshot_deletion(blob, ctx);
7575 	} else {
7576 		/* This blob does not have any clones - just remove it */
7577 		bs_blob_list_remove(blob);
7578 		bs_delete_blob_finish(seq, blob, 0);
7579 		free(ctx);
7580 	}
7581 }
7582 
7583 void
7584 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
7585 		    spdk_blob_op_complete cb_fn, void *cb_arg)
7586 {
7587 	struct spdk_bs_cpl	cpl;
7588 	spdk_bs_sequence_t	*seq;
7589 
7590 	SPDK_DEBUGLOG(blob, "Deleting blob 0x%" PRIx64 "\n", blobid);
7591 
7592 	assert(spdk_get_thread() == bs->md_thread);
7593 
7594 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7595 	cpl.u.blob_basic.cb_fn = cb_fn;
7596 	cpl.u.blob_basic.cb_arg = cb_arg;
7597 
7598 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
7599 	if (!seq) {
7600 		cb_fn(cb_arg, -ENOMEM);
7601 		return;
7602 	}
7603 
7604 	spdk_bs_open_blob(bs, blobid, bs_delete_open_cpl, seq);
7605 }
7606 
7607 /* END spdk_bs_delete_blob */
7608 
7609 /* START spdk_bs_open_blob */
7610 
7611 static void
7612 bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7613 {
7614 	struct spdk_blob *blob = cb_arg;
7615 	struct spdk_blob *existing;
7616 
7617 	if (bserrno != 0) {
7618 		blob_free(blob);
7619 		seq->cpl.u.blob_handle.blob = NULL;
7620 		bs_sequence_finish(seq, bserrno);
7621 		return;
7622 	}
7623 
7624 	existing = blob_lookup(blob->bs, blob->id);
7625 	if (existing) {
7626 		blob_free(blob);
7627 		existing->open_ref++;
7628 		seq->cpl.u.blob_handle.blob = existing;
7629 		bs_sequence_finish(seq, 0);
7630 		return;
7631 	}
7632 
7633 	blob->open_ref++;
7634 
7635 	spdk_bit_array_set(blob->bs->open_blobids, blob->id);
7636 	RB_INSERT(spdk_blob_tree, &blob->bs->open_blobs, blob);
7637 
7638 	bs_sequence_finish(seq, bserrno);
7639 }
7640 
7641 static inline void
7642 blob_open_opts_copy(const struct spdk_blob_open_opts *src, struct spdk_blob_open_opts *dst)
7643 {
7644 #define FIELD_OK(field) \
7645         offsetof(struct spdk_blob_open_opts, field) + sizeof(src->field) <= src->opts_size
7646 
7647 #define SET_FIELD(field) \
7648         if (FIELD_OK(field)) { \
7649                 dst->field = src->field; \
7650         } \
7651 
7652 	SET_FIELD(clear_method);
7653 	SET_FIELD(esnap_ctx);
7654 
7655 	dst->opts_size = src->opts_size;
7656 
7657 	/* You should not remove this statement, but need to update the assert statement
7658 	 * if you add a new field, and also add a corresponding SET_FIELD statement */
7659 	SPDK_STATIC_ASSERT(sizeof(struct spdk_blob_open_opts) == 24, "Incorrect size");
7660 
7661 #undef FIELD_OK
7662 #undef SET_FIELD
7663 }
7664 
7665 static void
7666 bs_open_blob(struct spdk_blob_store *bs,
7667 	     spdk_blob_id blobid,
7668 	     struct spdk_blob_open_opts *opts,
7669 	     spdk_blob_op_with_handle_complete cb_fn,
7670 	     void *cb_arg)
7671 {
7672 	struct spdk_blob		*blob;
7673 	struct spdk_bs_cpl		cpl;
7674 	struct spdk_blob_open_opts	opts_local;
7675 	spdk_bs_sequence_t		*seq;
7676 	uint32_t			page_num;
7677 
7678 	SPDK_DEBUGLOG(blob, "Opening blob 0x%" PRIx64 "\n", blobid);
7679 	assert(spdk_get_thread() == bs->md_thread);
7680 
7681 	page_num = bs_blobid_to_page(blobid);
7682 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
7683 		/* Invalid blobid */
7684 		cb_fn(cb_arg, NULL, -ENOENT);
7685 		return;
7686 	}
7687 
7688 	blob = blob_lookup(bs, blobid);
7689 	if (blob) {
7690 		blob->open_ref++;
7691 		cb_fn(cb_arg, blob, 0);
7692 		return;
7693 	}
7694 
7695 	blob = blob_alloc(bs, blobid);
7696 	if (!blob) {
7697 		cb_fn(cb_arg, NULL, -ENOMEM);
7698 		return;
7699 	}
7700 
7701 	spdk_blob_open_opts_init(&opts_local, sizeof(opts_local));
7702 	if (opts) {
7703 		blob_open_opts_copy(opts, &opts_local);
7704 	}
7705 
7706 	blob->clear_method = opts_local.clear_method;
7707 
7708 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
7709 	cpl.u.blob_handle.cb_fn = cb_fn;
7710 	cpl.u.blob_handle.cb_arg = cb_arg;
7711 	cpl.u.blob_handle.blob = blob;
7712 	cpl.u.blob_handle.esnap_ctx = opts_local.esnap_ctx;
7713 
7714 	seq = bs_sequence_start_bs(bs->md_channel, &cpl);
7715 	if (!seq) {
7716 		blob_free(blob);
7717 		cb_fn(cb_arg, NULL, -ENOMEM);
7718 		return;
7719 	}
7720 
7721 	blob_load(seq, blob, bs_open_blob_cpl, blob);
7722 }
7723 
7724 void
7725 spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
7726 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7727 {
7728 	bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
7729 }
7730 
7731 void
7732 spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
7733 		      struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7734 {
7735 	bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
7736 }
7737 
7738 /* END spdk_bs_open_blob */
7739 
7740 /* START spdk_blob_set_read_only */
7741 int
7742 spdk_blob_set_read_only(struct spdk_blob *blob)
7743 {
7744 	blob_verify_md_op(blob);
7745 
7746 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
7747 
7748 	blob->state = SPDK_BLOB_STATE_DIRTY;
7749 	return 0;
7750 }
7751 /* END spdk_blob_set_read_only */
7752 
7753 /* START spdk_blob_sync_md */
7754 
7755 static void
7756 blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7757 {
7758 	struct spdk_blob *blob = cb_arg;
7759 
7760 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
7761 		blob->data_ro = true;
7762 		blob->md_ro = true;
7763 	}
7764 
7765 	bs_sequence_finish(seq, bserrno);
7766 }
7767 
7768 static void
7769 blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7770 {
7771 	struct spdk_bs_cpl	cpl;
7772 	spdk_bs_sequence_t	*seq;
7773 
7774 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7775 	cpl.u.blob_basic.cb_fn = cb_fn;
7776 	cpl.u.blob_basic.cb_arg = cb_arg;
7777 
7778 	seq = bs_sequence_start_bs(blob->bs->md_channel, &cpl);
7779 	if (!seq) {
7780 		cb_fn(cb_arg, -ENOMEM);
7781 		return;
7782 	}
7783 
7784 	blob_persist(seq, blob, blob_sync_md_cpl, blob);
7785 }
7786 
7787 void
7788 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7789 {
7790 	blob_verify_md_op(blob);
7791 
7792 	SPDK_DEBUGLOG(blob, "Syncing blob 0x%" PRIx64 "\n", blob->id);
7793 
7794 	if (blob->md_ro) {
7795 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
7796 		cb_fn(cb_arg, 0);
7797 		return;
7798 	}
7799 
7800 	blob_sync_md(blob, cb_fn, cb_arg);
7801 }
7802 
7803 /* END spdk_blob_sync_md */
7804 
7805 struct spdk_blob_insert_cluster_ctx {
7806 	struct spdk_thread	*thread;
7807 	struct spdk_blob	*blob;
7808 	uint32_t		cluster_num;	/* cluster index in blob */
7809 	uint32_t		cluster;	/* cluster on disk */
7810 	uint32_t		extent_page;	/* extent page on disk */
7811 	struct spdk_blob_md_page *page; /* preallocated extent page */
7812 	int			rc;
7813 	spdk_blob_op_complete	cb_fn;
7814 	void			*cb_arg;
7815 };
7816 
7817 static void
7818 blob_insert_cluster_msg_cpl(void *arg)
7819 {
7820 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7821 
7822 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
7823 	free(ctx);
7824 }
7825 
7826 static void
7827 blob_insert_cluster_msg_cb(void *arg, int bserrno)
7828 {
7829 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7830 
7831 	ctx->rc = bserrno;
7832 	spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7833 }
7834 
7835 static void
7836 blob_insert_new_ep_cb(void *arg, int bserrno)
7837 {
7838 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7839 	uint32_t *extent_page;
7840 
7841 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7842 	*extent_page = ctx->extent_page;
7843 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7844 	blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7845 }
7846 
7847 struct spdk_blob_write_extent_page_ctx {
7848 	struct spdk_blob_store		*bs;
7849 
7850 	uint32_t			extent;
7851 	struct spdk_blob_md_page	*page;
7852 };
7853 
7854 static void
7855 blob_persist_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7856 {
7857 	struct spdk_blob_write_extent_page_ctx *ctx = cb_arg;
7858 
7859 	free(ctx);
7860 	bs_sequence_finish(seq, bserrno);
7861 }
7862 
7863 static void
7864 blob_write_extent_page_ready(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7865 {
7866 	struct spdk_blob_write_extent_page_ctx *ctx = cb_arg;
7867 
7868 	if (bserrno != 0) {
7869 		blob_persist_extent_page_cpl(seq, ctx, bserrno);
7870 		return;
7871 	}
7872 	bs_sequence_write_dev(seq, ctx->page, bs_md_page_to_lba(ctx->bs, ctx->extent),
7873 			      bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
7874 			      blob_persist_extent_page_cpl, ctx);
7875 }
7876 
7877 static void
7878 blob_write_extent_page(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
7879 		       struct spdk_blob_md_page *page, spdk_blob_op_complete cb_fn, void *cb_arg)
7880 {
7881 	struct spdk_blob_write_extent_page_ctx	*ctx;
7882 	spdk_bs_sequence_t			*seq;
7883 	struct spdk_bs_cpl			cpl;
7884 
7885 	ctx = calloc(1, sizeof(*ctx));
7886 	if (!ctx) {
7887 		cb_fn(cb_arg, -ENOMEM);
7888 		return;
7889 	}
7890 	ctx->bs = blob->bs;
7891 	ctx->extent = extent;
7892 	ctx->page = page;
7893 
7894 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7895 	cpl.u.blob_basic.cb_fn = cb_fn;
7896 	cpl.u.blob_basic.cb_arg = cb_arg;
7897 
7898 	seq = bs_sequence_start_bs(blob->bs->md_channel, &cpl);
7899 	if (!seq) {
7900 		free(ctx);
7901 		cb_fn(cb_arg, -ENOMEM);
7902 		return;
7903 	}
7904 
7905 	assert(page);
7906 	page->next = SPDK_INVALID_MD_PAGE;
7907 	page->id = blob->id;
7908 	page->sequence_num = 0;
7909 
7910 	blob_serialize_extent_page(blob, cluster_num, page);
7911 
7912 	page->crc = blob_md_page_calc_crc(page);
7913 
7914 	assert(spdk_bit_array_get(blob->bs->used_md_pages, extent) == true);
7915 
7916 	bs_mark_dirty(seq, blob->bs, blob_write_extent_page_ready, ctx);
7917 }
7918 
7919 static void
7920 blob_insert_cluster_msg(void *arg)
7921 {
7922 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7923 	uint32_t *extent_page;
7924 
7925 	ctx->rc = blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
7926 	if (ctx->rc != 0) {
7927 		spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7928 		return;
7929 	}
7930 
7931 	if (ctx->blob->use_extent_table == false) {
7932 		/* Extent table is not used, proceed with sync of md that will only use extents_rle. */
7933 		ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7934 		blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7935 		return;
7936 	}
7937 
7938 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7939 	if (*extent_page == 0) {
7940 		/* Extent page requires allocation.
7941 		 * It was already claimed in the used_md_pages map and placed in ctx. */
7942 		assert(ctx->extent_page != 0);
7943 		assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7944 		blob_write_extent_page(ctx->blob, ctx->extent_page, ctx->cluster_num, ctx->page,
7945 				       blob_insert_new_ep_cb, ctx);
7946 	} else {
7947 		/* It is possible for original thread to allocate extent page for
7948 		 * different cluster in the same extent page. In such case proceed with
7949 		 * updating the existing extent page, but release the additional one. */
7950 		if (ctx->extent_page != 0) {
7951 			spdk_spin_lock(&ctx->blob->bs->used_lock);
7952 			assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7953 			bs_release_md_page(ctx->blob->bs, ctx->extent_page);
7954 			spdk_spin_unlock(&ctx->blob->bs->used_lock);
7955 			ctx->extent_page = 0;
7956 		}
7957 		/* Extent page already allocated.
7958 		 * Every cluster allocation, requires just an update of single extent page. */
7959 		blob_write_extent_page(ctx->blob, *extent_page, ctx->cluster_num, ctx->page,
7960 				       blob_insert_cluster_msg_cb, ctx);
7961 	}
7962 }
7963 
7964 static void
7965 blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
7966 				 uint64_t cluster, uint32_t extent_page, struct spdk_blob_md_page *page,
7967 				 spdk_blob_op_complete cb_fn, void *cb_arg)
7968 {
7969 	struct spdk_blob_insert_cluster_ctx *ctx;
7970 
7971 	ctx = calloc(1, sizeof(*ctx));
7972 	if (ctx == NULL) {
7973 		cb_fn(cb_arg, -ENOMEM);
7974 		return;
7975 	}
7976 
7977 	ctx->thread = spdk_get_thread();
7978 	ctx->blob = blob;
7979 	ctx->cluster_num = cluster_num;
7980 	ctx->cluster = cluster;
7981 	ctx->extent_page = extent_page;
7982 	ctx->page = page;
7983 	ctx->cb_fn = cb_fn;
7984 	ctx->cb_arg = cb_arg;
7985 
7986 	spdk_thread_send_msg(blob->bs->md_thread, blob_insert_cluster_msg, ctx);
7987 }
7988 
7989 /* START spdk_blob_close */
7990 
7991 static void
7992 blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7993 {
7994 	struct spdk_blob *blob = cb_arg;
7995 
7996 	if (bserrno == 0) {
7997 		blob->open_ref--;
7998 		if (blob->open_ref == 0) {
7999 			/*
8000 			 * Blobs with active.num_pages == 0 are deleted blobs.
8001 			 *  these blobs are removed from the blob_store list
8002 			 *  when the deletion process starts - so don't try to
8003 			 *  remove them again.
8004 			 */
8005 			if (blob->active.num_pages > 0) {
8006 				spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
8007 				RB_REMOVE(spdk_blob_tree, &blob->bs->open_blobs, blob);
8008 			}
8009 			blob_free(blob);
8010 		}
8011 	}
8012 
8013 	bs_sequence_finish(seq, bserrno);
8014 }
8015 
8016 static void
8017 blob_close_esnap_done(void *cb_arg, struct spdk_blob *blob, int bserrno)
8018 {
8019 	spdk_bs_sequence_t	*seq = cb_arg;
8020 
8021 	if (bserrno != 0) {
8022 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": close failed with error %d\n",
8023 			      blob->id, bserrno);
8024 		bs_sequence_finish(seq, bserrno);
8025 		return;
8026 	}
8027 
8028 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": closed, syncing metadata on thread %s\n",
8029 		      blob->id, spdk_thread_get_name(spdk_get_thread()));
8030 
8031 	/* Sync metadata */
8032 	blob_persist(seq, blob, blob_close_cpl, blob);
8033 }
8034 
8035 void
8036 spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
8037 {
8038 	struct spdk_bs_cpl	cpl;
8039 	spdk_bs_sequence_t	*seq;
8040 
8041 	blob_verify_md_op(blob);
8042 
8043 	SPDK_DEBUGLOG(blob, "Closing blob 0x%" PRIx64 "\n", blob->id);
8044 
8045 	if (blob->open_ref == 0) {
8046 		cb_fn(cb_arg, -EBADF);
8047 		return;
8048 	}
8049 
8050 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
8051 	cpl.u.blob_basic.cb_fn = cb_fn;
8052 	cpl.u.blob_basic.cb_arg = cb_arg;
8053 
8054 	seq = bs_sequence_start_bs(blob->bs->md_channel, &cpl);
8055 	if (!seq) {
8056 		cb_fn(cb_arg, -ENOMEM);
8057 		return;
8058 	}
8059 
8060 	if (blob->open_ref == 1 && blob_is_esnap_clone(blob)) {
8061 		blob_esnap_destroy_bs_dev_channels(blob, false, blob_close_esnap_done, seq);
8062 		return;
8063 	}
8064 
8065 	/* Sync metadata */
8066 	blob_persist(seq, blob, blob_close_cpl, blob);
8067 }
8068 
8069 /* END spdk_blob_close */
8070 
8071 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
8072 {
8073 	return spdk_get_io_channel(bs);
8074 }
8075 
8076 void
8077 spdk_bs_free_io_channel(struct spdk_io_channel *channel)
8078 {
8079 	blob_esnap_destroy_bs_channel(spdk_io_channel_get_ctx(channel));
8080 	spdk_put_io_channel(channel);
8081 }
8082 
8083 void
8084 spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
8085 		   uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
8086 {
8087 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
8088 			       SPDK_BLOB_UNMAP);
8089 }
8090 
8091 void
8092 spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
8093 			  uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
8094 {
8095 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
8096 			       SPDK_BLOB_WRITE_ZEROES);
8097 }
8098 
8099 void
8100 spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
8101 		   void *payload, uint64_t offset, uint64_t length,
8102 		   spdk_blob_op_complete cb_fn, void *cb_arg)
8103 {
8104 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
8105 			       SPDK_BLOB_WRITE);
8106 }
8107 
8108 void
8109 spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
8110 		  void *payload, uint64_t offset, uint64_t length,
8111 		  spdk_blob_op_complete cb_fn, void *cb_arg)
8112 {
8113 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
8114 			       SPDK_BLOB_READ);
8115 }
8116 
8117 void
8118 spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
8119 		    struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
8120 		    spdk_blob_op_complete cb_fn, void *cb_arg)
8121 {
8122 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false, NULL);
8123 }
8124 
8125 void
8126 spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
8127 		   struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
8128 		   spdk_blob_op_complete cb_fn, void *cb_arg)
8129 {
8130 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true, NULL);
8131 }
8132 
8133 void
8134 spdk_blob_io_writev_ext(struct spdk_blob *blob, struct spdk_io_channel *channel,
8135 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
8136 			spdk_blob_op_complete cb_fn, void *cb_arg, struct spdk_blob_ext_io_opts *io_opts)
8137 {
8138 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false,
8139 				   io_opts);
8140 }
8141 
8142 void
8143 spdk_blob_io_readv_ext(struct spdk_blob *blob, struct spdk_io_channel *channel,
8144 		       struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
8145 		       spdk_blob_op_complete cb_fn, void *cb_arg, struct spdk_blob_ext_io_opts *io_opts)
8146 {
8147 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true,
8148 				   io_opts);
8149 }
8150 
8151 struct spdk_bs_iter_ctx {
8152 	int64_t page_num;
8153 	struct spdk_blob_store *bs;
8154 
8155 	spdk_blob_op_with_handle_complete cb_fn;
8156 	void *cb_arg;
8157 };
8158 
8159 static void
8160 bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
8161 {
8162 	struct spdk_bs_iter_ctx *ctx = cb_arg;
8163 	struct spdk_blob_store *bs = ctx->bs;
8164 	spdk_blob_id id;
8165 
8166 	if (bserrno == 0) {
8167 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
8168 		free(ctx);
8169 		return;
8170 	}
8171 
8172 	ctx->page_num++;
8173 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
8174 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
8175 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
8176 		free(ctx);
8177 		return;
8178 	}
8179 
8180 	id = bs_page_to_blobid(ctx->page_num);
8181 
8182 	spdk_bs_open_blob(bs, id, bs_iter_cpl, ctx);
8183 }
8184 
8185 void
8186 spdk_bs_iter_first(struct spdk_blob_store *bs,
8187 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
8188 {
8189 	struct spdk_bs_iter_ctx *ctx;
8190 
8191 	ctx = calloc(1, sizeof(*ctx));
8192 	if (!ctx) {
8193 		cb_fn(cb_arg, NULL, -ENOMEM);
8194 		return;
8195 	}
8196 
8197 	ctx->page_num = -1;
8198 	ctx->bs = bs;
8199 	ctx->cb_fn = cb_fn;
8200 	ctx->cb_arg = cb_arg;
8201 
8202 	bs_iter_cpl(ctx, NULL, -1);
8203 }
8204 
8205 static void
8206 bs_iter_close_cpl(void *cb_arg, int bserrno)
8207 {
8208 	struct spdk_bs_iter_ctx *ctx = cb_arg;
8209 
8210 	bs_iter_cpl(ctx, NULL, -1);
8211 }
8212 
8213 void
8214 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
8215 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
8216 {
8217 	struct spdk_bs_iter_ctx *ctx;
8218 
8219 	assert(blob != NULL);
8220 
8221 	ctx = calloc(1, sizeof(*ctx));
8222 	if (!ctx) {
8223 		cb_fn(cb_arg, NULL, -ENOMEM);
8224 		return;
8225 	}
8226 
8227 	ctx->page_num = bs_blobid_to_page(blob->id);
8228 	ctx->bs = bs;
8229 	ctx->cb_fn = cb_fn;
8230 	ctx->cb_arg = cb_arg;
8231 
8232 	/* Close the existing blob */
8233 	spdk_blob_close(blob, bs_iter_close_cpl, ctx);
8234 }
8235 
8236 static int
8237 blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
8238 	       uint16_t value_len, bool internal)
8239 {
8240 	struct spdk_xattr_tailq *xattrs;
8241 	struct spdk_xattr	*xattr;
8242 	size_t			desc_size;
8243 	void			*tmp;
8244 
8245 	blob_verify_md_op(blob);
8246 
8247 	if (blob->md_ro) {
8248 		return -EPERM;
8249 	}
8250 
8251 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
8252 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
8253 		SPDK_DEBUGLOG(blob, "Xattr '%s' of size %zu does not fix into single page %zu\n", name,
8254 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
8255 		return -ENOMEM;
8256 	}
8257 
8258 	if (internal) {
8259 		xattrs = &blob->xattrs_internal;
8260 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
8261 	} else {
8262 		xattrs = &blob->xattrs;
8263 	}
8264 
8265 	TAILQ_FOREACH(xattr, xattrs, link) {
8266 		if (!strcmp(name, xattr->name)) {
8267 			tmp = malloc(value_len);
8268 			if (!tmp) {
8269 				return -ENOMEM;
8270 			}
8271 
8272 			free(xattr->value);
8273 			xattr->value_len = value_len;
8274 			xattr->value = tmp;
8275 			memcpy(xattr->value, value, value_len);
8276 
8277 			blob->state = SPDK_BLOB_STATE_DIRTY;
8278 
8279 			return 0;
8280 		}
8281 	}
8282 
8283 	xattr = calloc(1, sizeof(*xattr));
8284 	if (!xattr) {
8285 		return -ENOMEM;
8286 	}
8287 
8288 	xattr->name = strdup(name);
8289 	if (!xattr->name) {
8290 		free(xattr);
8291 		return -ENOMEM;
8292 	}
8293 
8294 	xattr->value_len = value_len;
8295 	xattr->value = malloc(value_len);
8296 	if (!xattr->value) {
8297 		free(xattr->name);
8298 		free(xattr);
8299 		return -ENOMEM;
8300 	}
8301 	memcpy(xattr->value, value, value_len);
8302 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
8303 
8304 	blob->state = SPDK_BLOB_STATE_DIRTY;
8305 
8306 	return 0;
8307 }
8308 
8309 int
8310 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
8311 		    uint16_t value_len)
8312 {
8313 	return blob_set_xattr(blob, name, value, value_len, false);
8314 }
8315 
8316 static int
8317 blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
8318 {
8319 	struct spdk_xattr_tailq *xattrs;
8320 	struct spdk_xattr	*xattr;
8321 
8322 	blob_verify_md_op(blob);
8323 
8324 	if (blob->md_ro) {
8325 		return -EPERM;
8326 	}
8327 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
8328 
8329 	TAILQ_FOREACH(xattr, xattrs, link) {
8330 		if (!strcmp(name, xattr->name)) {
8331 			TAILQ_REMOVE(xattrs, xattr, link);
8332 			free(xattr->value);
8333 			free(xattr->name);
8334 			free(xattr);
8335 
8336 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
8337 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
8338 			}
8339 			blob->state = SPDK_BLOB_STATE_DIRTY;
8340 
8341 			return 0;
8342 		}
8343 	}
8344 
8345 	return -ENOENT;
8346 }
8347 
8348 int
8349 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
8350 {
8351 	return blob_remove_xattr(blob, name, false);
8352 }
8353 
8354 static int
8355 blob_get_xattr_value(struct spdk_blob *blob, const char *name,
8356 		     const void **value, size_t *value_len, bool internal)
8357 {
8358 	struct spdk_xattr	*xattr;
8359 	struct spdk_xattr_tailq *xattrs;
8360 
8361 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
8362 
8363 	TAILQ_FOREACH(xattr, xattrs, link) {
8364 		if (!strcmp(name, xattr->name)) {
8365 			*value = xattr->value;
8366 			*value_len = xattr->value_len;
8367 			return 0;
8368 		}
8369 	}
8370 	return -ENOENT;
8371 }
8372 
8373 int
8374 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
8375 			  const void **value, size_t *value_len)
8376 {
8377 	blob_verify_md_op(blob);
8378 
8379 	return blob_get_xattr_value(blob, name, value, value_len, false);
8380 }
8381 
8382 struct spdk_xattr_names {
8383 	uint32_t	count;
8384 	const char	*names[0];
8385 };
8386 
8387 static int
8388 blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
8389 {
8390 	struct spdk_xattr	*xattr;
8391 	int			count = 0;
8392 
8393 	TAILQ_FOREACH(xattr, xattrs, link) {
8394 		count++;
8395 	}
8396 
8397 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
8398 	if (*names == NULL) {
8399 		return -ENOMEM;
8400 	}
8401 
8402 	TAILQ_FOREACH(xattr, xattrs, link) {
8403 		(*names)->names[(*names)->count++] = xattr->name;
8404 	}
8405 
8406 	return 0;
8407 }
8408 
8409 int
8410 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
8411 {
8412 	blob_verify_md_op(blob);
8413 
8414 	return blob_get_xattr_names(&blob->xattrs, names);
8415 }
8416 
8417 uint32_t
8418 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
8419 {
8420 	assert(names != NULL);
8421 
8422 	return names->count;
8423 }
8424 
8425 const char *
8426 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
8427 {
8428 	if (index >= names->count) {
8429 		return NULL;
8430 	}
8431 
8432 	return names->names[index];
8433 }
8434 
8435 void
8436 spdk_xattr_names_free(struct spdk_xattr_names *names)
8437 {
8438 	free(names);
8439 }
8440 
8441 struct spdk_bs_type
8442 spdk_bs_get_bstype(struct spdk_blob_store *bs)
8443 {
8444 	return bs->bstype;
8445 }
8446 
8447 void
8448 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
8449 {
8450 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
8451 }
8452 
8453 bool
8454 spdk_blob_is_read_only(struct spdk_blob *blob)
8455 {
8456 	assert(blob != NULL);
8457 	return (blob->data_ro || blob->md_ro);
8458 }
8459 
8460 bool
8461 spdk_blob_is_snapshot(struct spdk_blob *blob)
8462 {
8463 	struct spdk_blob_list *snapshot_entry;
8464 
8465 	assert(blob != NULL);
8466 
8467 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
8468 	if (snapshot_entry == NULL) {
8469 		return false;
8470 	}
8471 
8472 	return true;
8473 }
8474 
8475 bool
8476 spdk_blob_is_clone(struct spdk_blob *blob)
8477 {
8478 	assert(blob != NULL);
8479 
8480 	if (blob->parent_id != SPDK_BLOBID_INVALID &&
8481 	    blob->parent_id != SPDK_BLOBID_EXTERNAL_SNAPSHOT) {
8482 		assert(spdk_blob_is_thin_provisioned(blob));
8483 		return true;
8484 	}
8485 
8486 	return false;
8487 }
8488 
8489 bool
8490 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
8491 {
8492 	assert(blob != NULL);
8493 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
8494 }
8495 
8496 bool
8497 spdk_blob_is_esnap_clone(const struct spdk_blob *blob)
8498 {
8499 	return blob_is_esnap_clone(blob);
8500 }
8501 
8502 static void
8503 blob_update_clear_method(struct spdk_blob *blob)
8504 {
8505 	enum blob_clear_method stored_cm;
8506 
8507 	assert(blob != NULL);
8508 
8509 	/* If BLOB_CLEAR_WITH_DEFAULT was passed in, use the setting stored
8510 	 * in metadata previously.  If something other than the default was
8511 	 * specified, ignore stored value and used what was passed in.
8512 	 */
8513 	stored_cm = ((blob->md_ro_flags & SPDK_BLOB_CLEAR_METHOD) >> SPDK_BLOB_CLEAR_METHOD_SHIFT);
8514 
8515 	if (blob->clear_method == BLOB_CLEAR_WITH_DEFAULT) {
8516 		blob->clear_method = stored_cm;
8517 	} else if (blob->clear_method != stored_cm) {
8518 		SPDK_WARNLOG("Using passed in clear method 0x%x instead of stored value of 0x%x\n",
8519 			     blob->clear_method, stored_cm);
8520 	}
8521 }
8522 
8523 spdk_blob_id
8524 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
8525 {
8526 	struct spdk_blob_list *snapshot_entry = NULL;
8527 	struct spdk_blob_list *clone_entry = NULL;
8528 
8529 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
8530 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
8531 			if (clone_entry->id == blob_id) {
8532 				return snapshot_entry->id;
8533 			}
8534 		}
8535 	}
8536 
8537 	return SPDK_BLOBID_INVALID;
8538 }
8539 
8540 int
8541 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
8542 		     size_t *count)
8543 {
8544 	struct spdk_blob_list *snapshot_entry, *clone_entry;
8545 	size_t n;
8546 
8547 	snapshot_entry = bs_get_snapshot_entry(bs, blobid);
8548 	if (snapshot_entry == NULL) {
8549 		*count = 0;
8550 		return 0;
8551 	}
8552 
8553 	if (ids == NULL || *count < snapshot_entry->clone_count) {
8554 		*count = snapshot_entry->clone_count;
8555 		return -ENOMEM;
8556 	}
8557 	*count = snapshot_entry->clone_count;
8558 
8559 	n = 0;
8560 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
8561 		ids[n++] = clone_entry->id;
8562 	}
8563 
8564 	return 0;
8565 }
8566 
8567 static void
8568 bs_load_grow_continue(struct spdk_bs_load_ctx *ctx)
8569 {
8570 	int rc;
8571 
8572 	if (ctx->super->size == 0) {
8573 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8574 	}
8575 
8576 	if (ctx->super->io_unit_size == 0) {
8577 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
8578 	}
8579 
8580 	/* Parse the super block */
8581 	ctx->bs->clean = 1;
8582 	ctx->bs->cluster_sz = ctx->super->cluster_size;
8583 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
8584 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
8585 	if (spdk_u32_is_pow2(ctx->bs->pages_per_cluster)) {
8586 		ctx->bs->pages_per_cluster_shift = spdk_u32log2(ctx->bs->pages_per_cluster);
8587 	}
8588 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
8589 	rc = spdk_bit_array_resize(&ctx->used_clusters, ctx->bs->total_clusters);
8590 	if (rc < 0) {
8591 		bs_load_ctx_fail(ctx, -ENOMEM);
8592 		return;
8593 	}
8594 	ctx->bs->md_start = ctx->super->md_start;
8595 	ctx->bs->md_len = ctx->super->md_len;
8596 	rc = spdk_bit_array_resize(&ctx->bs->open_blobids, ctx->bs->md_len);
8597 	if (rc < 0) {
8598 		bs_load_ctx_fail(ctx, -ENOMEM);
8599 		return;
8600 	}
8601 
8602 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
8603 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
8604 	ctx->bs->super_blob = ctx->super->super_blob;
8605 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
8606 
8607 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0) {
8608 		SPDK_ERRLOG("Can not grow an unclean blobstore, please load it normally to clean it.\n");
8609 		bs_load_ctx_fail(ctx, -EIO);
8610 		return;
8611 	} else {
8612 		bs_load_read_used_pages(ctx);
8613 	}
8614 }
8615 
8616 static void
8617 bs_load_grow_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8618 {
8619 	struct spdk_bs_load_ctx	*ctx = cb_arg;
8620 
8621 	if (bserrno != 0) {
8622 		bs_load_ctx_fail(ctx, bserrno);
8623 		return;
8624 	}
8625 	bs_load_grow_continue(ctx);
8626 }
8627 
8628 static void
8629 bs_load_grow_used_clusters_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8630 {
8631 	struct spdk_bs_load_ctx	*ctx = cb_arg;
8632 
8633 	if (bserrno != 0) {
8634 		bs_load_ctx_fail(ctx, bserrno);
8635 		return;
8636 	}
8637 
8638 	spdk_free(ctx->mask);
8639 
8640 	bs_sequence_write_dev(ctx->seq, ctx->super, bs_page_to_lba(ctx->bs, 0),
8641 			      bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
8642 			      bs_load_grow_super_write_cpl, ctx);
8643 }
8644 
8645 static void
8646 bs_load_grow_used_clusters_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8647 {
8648 	struct spdk_bs_load_ctx *ctx = cb_arg;
8649 	uint64_t		lba, lba_count;
8650 	uint64_t		dev_size;
8651 	uint64_t		total_clusters;
8652 
8653 	if (bserrno != 0) {
8654 		bs_load_ctx_fail(ctx, bserrno);
8655 		return;
8656 	}
8657 
8658 	/* The type must be correct */
8659 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
8660 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
8661 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
8662 					     struct spdk_blob_md_page) * 8));
8663 	dev_size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8664 	total_clusters = dev_size / ctx->super->cluster_size;
8665 	ctx->mask->length = total_clusters;
8666 
8667 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
8668 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
8669 	bs_sequence_write_dev(ctx->seq, ctx->mask, lba, lba_count,
8670 			      bs_load_grow_used_clusters_write_cpl, ctx);
8671 }
8672 
8673 static void
8674 bs_load_try_to_grow(struct spdk_bs_load_ctx *ctx)
8675 {
8676 	uint64_t dev_size, total_clusters, used_cluster_mask_len, max_used_cluster_mask;
8677 	uint64_t lba, lba_count, mask_size;
8678 
8679 	dev_size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8680 	total_clusters = dev_size / ctx->super->cluster_size;
8681 	used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
8682 				spdk_divide_round_up(total_clusters, 8),
8683 				SPDK_BS_PAGE_SIZE);
8684 	max_used_cluster_mask = ctx->super->used_blobid_mask_start - ctx->super->used_cluster_mask_start;
8685 	/* No necessary to grow or no space to grow */
8686 	if (ctx->super->size >= dev_size || used_cluster_mask_len > max_used_cluster_mask) {
8687 		SPDK_DEBUGLOG(blob, "No grow\n");
8688 		bs_load_grow_continue(ctx);
8689 		return;
8690 	}
8691 
8692 	SPDK_DEBUGLOG(blob, "Resize blobstore\n");
8693 
8694 	ctx->super->size = dev_size;
8695 	ctx->super->used_cluster_mask_len = used_cluster_mask_len;
8696 	ctx->super->crc = blob_md_page_calc_crc(ctx->super);
8697 
8698 	mask_size = used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
8699 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
8700 				 SPDK_MALLOC_DMA);
8701 	if (!ctx->mask) {
8702 		bs_load_ctx_fail(ctx, -ENOMEM);
8703 		return;
8704 	}
8705 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
8706 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
8707 	bs_sequence_read_dev(ctx->seq, ctx->mask, lba, lba_count,
8708 			     bs_load_grow_used_clusters_read_cpl, ctx);
8709 }
8710 
8711 static void
8712 bs_grow_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8713 {
8714 	struct spdk_bs_load_ctx *ctx = cb_arg;
8715 	uint32_t	crc;
8716 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
8717 
8718 	if (ctx->super->version > SPDK_BS_VERSION ||
8719 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
8720 		bs_load_ctx_fail(ctx, -EILSEQ);
8721 		return;
8722 	}
8723 
8724 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
8725 		   sizeof(ctx->super->signature)) != 0) {
8726 		bs_load_ctx_fail(ctx, -EILSEQ);
8727 		return;
8728 	}
8729 
8730 	crc = blob_md_page_calc_crc(ctx->super);
8731 	if (crc != ctx->super->crc) {
8732 		bs_load_ctx_fail(ctx, -EILSEQ);
8733 		return;
8734 	}
8735 
8736 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
8737 		SPDK_DEBUGLOG(blob, "Bstype matched - loading blobstore\n");
8738 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
8739 		SPDK_DEBUGLOG(blob, "Bstype wildcard used - loading blobstore regardless bstype\n");
8740 	} else {
8741 		SPDK_DEBUGLOG(blob, "Unexpected bstype\n");
8742 		SPDK_LOGDUMP(blob, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
8743 		SPDK_LOGDUMP(blob, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
8744 		bs_load_ctx_fail(ctx, -ENXIO);
8745 		return;
8746 	}
8747 
8748 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
8749 		SPDK_NOTICELOG("Size mismatch, dev size: %" PRIu64 ", blobstore size: %" PRIu64 "\n",
8750 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
8751 		bs_load_ctx_fail(ctx, -EILSEQ);
8752 		return;
8753 	}
8754 
8755 	bs_load_try_to_grow(ctx);
8756 
8757 }
8758 
8759 void
8760 spdk_bs_grow(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
8761 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
8762 {
8763 	struct spdk_blob_store	*bs;
8764 	struct spdk_bs_cpl	cpl;
8765 	struct spdk_bs_load_ctx *ctx;
8766 	struct spdk_bs_opts	opts = {};
8767 	int err;
8768 
8769 	SPDK_DEBUGLOG(blob, "Loading blobstore from dev %p\n", dev);
8770 
8771 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
8772 		SPDK_DEBUGLOG(blob, "unsupported dev block length of %d\n", dev->blocklen);
8773 		dev->destroy(dev);
8774 		cb_fn(cb_arg, NULL, -EINVAL);
8775 		return;
8776 	}
8777 
8778 	spdk_bs_opts_init(&opts, sizeof(opts));
8779 	if (o) {
8780 		if (bs_opts_copy(o, &opts)) {
8781 			return;
8782 		}
8783 	}
8784 
8785 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
8786 		dev->destroy(dev);
8787 		cb_fn(cb_arg, NULL, -EINVAL);
8788 		return;
8789 	}
8790 
8791 	err = bs_alloc(dev, &opts, &bs, &ctx);
8792 	if (err) {
8793 		dev->destroy(dev);
8794 		cb_fn(cb_arg, NULL, err);
8795 		return;
8796 	}
8797 
8798 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
8799 	cpl.u.bs_handle.cb_fn = cb_fn;
8800 	cpl.u.bs_handle.cb_arg = cb_arg;
8801 	cpl.u.bs_handle.bs = bs;
8802 
8803 	ctx->seq = bs_sequence_start_bs(bs->md_channel, &cpl);
8804 	if (!ctx->seq) {
8805 		spdk_free(ctx->super);
8806 		free(ctx);
8807 		bs_free(bs);
8808 		cb_fn(cb_arg, NULL, -ENOMEM);
8809 		return;
8810 	}
8811 
8812 	/* Read the super block */
8813 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
8814 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
8815 			     bs_grow_load_super_cpl, ctx);
8816 }
8817 
8818 int
8819 spdk_blob_get_esnap_id(struct spdk_blob *blob, const void **id, size_t *len)
8820 {
8821 	if (!blob_is_esnap_clone(blob)) {
8822 		return -EINVAL;
8823 	}
8824 
8825 	return blob_get_xattr_value(blob, BLOB_EXTERNAL_SNAPSHOT_ID, id, len, true);
8826 }
8827 
8828 struct spdk_io_channel *
8829 blob_esnap_get_io_channel(struct spdk_io_channel *ch, struct spdk_blob *blob)
8830 {
8831 	struct spdk_bs_channel		*bs_channel = spdk_io_channel_get_ctx(ch);
8832 	struct spdk_bs_dev		*bs_dev = blob->back_bs_dev;
8833 	struct blob_esnap_channel	find = {};
8834 	struct blob_esnap_channel	*esnap_channel, *existing;
8835 
8836 	find.blob_id = blob->id;
8837 	esnap_channel = RB_FIND(blob_esnap_channel_tree, &bs_channel->esnap_channels, &find);
8838 	if (spdk_likely(esnap_channel != NULL)) {
8839 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": using cached channel on thread %s\n",
8840 			      blob->id, spdk_thread_get_name(spdk_get_thread()));
8841 		return esnap_channel->channel;
8842 	}
8843 
8844 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": allocating channel on thread %s\n",
8845 		      blob->id, spdk_thread_get_name(spdk_get_thread()));
8846 
8847 	esnap_channel = calloc(1, sizeof(*esnap_channel));
8848 	if (esnap_channel == NULL) {
8849 		SPDK_NOTICELOG("blob 0x%" PRIx64 " channel allocation failed: no memory\n",
8850 			       find.blob_id);
8851 		return NULL;
8852 	}
8853 	esnap_channel->channel = bs_dev->create_channel(bs_dev);
8854 	if (esnap_channel->channel == NULL) {
8855 		SPDK_NOTICELOG("blob 0x%" PRIx64 " back channel allocation failed\n", blob->id);
8856 		free(esnap_channel);
8857 		return NULL;
8858 	}
8859 	esnap_channel->blob_id = find.blob_id;
8860 	existing = RB_INSERT(blob_esnap_channel_tree, &bs_channel->esnap_channels, esnap_channel);
8861 	if (spdk_unlikely(existing != NULL)) {
8862 		/*
8863 		 * This should be unreachable: all modifications to this tree happen on this thread.
8864 		 */
8865 		SPDK_ERRLOG("blob 0x%" PRIx64 "lost race to allocate a channel\n", find.blob_id);
8866 		assert(false);
8867 
8868 		bs_dev->destroy_channel(bs_dev, esnap_channel->channel);
8869 		free(esnap_channel);
8870 
8871 		return existing->channel;
8872 	}
8873 
8874 	return esnap_channel->channel;
8875 }
8876 
8877 static int
8878 blob_esnap_channel_compare(struct blob_esnap_channel *c1, struct blob_esnap_channel *c2)
8879 {
8880 	return (c1->blob_id < c2->blob_id ? -1 : c1->blob_id > c2->blob_id);
8881 }
8882 
8883 struct blob_esnap_destroy_ctx {
8884 	spdk_blob_op_with_handle_complete	cb_fn;
8885 	void					*cb_arg;
8886 	struct spdk_blob			*blob;
8887 	struct spdk_bs_dev			*back_bs_dev;
8888 	bool					abort_io;
8889 };
8890 
8891 static void
8892 blob_esnap_destroy_channels_done(struct spdk_io_channel_iter *i, int status)
8893 {
8894 	struct blob_esnap_destroy_ctx	*ctx = spdk_io_channel_iter_get_ctx(i);
8895 	struct spdk_blob		*blob = ctx->blob;
8896 	struct spdk_blob_store		*bs = blob->bs;
8897 
8898 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": done destroying channels for this blob\n",
8899 		      blob->id);
8900 
8901 	if (ctx->cb_fn != NULL) {
8902 		ctx->cb_fn(ctx->cb_arg, blob, status);
8903 	}
8904 	free(ctx);
8905 
8906 	bs->esnap_channels_unloading--;
8907 	if (bs->esnap_channels_unloading == 0 && bs->esnap_unload_cb_fn != NULL) {
8908 		spdk_bs_unload(bs, bs->esnap_unload_cb_fn, bs->esnap_unload_cb_arg);
8909 	}
8910 }
8911 
8912 static void
8913 blob_esnap_destroy_one_channel(struct spdk_io_channel_iter *i)
8914 {
8915 	struct blob_esnap_destroy_ctx	*ctx = spdk_io_channel_iter_get_ctx(i);
8916 	struct spdk_blob		*blob = ctx->blob;
8917 	struct spdk_bs_dev		*bs_dev = ctx->back_bs_dev;
8918 	struct spdk_io_channel		*channel = spdk_io_channel_iter_get_channel(i);
8919 	struct spdk_bs_channel		*bs_channel = spdk_io_channel_get_ctx(channel);
8920 	struct blob_esnap_channel	*esnap_channel;
8921 	struct blob_esnap_channel	find = {};
8922 
8923 	assert(spdk_get_thread() == spdk_io_channel_get_thread(channel));
8924 
8925 	find.blob_id = blob->id;
8926 	esnap_channel = RB_FIND(blob_esnap_channel_tree, &bs_channel->esnap_channels, &find);
8927 	if (esnap_channel != NULL) {
8928 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": destroying channel on thread %s\n",
8929 			      blob->id, spdk_thread_get_name(spdk_get_thread()));
8930 		RB_REMOVE(blob_esnap_channel_tree, &bs_channel->esnap_channels, esnap_channel);
8931 
8932 		if (ctx->abort_io) {
8933 			spdk_bs_user_op_t *op, *tmp;
8934 
8935 			TAILQ_FOREACH_SAFE(op, &bs_channel->queued_io, link, tmp) {
8936 				if (op->back_channel == esnap_channel->channel) {
8937 					TAILQ_REMOVE(&bs_channel->queued_io, op, link);
8938 					bs_user_op_abort(op, -EIO);
8939 				}
8940 			}
8941 		}
8942 
8943 		bs_dev->destroy_channel(bs_dev, esnap_channel->channel);
8944 		free(esnap_channel);
8945 	}
8946 
8947 	spdk_for_each_channel_continue(i, 0);
8948 }
8949 
8950 /*
8951  * Destroy the channels for a specific blob on each thread with a blobstore channel. This should be
8952  * used when closing an esnap clone blob and after decoupling from the parent.
8953  */
8954 static void
8955 blob_esnap_destroy_bs_dev_channels(struct spdk_blob *blob, bool abort_io,
8956 				   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
8957 {
8958 	struct blob_esnap_destroy_ctx	*ctx;
8959 
8960 	if (!blob_is_esnap_clone(blob) || blob->back_bs_dev == NULL) {
8961 		if (cb_fn != NULL) {
8962 			cb_fn(cb_arg, blob, 0);
8963 		}
8964 		return;
8965 	}
8966 
8967 	ctx = calloc(1, sizeof(*ctx));
8968 	if (ctx == NULL) {
8969 		if (cb_fn != NULL) {
8970 			cb_fn(cb_arg, blob, -ENOMEM);
8971 		}
8972 		return;
8973 	}
8974 	ctx->cb_fn = cb_fn;
8975 	ctx->cb_arg = cb_arg;
8976 	ctx->blob = blob;
8977 	ctx->back_bs_dev = blob->back_bs_dev;
8978 	ctx->abort_io = abort_io;
8979 
8980 	SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64 ": destroying channels for this blob\n",
8981 		      blob->id);
8982 
8983 	blob->bs->esnap_channels_unloading++;
8984 	spdk_for_each_channel(blob->bs, blob_esnap_destroy_one_channel, ctx,
8985 			      blob_esnap_destroy_channels_done);
8986 }
8987 
8988 /*
8989  * Destroy all bs_dev channels on a specific blobstore channel. This should be used when a
8990  * bs_channel is destroyed.
8991  */
8992 static void
8993 blob_esnap_destroy_bs_channel(struct spdk_bs_channel *ch)
8994 {
8995 	struct blob_esnap_channel *esnap_channel, *esnap_channel_tmp;
8996 
8997 	assert(spdk_get_thread() == spdk_io_channel_get_thread(spdk_io_channel_from_ctx(ch)));
8998 
8999 	SPDK_DEBUGLOG(blob_esnap, "destroying channels on thread %s\n",
9000 		      spdk_thread_get_name(spdk_get_thread()));
9001 	RB_FOREACH_SAFE(esnap_channel, blob_esnap_channel_tree, &ch->esnap_channels,
9002 			esnap_channel_tmp) {
9003 		SPDK_DEBUGLOG(blob_esnap, "blob 0x%" PRIx64
9004 			      ": destroying one channel in thread %s\n",
9005 			      esnap_channel->blob_id, spdk_thread_get_name(spdk_get_thread()));
9006 		RB_REMOVE(blob_esnap_channel_tree, &ch->esnap_channels, esnap_channel);
9007 		spdk_put_io_channel(esnap_channel->channel);
9008 		free(esnap_channel);
9009 	}
9010 	SPDK_DEBUGLOG(blob_esnap, "done destroying channels on thread %s\n",
9011 		      spdk_thread_get_name(spdk_get_thread()));
9012 }
9013 
9014 struct set_bs_dev_ctx {
9015 	struct spdk_blob	*blob;
9016 	struct spdk_bs_dev	*back_bs_dev;
9017 	spdk_blob_op_complete	cb_fn;
9018 	void			*cb_arg;
9019 	int			bserrno;
9020 };
9021 
9022 static void
9023 blob_set_back_bs_dev_done(void *_ctx, int bserrno)
9024 {
9025 	struct set_bs_dev_ctx	*ctx = _ctx;
9026 
9027 	if (bserrno != 0) {
9028 		/* Even though the unfreeze failed, the update may have succeed. */
9029 		SPDK_ERRLOG("blob 0x%" PRIx64 ": unfreeze failed with error %d\n", ctx->blob->id,
9030 			    bserrno);
9031 	}
9032 	ctx->cb_fn(ctx->cb_arg, ctx->bserrno);
9033 	free(ctx);
9034 }
9035 
9036 static void
9037 blob_frozen_set_back_bs_dev(void *_ctx, struct spdk_blob *blob, int bserrno)
9038 {
9039 	struct set_bs_dev_ctx	*ctx = _ctx;
9040 
9041 	if (bserrno != 0) {
9042 		SPDK_ERRLOG("blob 0x%" PRIx64 ": failed to release old back_bs_dev with error %d\n",
9043 			    blob->id, bserrno);
9044 		ctx->bserrno = bserrno;
9045 		blob_unfreeze_io(blob, blob_set_back_bs_dev_done, ctx);
9046 		return;
9047 	}
9048 
9049 	if (blob->back_bs_dev != NULL) {
9050 		blob->back_bs_dev->destroy(blob->back_bs_dev);
9051 	}
9052 
9053 	SPDK_NOTICELOG("blob 0x%" PRIx64 ": hotplugged back_bs_dev\n", blob->id);
9054 	blob->back_bs_dev = ctx->back_bs_dev;
9055 	ctx->bserrno = 0;
9056 
9057 	blob_unfreeze_io(blob, blob_set_back_bs_dev_done, ctx);
9058 }
9059 
9060 static void
9061 blob_frozen_destroy_esnap_channels(void *_ctx, int bserrno)
9062 {
9063 	struct set_bs_dev_ctx	*ctx = _ctx;
9064 	struct spdk_blob	*blob = ctx->blob;
9065 
9066 	if (bserrno != 0) {
9067 		SPDK_ERRLOG("blob 0x%" PRIx64 ": failed to freeze with error %d\n", blob->id,
9068 			    bserrno);
9069 		ctx->cb_fn(ctx->cb_arg, bserrno);
9070 		free(ctx);
9071 		return;
9072 	}
9073 
9074 	/*
9075 	 * This does not prevent future reads from the esnap device because any future IO will
9076 	 * lazily create a new esnap IO channel.
9077 	 */
9078 	blob_esnap_destroy_bs_dev_channels(blob, true, blob_frozen_set_back_bs_dev, ctx);
9079 }
9080 
9081 void
9082 spdk_blob_set_esnap_bs_dev(struct spdk_blob *blob, struct spdk_bs_dev *back_bs_dev,
9083 			   spdk_blob_op_complete cb_fn, void *cb_arg)
9084 {
9085 	struct set_bs_dev_ctx	*ctx;
9086 
9087 	if (!blob_is_esnap_clone(blob)) {
9088 		SPDK_ERRLOG("blob 0x%" PRIx64 ": not an esnap clone\n", blob->id);
9089 		cb_fn(cb_arg, -EINVAL);
9090 		return;
9091 	}
9092 
9093 	ctx = calloc(1, sizeof(*ctx));
9094 	if (ctx == NULL) {
9095 		SPDK_ERRLOG("blob 0x%" PRIx64 ": out of memory while setting back_bs_dev\n",
9096 			    blob->id);
9097 		cb_fn(cb_arg, -ENOMEM);
9098 		return;
9099 	}
9100 	ctx->cb_fn = cb_fn;
9101 	ctx->cb_arg = cb_arg;
9102 	ctx->back_bs_dev = back_bs_dev;
9103 	ctx->blob = blob;
9104 	blob_freeze_io(blob, blob_frozen_destroy_esnap_channels, ctx);
9105 }
9106 
9107 struct spdk_bs_dev *
9108 spdk_blob_get_esnap_bs_dev(const struct spdk_blob *blob)
9109 {
9110 	if (!blob_is_esnap_clone(blob)) {
9111 		SPDK_ERRLOG("blob 0x%" PRIx64 ": not an esnap clone\n", blob->id);
9112 		return NULL;
9113 	}
9114 
9115 	return blob->back_bs_dev;
9116 }
9117 
9118 bool
9119 spdk_blob_is_degraded(const struct spdk_blob *blob)
9120 {
9121 	if (blob->bs->dev->is_degraded != NULL && blob->bs->dev->is_degraded(blob->bs->dev)) {
9122 		return true;
9123 	}
9124 	if (blob->back_bs_dev == NULL || blob->back_bs_dev->is_degraded == NULL) {
9125 		return false;
9126 	}
9127 
9128 	return blob->back_bs_dev->is_degraded(blob->back_bs_dev);
9129 }
9130 
9131 SPDK_LOG_REGISTER_COMPONENT(blob)
9132 SPDK_LOG_REGISTER_COMPONENT(blob_esnap)
9133