xref: /spdk/lib/blob/blobstore.c (revision da2fd6651a9cd4732b0910d30291821e77f4d643)
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 	} original;
5565 	struct {
5566 		spdk_blob_id id;
5567 		struct spdk_blob *blob;
5568 	} new;
5569 
5570 	/* xattrs specified for snapshot/clones only. They have no impact on
5571 	 * the original blobs xattrs. */
5572 	const struct spdk_blob_xattr_opts *xattrs;
5573 };
5574 
5575 static void
5576 bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
5577 {
5578 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
5579 	struct spdk_bs_cpl *cpl = &ctx->cpl;
5580 
5581 	if (bserrno != 0) {
5582 		if (ctx->bserrno != 0) {
5583 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5584 		} else {
5585 			ctx->bserrno = bserrno;
5586 		}
5587 	}
5588 
5589 	switch (cpl->type) {
5590 	case SPDK_BS_CPL_TYPE_BLOBID:
5591 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
5592 		break;
5593 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
5594 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
5595 		break;
5596 	default:
5597 		SPDK_UNREACHABLE();
5598 		break;
5599 	}
5600 
5601 	free(ctx);
5602 }
5603 
5604 static void
5605 bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
5606 {
5607 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5608 	struct spdk_blob *origblob = ctx->original.blob;
5609 
5610 	if (bserrno != 0) {
5611 		if (ctx->bserrno != 0) {
5612 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
5613 		} else {
5614 			ctx->bserrno = bserrno;
5615 		}
5616 	}
5617 
5618 	ctx->original.id = origblob->id;
5619 	origblob->locked_operation_in_progress = false;
5620 
5621 	spdk_blob_close(origblob, bs_clone_snapshot_cleanup_finish, ctx);
5622 }
5623 
5624 static void
5625 bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
5626 {
5627 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5628 	struct spdk_blob *origblob = ctx->original.blob;
5629 
5630 	if (bserrno != 0) {
5631 		if (ctx->bserrno != 0) {
5632 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5633 		} else {
5634 			ctx->bserrno = bserrno;
5635 		}
5636 	}
5637 
5638 	if (ctx->frozen) {
5639 		/* Unfreeze any outstanding I/O */
5640 		blob_unfreeze_io(origblob, bs_snapshot_unfreeze_cpl, ctx);
5641 	} else {
5642 		bs_snapshot_unfreeze_cpl(ctx, 0);
5643 	}
5644 
5645 }
5646 
5647 static void
5648 bs_clone_snapshot_newblob_cleanup(struct spdk_clone_snapshot_ctx *ctx, int bserrno)
5649 {
5650 	struct spdk_blob *newblob = ctx->new.blob;
5651 
5652 	if (bserrno != 0) {
5653 		if (ctx->bserrno != 0) {
5654 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5655 		} else {
5656 			ctx->bserrno = bserrno;
5657 		}
5658 	}
5659 
5660 	ctx->new.id = newblob->id;
5661 	spdk_blob_close(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
5662 }
5663 
5664 /* END blob_cleanup */
5665 
5666 /* START spdk_bs_create_snapshot */
5667 
5668 static void
5669 bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
5670 {
5671 	uint64_t *cluster_temp;
5672 	uint32_t *extent_page_temp;
5673 
5674 	cluster_temp = blob1->active.clusters;
5675 	blob1->active.clusters = blob2->active.clusters;
5676 	blob2->active.clusters = cluster_temp;
5677 
5678 	extent_page_temp = blob1->active.extent_pages;
5679 	blob1->active.extent_pages = blob2->active.extent_pages;
5680 	blob2->active.extent_pages = extent_page_temp;
5681 }
5682 
5683 static void
5684 bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
5685 {
5686 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5687 	struct spdk_blob *origblob = ctx->original.blob;
5688 	struct spdk_blob *newblob = ctx->new.blob;
5689 
5690 	if (bserrno != 0) {
5691 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5692 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5693 		return;
5694 	}
5695 
5696 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
5697 	bserrno = blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
5698 	if (bserrno != 0) {
5699 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5700 		return;
5701 	}
5702 
5703 	bs_blob_list_add(ctx->original.blob);
5704 
5705 	spdk_blob_set_read_only(newblob);
5706 
5707 	/* sync snapshot metadata */
5708 	spdk_blob_sync_md(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
5709 }
5710 
5711 static void
5712 bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
5713 {
5714 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5715 	struct spdk_blob *origblob = ctx->original.blob;
5716 	struct spdk_blob *newblob = ctx->new.blob;
5717 
5718 	if (bserrno != 0) {
5719 		/* return cluster map back to original */
5720 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5721 
5722 		/* Newblob md sync failed. Valid clusters are only present in origblob.
5723 		 * Since I/O is frozen on origblob, not changes to zeroed out cluster map should have occured.
5724 		 * Newblob needs to be reverted to thin_provisioned state at creation to properly close. */
5725 		blob_set_thin_provision(newblob);
5726 		assert(spdk_mem_all_zero(newblob->active.clusters,
5727 					 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
5728 		assert(spdk_mem_all_zero(newblob->active.extent_pages,
5729 					 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
5730 
5731 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5732 		return;
5733 	}
5734 
5735 	/* Set internal xattr for snapshot id */
5736 	bserrno = blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
5737 	if (bserrno != 0) {
5738 		/* return cluster map back to original */
5739 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5740 		blob_set_thin_provision(newblob);
5741 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5742 		return;
5743 	}
5744 
5745 	/* Create new back_bs_dev for snapshot */
5746 	origblob->back_bs_dev = bs_create_blob_bs_dev(newblob);
5747 	if (origblob->back_bs_dev == NULL) {
5748 		/* return cluster map back to original */
5749 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5750 		blob_set_thin_provision(newblob);
5751 		bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
5752 		return;
5753 	}
5754 
5755 	bs_blob_list_remove(origblob);
5756 	origblob->parent_id = newblob->id;
5757 	/* set clone blob as thin provisioned */
5758 	blob_set_thin_provision(origblob);
5759 
5760 	bs_blob_list_add(newblob);
5761 
5762 	/* sync clone metadata */
5763 	spdk_blob_sync_md(origblob, bs_snapshot_origblob_sync_cpl, ctx);
5764 }
5765 
5766 static void
5767 bs_snapshot_freeze_cpl(void *cb_arg, int rc)
5768 {
5769 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5770 	struct spdk_blob *origblob = ctx->original.blob;
5771 	struct spdk_blob *newblob = ctx->new.blob;
5772 	int bserrno;
5773 
5774 	if (rc != 0) {
5775 		bs_clone_snapshot_newblob_cleanup(ctx, rc);
5776 		return;
5777 	}
5778 
5779 	ctx->frozen = true;
5780 
5781 	/* set new back_bs_dev for snapshot */
5782 	newblob->back_bs_dev = origblob->back_bs_dev;
5783 	/* Set invalid flags from origblob */
5784 	newblob->invalid_flags = origblob->invalid_flags;
5785 
5786 	/* inherit parent from original blob if set */
5787 	newblob->parent_id = origblob->parent_id;
5788 	if (origblob->parent_id != SPDK_BLOBID_INVALID) {
5789 		/* Set internal xattr for snapshot id */
5790 		bserrno = blob_set_xattr(newblob, BLOB_SNAPSHOT,
5791 					 &origblob->parent_id, sizeof(spdk_blob_id), true);
5792 		if (bserrno != 0) {
5793 			bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5794 			return;
5795 		}
5796 	}
5797 
5798 	/* swap cluster maps */
5799 	bs_snapshot_swap_cluster_maps(newblob, origblob);
5800 
5801 	/* Set the clear method on the new blob to match the original. */
5802 	blob_set_clear_method(newblob, origblob->clear_method);
5803 
5804 	/* sync snapshot metadata */
5805 	spdk_blob_sync_md(newblob, bs_snapshot_newblob_sync_cpl, ctx);
5806 }
5807 
5808 static void
5809 bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5810 {
5811 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5812 	struct spdk_blob *origblob = ctx->original.blob;
5813 	struct spdk_blob *newblob = _blob;
5814 
5815 	if (bserrno != 0) {
5816 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5817 		return;
5818 	}
5819 
5820 	ctx->new.blob = newblob;
5821 	assert(spdk_blob_is_thin_provisioned(newblob));
5822 	assert(spdk_mem_all_zero(newblob->active.clusters,
5823 				 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
5824 	assert(spdk_mem_all_zero(newblob->active.extent_pages,
5825 				 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
5826 
5827 	blob_freeze_io(origblob, bs_snapshot_freeze_cpl, ctx);
5828 }
5829 
5830 static void
5831 bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
5832 {
5833 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5834 	struct spdk_blob *origblob = ctx->original.blob;
5835 
5836 	if (bserrno != 0) {
5837 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5838 		return;
5839 	}
5840 
5841 	ctx->new.id = blobid;
5842 	ctx->cpl.u.blobid.blobid = blobid;
5843 
5844 	spdk_bs_open_blob(origblob->bs, ctx->new.id, bs_snapshot_newblob_open_cpl, ctx);
5845 }
5846 
5847 
5848 static void
5849 bs_xattr_snapshot(void *arg, const char *name,
5850 		  const void **value, size_t *value_len)
5851 {
5852 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
5853 
5854 	struct spdk_blob *blob = (struct spdk_blob *)arg;
5855 	*value = &blob->id;
5856 	*value_len = sizeof(blob->id);
5857 }
5858 
5859 static void
5860 bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5861 {
5862 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5863 	struct spdk_blob_opts opts;
5864 	struct spdk_blob_xattr_opts internal_xattrs;
5865 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
5866 
5867 	if (bserrno != 0) {
5868 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5869 		return;
5870 	}
5871 
5872 	ctx->original.blob = _blob;
5873 
5874 	if (_blob->data_ro || _blob->md_ro) {
5875 		SPDK_DEBUGLOG(blob, "Cannot create snapshot from read only blob with id %" PRIu64 "\n",
5876 			      _blob->id);
5877 		ctx->bserrno = -EINVAL;
5878 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5879 		return;
5880 	}
5881 
5882 	if (_blob->locked_operation_in_progress) {
5883 		SPDK_DEBUGLOG(blob, "Cannot create snapshot - another operation in progress\n");
5884 		ctx->bserrno = -EBUSY;
5885 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5886 		return;
5887 	}
5888 
5889 	_blob->locked_operation_in_progress = true;
5890 
5891 	spdk_blob_opts_init(&opts, sizeof(opts));
5892 	blob_xattrs_init(&internal_xattrs);
5893 
5894 	/* Change the size of new blob to the same as in original blob,
5895 	 * but do not allocate clusters */
5896 	opts.thin_provision = true;
5897 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
5898 	opts.use_extent_table = _blob->use_extent_table;
5899 
5900 	/* If there are any xattrs specified for snapshot, set them now */
5901 	if (ctx->xattrs) {
5902 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
5903 	}
5904 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
5905 	internal_xattrs.count = 1;
5906 	internal_xattrs.ctx = _blob;
5907 	internal_xattrs.names = xattrs_names;
5908 	internal_xattrs.get_value = bs_xattr_snapshot;
5909 
5910 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
5911 		       bs_snapshot_newblob_create_cpl, ctx);
5912 }
5913 
5914 void spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
5915 			     const struct spdk_blob_xattr_opts *snapshot_xattrs,
5916 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5917 {
5918 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
5919 
5920 	if (!ctx) {
5921 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
5922 		return;
5923 	}
5924 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
5925 	ctx->cpl.u.blobid.cb_fn = cb_fn;
5926 	ctx->cpl.u.blobid.cb_arg = cb_arg;
5927 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
5928 	ctx->bserrno = 0;
5929 	ctx->frozen = false;
5930 	ctx->original.id = blobid;
5931 	ctx->xattrs = snapshot_xattrs;
5932 
5933 	spdk_bs_open_blob(bs, ctx->original.id, bs_snapshot_origblob_open_cpl, ctx);
5934 }
5935 /* END spdk_bs_create_snapshot */
5936 
5937 /* START spdk_bs_create_clone */
5938 
5939 static void
5940 bs_xattr_clone(void *arg, const char *name,
5941 	       const void **value, size_t *value_len)
5942 {
5943 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
5944 
5945 	struct spdk_blob *blob = (struct spdk_blob *)arg;
5946 	*value = &blob->id;
5947 	*value_len = sizeof(blob->id);
5948 }
5949 
5950 static void
5951 bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5952 {
5953 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5954 	struct spdk_blob *clone = _blob;
5955 
5956 	ctx->new.blob = clone;
5957 	bs_blob_list_add(clone);
5958 
5959 	spdk_blob_close(clone, bs_clone_snapshot_origblob_cleanup, ctx);
5960 }
5961 
5962 static void
5963 bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
5964 {
5965 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5966 
5967 	ctx->cpl.u.blobid.blobid = blobid;
5968 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, bs_clone_newblob_open_cpl, ctx);
5969 }
5970 
5971 static void
5972 bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5973 {
5974 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5975 	struct spdk_blob_opts		opts;
5976 	struct spdk_blob_xattr_opts internal_xattrs;
5977 	char *xattr_names[] = { BLOB_SNAPSHOT };
5978 
5979 	if (bserrno != 0) {
5980 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5981 		return;
5982 	}
5983 
5984 	ctx->original.blob = _blob;
5985 
5986 	if (!_blob->data_ro || !_blob->md_ro) {
5987 		SPDK_DEBUGLOG(blob, "Clone not from read-only blob\n");
5988 		ctx->bserrno = -EINVAL;
5989 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5990 		return;
5991 	}
5992 
5993 	if (_blob->locked_operation_in_progress) {
5994 		SPDK_DEBUGLOG(blob, "Cannot create clone - another operation in progress\n");
5995 		ctx->bserrno = -EBUSY;
5996 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5997 		return;
5998 	}
5999 
6000 	_blob->locked_operation_in_progress = true;
6001 
6002 	spdk_blob_opts_init(&opts, sizeof(opts));
6003 	blob_xattrs_init(&internal_xattrs);
6004 
6005 	opts.thin_provision = true;
6006 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
6007 	opts.use_extent_table = _blob->use_extent_table;
6008 	if (ctx->xattrs) {
6009 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
6010 	}
6011 
6012 	/* Set internal xattr BLOB_SNAPSHOT */
6013 	internal_xattrs.count = 1;
6014 	internal_xattrs.ctx = _blob;
6015 	internal_xattrs.names = xattr_names;
6016 	internal_xattrs.get_value = bs_xattr_clone;
6017 
6018 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
6019 		       bs_clone_newblob_create_cpl, ctx);
6020 }
6021 
6022 void spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
6023 			  const struct spdk_blob_xattr_opts *clone_xattrs,
6024 			  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6025 {
6026 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
6027 
6028 	if (!ctx) {
6029 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
6030 		return;
6031 	}
6032 
6033 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6034 	ctx->cpl.u.blobid.cb_fn = cb_fn;
6035 	ctx->cpl.u.blobid.cb_arg = cb_arg;
6036 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
6037 	ctx->bserrno = 0;
6038 	ctx->xattrs = clone_xattrs;
6039 	ctx->original.id = blobid;
6040 
6041 	spdk_bs_open_blob(bs, ctx->original.id, bs_clone_origblob_open_cpl, ctx);
6042 }
6043 
6044 /* END spdk_bs_create_clone */
6045 
6046 /* START spdk_bs_inflate_blob */
6047 
6048 static void
6049 bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
6050 {
6051 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6052 	struct spdk_blob *_blob = ctx->original.blob;
6053 
6054 	if (bserrno != 0) {
6055 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6056 		return;
6057 	}
6058 
6059 	assert(_parent != NULL);
6060 
6061 	bs_blob_list_remove(_blob);
6062 	_blob->parent_id = _parent->id;
6063 	blob_set_xattr(_blob, BLOB_SNAPSHOT, &_blob->parent_id,
6064 		       sizeof(spdk_blob_id), true);
6065 
6066 	_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6067 	_blob->back_bs_dev = bs_create_blob_bs_dev(_parent);
6068 	bs_blob_list_add(_blob);
6069 
6070 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6071 }
6072 
6073 static void
6074 bs_inflate_blob_done(struct spdk_clone_snapshot_ctx *ctx)
6075 {
6076 	struct spdk_blob *_blob = ctx->original.blob;
6077 	struct spdk_blob *_parent;
6078 
6079 	if (ctx->allocate_all) {
6080 		/* remove thin provisioning */
6081 		bs_blob_list_remove(_blob);
6082 		blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
6083 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
6084 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6085 		_blob->back_bs_dev = NULL;
6086 		_blob->parent_id = SPDK_BLOBID_INVALID;
6087 	} else {
6088 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
6089 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
6090 			/* We must change the parent of the inflated blob */
6091 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
6092 					  bs_inflate_blob_set_parent_cpl, ctx);
6093 			return;
6094 		}
6095 
6096 		bs_blob_list_remove(_blob);
6097 		blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
6098 		_blob->parent_id = SPDK_BLOBID_INVALID;
6099 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6100 		_blob->back_bs_dev = bs_create_zeroes_dev();
6101 	}
6102 
6103 	_blob->state = SPDK_BLOB_STATE_DIRTY;
6104 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6105 }
6106 
6107 /* Check if cluster needs allocation */
6108 static inline bool
6109 bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
6110 {
6111 	struct spdk_blob_bs_dev *b;
6112 
6113 	assert(blob != NULL);
6114 
6115 	if (blob->active.clusters[cluster] != 0) {
6116 		/* Cluster is already allocated */
6117 		return false;
6118 	}
6119 
6120 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
6121 		/* Blob have no parent blob */
6122 		return allocate_all;
6123 	}
6124 
6125 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
6126 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
6127 }
6128 
6129 static void
6130 bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
6131 {
6132 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6133 	struct spdk_blob *_blob = ctx->original.blob;
6134 	uint64_t offset;
6135 
6136 	if (bserrno != 0) {
6137 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6138 		return;
6139 	}
6140 
6141 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
6142 		if (bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
6143 			break;
6144 		}
6145 	}
6146 
6147 	if (ctx->cluster < _blob->active.num_clusters) {
6148 		offset = bs_cluster_to_lba(_blob->bs, ctx->cluster);
6149 
6150 		/* We may safely increment a cluster before write */
6151 		ctx->cluster++;
6152 
6153 		/* Use zero length write to touch a cluster */
6154 		spdk_blob_io_write(_blob, ctx->channel, NULL, offset, 0,
6155 				   bs_inflate_blob_touch_next, ctx);
6156 	} else {
6157 		bs_inflate_blob_done(ctx);
6158 	}
6159 }
6160 
6161 static void
6162 bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6163 {
6164 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6165 	uint64_t clusters_needed;
6166 	uint64_t i;
6167 
6168 	if (bserrno != 0) {
6169 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6170 		return;
6171 	}
6172 
6173 	ctx->original.blob = _blob;
6174 
6175 	if (_blob->locked_operation_in_progress) {
6176 		SPDK_DEBUGLOG(blob, "Cannot inflate blob - another operation in progress\n");
6177 		ctx->bserrno = -EBUSY;
6178 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6179 		return;
6180 	}
6181 
6182 	_blob->locked_operation_in_progress = true;
6183 
6184 	if (!ctx->allocate_all && _blob->parent_id == SPDK_BLOBID_INVALID) {
6185 		/* This blob have no parent, so we cannot decouple it. */
6186 		SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
6187 		bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
6188 		return;
6189 	}
6190 
6191 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
6192 		/* This is not thin provisioned blob. No need to inflate. */
6193 		bs_clone_snapshot_origblob_cleanup(ctx, 0);
6194 		return;
6195 	}
6196 
6197 	/* Do two passes - one to verify that we can obtain enough clusters
6198 	 * and another to actually claim them.
6199 	 */
6200 	clusters_needed = 0;
6201 	for (i = 0; i < _blob->active.num_clusters; i++) {
6202 		if (bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
6203 			clusters_needed++;
6204 		}
6205 	}
6206 
6207 	if (clusters_needed > _blob->bs->num_free_clusters) {
6208 		/* Not enough free clusters. Cannot satisfy the request. */
6209 		bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
6210 		return;
6211 	}
6212 
6213 	ctx->cluster = 0;
6214 	bs_inflate_blob_touch_next(ctx, 0);
6215 }
6216 
6217 static void
6218 bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6219 		spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
6220 {
6221 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6222 
6223 	if (!ctx) {
6224 		cb_fn(cb_arg, -ENOMEM);
6225 		return;
6226 	}
6227 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6228 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
6229 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
6230 	ctx->bserrno = 0;
6231 	ctx->original.id = blobid;
6232 	ctx->channel = channel;
6233 	ctx->allocate_all = allocate_all;
6234 
6235 	spdk_bs_open_blob(bs, ctx->original.id, bs_inflate_blob_open_cpl, ctx);
6236 }
6237 
6238 void
6239 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6240 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6241 {
6242 	bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
6243 }
6244 
6245 void
6246 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6247 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6248 {
6249 	bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
6250 }
6251 /* END spdk_bs_inflate_blob */
6252 
6253 /* START spdk_blob_resize */
6254 struct spdk_bs_resize_ctx {
6255 	spdk_blob_op_complete cb_fn;
6256 	void *cb_arg;
6257 	struct spdk_blob *blob;
6258 	uint64_t sz;
6259 	int rc;
6260 };
6261 
6262 static void
6263 bs_resize_unfreeze_cpl(void *cb_arg, int rc)
6264 {
6265 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6266 
6267 	if (rc != 0) {
6268 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
6269 	}
6270 
6271 	if (ctx->rc != 0) {
6272 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
6273 		rc = ctx->rc;
6274 	}
6275 
6276 	ctx->blob->locked_operation_in_progress = false;
6277 
6278 	ctx->cb_fn(ctx->cb_arg, rc);
6279 	free(ctx);
6280 }
6281 
6282 static void
6283 bs_resize_freeze_cpl(void *cb_arg, int rc)
6284 {
6285 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6286 
6287 	if (rc != 0) {
6288 		ctx->blob->locked_operation_in_progress = false;
6289 		ctx->cb_fn(ctx->cb_arg, rc);
6290 		free(ctx);
6291 		return;
6292 	}
6293 
6294 	ctx->rc = blob_resize(ctx->blob, ctx->sz);
6295 
6296 	blob_unfreeze_io(ctx->blob, bs_resize_unfreeze_cpl, ctx);
6297 }
6298 
6299 void
6300 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
6301 {
6302 	struct spdk_bs_resize_ctx *ctx;
6303 
6304 	blob_verify_md_op(blob);
6305 
6306 	SPDK_DEBUGLOG(blob, "Resizing blob %" PRIu64 " to %" PRIu64 " clusters\n", blob->id, sz);
6307 
6308 	if (blob->md_ro) {
6309 		cb_fn(cb_arg, -EPERM);
6310 		return;
6311 	}
6312 
6313 	if (sz == blob->active.num_clusters) {
6314 		cb_fn(cb_arg, 0);
6315 		return;
6316 	}
6317 
6318 	if (blob->locked_operation_in_progress) {
6319 		cb_fn(cb_arg, -EBUSY);
6320 		return;
6321 	}
6322 
6323 	ctx = calloc(1, sizeof(*ctx));
6324 	if (!ctx) {
6325 		cb_fn(cb_arg, -ENOMEM);
6326 		return;
6327 	}
6328 
6329 	blob->locked_operation_in_progress = true;
6330 	ctx->cb_fn = cb_fn;
6331 	ctx->cb_arg = cb_arg;
6332 	ctx->blob = blob;
6333 	ctx->sz = sz;
6334 	blob_freeze_io(blob, bs_resize_freeze_cpl, ctx);
6335 }
6336 
6337 /* END spdk_blob_resize */
6338 
6339 
6340 /* START spdk_bs_delete_blob */
6341 
6342 static void
6343 bs_delete_close_cpl(void *cb_arg, int bserrno)
6344 {
6345 	spdk_bs_sequence_t *seq = cb_arg;
6346 
6347 	bs_sequence_finish(seq, bserrno);
6348 }
6349 
6350 static void
6351 bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6352 {
6353 	struct spdk_blob *blob = cb_arg;
6354 
6355 	if (bserrno != 0) {
6356 		/*
6357 		 * We already removed this blob from the blobstore tailq, so
6358 		 *  we need to free it here since this is the last reference
6359 		 *  to it.
6360 		 */
6361 		blob_free(blob);
6362 		bs_delete_close_cpl(seq, bserrno);
6363 		return;
6364 	}
6365 
6366 	/*
6367 	 * This will immediately decrement the ref_count and call
6368 	 *  the completion routine since the metadata state is clean.
6369 	 *  By calling spdk_blob_close, we reduce the number of call
6370 	 *  points into code that touches the blob->open_ref count
6371 	 *  and the blobstore's blob list.
6372 	 */
6373 	spdk_blob_close(blob, bs_delete_close_cpl, seq);
6374 }
6375 
6376 struct delete_snapshot_ctx {
6377 	struct spdk_blob_list *parent_snapshot_entry;
6378 	struct spdk_blob *snapshot;
6379 	bool snapshot_md_ro;
6380 	struct spdk_blob *clone;
6381 	bool clone_md_ro;
6382 	spdk_blob_op_with_handle_complete cb_fn;
6383 	void *cb_arg;
6384 	int bserrno;
6385 	uint32_t next_extent_page;
6386 };
6387 
6388 static void
6389 delete_blob_cleanup_finish(void *cb_arg, int bserrno)
6390 {
6391 	struct delete_snapshot_ctx *ctx = cb_arg;
6392 
6393 	if (bserrno != 0) {
6394 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
6395 	}
6396 
6397 	assert(ctx != NULL);
6398 
6399 	if (bserrno != 0 && ctx->bserrno == 0) {
6400 		ctx->bserrno = bserrno;
6401 	}
6402 
6403 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
6404 	free(ctx);
6405 }
6406 
6407 static void
6408 delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
6409 {
6410 	struct delete_snapshot_ctx *ctx = cb_arg;
6411 
6412 	if (bserrno != 0) {
6413 		ctx->bserrno = bserrno;
6414 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
6415 	}
6416 
6417 	if (ctx->bserrno != 0) {
6418 		assert(blob_lookup(ctx->snapshot->bs, ctx->snapshot->id) == NULL);
6419 		TAILQ_INSERT_HEAD(&ctx->snapshot->bs->blobs, ctx->snapshot, link);
6420 		spdk_bit_array_set(ctx->snapshot->bs->open_blobids, ctx->snapshot->id);
6421 	}
6422 
6423 	ctx->snapshot->locked_operation_in_progress = false;
6424 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6425 
6426 	spdk_blob_close(ctx->snapshot, delete_blob_cleanup_finish, ctx);
6427 }
6428 
6429 static void
6430 delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
6431 {
6432 	struct delete_snapshot_ctx *ctx = cb_arg;
6433 
6434 	ctx->clone->locked_operation_in_progress = false;
6435 	ctx->clone->md_ro = ctx->clone_md_ro;
6436 
6437 	spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
6438 }
6439 
6440 static void
6441 delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
6442 {
6443 	struct delete_snapshot_ctx *ctx = cb_arg;
6444 
6445 	if (bserrno) {
6446 		ctx->bserrno = bserrno;
6447 		delete_snapshot_cleanup_clone(ctx, 0);
6448 		return;
6449 	}
6450 
6451 	ctx->clone->locked_operation_in_progress = false;
6452 	spdk_blob_close(ctx->clone, delete_blob_cleanup_finish, ctx);
6453 }
6454 
6455 static void
6456 delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
6457 {
6458 	struct delete_snapshot_ctx *ctx = cb_arg;
6459 	struct spdk_blob_list *parent_snapshot_entry = NULL;
6460 	struct spdk_blob_list *snapshot_entry = NULL;
6461 	struct spdk_blob_list *clone_entry = NULL;
6462 	struct spdk_blob_list *snapshot_clone_entry = NULL;
6463 
6464 	if (bserrno) {
6465 		SPDK_ERRLOG("Failed to sync MD on blob\n");
6466 		ctx->bserrno = bserrno;
6467 		delete_snapshot_cleanup_clone(ctx, 0);
6468 		return;
6469 	}
6470 
6471 	/* Get snapshot entry for the snapshot we want to remove */
6472 	snapshot_entry = bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
6473 
6474 	assert(snapshot_entry != NULL);
6475 
6476 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
6477 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6478 	assert(clone_entry != NULL);
6479 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
6480 	snapshot_entry->clone_count--;
6481 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
6482 
6483 	if (ctx->snapshot->parent_id != SPDK_BLOBID_INVALID) {
6484 		/* This snapshot is at the same time a clone of another snapshot - we need to
6485 		 * update parent snapshot (remove current clone, add new one inherited from
6486 		 * the snapshot that is being removed) */
6487 
6488 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
6489 		 * snapshot that we are removing */
6490 		blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
6491 						    &snapshot_clone_entry);
6492 
6493 		/* Switch clone entry in parent snapshot */
6494 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
6495 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
6496 		free(snapshot_clone_entry);
6497 	} else {
6498 		/* No parent snapshot - just remove clone entry */
6499 		free(clone_entry);
6500 	}
6501 
6502 	/* Restore md_ro flags */
6503 	ctx->clone->md_ro = ctx->clone_md_ro;
6504 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6505 
6506 	blob_unfreeze_io(ctx->clone, delete_snapshot_unfreeze_cpl, ctx);
6507 }
6508 
6509 static void
6510 delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
6511 {
6512 	struct delete_snapshot_ctx *ctx = cb_arg;
6513 	uint64_t i;
6514 
6515 	ctx->snapshot->md_ro = false;
6516 
6517 	if (bserrno) {
6518 		SPDK_ERRLOG("Failed to sync MD on clone\n");
6519 		ctx->bserrno = bserrno;
6520 
6521 		/* Restore snapshot to previous state */
6522 		bserrno = blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
6523 		if (bserrno != 0) {
6524 			delete_snapshot_cleanup_clone(ctx, bserrno);
6525 			return;
6526 		}
6527 
6528 		spdk_blob_sync_md(ctx->snapshot, delete_snapshot_cleanup_clone, ctx);
6529 		return;
6530 	}
6531 
6532 	/* Clear cluster map entries for snapshot */
6533 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
6534 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
6535 			ctx->snapshot->active.clusters[i] = 0;
6536 		}
6537 	}
6538 	for (i = 0; i < ctx->snapshot->active.num_extent_pages &&
6539 	     i < ctx->clone->active.num_extent_pages; i++) {
6540 		if (ctx->clone->active.extent_pages[i] == ctx->snapshot->active.extent_pages[i]) {
6541 			ctx->snapshot->active.extent_pages[i] = 0;
6542 		}
6543 	}
6544 
6545 	blob_set_thin_provision(ctx->snapshot);
6546 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
6547 
6548 	if (ctx->parent_snapshot_entry != NULL) {
6549 		ctx->snapshot->back_bs_dev = NULL;
6550 	}
6551 
6552 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_cpl, ctx);
6553 }
6554 
6555 static void
6556 delete_snapshot_update_extent_pages_cpl(struct delete_snapshot_ctx *ctx)
6557 {
6558 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
6559 	ctx->clone->back_bs_dev->destroy(ctx->clone->back_bs_dev);
6560 
6561 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
6562 	if (ctx->parent_snapshot_entry != NULL) {
6563 		/* ...to parent snapshot */
6564 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
6565 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
6566 		blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
6567 			       sizeof(spdk_blob_id),
6568 			       true);
6569 	} else {
6570 		/* ...to blobid invalid and zeroes dev */
6571 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
6572 		ctx->clone->back_bs_dev = bs_create_zeroes_dev();
6573 		blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
6574 	}
6575 
6576 	spdk_blob_sync_md(ctx->clone, delete_snapshot_sync_clone_cpl, ctx);
6577 }
6578 
6579 static void
6580 delete_snapshot_update_extent_pages(void *cb_arg, int bserrno)
6581 {
6582 	struct delete_snapshot_ctx *ctx = cb_arg;
6583 	uint32_t *extent_page;
6584 	uint64_t i;
6585 
6586 	for (i = ctx->next_extent_page; i < ctx->snapshot->active.num_extent_pages &&
6587 	     i < ctx->clone->active.num_extent_pages; i++) {
6588 		if (ctx->snapshot->active.extent_pages[i] == 0) {
6589 			/* No extent page to use from snapshot */
6590 			continue;
6591 		}
6592 
6593 		extent_page = &ctx->clone->active.extent_pages[i];
6594 		if (*extent_page == 0) {
6595 			/* Copy extent page from snapshot when clone did not have a matching one */
6596 			*extent_page = ctx->snapshot->active.extent_pages[i];
6597 			continue;
6598 		}
6599 
6600 		/* Clone and snapshot both contain partialy filled matching extent pages.
6601 		 * Update the clone extent page in place with cluster map containing the mix of both. */
6602 		ctx->next_extent_page = i + 1;
6603 
6604 		blob_write_extent_page(ctx->clone, *extent_page, i * SPDK_EXTENTS_PER_EP,
6605 				       delete_snapshot_update_extent_pages, ctx);
6606 		return;
6607 	}
6608 	delete_snapshot_update_extent_pages_cpl(ctx);
6609 }
6610 
6611 static void
6612 delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
6613 {
6614 	struct delete_snapshot_ctx *ctx = cb_arg;
6615 	uint64_t i;
6616 
6617 	/* Temporarily override md_ro flag for clone for MD modification */
6618 	ctx->clone_md_ro = ctx->clone->md_ro;
6619 	ctx->clone->md_ro = false;
6620 
6621 	if (bserrno) {
6622 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
6623 		ctx->bserrno = bserrno;
6624 		delete_snapshot_cleanup_clone(ctx, 0);
6625 		return;
6626 	}
6627 
6628 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
6629 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
6630 		if (ctx->clone->active.clusters[i] == 0) {
6631 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
6632 		}
6633 	}
6634 	ctx->next_extent_page = 0;
6635 	delete_snapshot_update_extent_pages(ctx, 0);
6636 }
6637 
6638 static void
6639 delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
6640 {
6641 	struct delete_snapshot_ctx *ctx = cb_arg;
6642 
6643 	if (bserrno) {
6644 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
6645 		ctx->bserrno = bserrno;
6646 		delete_snapshot_cleanup_clone(ctx, 0);
6647 		return;
6648 	}
6649 
6650 	/* Temporarily override md_ro flag for snapshot for MD modification */
6651 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
6652 	ctx->snapshot->md_ro = false;
6653 
6654 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
6655 	ctx->bserrno = blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
6656 				      sizeof(spdk_blob_id), true);
6657 	if (ctx->bserrno != 0) {
6658 		delete_snapshot_cleanup_clone(ctx, 0);
6659 		return;
6660 	}
6661 
6662 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_xattr_cpl, ctx);
6663 }
6664 
6665 static void
6666 delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
6667 {
6668 	struct delete_snapshot_ctx *ctx = cb_arg;
6669 
6670 	if (bserrno) {
6671 		SPDK_ERRLOG("Failed to open clone\n");
6672 		ctx->bserrno = bserrno;
6673 		delete_snapshot_cleanup_snapshot(ctx, 0);
6674 		return;
6675 	}
6676 
6677 	ctx->clone = clone;
6678 
6679 	if (clone->locked_operation_in_progress) {
6680 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress on its clone\n");
6681 		ctx->bserrno = -EBUSY;
6682 		spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
6683 		return;
6684 	}
6685 
6686 	clone->locked_operation_in_progress = true;
6687 
6688 	blob_freeze_io(clone, delete_snapshot_freeze_io_cb, ctx);
6689 }
6690 
6691 static void
6692 update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
6693 {
6694 	struct spdk_blob_list *snapshot_entry = NULL;
6695 	struct spdk_blob_list *clone_entry = NULL;
6696 	struct spdk_blob_list *snapshot_clone_entry = NULL;
6697 
6698 	/* Get snapshot entry for the snapshot we want to remove */
6699 	snapshot_entry = bs_get_snapshot_entry(snapshot->bs, snapshot->id);
6700 
6701 	assert(snapshot_entry != NULL);
6702 
6703 	/* Get clone of the snapshot (at this point there can be only one clone) */
6704 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6705 	assert(snapshot_entry->clone_count == 1);
6706 	assert(clone_entry != NULL);
6707 
6708 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
6709 	 * snapshot that we are removing */
6710 	blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
6711 					    &snapshot_clone_entry);
6712 
6713 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, delete_snapshot_open_clone_cb, ctx);
6714 }
6715 
6716 static void
6717 bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
6718 {
6719 	spdk_bs_sequence_t *seq = cb_arg;
6720 	struct spdk_blob_list *snapshot_entry = NULL;
6721 	uint32_t page_num;
6722 
6723 	if (bserrno) {
6724 		SPDK_ERRLOG("Failed to remove blob\n");
6725 		bs_sequence_finish(seq, bserrno);
6726 		return;
6727 	}
6728 
6729 	/* Remove snapshot from the list */
6730 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
6731 	if (snapshot_entry != NULL) {
6732 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
6733 		free(snapshot_entry);
6734 	}
6735 
6736 	page_num = bs_blobid_to_page(blob->id);
6737 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
6738 	blob->state = SPDK_BLOB_STATE_DIRTY;
6739 	blob->active.num_pages = 0;
6740 	blob_resize(blob, 0);
6741 
6742 	blob_persist(seq, blob, bs_delete_persist_cpl, blob);
6743 }
6744 
6745 static int
6746 bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
6747 {
6748 	struct spdk_blob_list *snapshot_entry = NULL;
6749 	struct spdk_blob_list *clone_entry = NULL;
6750 	struct spdk_blob *clone = NULL;
6751 	bool has_one_clone = false;
6752 
6753 	/* Check if this is a snapshot with clones */
6754 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
6755 	if (snapshot_entry != NULL) {
6756 		if (snapshot_entry->clone_count > 1) {
6757 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
6758 			return -EBUSY;
6759 		} else if (snapshot_entry->clone_count == 1) {
6760 			has_one_clone = true;
6761 		}
6762 	}
6763 
6764 	/* Check if someone has this blob open (besides this delete context):
6765 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
6766 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
6767 	 *	and that is ok, because we will update it accordingly */
6768 	if (blob->open_ref <= 2 && has_one_clone) {
6769 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6770 		assert(clone_entry != NULL);
6771 		clone = blob_lookup(blob->bs, clone_entry->id);
6772 
6773 		if (blob->open_ref == 2 && clone == NULL) {
6774 			/* Clone is closed and someone else opened this blob */
6775 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
6776 			return -EBUSY;
6777 		}
6778 
6779 		*update_clone = true;
6780 		return 0;
6781 	}
6782 
6783 	if (blob->open_ref > 1) {
6784 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
6785 		return -EBUSY;
6786 	}
6787 
6788 	assert(has_one_clone == false);
6789 	*update_clone = false;
6790 	return 0;
6791 }
6792 
6793 static void
6794 bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
6795 {
6796 	spdk_bs_sequence_t *seq = cb_arg;
6797 
6798 	bs_sequence_finish(seq, -ENOMEM);
6799 }
6800 
6801 static void
6802 bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
6803 {
6804 	spdk_bs_sequence_t *seq = cb_arg;
6805 	struct delete_snapshot_ctx *ctx;
6806 	bool update_clone = false;
6807 
6808 	if (bserrno != 0) {
6809 		bs_sequence_finish(seq, bserrno);
6810 		return;
6811 	}
6812 
6813 	blob_verify_md_op(blob);
6814 
6815 	ctx = calloc(1, sizeof(*ctx));
6816 	if (ctx == NULL) {
6817 		spdk_blob_close(blob, bs_delete_enomem_close_cpl, seq);
6818 		return;
6819 	}
6820 
6821 	ctx->snapshot = blob;
6822 	ctx->cb_fn = bs_delete_blob_finish;
6823 	ctx->cb_arg = seq;
6824 
6825 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
6826 	ctx->bserrno = bs_is_blob_deletable(blob, &update_clone);
6827 	if (ctx->bserrno) {
6828 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
6829 		return;
6830 	}
6831 
6832 	if (blob->locked_operation_in_progress) {
6833 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress\n");
6834 		ctx->bserrno = -EBUSY;
6835 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
6836 		return;
6837 	}
6838 
6839 	blob->locked_operation_in_progress = true;
6840 
6841 	/*
6842 	 * Remove the blob from the blob_store list now, to ensure it does not
6843 	 *  get returned after this point by blob_lookup().
6844 	 */
6845 	spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
6846 	TAILQ_REMOVE(&blob->bs->blobs, blob, link);
6847 
6848 	if (update_clone) {
6849 		/* This blob is a snapshot with active clone - update clone first */
6850 		update_clone_on_snapshot_deletion(blob, ctx);
6851 	} else {
6852 		/* This blob does not have any clones - just remove it */
6853 		bs_blob_list_remove(blob);
6854 		bs_delete_blob_finish(seq, blob, 0);
6855 		free(ctx);
6856 	}
6857 }
6858 
6859 void
6860 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
6861 		    spdk_blob_op_complete cb_fn, void *cb_arg)
6862 {
6863 	struct spdk_bs_cpl	cpl;
6864 	spdk_bs_sequence_t	*seq;
6865 
6866 	SPDK_DEBUGLOG(blob, "Deleting blob %" PRIu64 "\n", blobid);
6867 
6868 	assert(spdk_get_thread() == bs->md_thread);
6869 
6870 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6871 	cpl.u.blob_basic.cb_fn = cb_fn;
6872 	cpl.u.blob_basic.cb_arg = cb_arg;
6873 
6874 	seq = bs_sequence_start(bs->md_channel, &cpl);
6875 	if (!seq) {
6876 		cb_fn(cb_arg, -ENOMEM);
6877 		return;
6878 	}
6879 
6880 	spdk_bs_open_blob(bs, blobid, bs_delete_open_cpl, seq);
6881 }
6882 
6883 /* END spdk_bs_delete_blob */
6884 
6885 /* START spdk_bs_open_blob */
6886 
6887 static void
6888 bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6889 {
6890 	struct spdk_blob *blob = cb_arg;
6891 	struct spdk_blob *existing;
6892 
6893 	if (bserrno != 0) {
6894 		blob_free(blob);
6895 		seq->cpl.u.blob_handle.blob = NULL;
6896 		bs_sequence_finish(seq, bserrno);
6897 		return;
6898 	}
6899 
6900 	existing = blob_lookup(blob->bs, blob->id);
6901 	if (existing) {
6902 		blob_free(blob);
6903 		existing->open_ref++;
6904 		seq->cpl.u.blob_handle.blob = existing;
6905 		bs_sequence_finish(seq, 0);
6906 		return;
6907 	}
6908 
6909 	blob->open_ref++;
6910 
6911 	spdk_bit_array_set(blob->bs->open_blobids, blob->id);
6912 	TAILQ_INSERT_HEAD(&blob->bs->blobs, blob, link);
6913 
6914 	bs_sequence_finish(seq, bserrno);
6915 }
6916 
6917 static inline void
6918 blob_open_opts_copy(const struct spdk_blob_open_opts *src, struct spdk_blob_open_opts *dst)
6919 {
6920 #define FIELD_OK(field) \
6921         offsetof(struct spdk_blob_opts, field) + sizeof(src->field) <= src->opts_size
6922 
6923 #define SET_FIELD(field) \
6924         if (FIELD_OK(field)) { \
6925                 dst->field = src->field; \
6926         } \
6927 
6928 	SET_FIELD(clear_method);
6929 
6930 	dst->opts_size = src->opts_size;
6931 
6932 	/* You should not remove this statement, but need to update the assert statement
6933 	 * if you add a new field, and also add a corresponding SET_FIELD statement */
6934 	SPDK_STATIC_ASSERT(sizeof(struct spdk_blob_open_opts) == 16, "Incorrect size");
6935 
6936 #undef FIELD_OK
6937 #undef SET_FIELD
6938 }
6939 
6940 static void
6941 bs_open_blob(struct spdk_blob_store *bs,
6942 	     spdk_blob_id blobid,
6943 	     struct spdk_blob_open_opts *opts,
6944 	     spdk_blob_op_with_handle_complete cb_fn,
6945 	     void *cb_arg)
6946 {
6947 	struct spdk_blob		*blob;
6948 	struct spdk_bs_cpl		cpl;
6949 	struct spdk_blob_open_opts	opts_local;
6950 	spdk_bs_sequence_t		*seq;
6951 	uint32_t			page_num;
6952 
6953 	SPDK_DEBUGLOG(blob, "Opening blob %" PRIu64 "\n", blobid);
6954 	assert(spdk_get_thread() == bs->md_thread);
6955 
6956 	page_num = bs_blobid_to_page(blobid);
6957 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
6958 		/* Invalid blobid */
6959 		cb_fn(cb_arg, NULL, -ENOENT);
6960 		return;
6961 	}
6962 
6963 	blob = blob_lookup(bs, blobid);
6964 	if (blob) {
6965 		blob->open_ref++;
6966 		cb_fn(cb_arg, blob, 0);
6967 		return;
6968 	}
6969 
6970 	blob = blob_alloc(bs, blobid);
6971 	if (!blob) {
6972 		cb_fn(cb_arg, NULL, -ENOMEM);
6973 		return;
6974 	}
6975 
6976 	spdk_blob_open_opts_init(&opts_local, sizeof(opts_local));
6977 	if (opts) {
6978 		blob_open_opts_copy(opts, &opts_local);
6979 	}
6980 
6981 	blob->clear_method = opts_local.clear_method;
6982 
6983 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
6984 	cpl.u.blob_handle.cb_fn = cb_fn;
6985 	cpl.u.blob_handle.cb_arg = cb_arg;
6986 	cpl.u.blob_handle.blob = blob;
6987 
6988 	seq = bs_sequence_start(bs->md_channel, &cpl);
6989 	if (!seq) {
6990 		blob_free(blob);
6991 		cb_fn(cb_arg, NULL, -ENOMEM);
6992 		return;
6993 	}
6994 
6995 	blob_load(seq, blob, bs_open_blob_cpl, blob);
6996 }
6997 
6998 void spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
6999 		       spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7000 {
7001 	bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
7002 }
7003 
7004 void spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
7005 			   struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7006 {
7007 	bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
7008 }
7009 
7010 /* END spdk_bs_open_blob */
7011 
7012 /* START spdk_blob_set_read_only */
7013 int spdk_blob_set_read_only(struct spdk_blob *blob)
7014 {
7015 	blob_verify_md_op(blob);
7016 
7017 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
7018 
7019 	blob->state = SPDK_BLOB_STATE_DIRTY;
7020 	return 0;
7021 }
7022 /* END spdk_blob_set_read_only */
7023 
7024 /* START spdk_blob_sync_md */
7025 
7026 static void
7027 blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7028 {
7029 	struct spdk_blob *blob = cb_arg;
7030 
7031 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
7032 		blob->data_ro = true;
7033 		blob->md_ro = true;
7034 	}
7035 
7036 	bs_sequence_finish(seq, bserrno);
7037 }
7038 
7039 static void
7040 blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7041 {
7042 	struct spdk_bs_cpl	cpl;
7043 	spdk_bs_sequence_t	*seq;
7044 
7045 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7046 	cpl.u.blob_basic.cb_fn = cb_fn;
7047 	cpl.u.blob_basic.cb_arg = cb_arg;
7048 
7049 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7050 	if (!seq) {
7051 		cb_fn(cb_arg, -ENOMEM);
7052 		return;
7053 	}
7054 
7055 	blob_persist(seq, blob, blob_sync_md_cpl, blob);
7056 }
7057 
7058 void
7059 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7060 {
7061 	blob_verify_md_op(blob);
7062 
7063 	SPDK_DEBUGLOG(blob, "Syncing blob %" PRIu64 "\n", blob->id);
7064 
7065 	if (blob->md_ro) {
7066 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
7067 		cb_fn(cb_arg, 0);
7068 		return;
7069 	}
7070 
7071 	blob_sync_md(blob, cb_fn, cb_arg);
7072 }
7073 
7074 /* END spdk_blob_sync_md */
7075 
7076 struct spdk_blob_insert_cluster_ctx {
7077 	struct spdk_thread	*thread;
7078 	struct spdk_blob	*blob;
7079 	uint32_t		cluster_num;	/* cluster index in blob */
7080 	uint32_t		cluster;	/* cluster on disk */
7081 	uint32_t		extent_page;	/* extent page on disk */
7082 	int			rc;
7083 	spdk_blob_op_complete	cb_fn;
7084 	void			*cb_arg;
7085 };
7086 
7087 static void
7088 blob_insert_cluster_msg_cpl(void *arg)
7089 {
7090 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7091 
7092 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
7093 	free(ctx);
7094 }
7095 
7096 static void
7097 blob_insert_cluster_msg_cb(void *arg, int bserrno)
7098 {
7099 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7100 
7101 	ctx->rc = bserrno;
7102 	spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7103 }
7104 
7105 static void
7106 blob_insert_new_ep_cb(void *arg, int bserrno)
7107 {
7108 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7109 	uint32_t *extent_page;
7110 
7111 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7112 	*extent_page = ctx->extent_page;
7113 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7114 	blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7115 }
7116 
7117 static void
7118 blob_persist_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7119 {
7120 	struct spdk_blob_md_page        *page = cb_arg;
7121 
7122 	bs_sequence_finish(seq, bserrno);
7123 	spdk_free(page);
7124 }
7125 
7126 static void
7127 blob_write_extent_page(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
7128 		       spdk_blob_op_complete cb_fn, void *cb_arg)
7129 {
7130 	spdk_bs_sequence_t		*seq;
7131 	struct spdk_bs_cpl		cpl;
7132 	struct spdk_blob_md_page	*page = NULL;
7133 	uint32_t			page_count = 0;
7134 	int				rc;
7135 
7136 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7137 	cpl.u.blob_basic.cb_fn = cb_fn;
7138 	cpl.u.blob_basic.cb_arg = cb_arg;
7139 
7140 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7141 	if (!seq) {
7142 		cb_fn(cb_arg, -ENOMEM);
7143 		return;
7144 	}
7145 	rc = blob_serialize_add_page(blob, &page, &page_count, &page);
7146 	if (rc < 0) {
7147 		bs_sequence_finish(seq, rc);
7148 		return;
7149 	}
7150 
7151 	blob_serialize_extent_page(blob, cluster_num, page);
7152 
7153 	page->crc = blob_md_page_calc_crc(page);
7154 
7155 	assert(spdk_bit_array_get(blob->bs->used_md_pages, extent) == true);
7156 
7157 	bs_sequence_write_dev(seq, page, bs_md_page_to_lba(blob->bs, extent),
7158 			      bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
7159 			      blob_persist_extent_page_cpl, page);
7160 }
7161 
7162 static void
7163 blob_insert_cluster_msg(void *arg)
7164 {
7165 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7166 	uint32_t *extent_page;
7167 
7168 	ctx->rc = blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
7169 	if (ctx->rc != 0) {
7170 		spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7171 		return;
7172 	}
7173 
7174 	if (ctx->blob->use_extent_table == false) {
7175 		/* Extent table is not used, proceed with sync of md that will only use extents_rle. */
7176 		ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7177 		blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7178 		return;
7179 	}
7180 
7181 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7182 	if (*extent_page == 0) {
7183 		/* Extent page requires allocation.
7184 		 * It was already claimed in the used_md_pages map and placed in ctx. */
7185 		assert(ctx->extent_page != 0);
7186 		assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7187 		blob_write_extent_page(ctx->blob, ctx->extent_page, ctx->cluster_num,
7188 				       blob_insert_new_ep_cb, ctx);
7189 	} else {
7190 		/* It is possible for original thread to allocate extent page for
7191 		 * different cluster in the same extent page. In such case proceed with
7192 		 * updating the existing extent page, but release the additional one. */
7193 		if (ctx->extent_page != 0) {
7194 			assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7195 			bs_release_md_page(ctx->blob->bs, ctx->extent_page);
7196 			ctx->extent_page = 0;
7197 		}
7198 		/* Extent page already allocated.
7199 		 * Every cluster allocation, requires just an update of single extent page. */
7200 		blob_write_extent_page(ctx->blob, *extent_page, ctx->cluster_num,
7201 				       blob_insert_cluster_msg_cb, ctx);
7202 	}
7203 }
7204 
7205 static void
7206 blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
7207 				 uint64_t cluster, uint32_t extent_page, spdk_blob_op_complete cb_fn, void *cb_arg)
7208 {
7209 	struct spdk_blob_insert_cluster_ctx *ctx;
7210 
7211 	ctx = calloc(1, sizeof(*ctx));
7212 	if (ctx == NULL) {
7213 		cb_fn(cb_arg, -ENOMEM);
7214 		return;
7215 	}
7216 
7217 	ctx->thread = spdk_get_thread();
7218 	ctx->blob = blob;
7219 	ctx->cluster_num = cluster_num;
7220 	ctx->cluster = cluster;
7221 	ctx->extent_page = extent_page;
7222 	ctx->cb_fn = cb_fn;
7223 	ctx->cb_arg = cb_arg;
7224 
7225 	spdk_thread_send_msg(blob->bs->md_thread, blob_insert_cluster_msg, ctx);
7226 }
7227 
7228 /* START spdk_blob_close */
7229 
7230 static void
7231 blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7232 {
7233 	struct spdk_blob *blob = cb_arg;
7234 
7235 	if (bserrno == 0) {
7236 		blob->open_ref--;
7237 		if (blob->open_ref == 0) {
7238 			/*
7239 			 * Blobs with active.num_pages == 0 are deleted blobs.
7240 			 *  these blobs are removed from the blob_store list
7241 			 *  when the deletion process starts - so don't try to
7242 			 *  remove them again.
7243 			 */
7244 			if (blob->active.num_pages > 0) {
7245 				spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
7246 				TAILQ_REMOVE(&blob->bs->blobs, blob, link);
7247 			}
7248 			blob_free(blob);
7249 		}
7250 	}
7251 
7252 	bs_sequence_finish(seq, bserrno);
7253 }
7254 
7255 void spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7256 {
7257 	struct spdk_bs_cpl	cpl;
7258 	spdk_bs_sequence_t	*seq;
7259 
7260 	blob_verify_md_op(blob);
7261 
7262 	SPDK_DEBUGLOG(blob, "Closing blob %" PRIu64 "\n", blob->id);
7263 
7264 	if (blob->open_ref == 0) {
7265 		cb_fn(cb_arg, -EBADF);
7266 		return;
7267 	}
7268 
7269 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7270 	cpl.u.blob_basic.cb_fn = cb_fn;
7271 	cpl.u.blob_basic.cb_arg = cb_arg;
7272 
7273 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7274 	if (!seq) {
7275 		cb_fn(cb_arg, -ENOMEM);
7276 		return;
7277 	}
7278 
7279 	/* Sync metadata */
7280 	blob_persist(seq, blob, blob_close_cpl, blob);
7281 }
7282 
7283 /* END spdk_blob_close */
7284 
7285 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
7286 {
7287 	return spdk_get_io_channel(bs);
7288 }
7289 
7290 void spdk_bs_free_io_channel(struct spdk_io_channel *channel)
7291 {
7292 	spdk_put_io_channel(channel);
7293 }
7294 
7295 void spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
7296 			uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7297 {
7298 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7299 			       SPDK_BLOB_UNMAP);
7300 }
7301 
7302 void spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
7303 			       uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7304 {
7305 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7306 			       SPDK_BLOB_WRITE_ZEROES);
7307 }
7308 
7309 void spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
7310 			void *payload, uint64_t offset, uint64_t length,
7311 			spdk_blob_op_complete cb_fn, void *cb_arg)
7312 {
7313 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7314 			       SPDK_BLOB_WRITE);
7315 }
7316 
7317 void spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
7318 		       void *payload, uint64_t offset, uint64_t length,
7319 		       spdk_blob_op_complete cb_fn, void *cb_arg)
7320 {
7321 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7322 			       SPDK_BLOB_READ);
7323 }
7324 
7325 void spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
7326 			 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7327 			 spdk_blob_op_complete cb_fn, void *cb_arg)
7328 {
7329 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false);
7330 }
7331 
7332 void spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
7333 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7334 			spdk_blob_op_complete cb_fn, void *cb_arg)
7335 {
7336 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true);
7337 }
7338 
7339 struct spdk_bs_iter_ctx {
7340 	int64_t page_num;
7341 	struct spdk_blob_store *bs;
7342 
7343 	spdk_blob_op_with_handle_complete cb_fn;
7344 	void *cb_arg;
7345 };
7346 
7347 static void
7348 bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
7349 {
7350 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7351 	struct spdk_blob_store *bs = ctx->bs;
7352 	spdk_blob_id id;
7353 
7354 	if (bserrno == 0) {
7355 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
7356 		free(ctx);
7357 		return;
7358 	}
7359 
7360 	ctx->page_num++;
7361 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
7362 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
7363 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
7364 		free(ctx);
7365 		return;
7366 	}
7367 
7368 	id = bs_page_to_blobid(ctx->page_num);
7369 
7370 	spdk_bs_open_blob(bs, id, bs_iter_cpl, ctx);
7371 }
7372 
7373 void
7374 spdk_bs_iter_first(struct spdk_blob_store *bs,
7375 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7376 {
7377 	struct spdk_bs_iter_ctx *ctx;
7378 
7379 	ctx = calloc(1, sizeof(*ctx));
7380 	if (!ctx) {
7381 		cb_fn(cb_arg, NULL, -ENOMEM);
7382 		return;
7383 	}
7384 
7385 	ctx->page_num = -1;
7386 	ctx->bs = bs;
7387 	ctx->cb_fn = cb_fn;
7388 	ctx->cb_arg = cb_arg;
7389 
7390 	bs_iter_cpl(ctx, NULL, -1);
7391 }
7392 
7393 static void
7394 bs_iter_close_cpl(void *cb_arg, int bserrno)
7395 {
7396 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7397 
7398 	bs_iter_cpl(ctx, NULL, -1);
7399 }
7400 
7401 void
7402 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
7403 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7404 {
7405 	struct spdk_bs_iter_ctx *ctx;
7406 
7407 	assert(blob != NULL);
7408 
7409 	ctx = calloc(1, sizeof(*ctx));
7410 	if (!ctx) {
7411 		cb_fn(cb_arg, NULL, -ENOMEM);
7412 		return;
7413 	}
7414 
7415 	ctx->page_num = bs_blobid_to_page(blob->id);
7416 	ctx->bs = bs;
7417 	ctx->cb_fn = cb_fn;
7418 	ctx->cb_arg = cb_arg;
7419 
7420 	/* Close the existing blob */
7421 	spdk_blob_close(blob, bs_iter_close_cpl, ctx);
7422 }
7423 
7424 static int
7425 blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7426 	       uint16_t value_len, bool internal)
7427 {
7428 	struct spdk_xattr_tailq *xattrs;
7429 	struct spdk_xattr	*xattr;
7430 	size_t			desc_size;
7431 	void			*tmp;
7432 
7433 	blob_verify_md_op(blob);
7434 
7435 	if (blob->md_ro) {
7436 		return -EPERM;
7437 	}
7438 
7439 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
7440 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
7441 		SPDK_DEBUGLOG(blob, "Xattr '%s' of size %zu does not fix into single page %zu\n", name,
7442 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
7443 		return -ENOMEM;
7444 	}
7445 
7446 	if (internal) {
7447 		xattrs = &blob->xattrs_internal;
7448 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
7449 	} else {
7450 		xattrs = &blob->xattrs;
7451 	}
7452 
7453 	TAILQ_FOREACH(xattr, xattrs, link) {
7454 		if (!strcmp(name, xattr->name)) {
7455 			tmp = malloc(value_len);
7456 			if (!tmp) {
7457 				return -ENOMEM;
7458 			}
7459 
7460 			free(xattr->value);
7461 			xattr->value_len = value_len;
7462 			xattr->value = tmp;
7463 			memcpy(xattr->value, value, value_len);
7464 
7465 			blob->state = SPDK_BLOB_STATE_DIRTY;
7466 
7467 			return 0;
7468 		}
7469 	}
7470 
7471 	xattr = calloc(1, sizeof(*xattr));
7472 	if (!xattr) {
7473 		return -ENOMEM;
7474 	}
7475 
7476 	xattr->name = strdup(name);
7477 	if (!xattr->name) {
7478 		free(xattr);
7479 		return -ENOMEM;
7480 	}
7481 
7482 	xattr->value_len = value_len;
7483 	xattr->value = malloc(value_len);
7484 	if (!xattr->value) {
7485 		free(xattr->name);
7486 		free(xattr);
7487 		return -ENOMEM;
7488 	}
7489 	memcpy(xattr->value, value, value_len);
7490 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
7491 
7492 	blob->state = SPDK_BLOB_STATE_DIRTY;
7493 
7494 	return 0;
7495 }
7496 
7497 int
7498 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7499 		    uint16_t value_len)
7500 {
7501 	return blob_set_xattr(blob, name, value, value_len, false);
7502 }
7503 
7504 static int
7505 blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
7506 {
7507 	struct spdk_xattr_tailq *xattrs;
7508 	struct spdk_xattr	*xattr;
7509 
7510 	blob_verify_md_op(blob);
7511 
7512 	if (blob->md_ro) {
7513 		return -EPERM;
7514 	}
7515 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
7516 
7517 	TAILQ_FOREACH(xattr, xattrs, link) {
7518 		if (!strcmp(name, xattr->name)) {
7519 			TAILQ_REMOVE(xattrs, xattr, link);
7520 			free(xattr->value);
7521 			free(xattr->name);
7522 			free(xattr);
7523 
7524 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
7525 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
7526 			}
7527 			blob->state = SPDK_BLOB_STATE_DIRTY;
7528 
7529 			return 0;
7530 		}
7531 	}
7532 
7533 	return -ENOENT;
7534 }
7535 
7536 int
7537 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
7538 {
7539 	return blob_remove_xattr(blob, name, false);
7540 }
7541 
7542 static int
7543 blob_get_xattr_value(struct spdk_blob *blob, const char *name,
7544 		     const void **value, size_t *value_len, bool internal)
7545 {
7546 	struct spdk_xattr	*xattr;
7547 	struct spdk_xattr_tailq *xattrs;
7548 
7549 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
7550 
7551 	TAILQ_FOREACH(xattr, xattrs, link) {
7552 		if (!strcmp(name, xattr->name)) {
7553 			*value = xattr->value;
7554 			*value_len = xattr->value_len;
7555 			return 0;
7556 		}
7557 	}
7558 	return -ENOENT;
7559 }
7560 
7561 int
7562 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
7563 			  const void **value, size_t *value_len)
7564 {
7565 	blob_verify_md_op(blob);
7566 
7567 	return blob_get_xattr_value(blob, name, value, value_len, false);
7568 }
7569 
7570 struct spdk_xattr_names {
7571 	uint32_t	count;
7572 	const char	*names[0];
7573 };
7574 
7575 static int
7576 blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
7577 {
7578 	struct spdk_xattr	*xattr;
7579 	int			count = 0;
7580 
7581 	TAILQ_FOREACH(xattr, xattrs, link) {
7582 		count++;
7583 	}
7584 
7585 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
7586 	if (*names == NULL) {
7587 		return -ENOMEM;
7588 	}
7589 
7590 	TAILQ_FOREACH(xattr, xattrs, link) {
7591 		(*names)->names[(*names)->count++] = xattr->name;
7592 	}
7593 
7594 	return 0;
7595 }
7596 
7597 int
7598 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
7599 {
7600 	blob_verify_md_op(blob);
7601 
7602 	return blob_get_xattr_names(&blob->xattrs, names);
7603 }
7604 
7605 uint32_t
7606 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
7607 {
7608 	assert(names != NULL);
7609 
7610 	return names->count;
7611 }
7612 
7613 const char *
7614 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
7615 {
7616 	if (index >= names->count) {
7617 		return NULL;
7618 	}
7619 
7620 	return names->names[index];
7621 }
7622 
7623 void
7624 spdk_xattr_names_free(struct spdk_xattr_names *names)
7625 {
7626 	free(names);
7627 }
7628 
7629 struct spdk_bs_type
7630 spdk_bs_get_bstype(struct spdk_blob_store *bs)
7631 {
7632 	return bs->bstype;
7633 }
7634 
7635 void
7636 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
7637 {
7638 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
7639 }
7640 
7641 bool
7642 spdk_blob_is_read_only(struct spdk_blob *blob)
7643 {
7644 	assert(blob != NULL);
7645 	return (blob->data_ro || blob->md_ro);
7646 }
7647 
7648 bool
7649 spdk_blob_is_snapshot(struct spdk_blob *blob)
7650 {
7651 	struct spdk_blob_list *snapshot_entry;
7652 
7653 	assert(blob != NULL);
7654 
7655 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7656 	if (snapshot_entry == NULL) {
7657 		return false;
7658 	}
7659 
7660 	return true;
7661 }
7662 
7663 bool
7664 spdk_blob_is_clone(struct spdk_blob *blob)
7665 {
7666 	assert(blob != NULL);
7667 
7668 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
7669 		assert(spdk_blob_is_thin_provisioned(blob));
7670 		return true;
7671 	}
7672 
7673 	return false;
7674 }
7675 
7676 bool
7677 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
7678 {
7679 	assert(blob != NULL);
7680 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
7681 }
7682 
7683 static void
7684 blob_update_clear_method(struct spdk_blob *blob)
7685 {
7686 	enum blob_clear_method stored_cm;
7687 
7688 	assert(blob != NULL);
7689 
7690 	/* If BLOB_CLEAR_WITH_DEFAULT was passed in, use the setting stored
7691 	 * in metadata previously.  If something other than the default was
7692 	 * specified, ignore stored value and used what was passed in.
7693 	 */
7694 	stored_cm = ((blob->md_ro_flags & SPDK_BLOB_CLEAR_METHOD) >> SPDK_BLOB_CLEAR_METHOD_SHIFT);
7695 
7696 	if (blob->clear_method == BLOB_CLEAR_WITH_DEFAULT) {
7697 		blob->clear_method = stored_cm;
7698 	} else if (blob->clear_method != stored_cm) {
7699 		SPDK_WARNLOG("Using passed in clear method 0x%x instead of stored value of 0x%x\n",
7700 			     blob->clear_method, stored_cm);
7701 	}
7702 }
7703 
7704 spdk_blob_id
7705 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
7706 {
7707 	struct spdk_blob_list *snapshot_entry = NULL;
7708 	struct spdk_blob_list *clone_entry = NULL;
7709 
7710 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
7711 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
7712 			if (clone_entry->id == blob_id) {
7713 				return snapshot_entry->id;
7714 			}
7715 		}
7716 	}
7717 
7718 	return SPDK_BLOBID_INVALID;
7719 }
7720 
7721 int
7722 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
7723 		     size_t *count)
7724 {
7725 	struct spdk_blob_list *snapshot_entry, *clone_entry;
7726 	size_t n;
7727 
7728 	snapshot_entry = bs_get_snapshot_entry(bs, blobid);
7729 	if (snapshot_entry == NULL) {
7730 		*count = 0;
7731 		return 0;
7732 	}
7733 
7734 	if (ids == NULL || *count < snapshot_entry->clone_count) {
7735 		*count = snapshot_entry->clone_count;
7736 		return -ENOMEM;
7737 	}
7738 	*count = snapshot_entry->clone_count;
7739 
7740 	n = 0;
7741 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
7742 		ids[n++] = clone_entry->id;
7743 	}
7744 
7745 	return 0;
7746 }
7747 
7748 SPDK_LOG_REGISTER_COMPONENT(blob)
7749