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