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