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