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