xref: /spdk/lib/blob/blobstore.c (revision cf64422ad71e4294d5683f6e51bfee7e12832000)
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 	blob = blob_alloc(bs, id);
5827 	if (!blob) {
5828 		rc = -ENOMEM;
5829 		goto error;
5830 	}
5831 
5832 	spdk_blob_opts_init(&opts_local, sizeof(opts_local));
5833 	if (opts) {
5834 		blob_opts_copy(opts, &opts_local);
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 	if (blob != NULL) {
5883 		blob_free(blob);
5884 	}
5885 	spdk_spin_lock(&bs->used_lock);
5886 	spdk_bit_array_clear(bs->used_blobids, page_idx);
5887 	bs_release_md_page(bs, page_idx);
5888 	spdk_spin_unlock(&bs->used_lock);
5889 	cb_fn(cb_arg, 0, rc);
5890 }
5891 
5892 void
5893 spdk_bs_create_blob(struct spdk_blob_store *bs,
5894 		    spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5895 {
5896 	bs_create_blob(bs, NULL, NULL, cb_fn, cb_arg);
5897 }
5898 
5899 void
5900 spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
5901 			spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5902 {
5903 	bs_create_blob(bs, opts, NULL, cb_fn, cb_arg);
5904 }
5905 
5906 /* END spdk_bs_create_blob */
5907 
5908 /* START blob_cleanup */
5909 
5910 struct spdk_clone_snapshot_ctx {
5911 	struct spdk_bs_cpl      cpl;
5912 	int bserrno;
5913 	bool frozen;
5914 
5915 	struct spdk_io_channel *channel;
5916 
5917 	/* Current cluster for inflate operation */
5918 	uint64_t cluster;
5919 
5920 	/* For inflation force allocation of all unallocated clusters and remove
5921 	 * thin-provisioning. Otherwise only decouple parent and keep clone thin. */
5922 	bool allocate_all;
5923 
5924 	struct {
5925 		spdk_blob_id id;
5926 		struct spdk_blob *blob;
5927 		bool md_ro;
5928 	} original;
5929 	struct {
5930 		spdk_blob_id id;
5931 		struct spdk_blob *blob;
5932 	} new;
5933 
5934 	/* xattrs specified for snapshot/clones only. They have no impact on
5935 	 * the original blobs xattrs. */
5936 	const struct spdk_blob_xattr_opts *xattrs;
5937 };
5938 
5939 static void
5940 bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
5941 {
5942 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
5943 	struct spdk_bs_cpl *cpl = &ctx->cpl;
5944 
5945 	if (bserrno != 0) {
5946 		if (ctx->bserrno != 0) {
5947 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5948 		} else {
5949 			ctx->bserrno = bserrno;
5950 		}
5951 	}
5952 
5953 	switch (cpl->type) {
5954 	case SPDK_BS_CPL_TYPE_BLOBID:
5955 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
5956 		break;
5957 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
5958 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
5959 		break;
5960 	default:
5961 		SPDK_UNREACHABLE();
5962 		break;
5963 	}
5964 
5965 	free(ctx);
5966 }
5967 
5968 static void
5969 bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
5970 {
5971 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5972 	struct spdk_blob *origblob = ctx->original.blob;
5973 
5974 	if (bserrno != 0) {
5975 		if (ctx->bserrno != 0) {
5976 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
5977 		} else {
5978 			ctx->bserrno = bserrno;
5979 		}
5980 	}
5981 
5982 	ctx->original.id = origblob->id;
5983 	origblob->locked_operation_in_progress = false;
5984 
5985 	/* Revert md_ro to original state */
5986 	origblob->md_ro = ctx->original.md_ro;
5987 
5988 	spdk_blob_close(origblob, bs_clone_snapshot_cleanup_finish, ctx);
5989 }
5990 
5991 static void
5992 bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
5993 {
5994 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5995 	struct spdk_blob *origblob = ctx->original.blob;
5996 
5997 	if (bserrno != 0) {
5998 		if (ctx->bserrno != 0) {
5999 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
6000 		} else {
6001 			ctx->bserrno = bserrno;
6002 		}
6003 	}
6004 
6005 	if (ctx->frozen) {
6006 		/* Unfreeze any outstanding I/O */
6007 		blob_unfreeze_io(origblob, bs_snapshot_unfreeze_cpl, ctx);
6008 	} else {
6009 		bs_snapshot_unfreeze_cpl(ctx, 0);
6010 	}
6011 
6012 }
6013 
6014 static void
6015 bs_clone_snapshot_newblob_cleanup(struct spdk_clone_snapshot_ctx *ctx, int bserrno)
6016 {
6017 	struct spdk_blob *newblob = ctx->new.blob;
6018 
6019 	if (bserrno != 0) {
6020 		if (ctx->bserrno != 0) {
6021 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
6022 		} else {
6023 			ctx->bserrno = bserrno;
6024 		}
6025 	}
6026 
6027 	ctx->new.id = newblob->id;
6028 	spdk_blob_close(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
6029 }
6030 
6031 /* END blob_cleanup */
6032 
6033 /* START spdk_bs_create_snapshot */
6034 
6035 static void
6036 bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
6037 {
6038 	uint64_t *cluster_temp;
6039 	uint32_t *extent_page_temp;
6040 
6041 	cluster_temp = blob1->active.clusters;
6042 	blob1->active.clusters = blob2->active.clusters;
6043 	blob2->active.clusters = cluster_temp;
6044 
6045 	extent_page_temp = blob1->active.extent_pages;
6046 	blob1->active.extent_pages = blob2->active.extent_pages;
6047 	blob2->active.extent_pages = extent_page_temp;
6048 }
6049 
6050 static void
6051 bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
6052 {
6053 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6054 	struct spdk_blob *origblob = ctx->original.blob;
6055 	struct spdk_blob *newblob = ctx->new.blob;
6056 
6057 	if (bserrno != 0) {
6058 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6059 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6060 		return;
6061 	}
6062 
6063 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
6064 	bserrno = blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
6065 	if (bserrno != 0) {
6066 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6067 		return;
6068 	}
6069 
6070 	bs_blob_list_add(ctx->original.blob);
6071 
6072 	spdk_blob_set_read_only(newblob);
6073 
6074 	/* sync snapshot metadata */
6075 	spdk_blob_sync_md(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
6076 }
6077 
6078 static void
6079 bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
6080 {
6081 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6082 	struct spdk_blob *origblob = ctx->original.blob;
6083 	struct spdk_blob *newblob = ctx->new.blob;
6084 
6085 	if (bserrno != 0) {
6086 		/* return cluster map back to original */
6087 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6088 
6089 		/* Newblob md sync failed. Valid clusters are only present in origblob.
6090 		 * Since I/O is frozen on origblob, not changes to zeroed out cluster map should have occurred.
6091 		 * Newblob needs to be reverted to thin_provisioned state at creation to properly close. */
6092 		blob_set_thin_provision(newblob);
6093 		assert(spdk_mem_all_zero(newblob->active.clusters,
6094 					 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
6095 		assert(spdk_mem_all_zero(newblob->active.extent_pages,
6096 					 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
6097 
6098 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6099 		return;
6100 	}
6101 
6102 	/* Set internal xattr for snapshot id */
6103 	bserrno = blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
6104 	if (bserrno != 0) {
6105 		/* return cluster map back to original */
6106 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6107 		blob_set_thin_provision(newblob);
6108 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6109 		return;
6110 	}
6111 
6112 	/* Create new back_bs_dev for snapshot */
6113 	origblob->back_bs_dev = bs_create_blob_bs_dev(newblob);
6114 	if (origblob->back_bs_dev == NULL) {
6115 		/* return cluster map back to original */
6116 		bs_snapshot_swap_cluster_maps(newblob, origblob);
6117 		blob_set_thin_provision(newblob);
6118 		bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
6119 		return;
6120 	}
6121 
6122 	bs_blob_list_remove(origblob);
6123 	origblob->parent_id = newblob->id;
6124 	/* set clone blob as thin provisioned */
6125 	blob_set_thin_provision(origblob);
6126 
6127 	bs_blob_list_add(newblob);
6128 
6129 	/* sync clone metadata */
6130 	spdk_blob_sync_md(origblob, bs_snapshot_origblob_sync_cpl, ctx);
6131 }
6132 
6133 static void
6134 bs_snapshot_freeze_cpl(void *cb_arg, int rc)
6135 {
6136 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6137 	struct spdk_blob *origblob = ctx->original.blob;
6138 	struct spdk_blob *newblob = ctx->new.blob;
6139 	int bserrno;
6140 
6141 	if (rc != 0) {
6142 		bs_clone_snapshot_newblob_cleanup(ctx, rc);
6143 		return;
6144 	}
6145 
6146 	ctx->frozen = true;
6147 
6148 	if (newblob->back_bs_dev) {
6149 		newblob->back_bs_dev->destroy(newblob->back_bs_dev);
6150 	}
6151 	/* set new back_bs_dev for snapshot */
6152 	newblob->back_bs_dev = origblob->back_bs_dev;
6153 	/* Set invalid flags from origblob */
6154 	newblob->invalid_flags = origblob->invalid_flags;
6155 
6156 	/* inherit parent from original blob if set */
6157 	newblob->parent_id = origblob->parent_id;
6158 	if (origblob->parent_id != SPDK_BLOBID_INVALID) {
6159 		/* Set internal xattr for snapshot id */
6160 		bserrno = blob_set_xattr(newblob, BLOB_SNAPSHOT,
6161 					 &origblob->parent_id, sizeof(spdk_blob_id), true);
6162 		if (bserrno != 0) {
6163 			bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
6164 			return;
6165 		}
6166 	}
6167 
6168 	/* swap cluster maps */
6169 	bs_snapshot_swap_cluster_maps(newblob, origblob);
6170 
6171 	/* Set the clear method on the new blob to match the original. */
6172 	blob_set_clear_method(newblob, origblob->clear_method);
6173 
6174 	/* sync snapshot metadata */
6175 	spdk_blob_sync_md(newblob, bs_snapshot_newblob_sync_cpl, ctx);
6176 }
6177 
6178 static void
6179 bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6180 {
6181 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6182 	struct spdk_blob *origblob = ctx->original.blob;
6183 	struct spdk_blob *newblob = _blob;
6184 
6185 	if (bserrno != 0) {
6186 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6187 		return;
6188 	}
6189 
6190 	ctx->new.blob = newblob;
6191 	assert(spdk_blob_is_thin_provisioned(newblob));
6192 	assert(spdk_mem_all_zero(newblob->active.clusters,
6193 				 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
6194 	assert(spdk_mem_all_zero(newblob->active.extent_pages,
6195 				 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
6196 
6197 	blob_freeze_io(origblob, bs_snapshot_freeze_cpl, ctx);
6198 }
6199 
6200 static void
6201 bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
6202 {
6203 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6204 	struct spdk_blob *origblob = ctx->original.blob;
6205 
6206 	if (bserrno != 0) {
6207 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6208 		return;
6209 	}
6210 
6211 	ctx->new.id = blobid;
6212 	ctx->cpl.u.blobid.blobid = blobid;
6213 
6214 	spdk_bs_open_blob(origblob->bs, ctx->new.id, bs_snapshot_newblob_open_cpl, ctx);
6215 }
6216 
6217 
6218 static void
6219 bs_xattr_snapshot(void *arg, const char *name,
6220 		  const void **value, size_t *value_len)
6221 {
6222 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
6223 
6224 	struct spdk_blob *blob = (struct spdk_blob *)arg;
6225 	*value = &blob->id;
6226 	*value_len = sizeof(blob->id);
6227 }
6228 
6229 static void
6230 bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6231 {
6232 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6233 	struct spdk_blob_opts opts;
6234 	struct spdk_blob_xattr_opts internal_xattrs;
6235 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
6236 
6237 	if (bserrno != 0) {
6238 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6239 		return;
6240 	}
6241 
6242 	ctx->original.blob = _blob;
6243 
6244 	if (_blob->data_ro || _blob->md_ro) {
6245 		SPDK_DEBUGLOG(blob, "Cannot create snapshot from read only blob with id %" PRIu64 "\n",
6246 			      _blob->id);
6247 		ctx->bserrno = -EINVAL;
6248 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6249 		return;
6250 	}
6251 
6252 	if (_blob->locked_operation_in_progress) {
6253 		SPDK_DEBUGLOG(blob, "Cannot create snapshot - another operation in progress\n");
6254 		ctx->bserrno = -EBUSY;
6255 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6256 		return;
6257 	}
6258 
6259 	_blob->locked_operation_in_progress = true;
6260 
6261 	spdk_blob_opts_init(&opts, sizeof(opts));
6262 	blob_xattrs_init(&internal_xattrs);
6263 
6264 	/* Change the size of new blob to the same as in original blob,
6265 	 * but do not allocate clusters */
6266 	opts.thin_provision = true;
6267 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
6268 	opts.use_extent_table = _blob->use_extent_table;
6269 
6270 	/* If there are any xattrs specified for snapshot, set them now */
6271 	if (ctx->xattrs) {
6272 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
6273 	}
6274 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
6275 	internal_xattrs.count = 1;
6276 	internal_xattrs.ctx = _blob;
6277 	internal_xattrs.names = xattrs_names;
6278 	internal_xattrs.get_value = bs_xattr_snapshot;
6279 
6280 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
6281 		       bs_snapshot_newblob_create_cpl, ctx);
6282 }
6283 
6284 void
6285 spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
6286 			const struct spdk_blob_xattr_opts *snapshot_xattrs,
6287 			spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6288 {
6289 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6290 
6291 	if (!ctx) {
6292 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
6293 		return;
6294 	}
6295 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6296 	ctx->cpl.u.blobid.cb_fn = cb_fn;
6297 	ctx->cpl.u.blobid.cb_arg = cb_arg;
6298 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
6299 	ctx->bserrno = 0;
6300 	ctx->frozen = false;
6301 	ctx->original.id = blobid;
6302 	ctx->xattrs = snapshot_xattrs;
6303 
6304 	spdk_bs_open_blob(bs, ctx->original.id, bs_snapshot_origblob_open_cpl, ctx);
6305 }
6306 /* END spdk_bs_create_snapshot */
6307 
6308 /* START spdk_bs_create_clone */
6309 
6310 static void
6311 bs_xattr_clone(void *arg, const char *name,
6312 	       const void **value, size_t *value_len)
6313 {
6314 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
6315 
6316 	struct spdk_blob *blob = (struct spdk_blob *)arg;
6317 	*value = &blob->id;
6318 	*value_len = sizeof(blob->id);
6319 }
6320 
6321 static void
6322 bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6323 {
6324 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6325 	struct spdk_blob *clone = _blob;
6326 
6327 	ctx->new.blob = clone;
6328 	bs_blob_list_add(clone);
6329 
6330 	spdk_blob_close(clone, bs_clone_snapshot_origblob_cleanup, ctx);
6331 }
6332 
6333 static void
6334 bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
6335 {
6336 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6337 
6338 	ctx->cpl.u.blobid.blobid = blobid;
6339 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, bs_clone_newblob_open_cpl, ctx);
6340 }
6341 
6342 static void
6343 bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6344 {
6345 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6346 	struct spdk_blob_opts		opts;
6347 	struct spdk_blob_xattr_opts internal_xattrs;
6348 	char *xattr_names[] = { BLOB_SNAPSHOT };
6349 
6350 	if (bserrno != 0) {
6351 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6352 		return;
6353 	}
6354 
6355 	ctx->original.blob = _blob;
6356 	ctx->original.md_ro = _blob->md_ro;
6357 
6358 	if (!_blob->data_ro || !_blob->md_ro) {
6359 		SPDK_DEBUGLOG(blob, "Clone not from read-only blob\n");
6360 		ctx->bserrno = -EINVAL;
6361 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6362 		return;
6363 	}
6364 
6365 	if (_blob->locked_operation_in_progress) {
6366 		SPDK_DEBUGLOG(blob, "Cannot create clone - another operation in progress\n");
6367 		ctx->bserrno = -EBUSY;
6368 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6369 		return;
6370 	}
6371 
6372 	_blob->locked_operation_in_progress = true;
6373 
6374 	spdk_blob_opts_init(&opts, sizeof(opts));
6375 	blob_xattrs_init(&internal_xattrs);
6376 
6377 	opts.thin_provision = true;
6378 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
6379 	opts.use_extent_table = _blob->use_extent_table;
6380 	if (ctx->xattrs) {
6381 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
6382 	}
6383 
6384 	/* Set internal xattr BLOB_SNAPSHOT */
6385 	internal_xattrs.count = 1;
6386 	internal_xattrs.ctx = _blob;
6387 	internal_xattrs.names = xattr_names;
6388 	internal_xattrs.get_value = bs_xattr_clone;
6389 
6390 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
6391 		       bs_clone_newblob_create_cpl, ctx);
6392 }
6393 
6394 void
6395 spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
6396 		     const struct spdk_blob_xattr_opts *clone_xattrs,
6397 		     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
6398 {
6399 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
6400 
6401 	if (!ctx) {
6402 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
6403 		return;
6404 	}
6405 
6406 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
6407 	ctx->cpl.u.blobid.cb_fn = cb_fn;
6408 	ctx->cpl.u.blobid.cb_arg = cb_arg;
6409 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
6410 	ctx->bserrno = 0;
6411 	ctx->xattrs = clone_xattrs;
6412 	ctx->original.id = blobid;
6413 
6414 	spdk_bs_open_blob(bs, ctx->original.id, bs_clone_origblob_open_cpl, ctx);
6415 }
6416 
6417 /* END spdk_bs_create_clone */
6418 
6419 /* START spdk_bs_inflate_blob */
6420 
6421 static void
6422 bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
6423 {
6424 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6425 	struct spdk_blob *_blob = ctx->original.blob;
6426 
6427 	if (bserrno != 0) {
6428 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6429 		return;
6430 	}
6431 
6432 	/* Temporarily override md_ro flag for MD modification */
6433 	_blob->md_ro = false;
6434 
6435 	bserrno = blob_set_xattr(_blob, BLOB_SNAPSHOT, &_parent->id, sizeof(spdk_blob_id), true);
6436 	if (bserrno != 0) {
6437 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6438 		return;
6439 	}
6440 
6441 	assert(_parent != NULL);
6442 
6443 	bs_blob_list_remove(_blob);
6444 	_blob->parent_id = _parent->id;
6445 
6446 	_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6447 	_blob->back_bs_dev = bs_create_blob_bs_dev(_parent);
6448 	bs_blob_list_add(_blob);
6449 
6450 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6451 }
6452 
6453 static void
6454 bs_inflate_blob_done(struct spdk_clone_snapshot_ctx *ctx)
6455 {
6456 	struct spdk_blob *_blob = ctx->original.blob;
6457 	struct spdk_blob *_parent;
6458 
6459 	if (ctx->allocate_all) {
6460 		/* remove thin provisioning */
6461 		bs_blob_list_remove(_blob);
6462 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
6463 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6464 		_blob->back_bs_dev = NULL;
6465 		_blob->parent_id = SPDK_BLOBID_INVALID;
6466 	} else {
6467 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
6468 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
6469 			/* We must change the parent of the inflated blob */
6470 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
6471 					  bs_inflate_blob_set_parent_cpl, ctx);
6472 			return;
6473 		}
6474 
6475 		bs_blob_list_remove(_blob);
6476 		_blob->parent_id = SPDK_BLOBID_INVALID;
6477 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
6478 		_blob->back_bs_dev = bs_create_zeroes_dev();
6479 	}
6480 
6481 	/* Temporarily override md_ro flag for MD modification */
6482 	_blob->md_ro = false;
6483 	blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
6484 	_blob->state = SPDK_BLOB_STATE_DIRTY;
6485 
6486 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
6487 }
6488 
6489 /* Check if cluster needs allocation */
6490 static inline bool
6491 bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
6492 {
6493 	struct spdk_blob_bs_dev *b;
6494 
6495 	assert(blob != NULL);
6496 
6497 	if (blob->active.clusters[cluster] != 0) {
6498 		/* Cluster is already allocated */
6499 		return false;
6500 	}
6501 
6502 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
6503 		/* Blob have no parent blob */
6504 		return allocate_all;
6505 	}
6506 
6507 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
6508 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
6509 }
6510 
6511 static void
6512 bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
6513 {
6514 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6515 	struct spdk_blob *_blob = ctx->original.blob;
6516 	struct spdk_bs_cpl cpl;
6517 	spdk_bs_user_op_t *op;
6518 	uint64_t offset;
6519 
6520 	if (bserrno != 0) {
6521 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
6522 		return;
6523 	}
6524 
6525 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
6526 		if (bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
6527 			break;
6528 		}
6529 	}
6530 
6531 	if (ctx->cluster < _blob->active.num_clusters) {
6532 		offset = bs_cluster_to_lba(_blob->bs, ctx->cluster);
6533 
6534 		/* We may safely increment a cluster before copying */
6535 		ctx->cluster++;
6536 
6537 		/* Use a dummy 0B read as a context for cluster copy */
6538 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6539 		cpl.u.blob_basic.cb_fn = bs_inflate_blob_touch_next;
6540 		cpl.u.blob_basic.cb_arg = ctx;
6541 
6542 		op = bs_user_op_alloc(ctx->channel, &cpl, SPDK_BLOB_READ, _blob,
6543 				      NULL, 0, offset, 0);
6544 		if (!op) {
6545 			bs_clone_snapshot_origblob_cleanup(ctx, -ENOMEM);
6546 			return;
6547 		}
6548 
6549 		bs_allocate_and_copy_cluster(_blob, ctx->channel, offset, op);
6550 	} else {
6551 		bs_inflate_blob_done(ctx);
6552 	}
6553 }
6554 
6555 static void
6556 bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
6557 {
6558 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
6559 	uint64_t clusters_needed;
6560 	uint64_t i;
6561 
6562 	if (bserrno != 0) {
6563 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
6564 		return;
6565 	}
6566 
6567 	ctx->original.blob = _blob;
6568 	ctx->original.md_ro = _blob->md_ro;
6569 
6570 	if (_blob->locked_operation_in_progress) {
6571 		SPDK_DEBUGLOG(blob, "Cannot inflate blob - another operation in progress\n");
6572 		ctx->bserrno = -EBUSY;
6573 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
6574 		return;
6575 	}
6576 
6577 	_blob->locked_operation_in_progress = true;
6578 
6579 	if (!ctx->allocate_all && _blob->parent_id == SPDK_BLOBID_INVALID) {
6580 		/* This blob have no parent, so we cannot decouple it. */
6581 		SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
6582 		bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
6583 		return;
6584 	}
6585 
6586 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
6587 		/* This is not thin provisioned blob. No need to inflate. */
6588 		bs_clone_snapshot_origblob_cleanup(ctx, 0);
6589 		return;
6590 	}
6591 
6592 	/* Do two passes - one to verify that we can obtain enough clusters
6593 	 * and another to actually claim them.
6594 	 */
6595 	clusters_needed = 0;
6596 	for (i = 0; i < _blob->active.num_clusters; i++) {
6597 		if (bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
6598 			clusters_needed++;
6599 		}
6600 	}
6601 
6602 	if (clusters_needed > _blob->bs->num_free_clusters) {
6603 		/* Not enough free clusters. Cannot satisfy the request. */
6604 		bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
6605 		return;
6606 	}
6607 
6608 	ctx->cluster = 0;
6609 	bs_inflate_blob_touch_next(ctx, 0);
6610 }
6611 
6612 static void
6613 bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6614 		spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
6615 {
6616 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6617 
6618 	if (!ctx) {
6619 		cb_fn(cb_arg, -ENOMEM);
6620 		return;
6621 	}
6622 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6623 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
6624 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
6625 	ctx->bserrno = 0;
6626 	ctx->original.id = blobid;
6627 	ctx->channel = channel;
6628 	ctx->allocate_all = allocate_all;
6629 
6630 	spdk_bs_open_blob(bs, ctx->original.id, bs_inflate_blob_open_cpl, ctx);
6631 }
6632 
6633 void
6634 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6635 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6636 {
6637 	bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
6638 }
6639 
6640 void
6641 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6642 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6643 {
6644 	bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
6645 }
6646 /* END spdk_bs_inflate_blob */
6647 
6648 /* START spdk_blob_resize */
6649 struct spdk_bs_resize_ctx {
6650 	spdk_blob_op_complete cb_fn;
6651 	void *cb_arg;
6652 	struct spdk_blob *blob;
6653 	uint64_t sz;
6654 	int rc;
6655 };
6656 
6657 static void
6658 bs_resize_unfreeze_cpl(void *cb_arg, int rc)
6659 {
6660 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6661 
6662 	if (rc != 0) {
6663 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
6664 	}
6665 
6666 	if (ctx->rc != 0) {
6667 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
6668 		rc = ctx->rc;
6669 	}
6670 
6671 	ctx->blob->locked_operation_in_progress = false;
6672 
6673 	ctx->cb_fn(ctx->cb_arg, rc);
6674 	free(ctx);
6675 }
6676 
6677 static void
6678 bs_resize_freeze_cpl(void *cb_arg, int rc)
6679 {
6680 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6681 
6682 	if (rc != 0) {
6683 		ctx->blob->locked_operation_in_progress = false;
6684 		ctx->cb_fn(ctx->cb_arg, rc);
6685 		free(ctx);
6686 		return;
6687 	}
6688 
6689 	ctx->rc = blob_resize(ctx->blob, ctx->sz);
6690 
6691 	blob_unfreeze_io(ctx->blob, bs_resize_unfreeze_cpl, ctx);
6692 }
6693 
6694 void
6695 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
6696 {
6697 	struct spdk_bs_resize_ctx *ctx;
6698 
6699 	blob_verify_md_op(blob);
6700 
6701 	SPDK_DEBUGLOG(blob, "Resizing blob 0x%" PRIx64 " to %" PRIu64 " clusters\n", blob->id, sz);
6702 
6703 	if (blob->md_ro) {
6704 		cb_fn(cb_arg, -EPERM);
6705 		return;
6706 	}
6707 
6708 	if (sz == blob->active.num_clusters) {
6709 		cb_fn(cb_arg, 0);
6710 		return;
6711 	}
6712 
6713 	if (blob->locked_operation_in_progress) {
6714 		cb_fn(cb_arg, -EBUSY);
6715 		return;
6716 	}
6717 
6718 	ctx = calloc(1, sizeof(*ctx));
6719 	if (!ctx) {
6720 		cb_fn(cb_arg, -ENOMEM);
6721 		return;
6722 	}
6723 
6724 	blob->locked_operation_in_progress = true;
6725 	ctx->cb_fn = cb_fn;
6726 	ctx->cb_arg = cb_arg;
6727 	ctx->blob = blob;
6728 	ctx->sz = sz;
6729 	blob_freeze_io(blob, bs_resize_freeze_cpl, ctx);
6730 }
6731 
6732 /* END spdk_blob_resize */
6733 
6734 
6735 /* START spdk_bs_delete_blob */
6736 
6737 static void
6738 bs_delete_close_cpl(void *cb_arg, int bserrno)
6739 {
6740 	spdk_bs_sequence_t *seq = cb_arg;
6741 
6742 	bs_sequence_finish(seq, bserrno);
6743 }
6744 
6745 static void
6746 bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6747 {
6748 	struct spdk_blob *blob = cb_arg;
6749 
6750 	if (bserrno != 0) {
6751 		/*
6752 		 * We already removed this blob from the blobstore tailq, so
6753 		 *  we need to free it here since this is the last reference
6754 		 *  to it.
6755 		 */
6756 		blob_free(blob);
6757 		bs_delete_close_cpl(seq, bserrno);
6758 		return;
6759 	}
6760 
6761 	/*
6762 	 * This will immediately decrement the ref_count and call
6763 	 *  the completion routine since the metadata state is clean.
6764 	 *  By calling spdk_blob_close, we reduce the number of call
6765 	 *  points into code that touches the blob->open_ref count
6766 	 *  and the blobstore's blob list.
6767 	 */
6768 	spdk_blob_close(blob, bs_delete_close_cpl, seq);
6769 }
6770 
6771 struct delete_snapshot_ctx {
6772 	struct spdk_blob_list *parent_snapshot_entry;
6773 	struct spdk_blob *snapshot;
6774 	struct spdk_blob_md_page *page;
6775 	bool snapshot_md_ro;
6776 	struct spdk_blob *clone;
6777 	bool clone_md_ro;
6778 	spdk_blob_op_with_handle_complete cb_fn;
6779 	void *cb_arg;
6780 	int bserrno;
6781 	uint32_t next_extent_page;
6782 };
6783 
6784 static void
6785 delete_blob_cleanup_finish(void *cb_arg, int bserrno)
6786 {
6787 	struct delete_snapshot_ctx *ctx = cb_arg;
6788 
6789 	if (bserrno != 0) {
6790 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
6791 	}
6792 
6793 	assert(ctx != NULL);
6794 
6795 	if (bserrno != 0 && ctx->bserrno == 0) {
6796 		ctx->bserrno = bserrno;
6797 	}
6798 
6799 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
6800 	spdk_free(ctx->page);
6801 	free(ctx);
6802 }
6803 
6804 static void
6805 delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
6806 {
6807 	struct delete_snapshot_ctx *ctx = cb_arg;
6808 
6809 	if (bserrno != 0) {
6810 		ctx->bserrno = bserrno;
6811 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
6812 	}
6813 
6814 	if (ctx->bserrno != 0) {
6815 		assert(blob_lookup(ctx->snapshot->bs, ctx->snapshot->id) == NULL);
6816 		RB_INSERT(spdk_blob_tree, &ctx->snapshot->bs->open_blobs, ctx->snapshot);
6817 		spdk_bit_array_set(ctx->snapshot->bs->open_blobids, ctx->snapshot->id);
6818 	}
6819 
6820 	ctx->snapshot->locked_operation_in_progress = false;
6821 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6822 
6823 	spdk_blob_close(ctx->snapshot, delete_blob_cleanup_finish, ctx);
6824 }
6825 
6826 static void
6827 delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
6828 {
6829 	struct delete_snapshot_ctx *ctx = cb_arg;
6830 
6831 	ctx->clone->locked_operation_in_progress = false;
6832 	ctx->clone->md_ro = ctx->clone_md_ro;
6833 
6834 	spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
6835 }
6836 
6837 static void
6838 delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
6839 {
6840 	struct delete_snapshot_ctx *ctx = cb_arg;
6841 
6842 	if (bserrno) {
6843 		ctx->bserrno = bserrno;
6844 		delete_snapshot_cleanup_clone(ctx, 0);
6845 		return;
6846 	}
6847 
6848 	ctx->clone->locked_operation_in_progress = false;
6849 	spdk_blob_close(ctx->clone, delete_blob_cleanup_finish, ctx);
6850 }
6851 
6852 static void
6853 delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
6854 {
6855 	struct delete_snapshot_ctx *ctx = cb_arg;
6856 	struct spdk_blob_list *parent_snapshot_entry = NULL;
6857 	struct spdk_blob_list *snapshot_entry = NULL;
6858 	struct spdk_blob_list *clone_entry = NULL;
6859 	struct spdk_blob_list *snapshot_clone_entry = NULL;
6860 
6861 	if (bserrno) {
6862 		SPDK_ERRLOG("Failed to sync MD on blob\n");
6863 		ctx->bserrno = bserrno;
6864 		delete_snapshot_cleanup_clone(ctx, 0);
6865 		return;
6866 	}
6867 
6868 	/* Get snapshot entry for the snapshot we want to remove */
6869 	snapshot_entry = bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
6870 
6871 	assert(snapshot_entry != NULL);
6872 
6873 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
6874 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6875 	assert(clone_entry != NULL);
6876 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
6877 	snapshot_entry->clone_count--;
6878 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
6879 
6880 	if (ctx->snapshot->parent_id != SPDK_BLOBID_INVALID) {
6881 		/* This snapshot is at the same time a clone of another snapshot - we need to
6882 		 * update parent snapshot (remove current clone, add new one inherited from
6883 		 * the snapshot that is being removed) */
6884 
6885 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
6886 		 * snapshot that we are removing */
6887 		blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
6888 						    &snapshot_clone_entry);
6889 
6890 		/* Switch clone entry in parent snapshot */
6891 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
6892 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
6893 		free(snapshot_clone_entry);
6894 	} else {
6895 		/* No parent snapshot - just remove clone entry */
6896 		free(clone_entry);
6897 	}
6898 
6899 	/* Restore md_ro flags */
6900 	ctx->clone->md_ro = ctx->clone_md_ro;
6901 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6902 
6903 	blob_unfreeze_io(ctx->clone, delete_snapshot_unfreeze_cpl, ctx);
6904 }
6905 
6906 static void
6907 delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
6908 {
6909 	struct delete_snapshot_ctx *ctx = cb_arg;
6910 	uint64_t i;
6911 
6912 	ctx->snapshot->md_ro = false;
6913 
6914 	if (bserrno) {
6915 		SPDK_ERRLOG("Failed to sync MD on clone\n");
6916 		ctx->bserrno = bserrno;
6917 
6918 		/* Restore snapshot to previous state */
6919 		bserrno = blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
6920 		if (bserrno != 0) {
6921 			delete_snapshot_cleanup_clone(ctx, bserrno);
6922 			return;
6923 		}
6924 
6925 		spdk_blob_sync_md(ctx->snapshot, delete_snapshot_cleanup_clone, ctx);
6926 		return;
6927 	}
6928 
6929 	/* Clear cluster map entries for snapshot */
6930 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
6931 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
6932 			ctx->snapshot->active.clusters[i] = 0;
6933 		}
6934 	}
6935 	for (i = 0; i < ctx->snapshot->active.num_extent_pages &&
6936 	     i < ctx->clone->active.num_extent_pages; i++) {
6937 		if (ctx->clone->active.extent_pages[i] == ctx->snapshot->active.extent_pages[i]) {
6938 			ctx->snapshot->active.extent_pages[i] = 0;
6939 		}
6940 	}
6941 
6942 	blob_set_thin_provision(ctx->snapshot);
6943 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
6944 
6945 	if (ctx->parent_snapshot_entry != NULL) {
6946 		ctx->snapshot->back_bs_dev = NULL;
6947 	}
6948 
6949 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_cpl, ctx);
6950 }
6951 
6952 static void
6953 delete_snapshot_update_extent_pages_cpl(struct delete_snapshot_ctx *ctx)
6954 {
6955 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
6956 	ctx->clone->back_bs_dev->destroy(ctx->clone->back_bs_dev);
6957 
6958 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
6959 	if (ctx->parent_snapshot_entry != NULL) {
6960 		/* ...to parent snapshot */
6961 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
6962 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
6963 		blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
6964 			       sizeof(spdk_blob_id),
6965 			       true);
6966 	} else {
6967 		/* ...to blobid invalid and zeroes dev */
6968 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
6969 		ctx->clone->back_bs_dev = bs_create_zeroes_dev();
6970 		blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
6971 	}
6972 
6973 	spdk_blob_sync_md(ctx->clone, delete_snapshot_sync_clone_cpl, ctx);
6974 }
6975 
6976 static void
6977 delete_snapshot_update_extent_pages(void *cb_arg, int bserrno)
6978 {
6979 	struct delete_snapshot_ctx *ctx = cb_arg;
6980 	uint32_t *extent_page;
6981 	uint64_t i;
6982 
6983 	for (i = ctx->next_extent_page; i < ctx->snapshot->active.num_extent_pages &&
6984 	     i < ctx->clone->active.num_extent_pages; i++) {
6985 		if (ctx->snapshot->active.extent_pages[i] == 0) {
6986 			/* No extent page to use from snapshot */
6987 			continue;
6988 		}
6989 
6990 		extent_page = &ctx->clone->active.extent_pages[i];
6991 		if (*extent_page == 0) {
6992 			/* Copy extent page from snapshot when clone did not have a matching one */
6993 			*extent_page = ctx->snapshot->active.extent_pages[i];
6994 			continue;
6995 		}
6996 
6997 		/* Clone and snapshot both contain partially filled matching extent pages.
6998 		 * Update the clone extent page in place with cluster map containing the mix of both. */
6999 		ctx->next_extent_page = i + 1;
7000 		memset(ctx->page, 0, SPDK_BS_PAGE_SIZE);
7001 
7002 		blob_write_extent_page(ctx->clone, *extent_page, i * SPDK_EXTENTS_PER_EP, ctx->page,
7003 				       delete_snapshot_update_extent_pages, ctx);
7004 		return;
7005 	}
7006 	delete_snapshot_update_extent_pages_cpl(ctx);
7007 }
7008 
7009 static void
7010 delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
7011 {
7012 	struct delete_snapshot_ctx *ctx = cb_arg;
7013 	uint64_t i;
7014 
7015 	/* Temporarily override md_ro flag for clone for MD modification */
7016 	ctx->clone_md_ro = ctx->clone->md_ro;
7017 	ctx->clone->md_ro = false;
7018 
7019 	if (bserrno) {
7020 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
7021 		ctx->bserrno = bserrno;
7022 		delete_snapshot_cleanup_clone(ctx, 0);
7023 		return;
7024 	}
7025 
7026 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
7027 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
7028 		if (ctx->clone->active.clusters[i] == 0) {
7029 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
7030 		}
7031 	}
7032 	ctx->next_extent_page = 0;
7033 	delete_snapshot_update_extent_pages(ctx, 0);
7034 }
7035 
7036 static void
7037 delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
7038 {
7039 	struct delete_snapshot_ctx *ctx = cb_arg;
7040 
7041 	if (bserrno) {
7042 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
7043 		ctx->bserrno = bserrno;
7044 		delete_snapshot_cleanup_clone(ctx, 0);
7045 		return;
7046 	}
7047 
7048 	/* Temporarily override md_ro flag for snapshot for MD modification */
7049 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
7050 	ctx->snapshot->md_ro = false;
7051 
7052 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
7053 	ctx->bserrno = blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
7054 				      sizeof(spdk_blob_id), true);
7055 	if (ctx->bserrno != 0) {
7056 		delete_snapshot_cleanup_clone(ctx, 0);
7057 		return;
7058 	}
7059 
7060 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_xattr_cpl, ctx);
7061 }
7062 
7063 static void
7064 delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
7065 {
7066 	struct delete_snapshot_ctx *ctx = cb_arg;
7067 
7068 	if (bserrno) {
7069 		SPDK_ERRLOG("Failed to open clone\n");
7070 		ctx->bserrno = bserrno;
7071 		delete_snapshot_cleanup_snapshot(ctx, 0);
7072 		return;
7073 	}
7074 
7075 	ctx->clone = clone;
7076 
7077 	if (clone->locked_operation_in_progress) {
7078 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress on its clone\n");
7079 		ctx->bserrno = -EBUSY;
7080 		spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
7081 		return;
7082 	}
7083 
7084 	clone->locked_operation_in_progress = true;
7085 
7086 	blob_freeze_io(clone, delete_snapshot_freeze_io_cb, ctx);
7087 }
7088 
7089 static void
7090 update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
7091 {
7092 	struct spdk_blob_list *snapshot_entry = NULL;
7093 	struct spdk_blob_list *clone_entry = NULL;
7094 	struct spdk_blob_list *snapshot_clone_entry = NULL;
7095 
7096 	/* Get snapshot entry for the snapshot we want to remove */
7097 	snapshot_entry = bs_get_snapshot_entry(snapshot->bs, snapshot->id);
7098 
7099 	assert(snapshot_entry != NULL);
7100 
7101 	/* Get clone of the snapshot (at this point there can be only one clone) */
7102 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
7103 	assert(snapshot_entry->clone_count == 1);
7104 	assert(clone_entry != NULL);
7105 
7106 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
7107 	 * snapshot that we are removing */
7108 	blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
7109 					    &snapshot_clone_entry);
7110 
7111 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, delete_snapshot_open_clone_cb, ctx);
7112 }
7113 
7114 static void
7115 bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
7116 {
7117 	spdk_bs_sequence_t *seq = cb_arg;
7118 	struct spdk_blob_list *snapshot_entry = NULL;
7119 	uint32_t page_num;
7120 
7121 	if (bserrno) {
7122 		SPDK_ERRLOG("Failed to remove blob\n");
7123 		bs_sequence_finish(seq, bserrno);
7124 		return;
7125 	}
7126 
7127 	/* Remove snapshot from the list */
7128 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7129 	if (snapshot_entry != NULL) {
7130 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
7131 		free(snapshot_entry);
7132 	}
7133 
7134 	page_num = bs_blobid_to_page(blob->id);
7135 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
7136 	blob->state = SPDK_BLOB_STATE_DIRTY;
7137 	blob->active.num_pages = 0;
7138 	blob_resize(blob, 0);
7139 
7140 	blob_persist(seq, blob, bs_delete_persist_cpl, blob);
7141 }
7142 
7143 static int
7144 bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
7145 {
7146 	struct spdk_blob_list *snapshot_entry = NULL;
7147 	struct spdk_blob_list *clone_entry = NULL;
7148 	struct spdk_blob *clone = NULL;
7149 	bool has_one_clone = false;
7150 
7151 	/* Check if this is a snapshot with clones */
7152 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7153 	if (snapshot_entry != NULL) {
7154 		if (snapshot_entry->clone_count > 1) {
7155 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
7156 			return -EBUSY;
7157 		} else if (snapshot_entry->clone_count == 1) {
7158 			has_one_clone = true;
7159 		}
7160 	}
7161 
7162 	/* Check if someone has this blob open (besides this delete context):
7163 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
7164 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
7165 	 *	and that is ok, because we will update it accordingly */
7166 	if (blob->open_ref <= 2 && has_one_clone) {
7167 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
7168 		assert(clone_entry != NULL);
7169 		clone = blob_lookup(blob->bs, clone_entry->id);
7170 
7171 		if (blob->open_ref == 2 && clone == NULL) {
7172 			/* Clone is closed and someone else opened this blob */
7173 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
7174 			return -EBUSY;
7175 		}
7176 
7177 		*update_clone = true;
7178 		return 0;
7179 	}
7180 
7181 	if (blob->open_ref > 1) {
7182 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
7183 		return -EBUSY;
7184 	}
7185 
7186 	assert(has_one_clone == false);
7187 	*update_clone = false;
7188 	return 0;
7189 }
7190 
7191 static void
7192 bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
7193 {
7194 	spdk_bs_sequence_t *seq = cb_arg;
7195 
7196 	bs_sequence_finish(seq, -ENOMEM);
7197 }
7198 
7199 static void
7200 bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
7201 {
7202 	spdk_bs_sequence_t *seq = cb_arg;
7203 	struct delete_snapshot_ctx *ctx;
7204 	bool update_clone = false;
7205 
7206 	if (bserrno != 0) {
7207 		bs_sequence_finish(seq, bserrno);
7208 		return;
7209 	}
7210 
7211 	blob_verify_md_op(blob);
7212 
7213 	ctx = calloc(1, sizeof(*ctx));
7214 	if (ctx == NULL) {
7215 		spdk_blob_close(blob, bs_delete_enomem_close_cpl, seq);
7216 		return;
7217 	}
7218 
7219 	ctx->snapshot = blob;
7220 	ctx->cb_fn = bs_delete_blob_finish;
7221 	ctx->cb_arg = seq;
7222 
7223 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
7224 	ctx->bserrno = bs_is_blob_deletable(blob, &update_clone);
7225 	if (ctx->bserrno) {
7226 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7227 		return;
7228 	}
7229 
7230 	if (blob->locked_operation_in_progress) {
7231 		SPDK_DEBUGLOG(blob, "Cannot remove blob - another operation in progress\n");
7232 		ctx->bserrno = -EBUSY;
7233 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7234 		return;
7235 	}
7236 
7237 	blob->locked_operation_in_progress = true;
7238 
7239 	/*
7240 	 * Remove the blob from the blob_store list now, to ensure it does not
7241 	 *  get returned after this point by blob_lookup().
7242 	 */
7243 	spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
7244 	RB_REMOVE(spdk_blob_tree, &blob->bs->open_blobs, blob);
7245 
7246 	if (update_clone) {
7247 		ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, 0, NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
7248 		if (!ctx->page) {
7249 			ctx->bserrno = -ENOMEM;
7250 			spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
7251 			return;
7252 		}
7253 		/* This blob is a snapshot with active clone - update clone first */
7254 		update_clone_on_snapshot_deletion(blob, ctx);
7255 	} else {
7256 		/* This blob does not have any clones - just remove it */
7257 		bs_blob_list_remove(blob);
7258 		bs_delete_blob_finish(seq, blob, 0);
7259 		free(ctx);
7260 	}
7261 }
7262 
7263 void
7264 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
7265 		    spdk_blob_op_complete cb_fn, void *cb_arg)
7266 {
7267 	struct spdk_bs_cpl	cpl;
7268 	spdk_bs_sequence_t	*seq;
7269 
7270 	SPDK_DEBUGLOG(blob, "Deleting blob 0x%" PRIx64 "\n", blobid);
7271 
7272 	assert(spdk_get_thread() == bs->md_thread);
7273 
7274 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7275 	cpl.u.blob_basic.cb_fn = cb_fn;
7276 	cpl.u.blob_basic.cb_arg = cb_arg;
7277 
7278 	seq = bs_sequence_start(bs->md_channel, &cpl);
7279 	if (!seq) {
7280 		cb_fn(cb_arg, -ENOMEM);
7281 		return;
7282 	}
7283 
7284 	spdk_bs_open_blob(bs, blobid, bs_delete_open_cpl, seq);
7285 }
7286 
7287 /* END spdk_bs_delete_blob */
7288 
7289 /* START spdk_bs_open_blob */
7290 
7291 static void
7292 bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7293 {
7294 	struct spdk_blob *blob = cb_arg;
7295 	struct spdk_blob *existing;
7296 
7297 	if (bserrno != 0) {
7298 		blob_free(blob);
7299 		seq->cpl.u.blob_handle.blob = NULL;
7300 		bs_sequence_finish(seq, bserrno);
7301 		return;
7302 	}
7303 
7304 	existing = blob_lookup(blob->bs, blob->id);
7305 	if (existing) {
7306 		blob_free(blob);
7307 		existing->open_ref++;
7308 		seq->cpl.u.blob_handle.blob = existing;
7309 		bs_sequence_finish(seq, 0);
7310 		return;
7311 	}
7312 
7313 	blob->open_ref++;
7314 
7315 	spdk_bit_array_set(blob->bs->open_blobids, blob->id);
7316 	RB_INSERT(spdk_blob_tree, &blob->bs->open_blobs, blob);
7317 
7318 	bs_sequence_finish(seq, bserrno);
7319 }
7320 
7321 static inline void
7322 blob_open_opts_copy(const struct spdk_blob_open_opts *src, struct spdk_blob_open_opts *dst)
7323 {
7324 #define FIELD_OK(field) \
7325         offsetof(struct spdk_blob_open_opts, field) + sizeof(src->field) <= src->opts_size
7326 
7327 #define SET_FIELD(field) \
7328         if (FIELD_OK(field)) { \
7329                 dst->field = src->field; \
7330         } \
7331 
7332 	SET_FIELD(clear_method);
7333 
7334 	dst->opts_size = src->opts_size;
7335 
7336 	/* You should not remove this statement, but need to update the assert statement
7337 	 * if you add a new field, and also add a corresponding SET_FIELD statement */
7338 	SPDK_STATIC_ASSERT(sizeof(struct spdk_blob_open_opts) == 16, "Incorrect size");
7339 
7340 #undef FIELD_OK
7341 #undef SET_FIELD
7342 }
7343 
7344 static void
7345 bs_open_blob(struct spdk_blob_store *bs,
7346 	     spdk_blob_id blobid,
7347 	     struct spdk_blob_open_opts *opts,
7348 	     spdk_blob_op_with_handle_complete cb_fn,
7349 	     void *cb_arg)
7350 {
7351 	struct spdk_blob		*blob;
7352 	struct spdk_bs_cpl		cpl;
7353 	struct spdk_blob_open_opts	opts_local;
7354 	spdk_bs_sequence_t		*seq;
7355 	uint32_t			page_num;
7356 
7357 	SPDK_DEBUGLOG(blob, "Opening blob 0x%" PRIx64 "\n", blobid);
7358 	assert(spdk_get_thread() == bs->md_thread);
7359 
7360 	page_num = bs_blobid_to_page(blobid);
7361 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
7362 		/* Invalid blobid */
7363 		cb_fn(cb_arg, NULL, -ENOENT);
7364 		return;
7365 	}
7366 
7367 	blob = blob_lookup(bs, blobid);
7368 	if (blob) {
7369 		blob->open_ref++;
7370 		cb_fn(cb_arg, blob, 0);
7371 		return;
7372 	}
7373 
7374 	blob = blob_alloc(bs, blobid);
7375 	if (!blob) {
7376 		cb_fn(cb_arg, NULL, -ENOMEM);
7377 		return;
7378 	}
7379 
7380 	spdk_blob_open_opts_init(&opts_local, sizeof(opts_local));
7381 	if (opts) {
7382 		blob_open_opts_copy(opts, &opts_local);
7383 	}
7384 
7385 	blob->clear_method = opts_local.clear_method;
7386 
7387 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
7388 	cpl.u.blob_handle.cb_fn = cb_fn;
7389 	cpl.u.blob_handle.cb_arg = cb_arg;
7390 	cpl.u.blob_handle.blob = blob;
7391 
7392 	seq = bs_sequence_start(bs->md_channel, &cpl);
7393 	if (!seq) {
7394 		blob_free(blob);
7395 		cb_fn(cb_arg, NULL, -ENOMEM);
7396 		return;
7397 	}
7398 
7399 	blob_load(seq, blob, bs_open_blob_cpl, blob);
7400 }
7401 
7402 void
7403 spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
7404 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7405 {
7406 	bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
7407 }
7408 
7409 void
7410 spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
7411 		      struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7412 {
7413 	bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
7414 }
7415 
7416 /* END spdk_bs_open_blob */
7417 
7418 /* START spdk_blob_set_read_only */
7419 int
7420 spdk_blob_set_read_only(struct spdk_blob *blob)
7421 {
7422 	blob_verify_md_op(blob);
7423 
7424 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
7425 
7426 	blob->state = SPDK_BLOB_STATE_DIRTY;
7427 	return 0;
7428 }
7429 /* END spdk_blob_set_read_only */
7430 
7431 /* START spdk_blob_sync_md */
7432 
7433 static void
7434 blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7435 {
7436 	struct spdk_blob *blob = cb_arg;
7437 
7438 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
7439 		blob->data_ro = true;
7440 		blob->md_ro = true;
7441 	}
7442 
7443 	bs_sequence_finish(seq, bserrno);
7444 }
7445 
7446 static void
7447 blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7448 {
7449 	struct spdk_bs_cpl	cpl;
7450 	spdk_bs_sequence_t	*seq;
7451 
7452 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7453 	cpl.u.blob_basic.cb_fn = cb_fn;
7454 	cpl.u.blob_basic.cb_arg = cb_arg;
7455 
7456 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7457 	if (!seq) {
7458 		cb_fn(cb_arg, -ENOMEM);
7459 		return;
7460 	}
7461 
7462 	blob_persist(seq, blob, blob_sync_md_cpl, blob);
7463 }
7464 
7465 void
7466 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7467 {
7468 	blob_verify_md_op(blob);
7469 
7470 	SPDK_DEBUGLOG(blob, "Syncing blob 0x%" PRIx64 "\n", blob->id);
7471 
7472 	if (blob->md_ro) {
7473 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
7474 		cb_fn(cb_arg, 0);
7475 		return;
7476 	}
7477 
7478 	blob_sync_md(blob, cb_fn, cb_arg);
7479 }
7480 
7481 /* END spdk_blob_sync_md */
7482 
7483 struct spdk_blob_insert_cluster_ctx {
7484 	struct spdk_thread	*thread;
7485 	struct spdk_blob	*blob;
7486 	uint32_t		cluster_num;	/* cluster index in blob */
7487 	uint32_t		cluster;	/* cluster on disk */
7488 	uint32_t		extent_page;	/* extent page on disk */
7489 	struct spdk_blob_md_page *page; /* preallocated extent page */
7490 	int			rc;
7491 	spdk_blob_op_complete	cb_fn;
7492 	void			*cb_arg;
7493 };
7494 
7495 static void
7496 blob_insert_cluster_msg_cpl(void *arg)
7497 {
7498 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7499 
7500 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
7501 	free(ctx);
7502 }
7503 
7504 static void
7505 blob_insert_cluster_msg_cb(void *arg, int bserrno)
7506 {
7507 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7508 
7509 	ctx->rc = bserrno;
7510 	spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7511 }
7512 
7513 static void
7514 blob_insert_new_ep_cb(void *arg, int bserrno)
7515 {
7516 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7517 	uint32_t *extent_page;
7518 
7519 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7520 	*extent_page = ctx->extent_page;
7521 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7522 	blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7523 }
7524 
7525 struct spdk_blob_write_extent_page_ctx {
7526 	struct spdk_blob_store		*bs;
7527 
7528 	uint32_t			extent;
7529 	struct spdk_blob_md_page	*page;
7530 };
7531 
7532 static void
7533 blob_persist_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7534 {
7535 	struct spdk_blob_write_extent_page_ctx *ctx = cb_arg;
7536 
7537 	free(ctx);
7538 	bs_sequence_finish(seq, bserrno);
7539 }
7540 
7541 static void
7542 blob_write_extent_page_ready(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7543 {
7544 	struct spdk_blob_write_extent_page_ctx *ctx = cb_arg;
7545 
7546 	if (bserrno != 0) {
7547 		blob_persist_extent_page_cpl(seq, ctx, bserrno);
7548 		return;
7549 	}
7550 	bs_sequence_write_dev(seq, ctx->page, bs_md_page_to_lba(ctx->bs, ctx->extent),
7551 			      bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
7552 			      blob_persist_extent_page_cpl, ctx);
7553 }
7554 
7555 static void
7556 blob_write_extent_page(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
7557 		       struct spdk_blob_md_page *page, spdk_blob_op_complete cb_fn, void *cb_arg)
7558 {
7559 	struct spdk_blob_write_extent_page_ctx	*ctx;
7560 	spdk_bs_sequence_t			*seq;
7561 	struct spdk_bs_cpl			cpl;
7562 
7563 	ctx = calloc(1, sizeof(*ctx));
7564 	if (!ctx) {
7565 		cb_fn(cb_arg, -ENOMEM);
7566 		return;
7567 	}
7568 	ctx->bs = blob->bs;
7569 	ctx->extent = extent;
7570 	ctx->page = page;
7571 
7572 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7573 	cpl.u.blob_basic.cb_fn = cb_fn;
7574 	cpl.u.blob_basic.cb_arg = cb_arg;
7575 
7576 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7577 	if (!seq) {
7578 		free(ctx);
7579 		cb_fn(cb_arg, -ENOMEM);
7580 		return;
7581 	}
7582 
7583 	assert(page);
7584 	page->next = SPDK_INVALID_MD_PAGE;
7585 	page->id = blob->id;
7586 	page->sequence_num = 0;
7587 
7588 	blob_serialize_extent_page(blob, cluster_num, page);
7589 
7590 	page->crc = blob_md_page_calc_crc(page);
7591 
7592 	assert(spdk_bit_array_get(blob->bs->used_md_pages, extent) == true);
7593 
7594 	bs_mark_dirty(seq, blob->bs, blob_write_extent_page_ready, ctx);
7595 }
7596 
7597 static void
7598 blob_insert_cluster_msg(void *arg)
7599 {
7600 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
7601 	uint32_t *extent_page;
7602 
7603 	ctx->rc = blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
7604 	if (ctx->rc != 0) {
7605 		spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
7606 		return;
7607 	}
7608 
7609 	if (ctx->blob->use_extent_table == false) {
7610 		/* Extent table is not used, proceed with sync of md that will only use extents_rle. */
7611 		ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
7612 		blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
7613 		return;
7614 	}
7615 
7616 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
7617 	if (*extent_page == 0) {
7618 		/* Extent page requires allocation.
7619 		 * It was already claimed in the used_md_pages map and placed in ctx. */
7620 		assert(ctx->extent_page != 0);
7621 		assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7622 		blob_write_extent_page(ctx->blob, ctx->extent_page, ctx->cluster_num, ctx->page,
7623 				       blob_insert_new_ep_cb, ctx);
7624 	} else {
7625 		/* It is possible for original thread to allocate extent page for
7626 		 * different cluster in the same extent page. In such case proceed with
7627 		 * updating the existing extent page, but release the additional one. */
7628 		if (ctx->extent_page != 0) {
7629 			spdk_spin_lock(&ctx->blob->bs->used_lock);
7630 			assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
7631 			bs_release_md_page(ctx->blob->bs, ctx->extent_page);
7632 			spdk_spin_unlock(&ctx->blob->bs->used_lock);
7633 			ctx->extent_page = 0;
7634 		}
7635 		/* Extent page already allocated.
7636 		 * Every cluster allocation, requires just an update of single extent page. */
7637 		blob_write_extent_page(ctx->blob, *extent_page, ctx->cluster_num, ctx->page,
7638 				       blob_insert_cluster_msg_cb, ctx);
7639 	}
7640 }
7641 
7642 static void
7643 blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
7644 				 uint64_t cluster, uint32_t extent_page, struct spdk_blob_md_page *page,
7645 				 spdk_blob_op_complete cb_fn, void *cb_arg)
7646 {
7647 	struct spdk_blob_insert_cluster_ctx *ctx;
7648 
7649 	ctx = calloc(1, sizeof(*ctx));
7650 	if (ctx == NULL) {
7651 		cb_fn(cb_arg, -ENOMEM);
7652 		return;
7653 	}
7654 
7655 	ctx->thread = spdk_get_thread();
7656 	ctx->blob = blob;
7657 	ctx->cluster_num = cluster_num;
7658 	ctx->cluster = cluster;
7659 	ctx->extent_page = extent_page;
7660 	ctx->page = page;
7661 	ctx->cb_fn = cb_fn;
7662 	ctx->cb_arg = cb_arg;
7663 
7664 	spdk_thread_send_msg(blob->bs->md_thread, blob_insert_cluster_msg, ctx);
7665 }
7666 
7667 /* START spdk_blob_close */
7668 
7669 static void
7670 blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
7671 {
7672 	struct spdk_blob *blob = cb_arg;
7673 
7674 	if (bserrno == 0) {
7675 		blob->open_ref--;
7676 		if (blob->open_ref == 0) {
7677 			/*
7678 			 * Blobs with active.num_pages == 0 are deleted blobs.
7679 			 *  these blobs are removed from the blob_store list
7680 			 *  when the deletion process starts - so don't try to
7681 			 *  remove them again.
7682 			 */
7683 			if (blob->active.num_pages > 0) {
7684 				spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
7685 				RB_REMOVE(spdk_blob_tree, &blob->bs->open_blobs, blob);
7686 			}
7687 			blob_free(blob);
7688 		}
7689 	}
7690 
7691 	bs_sequence_finish(seq, bserrno);
7692 }
7693 
7694 void
7695 spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
7696 {
7697 	struct spdk_bs_cpl	cpl;
7698 	spdk_bs_sequence_t	*seq;
7699 
7700 	blob_verify_md_op(blob);
7701 
7702 	SPDK_DEBUGLOG(blob, "Closing blob 0x%" PRIx64 "\n", blob->id);
7703 
7704 	if (blob->open_ref == 0) {
7705 		cb_fn(cb_arg, -EBADF);
7706 		return;
7707 	}
7708 
7709 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
7710 	cpl.u.blob_basic.cb_fn = cb_fn;
7711 	cpl.u.blob_basic.cb_arg = cb_arg;
7712 
7713 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7714 	if (!seq) {
7715 		cb_fn(cb_arg, -ENOMEM);
7716 		return;
7717 	}
7718 
7719 	/* Sync metadata */
7720 	blob_persist(seq, blob, blob_close_cpl, blob);
7721 }
7722 
7723 /* END spdk_blob_close */
7724 
7725 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
7726 {
7727 	return spdk_get_io_channel(bs);
7728 }
7729 
7730 void
7731 spdk_bs_free_io_channel(struct spdk_io_channel *channel)
7732 {
7733 	spdk_put_io_channel(channel);
7734 }
7735 
7736 void
7737 spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
7738 		   uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7739 {
7740 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7741 			       SPDK_BLOB_UNMAP);
7742 }
7743 
7744 void
7745 spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
7746 			  uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7747 {
7748 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7749 			       SPDK_BLOB_WRITE_ZEROES);
7750 }
7751 
7752 void
7753 spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
7754 		   void *payload, uint64_t offset, uint64_t length,
7755 		   spdk_blob_op_complete cb_fn, void *cb_arg)
7756 {
7757 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7758 			       SPDK_BLOB_WRITE);
7759 }
7760 
7761 void
7762 spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
7763 		  void *payload, uint64_t offset, uint64_t length,
7764 		  spdk_blob_op_complete cb_fn, void *cb_arg)
7765 {
7766 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7767 			       SPDK_BLOB_READ);
7768 }
7769 
7770 void
7771 spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
7772 		    struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7773 		    spdk_blob_op_complete cb_fn, void *cb_arg)
7774 {
7775 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false, NULL);
7776 }
7777 
7778 void
7779 spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
7780 		   struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7781 		   spdk_blob_op_complete cb_fn, void *cb_arg)
7782 {
7783 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true, NULL);
7784 }
7785 
7786 void
7787 spdk_blob_io_writev_ext(struct spdk_blob *blob, struct spdk_io_channel *channel,
7788 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7789 			spdk_blob_op_complete cb_fn, void *cb_arg, struct spdk_blob_ext_io_opts *io_opts)
7790 {
7791 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false,
7792 				   io_opts);
7793 }
7794 
7795 void
7796 spdk_blob_io_readv_ext(struct spdk_blob *blob, struct spdk_io_channel *channel,
7797 		       struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7798 		       spdk_blob_op_complete cb_fn, void *cb_arg, struct spdk_blob_ext_io_opts *io_opts)
7799 {
7800 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true,
7801 				   io_opts);
7802 }
7803 
7804 struct spdk_bs_iter_ctx {
7805 	int64_t page_num;
7806 	struct spdk_blob_store *bs;
7807 
7808 	spdk_blob_op_with_handle_complete cb_fn;
7809 	void *cb_arg;
7810 };
7811 
7812 static void
7813 bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
7814 {
7815 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7816 	struct spdk_blob_store *bs = ctx->bs;
7817 	spdk_blob_id id;
7818 
7819 	if (bserrno == 0) {
7820 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
7821 		free(ctx);
7822 		return;
7823 	}
7824 
7825 	ctx->page_num++;
7826 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
7827 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
7828 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
7829 		free(ctx);
7830 		return;
7831 	}
7832 
7833 	id = bs_page_to_blobid(ctx->page_num);
7834 
7835 	spdk_bs_open_blob(bs, id, bs_iter_cpl, ctx);
7836 }
7837 
7838 void
7839 spdk_bs_iter_first(struct spdk_blob_store *bs,
7840 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7841 {
7842 	struct spdk_bs_iter_ctx *ctx;
7843 
7844 	ctx = calloc(1, sizeof(*ctx));
7845 	if (!ctx) {
7846 		cb_fn(cb_arg, NULL, -ENOMEM);
7847 		return;
7848 	}
7849 
7850 	ctx->page_num = -1;
7851 	ctx->bs = bs;
7852 	ctx->cb_fn = cb_fn;
7853 	ctx->cb_arg = cb_arg;
7854 
7855 	bs_iter_cpl(ctx, NULL, -1);
7856 }
7857 
7858 static void
7859 bs_iter_close_cpl(void *cb_arg, int bserrno)
7860 {
7861 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7862 
7863 	bs_iter_cpl(ctx, NULL, -1);
7864 }
7865 
7866 void
7867 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
7868 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7869 {
7870 	struct spdk_bs_iter_ctx *ctx;
7871 
7872 	assert(blob != NULL);
7873 
7874 	ctx = calloc(1, sizeof(*ctx));
7875 	if (!ctx) {
7876 		cb_fn(cb_arg, NULL, -ENOMEM);
7877 		return;
7878 	}
7879 
7880 	ctx->page_num = bs_blobid_to_page(blob->id);
7881 	ctx->bs = bs;
7882 	ctx->cb_fn = cb_fn;
7883 	ctx->cb_arg = cb_arg;
7884 
7885 	/* Close the existing blob */
7886 	spdk_blob_close(blob, bs_iter_close_cpl, ctx);
7887 }
7888 
7889 static int
7890 blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7891 	       uint16_t value_len, bool internal)
7892 {
7893 	struct spdk_xattr_tailq *xattrs;
7894 	struct spdk_xattr	*xattr;
7895 	size_t			desc_size;
7896 	void			*tmp;
7897 
7898 	blob_verify_md_op(blob);
7899 
7900 	if (blob->md_ro) {
7901 		return -EPERM;
7902 	}
7903 
7904 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
7905 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
7906 		SPDK_DEBUGLOG(blob, "Xattr '%s' of size %zu does not fix into single page %zu\n", name,
7907 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
7908 		return -ENOMEM;
7909 	}
7910 
7911 	if (internal) {
7912 		xattrs = &blob->xattrs_internal;
7913 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
7914 	} else {
7915 		xattrs = &blob->xattrs;
7916 	}
7917 
7918 	TAILQ_FOREACH(xattr, xattrs, link) {
7919 		if (!strcmp(name, xattr->name)) {
7920 			tmp = malloc(value_len);
7921 			if (!tmp) {
7922 				return -ENOMEM;
7923 			}
7924 
7925 			free(xattr->value);
7926 			xattr->value_len = value_len;
7927 			xattr->value = tmp;
7928 			memcpy(xattr->value, value, value_len);
7929 
7930 			blob->state = SPDK_BLOB_STATE_DIRTY;
7931 
7932 			return 0;
7933 		}
7934 	}
7935 
7936 	xattr = calloc(1, sizeof(*xattr));
7937 	if (!xattr) {
7938 		return -ENOMEM;
7939 	}
7940 
7941 	xattr->name = strdup(name);
7942 	if (!xattr->name) {
7943 		free(xattr);
7944 		return -ENOMEM;
7945 	}
7946 
7947 	xattr->value_len = value_len;
7948 	xattr->value = malloc(value_len);
7949 	if (!xattr->value) {
7950 		free(xattr->name);
7951 		free(xattr);
7952 		return -ENOMEM;
7953 	}
7954 	memcpy(xattr->value, value, value_len);
7955 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
7956 
7957 	blob->state = SPDK_BLOB_STATE_DIRTY;
7958 
7959 	return 0;
7960 }
7961 
7962 int
7963 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7964 		    uint16_t value_len)
7965 {
7966 	return blob_set_xattr(blob, name, value, value_len, false);
7967 }
7968 
7969 static int
7970 blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
7971 {
7972 	struct spdk_xattr_tailq *xattrs;
7973 	struct spdk_xattr	*xattr;
7974 
7975 	blob_verify_md_op(blob);
7976 
7977 	if (blob->md_ro) {
7978 		return -EPERM;
7979 	}
7980 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
7981 
7982 	TAILQ_FOREACH(xattr, xattrs, link) {
7983 		if (!strcmp(name, xattr->name)) {
7984 			TAILQ_REMOVE(xattrs, xattr, link);
7985 			free(xattr->value);
7986 			free(xattr->name);
7987 			free(xattr);
7988 
7989 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
7990 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
7991 			}
7992 			blob->state = SPDK_BLOB_STATE_DIRTY;
7993 
7994 			return 0;
7995 		}
7996 	}
7997 
7998 	return -ENOENT;
7999 }
8000 
8001 int
8002 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
8003 {
8004 	return blob_remove_xattr(blob, name, false);
8005 }
8006 
8007 static int
8008 blob_get_xattr_value(struct spdk_blob *blob, const char *name,
8009 		     const void **value, size_t *value_len, bool internal)
8010 {
8011 	struct spdk_xattr	*xattr;
8012 	struct spdk_xattr_tailq *xattrs;
8013 
8014 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
8015 
8016 	TAILQ_FOREACH(xattr, xattrs, link) {
8017 		if (!strcmp(name, xattr->name)) {
8018 			*value = xattr->value;
8019 			*value_len = xattr->value_len;
8020 			return 0;
8021 		}
8022 	}
8023 	return -ENOENT;
8024 }
8025 
8026 int
8027 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
8028 			  const void **value, size_t *value_len)
8029 {
8030 	blob_verify_md_op(blob);
8031 
8032 	return blob_get_xattr_value(blob, name, value, value_len, false);
8033 }
8034 
8035 struct spdk_xattr_names {
8036 	uint32_t	count;
8037 	const char	*names[0];
8038 };
8039 
8040 static int
8041 blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
8042 {
8043 	struct spdk_xattr	*xattr;
8044 	int			count = 0;
8045 
8046 	TAILQ_FOREACH(xattr, xattrs, link) {
8047 		count++;
8048 	}
8049 
8050 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
8051 	if (*names == NULL) {
8052 		return -ENOMEM;
8053 	}
8054 
8055 	TAILQ_FOREACH(xattr, xattrs, link) {
8056 		(*names)->names[(*names)->count++] = xattr->name;
8057 	}
8058 
8059 	return 0;
8060 }
8061 
8062 int
8063 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
8064 {
8065 	blob_verify_md_op(blob);
8066 
8067 	return blob_get_xattr_names(&blob->xattrs, names);
8068 }
8069 
8070 uint32_t
8071 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
8072 {
8073 	assert(names != NULL);
8074 
8075 	return names->count;
8076 }
8077 
8078 const char *
8079 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
8080 {
8081 	if (index >= names->count) {
8082 		return NULL;
8083 	}
8084 
8085 	return names->names[index];
8086 }
8087 
8088 void
8089 spdk_xattr_names_free(struct spdk_xattr_names *names)
8090 {
8091 	free(names);
8092 }
8093 
8094 struct spdk_bs_type
8095 spdk_bs_get_bstype(struct spdk_blob_store *bs)
8096 {
8097 	return bs->bstype;
8098 }
8099 
8100 void
8101 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
8102 {
8103 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
8104 }
8105 
8106 bool
8107 spdk_blob_is_read_only(struct spdk_blob *blob)
8108 {
8109 	assert(blob != NULL);
8110 	return (blob->data_ro || blob->md_ro);
8111 }
8112 
8113 bool
8114 spdk_blob_is_snapshot(struct spdk_blob *blob)
8115 {
8116 	struct spdk_blob_list *snapshot_entry;
8117 
8118 	assert(blob != NULL);
8119 
8120 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
8121 	if (snapshot_entry == NULL) {
8122 		return false;
8123 	}
8124 
8125 	return true;
8126 }
8127 
8128 bool
8129 spdk_blob_is_clone(struct spdk_blob *blob)
8130 {
8131 	assert(blob != NULL);
8132 
8133 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
8134 		assert(spdk_blob_is_thin_provisioned(blob));
8135 		return true;
8136 	}
8137 
8138 	return false;
8139 }
8140 
8141 bool
8142 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
8143 {
8144 	assert(blob != NULL);
8145 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
8146 }
8147 
8148 static void
8149 blob_update_clear_method(struct spdk_blob *blob)
8150 {
8151 	enum blob_clear_method stored_cm;
8152 
8153 	assert(blob != NULL);
8154 
8155 	/* If BLOB_CLEAR_WITH_DEFAULT was passed in, use the setting stored
8156 	 * in metadata previously.  If something other than the default was
8157 	 * specified, ignore stored value and used what was passed in.
8158 	 */
8159 	stored_cm = ((blob->md_ro_flags & SPDK_BLOB_CLEAR_METHOD) >> SPDK_BLOB_CLEAR_METHOD_SHIFT);
8160 
8161 	if (blob->clear_method == BLOB_CLEAR_WITH_DEFAULT) {
8162 		blob->clear_method = stored_cm;
8163 	} else if (blob->clear_method != stored_cm) {
8164 		SPDK_WARNLOG("Using passed in clear method 0x%x instead of stored value of 0x%x\n",
8165 			     blob->clear_method, stored_cm);
8166 	}
8167 }
8168 
8169 spdk_blob_id
8170 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
8171 {
8172 	struct spdk_blob_list *snapshot_entry = NULL;
8173 	struct spdk_blob_list *clone_entry = NULL;
8174 
8175 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
8176 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
8177 			if (clone_entry->id == blob_id) {
8178 				return snapshot_entry->id;
8179 			}
8180 		}
8181 	}
8182 
8183 	return SPDK_BLOBID_INVALID;
8184 }
8185 
8186 int
8187 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
8188 		     size_t *count)
8189 {
8190 	struct spdk_blob_list *snapshot_entry, *clone_entry;
8191 	size_t n;
8192 
8193 	snapshot_entry = bs_get_snapshot_entry(bs, blobid);
8194 	if (snapshot_entry == NULL) {
8195 		*count = 0;
8196 		return 0;
8197 	}
8198 
8199 	if (ids == NULL || *count < snapshot_entry->clone_count) {
8200 		*count = snapshot_entry->clone_count;
8201 		return -ENOMEM;
8202 	}
8203 	*count = snapshot_entry->clone_count;
8204 
8205 	n = 0;
8206 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
8207 		ids[n++] = clone_entry->id;
8208 	}
8209 
8210 	return 0;
8211 }
8212 
8213 static void
8214 bs_load_grow_continue(struct spdk_bs_load_ctx *ctx)
8215 {
8216 	int rc;
8217 
8218 	if (ctx->super->size == 0) {
8219 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8220 	}
8221 
8222 	if (ctx->super->io_unit_size == 0) {
8223 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
8224 	}
8225 
8226 	/* Parse the super block */
8227 	ctx->bs->clean = 1;
8228 	ctx->bs->cluster_sz = ctx->super->cluster_size;
8229 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
8230 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
8231 	if (spdk_u32_is_pow2(ctx->bs->pages_per_cluster)) {
8232 		ctx->bs->pages_per_cluster_shift = spdk_u32log2(ctx->bs->pages_per_cluster);
8233 	}
8234 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
8235 	rc = spdk_bit_array_resize(&ctx->used_clusters, ctx->bs->total_clusters);
8236 	if (rc < 0) {
8237 		bs_load_ctx_fail(ctx, -ENOMEM);
8238 		return;
8239 	}
8240 	ctx->bs->md_start = ctx->super->md_start;
8241 	ctx->bs->md_len = ctx->super->md_len;
8242 	rc = spdk_bit_array_resize(&ctx->bs->open_blobids, ctx->bs->md_len);
8243 	if (rc < 0) {
8244 		bs_load_ctx_fail(ctx, -ENOMEM);
8245 		return;
8246 	}
8247 
8248 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
8249 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
8250 	ctx->bs->super_blob = ctx->super->super_blob;
8251 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
8252 
8253 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0) {
8254 		SPDK_ERRLOG("Can not grow an unclean blobstore, please load it normally to clean it.\n");
8255 		bs_load_ctx_fail(ctx, -EIO);
8256 		return;
8257 	} else {
8258 		bs_load_read_used_pages(ctx);
8259 	}
8260 }
8261 
8262 static void
8263 bs_load_grow_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8264 {
8265 	struct spdk_bs_load_ctx	*ctx = cb_arg;
8266 
8267 	if (bserrno != 0) {
8268 		bs_load_ctx_fail(ctx, bserrno);
8269 		return;
8270 	}
8271 	bs_load_grow_continue(ctx);
8272 }
8273 
8274 static void
8275 bs_load_grow_used_clusters_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8276 {
8277 	struct spdk_bs_load_ctx	*ctx = cb_arg;
8278 
8279 	if (bserrno != 0) {
8280 		bs_load_ctx_fail(ctx, bserrno);
8281 		return;
8282 	}
8283 
8284 	spdk_free(ctx->mask);
8285 
8286 	bs_sequence_write_dev(ctx->seq, ctx->super, bs_page_to_lba(ctx->bs, 0),
8287 			      bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
8288 			      bs_load_grow_super_write_cpl, ctx);
8289 }
8290 
8291 static void
8292 bs_load_grow_used_clusters_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8293 {
8294 	struct spdk_bs_load_ctx *ctx = cb_arg;
8295 	uint64_t		lba, lba_count;
8296 	uint64_t		dev_size;
8297 	uint64_t		total_clusters;
8298 
8299 	if (bserrno != 0) {
8300 		bs_load_ctx_fail(ctx, bserrno);
8301 		return;
8302 	}
8303 
8304 	/* The type must be correct */
8305 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
8306 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
8307 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
8308 					     struct spdk_blob_md_page) * 8));
8309 	dev_size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8310 	total_clusters = dev_size / ctx->super->cluster_size;
8311 	ctx->mask->length = total_clusters;
8312 
8313 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
8314 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
8315 	bs_sequence_write_dev(ctx->seq, ctx->mask, lba, lba_count,
8316 			      bs_load_grow_used_clusters_write_cpl, ctx);
8317 }
8318 
8319 static void
8320 bs_load_try_to_grow(struct spdk_bs_load_ctx *ctx)
8321 {
8322 	uint64_t dev_size, total_clusters, used_cluster_mask_len, max_used_cluster_mask;
8323 	uint64_t lba, lba_count, mask_size;
8324 
8325 	dev_size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
8326 	total_clusters = dev_size / ctx->super->cluster_size;
8327 	used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
8328 				spdk_divide_round_up(total_clusters, 8),
8329 				SPDK_BS_PAGE_SIZE);
8330 	max_used_cluster_mask = ctx->super->used_blobid_mask_start - ctx->super->used_cluster_mask_start;
8331 	/* No necessary to grow or no space to grow */
8332 	if (ctx->super->size >= dev_size || used_cluster_mask_len > max_used_cluster_mask) {
8333 		SPDK_DEBUGLOG(blob, "No grow\n");
8334 		bs_load_grow_continue(ctx);
8335 		return;
8336 	}
8337 
8338 	SPDK_DEBUGLOG(blob, "Resize blobstore\n");
8339 
8340 	ctx->super->size = dev_size;
8341 	ctx->super->used_cluster_mask_len = used_cluster_mask_len;
8342 	ctx->super->crc = blob_md_page_calc_crc(ctx->super);
8343 
8344 	mask_size = used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
8345 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
8346 				 SPDK_MALLOC_DMA);
8347 	if (!ctx->mask) {
8348 		bs_load_ctx_fail(ctx, -ENOMEM);
8349 		return;
8350 	}
8351 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
8352 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
8353 	bs_sequence_read_dev(ctx->seq, ctx->mask, lba, lba_count,
8354 			     bs_load_grow_used_clusters_read_cpl, ctx);
8355 }
8356 
8357 static void
8358 bs_grow_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
8359 {
8360 	struct spdk_bs_load_ctx *ctx = cb_arg;
8361 	uint32_t	crc;
8362 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
8363 
8364 	if (ctx->super->version > SPDK_BS_VERSION ||
8365 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
8366 		bs_load_ctx_fail(ctx, -EILSEQ);
8367 		return;
8368 	}
8369 
8370 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
8371 		   sizeof(ctx->super->signature)) != 0) {
8372 		bs_load_ctx_fail(ctx, -EILSEQ);
8373 		return;
8374 	}
8375 
8376 	crc = blob_md_page_calc_crc(ctx->super);
8377 	if (crc != ctx->super->crc) {
8378 		bs_load_ctx_fail(ctx, -EILSEQ);
8379 		return;
8380 	}
8381 
8382 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
8383 		SPDK_DEBUGLOG(blob, "Bstype matched - loading blobstore\n");
8384 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
8385 		SPDK_DEBUGLOG(blob, "Bstype wildcard used - loading blobstore regardless bstype\n");
8386 	} else {
8387 		SPDK_DEBUGLOG(blob, "Unexpected bstype\n");
8388 		SPDK_LOGDUMP(blob, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
8389 		SPDK_LOGDUMP(blob, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
8390 		bs_load_ctx_fail(ctx, -ENXIO);
8391 		return;
8392 	}
8393 
8394 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
8395 		SPDK_NOTICELOG("Size mismatch, dev size: %" PRIu64 ", blobstore size: %" PRIu64 "\n",
8396 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
8397 		bs_load_ctx_fail(ctx, -EILSEQ);
8398 		return;
8399 	}
8400 
8401 	bs_load_try_to_grow(ctx);
8402 
8403 }
8404 
8405 void
8406 spdk_bs_grow(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
8407 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
8408 {
8409 	struct spdk_blob_store	*bs;
8410 	struct spdk_bs_cpl	cpl;
8411 	struct spdk_bs_load_ctx *ctx;
8412 	struct spdk_bs_opts	opts = {};
8413 	int err;
8414 
8415 	SPDK_DEBUGLOG(blob, "Loading blobstore from dev %p\n", dev);
8416 
8417 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
8418 		SPDK_DEBUGLOG(blob, "unsupported dev block length of %d\n", dev->blocklen);
8419 		dev->destroy(dev);
8420 		cb_fn(cb_arg, NULL, -EINVAL);
8421 		return;
8422 	}
8423 
8424 	spdk_bs_opts_init(&opts, sizeof(opts));
8425 	if (o) {
8426 		if (bs_opts_copy(o, &opts)) {
8427 			return;
8428 		}
8429 	}
8430 
8431 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
8432 		dev->destroy(dev);
8433 		cb_fn(cb_arg, NULL, -EINVAL);
8434 		return;
8435 	}
8436 
8437 	err = bs_alloc(dev, &opts, &bs, &ctx);
8438 	if (err) {
8439 		dev->destroy(dev);
8440 		cb_fn(cb_arg, NULL, err);
8441 		return;
8442 	}
8443 
8444 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
8445 	cpl.u.bs_handle.cb_fn = cb_fn;
8446 	cpl.u.bs_handle.cb_arg = cb_arg;
8447 	cpl.u.bs_handle.bs = bs;
8448 
8449 	ctx->seq = bs_sequence_start(bs->md_channel, &cpl);
8450 	if (!ctx->seq) {
8451 		spdk_free(ctx->super);
8452 		free(ctx);
8453 		bs_free(bs);
8454 		cb_fn(cb_arg, NULL, -ENOMEM);
8455 		return;
8456 	}
8457 
8458 	/* Read the super block */
8459 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
8460 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
8461 			     bs_grow_load_super_cpl, ctx);
8462 }
8463 
8464 SPDK_LOG_REGISTER_COMPONENT(blob)
8465