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