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