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