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