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