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