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