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