xref: /spdk/lib/blob/blobstore.c (revision ae7b5890ef728af40bd233a5011b924c482603bf)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "spdk/blob.h"
37 #include "spdk/crc32.h"
38 #include "spdk/env.h"
39 #include "spdk/queue.h"
40 #include "spdk/thread.h"
41 #include "spdk/bit_array.h"
42 #include "spdk/likely.h"
43 #include "spdk/util.h"
44 
45 #include "spdk_internal/assert.h"
46 #include "spdk_internal/log.h"
47 
48 #include "blobstore.h"
49 
50 #define BLOB_CRC32C_INITIAL    0xffffffffUL
51 
52 static int spdk_bs_register_md_thread(struct spdk_blob_store *bs);
53 static int spdk_bs_unregister_md_thread(struct spdk_blob_store *bs);
54 static void _spdk_blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno);
55 static void _spdk_blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
56 		uint64_t cluster, spdk_blob_op_complete cb_fn, void *cb_arg);
57 
58 static int _spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
59 				uint16_t value_len, bool internal);
60 static int _spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
61 				      const void **value, size_t *value_len, bool internal);
62 static int _spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal);
63 
64 static void
65 _spdk_blob_verify_md_op(struct spdk_blob *blob)
66 {
67 	assert(blob != NULL);
68 	assert(spdk_get_thread() == blob->bs->md_thread);
69 	assert(blob->state != SPDK_BLOB_STATE_LOADING);
70 }
71 
72 static struct spdk_blob_list *
73 _spdk_bs_get_snapshot_entry(struct spdk_blob_store *bs, spdk_blob_id blobid)
74 {
75 	struct spdk_blob_list *snapshot_entry = NULL;
76 
77 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
78 		if (snapshot_entry->id == blobid) {
79 			break;
80 		}
81 	}
82 
83 	return snapshot_entry;
84 }
85 
86 static void
87 _spdk_bs_claim_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
88 {
89 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
90 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == false);
91 	assert(bs->num_free_clusters > 0);
92 
93 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %u\n", cluster_num);
94 
95 	spdk_bit_array_set(bs->used_clusters, cluster_num);
96 	bs->num_free_clusters--;
97 }
98 
99 static int
100 _spdk_blob_insert_cluster(struct spdk_blob *blob, uint32_t cluster_num, uint64_t cluster)
101 {
102 	uint64_t *cluster_lba = &blob->active.clusters[cluster_num];
103 
104 	_spdk_blob_verify_md_op(blob);
105 
106 	if (*cluster_lba != 0) {
107 		return -EEXIST;
108 	}
109 
110 	*cluster_lba = _spdk_bs_cluster_to_lba(blob->bs, cluster);
111 	return 0;
112 }
113 
114 static int
115 _spdk_bs_allocate_cluster(struct spdk_blob *blob, uint32_t cluster_num,
116 			  uint64_t *lowest_free_cluster, bool update_map)
117 {
118 	pthread_mutex_lock(&blob->bs->used_clusters_mutex);
119 	*lowest_free_cluster = spdk_bit_array_find_first_clear(blob->bs->used_clusters,
120 			       *lowest_free_cluster);
121 	if (*lowest_free_cluster == UINT32_MAX) {
122 		/* No more free clusters. Cannot satisfy the request */
123 		pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
124 		return -ENOSPC;
125 	}
126 
127 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %lu for blob %lu\n", *lowest_free_cluster, blob->id);
128 	_spdk_bs_claim_cluster(blob->bs, *lowest_free_cluster);
129 	pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
130 
131 	if (update_map) {
132 		_spdk_blob_insert_cluster(blob, cluster_num, *lowest_free_cluster);
133 	}
134 
135 	return 0;
136 }
137 
138 static void
139 _spdk_bs_release_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
140 {
141 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
142 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == true);
143 	assert(bs->num_free_clusters < bs->total_clusters);
144 
145 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Releasing cluster %u\n", cluster_num);
146 
147 	pthread_mutex_lock(&bs->used_clusters_mutex);
148 	spdk_bit_array_clear(bs->used_clusters, cluster_num);
149 	bs->num_free_clusters++;
150 	pthread_mutex_unlock(&bs->used_clusters_mutex);
151 }
152 
153 static void
154 _spdk_blob_xattrs_init(struct spdk_blob_xattr_opts *xattrs)
155 {
156 	xattrs->count = 0;
157 	xattrs->names = NULL;
158 	xattrs->ctx = NULL;
159 	xattrs->get_value = NULL;
160 }
161 
162 void
163 spdk_blob_opts_init(struct spdk_blob_opts *opts)
164 {
165 	opts->num_clusters = 0;
166 	opts->thin_provision = false;
167 	_spdk_blob_xattrs_init(&opts->xattrs);
168 }
169 
170 void
171 spdk_blob_open_opts_init(struct spdk_blob_open_opts *opts)
172 {
173 	opts->clear_method = BLOB_CLEAR_WITH_UNMAP;
174 }
175 
176 static struct spdk_blob *
177 _spdk_blob_alloc(struct spdk_blob_store *bs, spdk_blob_id id)
178 {
179 	struct spdk_blob *blob;
180 
181 	blob = calloc(1, sizeof(*blob));
182 	if (!blob) {
183 		return NULL;
184 	}
185 
186 	blob->id = id;
187 	blob->bs = bs;
188 
189 	blob->parent_id = SPDK_BLOBID_INVALID;
190 
191 	blob->state = SPDK_BLOB_STATE_DIRTY;
192 	blob->active.num_pages = 1;
193 	blob->active.pages = calloc(1, sizeof(*blob->active.pages));
194 	if (!blob->active.pages) {
195 		free(blob);
196 		return NULL;
197 	}
198 
199 	blob->active.pages[0] = _spdk_bs_blobid_to_page(id);
200 
201 	TAILQ_INIT(&blob->xattrs);
202 	TAILQ_INIT(&blob->xattrs_internal);
203 
204 	return blob;
205 }
206 
207 static void
208 _spdk_xattrs_free(struct spdk_xattr_tailq *xattrs)
209 {
210 	struct spdk_xattr	*xattr, *xattr_tmp;
211 
212 	TAILQ_FOREACH_SAFE(xattr, xattrs, link, xattr_tmp) {
213 		TAILQ_REMOVE(xattrs, xattr, link);
214 		free(xattr->name);
215 		free(xattr->value);
216 		free(xattr);
217 	}
218 }
219 
220 static void
221 _spdk_blob_free(struct spdk_blob *blob)
222 {
223 	assert(blob != NULL);
224 
225 	free(blob->active.clusters);
226 	free(blob->clean.clusters);
227 	free(blob->active.pages);
228 	free(blob->clean.pages);
229 
230 	_spdk_xattrs_free(&blob->xattrs);
231 	_spdk_xattrs_free(&blob->xattrs_internal);
232 
233 	if (blob->back_bs_dev) {
234 		blob->back_bs_dev->destroy(blob->back_bs_dev);
235 	}
236 
237 	free(blob);
238 }
239 
240 struct freeze_io_ctx {
241 	struct spdk_bs_cpl cpl;
242 	struct spdk_blob *blob;
243 };
244 
245 static void
246 _spdk_blob_io_sync(struct spdk_io_channel_iter *i)
247 {
248 	spdk_for_each_channel_continue(i, 0);
249 }
250 
251 static void
252 _spdk_blob_execute_queued_io(struct spdk_io_channel_iter *i)
253 {
254 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
255 	struct spdk_bs_channel *ch = spdk_io_channel_get_ctx(_ch);
256 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
257 	struct spdk_bs_request_set	*set;
258 	struct spdk_bs_user_op_args	*args;
259 	spdk_bs_user_op_t *op, *tmp;
260 
261 	TAILQ_FOREACH_SAFE(op, &ch->queued_io, link, tmp) {
262 		set = (struct spdk_bs_request_set *)op;
263 		args = &set->u.user_op;
264 
265 		if (args->blob == ctx->blob) {
266 			TAILQ_REMOVE(&ch->queued_io, op, link);
267 			spdk_bs_user_op_execute(op);
268 		}
269 	}
270 
271 	spdk_for_each_channel_continue(i, 0);
272 }
273 
274 static void
275 _spdk_blob_io_cpl(struct spdk_io_channel_iter *i, int status)
276 {
277 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
278 
279 	ctx->cpl.u.blob_basic.cb_fn(ctx->cpl.u.blob_basic.cb_arg, 0);
280 
281 	free(ctx);
282 }
283 
284 static void
285 _spdk_blob_freeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
286 {
287 	struct freeze_io_ctx *ctx;
288 
289 	ctx = calloc(1, sizeof(*ctx));
290 	if (!ctx) {
291 		cb_fn(cb_arg, -ENOMEM);
292 		return;
293 	}
294 
295 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
296 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
297 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
298 	ctx->blob = blob;
299 
300 	/* Freeze I/O on blob */
301 	blob->frozen_refcnt++;
302 
303 	if (blob->frozen_refcnt == 1) {
304 		spdk_for_each_channel(blob->bs, _spdk_blob_io_sync, ctx, _spdk_blob_io_cpl);
305 	} else {
306 		cb_fn(cb_arg, 0);
307 		free(ctx);
308 	}
309 }
310 
311 static void
312 _spdk_blob_unfreeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
313 {
314 	struct freeze_io_ctx *ctx;
315 
316 	ctx = calloc(1, sizeof(*ctx));
317 	if (!ctx) {
318 		cb_fn(cb_arg, -ENOMEM);
319 		return;
320 	}
321 
322 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
323 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
324 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
325 	ctx->blob = blob;
326 
327 	assert(blob->frozen_refcnt > 0);
328 
329 	blob->frozen_refcnt--;
330 
331 	if (blob->frozen_refcnt == 0) {
332 		spdk_for_each_channel(blob->bs, _spdk_blob_execute_queued_io, ctx, _spdk_blob_io_cpl);
333 	} else {
334 		cb_fn(cb_arg, 0);
335 		free(ctx);
336 	}
337 }
338 
339 static int
340 _spdk_blob_mark_clean(struct spdk_blob *blob)
341 {
342 	uint64_t *clusters = NULL;
343 	uint32_t *pages = NULL;
344 
345 	assert(blob != NULL);
346 
347 	if (blob->active.num_clusters) {
348 		assert(blob->active.clusters);
349 		clusters = calloc(blob->active.num_clusters, sizeof(*blob->active.clusters));
350 		if (!clusters) {
351 			return -ENOMEM;
352 		}
353 		memcpy(clusters, blob->active.clusters, blob->active.num_clusters * sizeof(*clusters));
354 	}
355 
356 	if (blob->active.num_pages) {
357 		assert(blob->active.pages);
358 		pages = calloc(blob->active.num_pages, sizeof(*blob->active.pages));
359 		if (!pages) {
360 			free(clusters);
361 			return -ENOMEM;
362 		}
363 		memcpy(pages, blob->active.pages, blob->active.num_pages * sizeof(*pages));
364 	}
365 
366 	free(blob->clean.clusters);
367 	free(blob->clean.pages);
368 
369 	blob->clean.num_clusters = blob->active.num_clusters;
370 	blob->clean.clusters = blob->active.clusters;
371 	blob->clean.num_pages = blob->active.num_pages;
372 	blob->clean.pages = blob->active.pages;
373 
374 	blob->active.clusters = clusters;
375 	blob->active.pages = pages;
376 
377 	/* If the metadata was dirtied again while the metadata was being written to disk,
378 	 *  we do not want to revert the DIRTY state back to CLEAN here.
379 	 */
380 	if (blob->state == SPDK_BLOB_STATE_LOADING) {
381 		blob->state = SPDK_BLOB_STATE_CLEAN;
382 	}
383 
384 	return 0;
385 }
386 
387 static int
388 _spdk_blob_deserialize_xattr(struct spdk_blob *blob,
389 			     struct spdk_blob_md_descriptor_xattr *desc_xattr, bool internal)
390 {
391 	struct spdk_xattr                       *xattr;
392 
393 	if (desc_xattr->length != sizeof(desc_xattr->name_length) +
394 	    sizeof(desc_xattr->value_length) +
395 	    desc_xattr->name_length + desc_xattr->value_length) {
396 		return -EINVAL;
397 	}
398 
399 	xattr = calloc(1, sizeof(*xattr));
400 	if (xattr == NULL) {
401 		return -ENOMEM;
402 	}
403 
404 	xattr->name = malloc(desc_xattr->name_length + 1);
405 	if (xattr->name == NULL) {
406 		free(xattr);
407 		return -ENOMEM;
408 	}
409 	memcpy(xattr->name, desc_xattr->name, desc_xattr->name_length);
410 	xattr->name[desc_xattr->name_length] = '\0';
411 
412 	xattr->value = malloc(desc_xattr->value_length);
413 	if (xattr->value == NULL) {
414 		free(xattr->name);
415 		free(xattr);
416 		return -ENOMEM;
417 	}
418 	xattr->value_len = desc_xattr->value_length;
419 	memcpy(xattr->value,
420 	       (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
421 	       desc_xattr->value_length);
422 
423 	TAILQ_INSERT_TAIL(internal ? &blob->xattrs_internal : &blob->xattrs, xattr, link);
424 
425 	return 0;
426 }
427 
428 
429 static int
430 _spdk_blob_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob *blob)
431 {
432 	struct spdk_blob_md_descriptor *desc;
433 	size_t	cur_desc = 0;
434 	void *tmp;
435 
436 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
437 	while (cur_desc < sizeof(page->descriptors)) {
438 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
439 			if (desc->length == 0) {
440 				/* If padding and length are 0, this terminates the page */
441 				break;
442 			}
443 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
444 			struct spdk_blob_md_descriptor_flags	*desc_flags;
445 
446 			desc_flags = (struct spdk_blob_md_descriptor_flags *)desc;
447 
448 			if (desc_flags->length != sizeof(*desc_flags) - sizeof(*desc)) {
449 				return -EINVAL;
450 			}
451 
452 			if ((desc_flags->invalid_flags | SPDK_BLOB_INVALID_FLAGS_MASK) !=
453 			    SPDK_BLOB_INVALID_FLAGS_MASK) {
454 				return -EINVAL;
455 			}
456 
457 			if ((desc_flags->data_ro_flags | SPDK_BLOB_DATA_RO_FLAGS_MASK) !=
458 			    SPDK_BLOB_DATA_RO_FLAGS_MASK) {
459 				blob->data_ro = true;
460 				blob->md_ro = true;
461 			}
462 
463 			if ((desc_flags->md_ro_flags | SPDK_BLOB_MD_RO_FLAGS_MASK) !=
464 			    SPDK_BLOB_MD_RO_FLAGS_MASK) {
465 				blob->md_ro = true;
466 			}
467 
468 			if ((desc_flags->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
469 				blob->data_ro = true;
470 				blob->md_ro = true;
471 			}
472 
473 			blob->invalid_flags = desc_flags->invalid_flags;
474 			blob->data_ro_flags = desc_flags->data_ro_flags;
475 			blob->md_ro_flags = desc_flags->md_ro_flags;
476 
477 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT) {
478 			struct spdk_blob_md_descriptor_extent	*desc_extent;
479 			unsigned int				i, j;
480 			unsigned int				cluster_count = blob->active.num_clusters;
481 
482 			desc_extent = (struct spdk_blob_md_descriptor_extent *)desc;
483 
484 			if (desc_extent->length == 0 ||
485 			    (desc_extent->length % sizeof(desc_extent->extents[0]) != 0)) {
486 				return -EINVAL;
487 			}
488 
489 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->extents[0]); i++) {
490 				for (j = 0; j < desc_extent->extents[i].length; j++) {
491 					if (desc_extent->extents[i].cluster_idx != 0) {
492 						if (!spdk_bit_array_get(blob->bs->used_clusters,
493 									desc_extent->extents[i].cluster_idx + j)) {
494 							return -EINVAL;
495 						}
496 					}
497 					cluster_count++;
498 				}
499 			}
500 
501 			if (cluster_count == 0) {
502 				return -EINVAL;
503 			}
504 			tmp = realloc(blob->active.clusters, cluster_count * sizeof(uint64_t));
505 			if (tmp == NULL) {
506 				return -ENOMEM;
507 			}
508 			blob->active.clusters = tmp;
509 			blob->active.cluster_array_size = cluster_count;
510 
511 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->extents[0]); i++) {
512 				for (j = 0; j < desc_extent->extents[i].length; j++) {
513 					if (desc_extent->extents[i].cluster_idx != 0) {
514 						blob->active.clusters[blob->active.num_clusters++] = _spdk_bs_cluster_to_lba(blob->bs,
515 								desc_extent->extents[i].cluster_idx + j);
516 					} else if (spdk_blob_is_thin_provisioned(blob)) {
517 						blob->active.clusters[blob->active.num_clusters++] = 0;
518 					} else {
519 						return -EINVAL;
520 					}
521 				}
522 			}
523 
524 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
525 			int rc;
526 
527 			rc = _spdk_blob_deserialize_xattr(blob,
528 							  (struct spdk_blob_md_descriptor_xattr *) desc, false);
529 			if (rc != 0) {
530 				return rc;
531 			}
532 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
533 			int rc;
534 
535 			rc = _spdk_blob_deserialize_xattr(blob,
536 							  (struct spdk_blob_md_descriptor_xattr *) desc, true);
537 			if (rc != 0) {
538 				return rc;
539 			}
540 		} else {
541 			/* Unrecognized descriptor type.  Do not fail - just continue to the
542 			 *  next descriptor.  If this descriptor is associated with some feature
543 			 *  defined in a newer version of blobstore, that version of blobstore
544 			 *  should create and set an associated feature flag to specify if this
545 			 *  blob can be loaded or not.
546 			 */
547 		}
548 
549 		/* Advance to the next descriptor */
550 		cur_desc += sizeof(*desc) + desc->length;
551 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
552 			break;
553 		}
554 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
555 	}
556 
557 	return 0;
558 }
559 
560 static int
561 _spdk_blob_parse(const struct spdk_blob_md_page *pages, uint32_t page_count,
562 		 struct spdk_blob *blob)
563 {
564 	const struct spdk_blob_md_page *page;
565 	uint32_t i;
566 	int rc;
567 
568 	assert(page_count > 0);
569 	assert(pages[0].sequence_num == 0);
570 	assert(blob != NULL);
571 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
572 	assert(blob->active.clusters == NULL);
573 
574 	/* The blobid provided doesn't match what's in the MD, this can
575 	 * happen for example if a bogus blobid is passed in through open.
576 	 */
577 	if (blob->id != pages[0].id) {
578 		SPDK_ERRLOG("Blobid (%lu) doesn't match what's in metadata (%lu)\n",
579 			    blob->id, pages[0].id);
580 		return -ENOENT;
581 	}
582 
583 	for (i = 0; i < page_count; i++) {
584 		page = &pages[i];
585 
586 		assert(page->id == blob->id);
587 		assert(page->sequence_num == i);
588 
589 		rc = _spdk_blob_parse_page(page, blob);
590 		if (rc != 0) {
591 			return rc;
592 		}
593 	}
594 
595 	return 0;
596 }
597 
598 static int
599 _spdk_blob_serialize_add_page(const struct spdk_blob *blob,
600 			      struct spdk_blob_md_page **pages,
601 			      uint32_t *page_count,
602 			      struct spdk_blob_md_page **last_page)
603 {
604 	struct spdk_blob_md_page *page;
605 
606 	assert(pages != NULL);
607 	assert(page_count != NULL);
608 
609 	if (*page_count == 0) {
610 		assert(*pages == NULL);
611 		*page_count = 1;
612 		*pages = spdk_malloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
613 				     NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
614 	} else {
615 		assert(*pages != NULL);
616 		(*page_count)++;
617 		*pages = spdk_realloc(*pages,
618 				      SPDK_BS_PAGE_SIZE * (*page_count),
619 				      SPDK_BS_PAGE_SIZE);
620 	}
621 
622 	if (*pages == NULL) {
623 		*page_count = 0;
624 		*last_page = NULL;
625 		return -ENOMEM;
626 	}
627 
628 	page = &(*pages)[*page_count - 1];
629 	memset(page, 0, sizeof(*page));
630 	page->id = blob->id;
631 	page->sequence_num = *page_count - 1;
632 	page->next = SPDK_INVALID_MD_PAGE;
633 	*last_page = page;
634 
635 	return 0;
636 }
637 
638 /* Transform the in-memory representation 'xattr' into an on-disk xattr descriptor.
639  * Update required_sz on both success and failure.
640  *
641  */
642 static int
643 _spdk_blob_serialize_xattr(const struct spdk_xattr *xattr,
644 			   uint8_t *buf, size_t buf_sz,
645 			   size_t *required_sz, bool internal)
646 {
647 	struct spdk_blob_md_descriptor_xattr	*desc;
648 
649 	*required_sz = sizeof(struct spdk_blob_md_descriptor_xattr) +
650 		       strlen(xattr->name) +
651 		       xattr->value_len;
652 
653 	if (buf_sz < *required_sz) {
654 		return -1;
655 	}
656 
657 	desc = (struct spdk_blob_md_descriptor_xattr *)buf;
658 
659 	desc->type = internal ? SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL : SPDK_MD_DESCRIPTOR_TYPE_XATTR;
660 	desc->length = sizeof(desc->name_length) +
661 		       sizeof(desc->value_length) +
662 		       strlen(xattr->name) +
663 		       xattr->value_len;
664 	desc->name_length = strlen(xattr->name);
665 	desc->value_length = xattr->value_len;
666 
667 	memcpy(desc->name, xattr->name, desc->name_length);
668 	memcpy((void *)((uintptr_t)desc->name + desc->name_length),
669 	       xattr->value,
670 	       desc->value_length);
671 
672 	return 0;
673 }
674 
675 static void
676 _spdk_blob_serialize_extent(const struct spdk_blob *blob,
677 			    uint64_t start_cluster, uint64_t *next_cluster,
678 			    uint8_t *buf, size_t buf_sz)
679 {
680 	struct spdk_blob_md_descriptor_extent *desc;
681 	size_t cur_sz;
682 	uint64_t i, extent_idx;
683 	uint64_t lba, lba_per_cluster, lba_count;
684 
685 	/* The buffer must have room for at least one extent */
686 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc->extents[0]);
687 	if (buf_sz < cur_sz) {
688 		*next_cluster = start_cluster;
689 		return;
690 	}
691 
692 	desc = (struct spdk_blob_md_descriptor_extent *)buf;
693 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT;
694 
695 	lba_per_cluster = _spdk_bs_cluster_to_lba(blob->bs, 1);
696 
697 	lba = blob->active.clusters[start_cluster];
698 	lba_count = lba_per_cluster;
699 	extent_idx = 0;
700 	for (i = start_cluster + 1; i < blob->active.num_clusters; i++) {
701 		if ((lba + lba_count) == blob->active.clusters[i]) {
702 			lba_count += lba_per_cluster;
703 			continue;
704 		} else if (lba == 0 && blob->active.clusters[i] == 0) {
705 			lba_count += lba_per_cluster;
706 			continue;
707 		}
708 		desc->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
709 		desc->extents[extent_idx].length = lba_count / lba_per_cluster;
710 		extent_idx++;
711 
712 		cur_sz += sizeof(desc->extents[extent_idx]);
713 
714 		if (buf_sz < cur_sz) {
715 			/* If we ran out of buffer space, return */
716 			desc->length = sizeof(desc->extents[0]) * extent_idx;
717 			*next_cluster = i;
718 			return;
719 		}
720 
721 		lba = blob->active.clusters[i];
722 		lba_count = lba_per_cluster;
723 	}
724 
725 	desc->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
726 	desc->extents[extent_idx].length = lba_count / lba_per_cluster;
727 	extent_idx++;
728 
729 	desc->length = sizeof(desc->extents[0]) * extent_idx;
730 	*next_cluster = blob->active.num_clusters;
731 
732 	return;
733 }
734 
735 static void
736 _spdk_blob_serialize_flags(const struct spdk_blob *blob,
737 			   uint8_t *buf, size_t *buf_sz)
738 {
739 	struct spdk_blob_md_descriptor_flags *desc;
740 
741 	/*
742 	 * Flags get serialized first, so we should always have room for the flags
743 	 *  descriptor.
744 	 */
745 	assert(*buf_sz >= sizeof(*desc));
746 
747 	desc = (struct spdk_blob_md_descriptor_flags *)buf;
748 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_FLAGS;
749 	desc->length = sizeof(*desc) - sizeof(struct spdk_blob_md_descriptor);
750 	desc->invalid_flags = blob->invalid_flags;
751 	desc->data_ro_flags = blob->data_ro_flags;
752 	desc->md_ro_flags = blob->md_ro_flags;
753 
754 	*buf_sz -= sizeof(*desc);
755 }
756 
757 static int
758 _spdk_blob_serialize_xattrs(const struct spdk_blob *blob,
759 			    const struct spdk_xattr_tailq *xattrs, bool internal,
760 			    struct spdk_blob_md_page **pages,
761 			    struct spdk_blob_md_page *cur_page,
762 			    uint32_t *page_count, uint8_t **buf,
763 			    size_t *remaining_sz)
764 {
765 	const struct spdk_xattr	*xattr;
766 	int	rc;
767 
768 	TAILQ_FOREACH(xattr, xattrs, link) {
769 		size_t required_sz = 0;
770 
771 		rc = _spdk_blob_serialize_xattr(xattr,
772 						*buf, *remaining_sz,
773 						&required_sz, internal);
774 		if (rc < 0) {
775 			/* Need to add a new page to the chain */
776 			rc = _spdk_blob_serialize_add_page(blob, pages, page_count,
777 							   &cur_page);
778 			if (rc < 0) {
779 				spdk_free(*pages);
780 				*pages = NULL;
781 				*page_count = 0;
782 				return rc;
783 			}
784 
785 			*buf = (uint8_t *)cur_page->descriptors;
786 			*remaining_sz = sizeof(cur_page->descriptors);
787 
788 			/* Try again */
789 			required_sz = 0;
790 			rc = _spdk_blob_serialize_xattr(xattr,
791 							*buf, *remaining_sz,
792 							&required_sz, internal);
793 
794 			if (rc < 0) {
795 				spdk_free(*pages);
796 				*pages = NULL;
797 				*page_count = 0;
798 				return rc;
799 			}
800 		}
801 
802 		*remaining_sz -= required_sz;
803 		*buf += required_sz;
804 	}
805 
806 	return 0;
807 }
808 
809 static int
810 _spdk_blob_serialize(const struct spdk_blob *blob, struct spdk_blob_md_page **pages,
811 		     uint32_t *page_count)
812 {
813 	struct spdk_blob_md_page		*cur_page;
814 	int					rc;
815 	uint8_t					*buf;
816 	size_t					remaining_sz;
817 	uint64_t				last_cluster;
818 
819 	assert(pages != NULL);
820 	assert(page_count != NULL);
821 	assert(blob != NULL);
822 	assert(blob->state == SPDK_BLOB_STATE_DIRTY);
823 
824 	*pages = NULL;
825 	*page_count = 0;
826 
827 	/* A blob always has at least 1 page, even if it has no descriptors */
828 	rc = _spdk_blob_serialize_add_page(blob, pages, page_count, &cur_page);
829 	if (rc < 0) {
830 		return rc;
831 	}
832 
833 	buf = (uint8_t *)cur_page->descriptors;
834 	remaining_sz = sizeof(cur_page->descriptors);
835 
836 	/* Serialize flags */
837 	_spdk_blob_serialize_flags(blob, buf, &remaining_sz);
838 	buf += sizeof(struct spdk_blob_md_descriptor_flags);
839 
840 	/* Serialize xattrs */
841 	rc = _spdk_blob_serialize_xattrs(blob, &blob->xattrs, false,
842 					 pages, cur_page, page_count, &buf, &remaining_sz);
843 	if (rc < 0) {
844 		return rc;
845 	}
846 
847 	/* Serialize internal xattrs */
848 	rc = _spdk_blob_serialize_xattrs(blob, &blob->xattrs_internal, true,
849 					 pages, cur_page, page_count, &buf, &remaining_sz);
850 	if (rc < 0) {
851 		return rc;
852 	}
853 
854 	/* Serialize extents */
855 	last_cluster = 0;
856 	while (last_cluster < blob->active.num_clusters) {
857 		_spdk_blob_serialize_extent(blob, last_cluster, &last_cluster,
858 					    buf, remaining_sz);
859 
860 		if (last_cluster == blob->active.num_clusters) {
861 			break;
862 		}
863 
864 		rc = _spdk_blob_serialize_add_page(blob, pages, page_count,
865 						   &cur_page);
866 		if (rc < 0) {
867 			return rc;
868 		}
869 
870 		buf = (uint8_t *)cur_page->descriptors;
871 		remaining_sz = sizeof(cur_page->descriptors);
872 	}
873 
874 	return 0;
875 }
876 
877 struct spdk_blob_load_ctx {
878 	struct spdk_blob		*blob;
879 
880 	struct spdk_blob_md_page	*pages;
881 	uint32_t			num_pages;
882 	spdk_bs_sequence_t	        *seq;
883 
884 	spdk_bs_sequence_cpl		cb_fn;
885 	void				*cb_arg;
886 };
887 
888 static uint32_t
889 _spdk_blob_md_page_calc_crc(void *page)
890 {
891 	uint32_t		crc;
892 
893 	crc = BLOB_CRC32C_INITIAL;
894 	crc = spdk_crc32c_update(page, SPDK_BS_PAGE_SIZE - 4, crc);
895 	crc ^= BLOB_CRC32C_INITIAL;
896 
897 	return crc;
898 
899 }
900 
901 static void
902 _spdk_blob_load_final(void *cb_arg, int bserrno)
903 {
904 	struct spdk_blob_load_ctx	*ctx = cb_arg;
905 	struct spdk_blob		*blob = ctx->blob;
906 
907 	_spdk_blob_mark_clean(blob);
908 
909 	ctx->cb_fn(ctx->seq, ctx->cb_arg, bserrno);
910 
911 	/* Free the memory */
912 	spdk_free(ctx->pages);
913 	free(ctx);
914 }
915 
916 static void
917 _spdk_blob_load_snapshot_cpl(void *cb_arg, struct spdk_blob *snapshot, int bserrno)
918 {
919 	struct spdk_blob_load_ctx	*ctx = cb_arg;
920 	struct spdk_blob		*blob = ctx->blob;
921 
922 	if (bserrno != 0) {
923 		goto error;
924 	}
925 
926 	blob->back_bs_dev = spdk_bs_create_blob_bs_dev(snapshot);
927 
928 	if (blob->back_bs_dev == NULL) {
929 		bserrno = -ENOMEM;
930 		goto error;
931 	}
932 
933 	_spdk_blob_load_final(ctx, bserrno);
934 	return;
935 
936 error:
937 	SPDK_ERRLOG("Snapshot fail\n");
938 	_spdk_blob_free(blob);
939 	ctx->cb_fn(ctx->seq, NULL, bserrno);
940 	spdk_free(ctx->pages);
941 	free(ctx);
942 }
943 
944 static void
945 _spdk_blob_load_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
946 {
947 	struct spdk_blob_load_ctx	*ctx = cb_arg;
948 	struct spdk_blob		*blob = ctx->blob;
949 	struct spdk_blob_md_page	*page;
950 	const void			*value;
951 	size_t				len;
952 	int				rc;
953 	uint32_t			crc;
954 
955 	if (bserrno) {
956 		SPDK_ERRLOG("Metadata page read failed: %d\n", bserrno);
957 		_spdk_blob_free(blob);
958 		ctx->cb_fn(seq, NULL, bserrno);
959 		spdk_free(ctx->pages);
960 		free(ctx);
961 		return;
962 	}
963 
964 	page = &ctx->pages[ctx->num_pages - 1];
965 	crc = _spdk_blob_md_page_calc_crc(page);
966 	if (crc != page->crc) {
967 		SPDK_ERRLOG("Metadata page %d crc mismatch\n", ctx->num_pages);
968 		_spdk_blob_free(blob);
969 		ctx->cb_fn(seq, NULL, -EINVAL);
970 		spdk_free(ctx->pages);
971 		free(ctx);
972 		return;
973 	}
974 
975 	if (page->next != SPDK_INVALID_MD_PAGE) {
976 		uint32_t next_page = page->next;
977 		uint64_t next_lba = _spdk_bs_page_to_lba(blob->bs, blob->bs->md_start + next_page);
978 		uint64_t max_md_lba = _spdk_bs_page_to_lba(blob->bs, blob->bs->md_start + blob->bs->md_len);
979 
980 		if (next_lba >= max_md_lba) {
981 			assert(false);
982 		}
983 
984 		/* Read the next page */
985 		ctx->num_pages++;
986 		ctx->pages = spdk_realloc(ctx->pages, (sizeof(*page) * ctx->num_pages),
987 					  sizeof(*page));
988 		if (ctx->pages == NULL) {
989 			ctx->cb_fn(seq, ctx->cb_arg, -ENOMEM);
990 			free(ctx);
991 			return;
992 		}
993 
994 		spdk_bs_sequence_read_dev(seq, &ctx->pages[ctx->num_pages - 1],
995 					  next_lba,
996 					  _spdk_bs_byte_to_lba(blob->bs, sizeof(*page)),
997 					  _spdk_blob_load_cpl, ctx);
998 		return;
999 	}
1000 
1001 	/* Parse the pages */
1002 	rc = _spdk_blob_parse(ctx->pages, ctx->num_pages, blob);
1003 	if (rc) {
1004 		_spdk_blob_free(blob);
1005 		ctx->cb_fn(seq, NULL, rc);
1006 		spdk_free(ctx->pages);
1007 		free(ctx);
1008 		return;
1009 	}
1010 	ctx->seq = seq;
1011 
1012 
1013 	if (spdk_blob_is_thin_provisioned(blob)) {
1014 		rc = _spdk_blob_get_xattr_value(blob, BLOB_SNAPSHOT, &value, &len, true);
1015 		if (rc == 0) {
1016 			if (len != sizeof(spdk_blob_id)) {
1017 				_spdk_blob_free(blob);
1018 				ctx->cb_fn(seq, NULL, -EINVAL);
1019 				spdk_free(ctx->pages);
1020 				free(ctx);
1021 				return;
1022 			}
1023 			/* open snapshot blob and continue in the callback function */
1024 			blob->parent_id = *(spdk_blob_id *)value;
1025 			spdk_bs_open_blob(blob->bs, blob->parent_id,
1026 					  _spdk_blob_load_snapshot_cpl, ctx);
1027 			return;
1028 		} else {
1029 			/* add zeroes_dev for thin provisioned blob */
1030 			blob->back_bs_dev = spdk_bs_create_zeroes_dev();
1031 		}
1032 	} else {
1033 		/* standard blob */
1034 		blob->back_bs_dev = NULL;
1035 	}
1036 	_spdk_blob_load_final(ctx, bserrno);
1037 }
1038 
1039 /* Load a blob from disk given a blobid */
1040 static void
1041 _spdk_blob_load(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1042 		spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1043 {
1044 	struct spdk_blob_load_ctx *ctx;
1045 	struct spdk_blob_store *bs;
1046 	uint32_t page_num;
1047 	uint64_t lba;
1048 
1049 	_spdk_blob_verify_md_op(blob);
1050 
1051 	bs = blob->bs;
1052 
1053 	ctx = calloc(1, sizeof(*ctx));
1054 	if (!ctx) {
1055 		cb_fn(seq, cb_arg, -ENOMEM);
1056 		return;
1057 	}
1058 
1059 	ctx->blob = blob;
1060 	ctx->pages = spdk_realloc(ctx->pages, SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE);
1061 	if (!ctx->pages) {
1062 		free(ctx);
1063 		cb_fn(seq, cb_arg, -ENOMEM);
1064 		return;
1065 	}
1066 	ctx->num_pages = 1;
1067 	ctx->cb_fn = cb_fn;
1068 	ctx->cb_arg = cb_arg;
1069 
1070 	page_num = _spdk_bs_blobid_to_page(blob->id);
1071 	lba = _spdk_bs_page_to_lba(blob->bs, bs->md_start + page_num);
1072 
1073 	blob->state = SPDK_BLOB_STATE_LOADING;
1074 
1075 	spdk_bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1076 				  _spdk_bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE),
1077 				  _spdk_blob_load_cpl, ctx);
1078 }
1079 
1080 struct spdk_blob_persist_ctx {
1081 	struct spdk_blob		*blob;
1082 
1083 	struct spdk_bs_super_block	*super;
1084 
1085 	struct spdk_blob_md_page	*pages;
1086 
1087 	uint64_t			idx;
1088 
1089 	spdk_bs_sequence_t		*seq;
1090 	spdk_bs_sequence_cpl		cb_fn;
1091 	void				*cb_arg;
1092 };
1093 
1094 static void
1095 spdk_bs_batch_clear_dev(struct spdk_blob_persist_ctx *ctx, spdk_bs_batch_t *batch, uint64_t lba,
1096 			uint32_t lba_count)
1097 {
1098 	if (ctx->blob->clear_method == BLOB_CLEAR_WITH_DEFAULT ||
1099 	    ctx->blob->clear_method == BLOB_CLEAR_WITH_UNMAP) {
1100 		spdk_bs_batch_unmap_dev(batch, lba, lba_count);
1101 	} else if (ctx->blob->clear_method == BLOB_CLEAR_WITH_WRITE_ZEROES) {
1102 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1103 	}
1104 }
1105 
1106 static void
1107 _spdk_blob_persist_complete(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1108 {
1109 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1110 	struct spdk_blob		*blob = ctx->blob;
1111 
1112 	if (bserrno == 0) {
1113 		_spdk_blob_mark_clean(blob);
1114 	}
1115 
1116 	/* Call user callback */
1117 	ctx->cb_fn(seq, ctx->cb_arg, bserrno);
1118 
1119 	/* Free the memory */
1120 	spdk_free(ctx->pages);
1121 	free(ctx);
1122 }
1123 
1124 static void
1125 _spdk_blob_persist_clear_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1126 {
1127 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1128 	struct spdk_blob		*blob = ctx->blob;
1129 	struct spdk_blob_store		*bs = blob->bs;
1130 	size_t				i;
1131 
1132 	/* Release all clusters that were truncated */
1133 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1134 		uint32_t cluster_num = _spdk_bs_lba_to_cluster(bs, blob->active.clusters[i]);
1135 
1136 		/* Nothing to release if it was not allocated */
1137 		if (blob->active.clusters[i] != 0) {
1138 			_spdk_bs_release_cluster(bs, cluster_num);
1139 		}
1140 	}
1141 
1142 	if (blob->active.num_clusters == 0) {
1143 		free(blob->active.clusters);
1144 		blob->active.clusters = NULL;
1145 		blob->active.cluster_array_size = 0;
1146 	} else if (blob->active.num_clusters != blob->active.cluster_array_size) {
1147 #ifndef __clang_analyzer__
1148 		void *tmp;
1149 
1150 		/* scan-build really can't figure reallocs, workaround it */
1151 		tmp = realloc(blob->active.clusters, sizeof(uint64_t) * blob->active.num_clusters);
1152 		assert(tmp != NULL);
1153 		blob->active.clusters = tmp;
1154 #endif
1155 		blob->active.cluster_array_size = blob->active.num_clusters;
1156 	}
1157 
1158 	_spdk_blob_persist_complete(seq, ctx, bserrno);
1159 }
1160 
1161 static void
1162 _spdk_blob_persist_clear_clusters(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1163 {
1164 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1165 	struct spdk_blob		*blob = ctx->blob;
1166 	struct spdk_blob_store		*bs = blob->bs;
1167 	spdk_bs_batch_t			*batch;
1168 	size_t				i;
1169 	uint64_t			lba;
1170 	uint32_t			lba_count;
1171 
1172 	/* Clusters don't move around in blobs. The list shrinks or grows
1173 	 * at the end, but no changes ever occur in the middle of the list.
1174 	 */
1175 
1176 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_clear_clusters_cpl, ctx);
1177 
1178 	/* Clear all clusters that were truncated */
1179 	lba = 0;
1180 	lba_count = 0;
1181 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1182 		uint64_t next_lba = blob->active.clusters[i];
1183 		uint32_t next_lba_count = _spdk_bs_cluster_to_lba(bs, 1);
1184 
1185 		if (next_lba > 0 && (lba + lba_count) == next_lba) {
1186 			/* This cluster is contiguous with the previous one. */
1187 			lba_count += next_lba_count;
1188 			continue;
1189 		}
1190 
1191 		/* This cluster is not contiguous with the previous one. */
1192 
1193 		/* If a run of LBAs previously existing, clear them now */
1194 		if (lba_count > 0) {
1195 			spdk_bs_batch_clear_dev(ctx, batch, lba, lba_count);
1196 		}
1197 
1198 		/* Start building the next batch */
1199 		lba = next_lba;
1200 		if (next_lba > 0) {
1201 			lba_count = next_lba_count;
1202 		} else {
1203 			lba_count = 0;
1204 		}
1205 	}
1206 
1207 	/* If we ended with a contiguous set of LBAs, clear them now */
1208 	if (lba_count > 0) {
1209 		spdk_bs_batch_clear_dev(ctx, batch, lba, lba_count);
1210 	}
1211 
1212 	spdk_bs_batch_close(batch);
1213 }
1214 
1215 static void
1216 _spdk_blob_persist_zero_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1217 {
1218 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1219 	struct spdk_blob		*blob = ctx->blob;
1220 	struct spdk_blob_store		*bs = blob->bs;
1221 	size_t				i;
1222 
1223 	/* This loop starts at 1 because the first page is special and handled
1224 	 * below. The pages (except the first) are never written in place,
1225 	 * so any pages in the clean list must be zeroed.
1226 	 */
1227 	for (i = 1; i < blob->clean.num_pages; i++) {
1228 		spdk_bit_array_clear(bs->used_md_pages, blob->clean.pages[i]);
1229 	}
1230 
1231 	if (blob->active.num_pages == 0) {
1232 		uint32_t page_num;
1233 
1234 		page_num = _spdk_bs_blobid_to_page(blob->id);
1235 		spdk_bit_array_clear(bs->used_md_pages, page_num);
1236 	}
1237 
1238 	/* Move on to clearing clusters */
1239 	_spdk_blob_persist_clear_clusters(seq, ctx, 0);
1240 }
1241 
1242 static void
1243 _spdk_blob_persist_zero_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1244 {
1245 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1246 	struct spdk_blob		*blob = ctx->blob;
1247 	struct spdk_blob_store		*bs = blob->bs;
1248 	uint64_t			lba;
1249 	uint32_t			lba_count;
1250 	spdk_bs_batch_t			*batch;
1251 	size_t				i;
1252 
1253 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_zero_pages_cpl, ctx);
1254 
1255 	lba_count = _spdk_bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE);
1256 
1257 	/* This loop starts at 1 because the first page is special and handled
1258 	 * below. The pages (except the first) are never written in place,
1259 	 * so any pages in the clean list must be zeroed.
1260 	 */
1261 	for (i = 1; i < blob->clean.num_pages; i++) {
1262 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + blob->clean.pages[i]);
1263 
1264 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1265 	}
1266 
1267 	/* The first page will only be zeroed if this is a delete. */
1268 	if (blob->active.num_pages == 0) {
1269 		uint32_t page_num;
1270 
1271 		/* The first page in the metadata goes where the blobid indicates */
1272 		page_num = _spdk_bs_blobid_to_page(blob->id);
1273 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + page_num);
1274 
1275 		spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1276 	}
1277 
1278 	spdk_bs_batch_close(batch);
1279 }
1280 
1281 static void
1282 _spdk_blob_persist_write_page_root(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1283 {
1284 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1285 	struct spdk_blob		*blob = ctx->blob;
1286 	struct spdk_blob_store		*bs = blob->bs;
1287 	uint64_t			lba;
1288 	uint32_t			lba_count;
1289 	struct spdk_blob_md_page	*page;
1290 
1291 	if (blob->active.num_pages == 0) {
1292 		/* Move on to the next step */
1293 		_spdk_blob_persist_zero_pages(seq, ctx, 0);
1294 		return;
1295 	}
1296 
1297 	lba_count = _spdk_bs_byte_to_lba(bs, sizeof(*page));
1298 
1299 	page = &ctx->pages[0];
1300 	/* The first page in the metadata goes where the blobid indicates */
1301 	lba = _spdk_bs_page_to_lba(bs, bs->md_start + _spdk_bs_blobid_to_page(blob->id));
1302 
1303 	spdk_bs_sequence_write_dev(seq, page, lba, lba_count,
1304 				   _spdk_blob_persist_zero_pages, ctx);
1305 }
1306 
1307 static void
1308 _spdk_blob_persist_write_page_chain(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1309 {
1310 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1311 	struct spdk_blob		*blob = ctx->blob;
1312 	struct spdk_blob_store		*bs = blob->bs;
1313 	uint64_t			lba;
1314 	uint32_t			lba_count;
1315 	struct spdk_blob_md_page	*page;
1316 	spdk_bs_batch_t			*batch;
1317 	size_t				i;
1318 
1319 	/* Clusters don't move around in blobs. The list shrinks or grows
1320 	 * at the end, but no changes ever occur in the middle of the list.
1321 	 */
1322 
1323 	lba_count = _spdk_bs_byte_to_lba(bs, sizeof(*page));
1324 
1325 	batch = spdk_bs_sequence_to_batch(seq, _spdk_blob_persist_write_page_root, ctx);
1326 
1327 	/* This starts at 1. The root page is not written until
1328 	 * all of the others are finished
1329 	 */
1330 	for (i = 1; i < blob->active.num_pages; i++) {
1331 		page = &ctx->pages[i];
1332 		assert(page->sequence_num == i);
1333 
1334 		lba = _spdk_bs_page_to_lba(bs, bs->md_start + blob->active.pages[i]);
1335 
1336 		spdk_bs_batch_write_dev(batch, page, lba, lba_count);
1337 	}
1338 
1339 	spdk_bs_batch_close(batch);
1340 }
1341 
1342 static int
1343 _spdk_blob_resize(struct spdk_blob *blob, uint64_t sz)
1344 {
1345 	uint64_t	i;
1346 	uint64_t	*tmp;
1347 	uint64_t	lfc; /* lowest free cluster */
1348 	uint64_t	num_clusters;
1349 	struct spdk_blob_store *bs;
1350 
1351 	bs = blob->bs;
1352 
1353 	_spdk_blob_verify_md_op(blob);
1354 
1355 	if (blob->active.num_clusters == sz) {
1356 		return 0;
1357 	}
1358 
1359 	if (blob->active.num_clusters < blob->active.cluster_array_size) {
1360 		/* If this blob was resized to be larger, then smaller, then
1361 		 * larger without syncing, then the cluster array already
1362 		 * contains spare assigned clusters we can use.
1363 		 */
1364 		num_clusters = spdk_min(blob->active.cluster_array_size,
1365 					sz);
1366 	} else {
1367 		num_clusters = blob->active.num_clusters;
1368 	}
1369 
1370 	/* Do two passes - one to verify that we can obtain enough clusters
1371 	 * and another to actually claim them.
1372 	 */
1373 
1374 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1375 		lfc = 0;
1376 		for (i = num_clusters; i < sz; i++) {
1377 			lfc = spdk_bit_array_find_first_clear(bs->used_clusters, lfc);
1378 			if (lfc == UINT32_MAX) {
1379 				/* No more free clusters. Cannot satisfy the request */
1380 				return -ENOSPC;
1381 			}
1382 			lfc++;
1383 		}
1384 	}
1385 
1386 	if (sz > num_clusters) {
1387 		/* Expand the cluster array if necessary.
1388 		 * We only shrink the array when persisting.
1389 		 */
1390 		tmp = realloc(blob->active.clusters, sizeof(uint64_t) * sz);
1391 		if (sz > 0 && tmp == NULL) {
1392 			return -ENOMEM;
1393 		}
1394 		memset(tmp + blob->active.cluster_array_size, 0,
1395 		       sizeof(uint64_t) * (sz - blob->active.cluster_array_size));
1396 		blob->active.clusters = tmp;
1397 		blob->active.cluster_array_size = sz;
1398 	}
1399 
1400 	blob->state = SPDK_BLOB_STATE_DIRTY;
1401 
1402 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1403 		lfc = 0;
1404 		for (i = num_clusters; i < sz; i++) {
1405 			_spdk_bs_allocate_cluster(blob, i, &lfc, true);
1406 			lfc++;
1407 		}
1408 	}
1409 
1410 	blob->active.num_clusters = sz;
1411 
1412 	return 0;
1413 }
1414 
1415 static void
1416 _spdk_blob_persist_start(struct spdk_blob_persist_ctx *ctx)
1417 {
1418 	spdk_bs_sequence_t *seq = ctx->seq;
1419 	struct spdk_blob *blob = ctx->blob;
1420 	struct spdk_blob_store *bs = blob->bs;
1421 	uint64_t i;
1422 	uint32_t page_num;
1423 	void *tmp;
1424 	int rc;
1425 
1426 	if (blob->active.num_pages == 0) {
1427 		/* This is the signal that the blob should be deleted.
1428 		 * Immediately jump to the clean up routine. */
1429 		assert(blob->clean.num_pages > 0);
1430 		ctx->idx = blob->clean.num_pages - 1;
1431 		blob->state = SPDK_BLOB_STATE_CLEAN;
1432 		_spdk_blob_persist_zero_pages(seq, ctx, 0);
1433 		return;
1434 
1435 	}
1436 
1437 	/* Generate the new metadata */
1438 	rc = _spdk_blob_serialize(blob, &ctx->pages, &blob->active.num_pages);
1439 	if (rc < 0) {
1440 		_spdk_blob_persist_complete(seq, ctx, rc);
1441 		return;
1442 	}
1443 
1444 	assert(blob->active.num_pages >= 1);
1445 
1446 	/* Resize the cache of page indices */
1447 	tmp = realloc(blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
1448 	if (!tmp) {
1449 		_spdk_blob_persist_complete(seq, ctx, -ENOMEM);
1450 		return;
1451 	}
1452 	blob->active.pages = tmp;
1453 
1454 	/* Assign this metadata to pages. This requires two passes -
1455 	 * one to verify that there are enough pages and a second
1456 	 * to actually claim them. */
1457 	page_num = 0;
1458 	/* Note that this loop starts at one. The first page location is fixed by the blobid. */
1459 	for (i = 1; i < blob->active.num_pages; i++) {
1460 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1461 		if (page_num == UINT32_MAX) {
1462 			_spdk_blob_persist_complete(seq, ctx, -ENOMEM);
1463 			return;
1464 		}
1465 		page_num++;
1466 	}
1467 
1468 	page_num = 0;
1469 	blob->active.pages[0] = _spdk_bs_blobid_to_page(blob->id);
1470 	for (i = 1; i < blob->active.num_pages; i++) {
1471 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1472 		ctx->pages[i - 1].next = page_num;
1473 		/* Now that previous metadata page is complete, calculate the crc for it. */
1474 		ctx->pages[i - 1].crc = _spdk_blob_md_page_calc_crc(&ctx->pages[i - 1]);
1475 		blob->active.pages[i] = page_num;
1476 		spdk_bit_array_set(bs->used_md_pages, page_num);
1477 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming page %u for blob %lu\n", page_num, blob->id);
1478 		page_num++;
1479 	}
1480 	ctx->pages[i - 1].crc = _spdk_blob_md_page_calc_crc(&ctx->pages[i - 1]);
1481 	/* Start writing the metadata from last page to first */
1482 	ctx->idx = blob->active.num_pages - 1;
1483 	blob->state = SPDK_BLOB_STATE_CLEAN;
1484 	_spdk_blob_persist_write_page_chain(seq, ctx, 0);
1485 }
1486 
1487 static void
1488 _spdk_blob_persist_dirty_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1489 {
1490 	struct spdk_blob_persist_ctx *ctx = cb_arg;
1491 
1492 	ctx->blob->bs->clean = 0;
1493 
1494 	spdk_free(ctx->super);
1495 
1496 	_spdk_blob_persist_start(ctx);
1497 }
1498 
1499 static void
1500 _spdk_bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
1501 		     struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg);
1502 
1503 
1504 static void
1505 _spdk_blob_persist_dirty(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1506 {
1507 	struct spdk_blob_persist_ctx *ctx = cb_arg;
1508 
1509 	ctx->super->clean = 0;
1510 	if (ctx->super->size == 0) {
1511 		ctx->super->size = ctx->blob->bs->dev->blockcnt * ctx->blob->bs->dev->blocklen;
1512 	}
1513 
1514 	_spdk_bs_write_super(seq, ctx->blob->bs, ctx->super, _spdk_blob_persist_dirty_cpl, ctx);
1515 }
1516 
1517 
1518 /* Write a blob to disk */
1519 static void
1520 _spdk_blob_persist(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1521 		   spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1522 {
1523 	struct spdk_blob_persist_ctx *ctx;
1524 
1525 	_spdk_blob_verify_md_op(blob);
1526 
1527 	if (blob->state == SPDK_BLOB_STATE_CLEAN) {
1528 		cb_fn(seq, cb_arg, 0);
1529 		return;
1530 	}
1531 
1532 	ctx = calloc(1, sizeof(*ctx));
1533 	if (!ctx) {
1534 		cb_fn(seq, cb_arg, -ENOMEM);
1535 		return;
1536 	}
1537 	ctx->blob = blob;
1538 	ctx->seq = seq;
1539 	ctx->cb_fn = cb_fn;
1540 	ctx->cb_arg = cb_arg;
1541 
1542 	if (blob->bs->clean) {
1543 		ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
1544 					  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1545 		if (!ctx->super) {
1546 			cb_fn(seq, cb_arg, -ENOMEM);
1547 			free(ctx);
1548 			return;
1549 		}
1550 
1551 		spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(blob->bs, 0),
1552 					  _spdk_bs_byte_to_lba(blob->bs, sizeof(*ctx->super)),
1553 					  _spdk_blob_persist_dirty, ctx);
1554 	} else {
1555 		_spdk_blob_persist_start(ctx);
1556 	}
1557 }
1558 
1559 struct spdk_blob_copy_cluster_ctx {
1560 	struct spdk_blob *blob;
1561 	uint8_t *buf;
1562 	uint64_t page;
1563 	uint64_t new_cluster;
1564 	spdk_bs_sequence_t *seq;
1565 };
1566 
1567 static void
1568 _spdk_blob_allocate_and_copy_cluster_cpl(void *cb_arg, int bserrno)
1569 {
1570 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1571 	struct spdk_bs_request_set *set = (struct spdk_bs_request_set *)ctx->seq;
1572 	TAILQ_HEAD(, spdk_bs_request_set) requests;
1573 	spdk_bs_user_op_t *op;
1574 
1575 	TAILQ_INIT(&requests);
1576 	TAILQ_SWAP(&set->channel->need_cluster_alloc, &requests, spdk_bs_request_set, link);
1577 
1578 	while (!TAILQ_EMPTY(&requests)) {
1579 		op = TAILQ_FIRST(&requests);
1580 		TAILQ_REMOVE(&requests, op, link);
1581 		if (bserrno == 0) {
1582 			spdk_bs_user_op_execute(op);
1583 		} else {
1584 			spdk_bs_user_op_abort(op);
1585 		}
1586 	}
1587 
1588 	spdk_free(ctx->buf);
1589 	free(ctx);
1590 }
1591 
1592 static void
1593 _spdk_blob_insert_cluster_cpl(void *cb_arg, int bserrno)
1594 {
1595 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1596 
1597 	if (bserrno) {
1598 		if (bserrno == -EEXIST) {
1599 			/* The metadata insert failed because another thread
1600 			 * allocated the cluster first. Free our cluster
1601 			 * but continue without error. */
1602 			bserrno = 0;
1603 		}
1604 		_spdk_bs_release_cluster(ctx->blob->bs, ctx->new_cluster);
1605 	}
1606 
1607 	spdk_bs_sequence_finish(ctx->seq, bserrno);
1608 }
1609 
1610 static void
1611 _spdk_blob_write_copy_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1612 {
1613 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1614 	uint32_t cluster_number;
1615 
1616 	if (bserrno) {
1617 		/* The write failed, so jump to the final completion handler */
1618 		spdk_bs_sequence_finish(seq, bserrno);
1619 		return;
1620 	}
1621 
1622 	cluster_number = _spdk_bs_page_to_cluster(ctx->blob->bs, ctx->page);
1623 
1624 	_spdk_blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
1625 					       _spdk_blob_insert_cluster_cpl, ctx);
1626 }
1627 
1628 static void
1629 _spdk_blob_write_copy(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1630 {
1631 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
1632 
1633 	if (bserrno != 0) {
1634 		/* The read failed, so jump to the final completion handler */
1635 		spdk_bs_sequence_finish(seq, bserrno);
1636 		return;
1637 	}
1638 
1639 	/* Write whole cluster */
1640 	spdk_bs_sequence_write_dev(seq, ctx->buf,
1641 				   _spdk_bs_cluster_to_lba(ctx->blob->bs, ctx->new_cluster),
1642 				   _spdk_bs_cluster_to_lba(ctx->blob->bs, 1),
1643 				   _spdk_blob_write_copy_cpl, ctx);
1644 }
1645 
1646 static void
1647 _spdk_bs_allocate_and_copy_cluster(struct spdk_blob *blob,
1648 				   struct spdk_io_channel *_ch,
1649 				   uint64_t io_unit, spdk_bs_user_op_t *op)
1650 {
1651 	struct spdk_bs_cpl cpl;
1652 	struct spdk_bs_channel *ch;
1653 	struct spdk_blob_copy_cluster_ctx *ctx;
1654 	uint32_t cluster_start_page;
1655 	uint32_t cluster_number;
1656 	int rc;
1657 
1658 	ch = spdk_io_channel_get_ctx(_ch);
1659 
1660 	if (!TAILQ_EMPTY(&ch->need_cluster_alloc)) {
1661 		/* There are already operations pending. Queue this user op
1662 		 * and return because it will be re-executed when the outstanding
1663 		 * cluster allocation completes. */
1664 		TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
1665 		return;
1666 	}
1667 
1668 	/* Round the io_unit offset down to the first page in the cluster */
1669 	cluster_start_page = _spdk_bs_io_unit_to_cluster_start(blob, io_unit);
1670 
1671 	/* Calculate which index in the metadata cluster array the corresponding
1672 	 * cluster is supposed to be at. */
1673 	cluster_number = _spdk_bs_io_unit_to_cluster_number(blob, io_unit);
1674 
1675 	ctx = calloc(1, sizeof(*ctx));
1676 	if (!ctx) {
1677 		spdk_bs_user_op_abort(op);
1678 		return;
1679 	}
1680 
1681 	assert(blob->bs->cluster_sz % blob->back_bs_dev->blocklen == 0);
1682 
1683 	ctx->blob = blob;
1684 	ctx->page = cluster_start_page;
1685 
1686 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
1687 		ctx->buf = spdk_malloc(blob->bs->cluster_sz, blob->back_bs_dev->blocklen,
1688 				       NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1689 		if (!ctx->buf) {
1690 			SPDK_ERRLOG("DMA allocation for cluster of size = %" PRIu32 " failed.\n",
1691 				    blob->bs->cluster_sz);
1692 			free(ctx);
1693 			spdk_bs_user_op_abort(op);
1694 			return;
1695 		}
1696 	}
1697 
1698 	rc = _spdk_bs_allocate_cluster(blob, cluster_number, &ctx->new_cluster, false);
1699 	if (rc != 0) {
1700 		spdk_free(ctx->buf);
1701 		free(ctx);
1702 		spdk_bs_user_op_abort(op);
1703 		return;
1704 	}
1705 
1706 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1707 	cpl.u.blob_basic.cb_fn = _spdk_blob_allocate_and_copy_cluster_cpl;
1708 	cpl.u.blob_basic.cb_arg = ctx;
1709 
1710 	ctx->seq = spdk_bs_sequence_start(_ch, &cpl);
1711 	if (!ctx->seq) {
1712 		_spdk_bs_release_cluster(blob->bs, ctx->new_cluster);
1713 		spdk_free(ctx->buf);
1714 		free(ctx);
1715 		spdk_bs_user_op_abort(op);
1716 		return;
1717 	}
1718 
1719 	/* Queue the user op to block other incoming operations */
1720 	TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
1721 
1722 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
1723 		/* Read cluster from backing device */
1724 		spdk_bs_sequence_read_bs_dev(ctx->seq, blob->back_bs_dev, ctx->buf,
1725 					     _spdk_bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page),
1726 					     _spdk_bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz),
1727 					     _spdk_blob_write_copy, ctx);
1728 	} else {
1729 		_spdk_blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
1730 						       _spdk_blob_insert_cluster_cpl, ctx);
1731 	}
1732 }
1733 
1734 static void
1735 _spdk_blob_calculate_lba_and_lba_count(struct spdk_blob *blob, uint64_t io_unit, uint64_t length,
1736 				       uint64_t *lba,	uint32_t *lba_count)
1737 {
1738 	*lba_count = length;
1739 
1740 	if (!_spdk_bs_io_unit_is_allocated(blob, io_unit)) {
1741 		assert(blob->back_bs_dev != NULL);
1742 		*lba = _spdk_bs_io_unit_to_back_dev_lba(blob, io_unit);
1743 		*lba_count = _spdk_bs_io_unit_to_back_dev_lba(blob, *lba_count);
1744 	} else {
1745 		*lba = _spdk_bs_blob_io_unit_to_lba(blob, io_unit);
1746 	}
1747 }
1748 
1749 struct op_split_ctx {
1750 	struct spdk_blob *blob;
1751 	struct spdk_io_channel *channel;
1752 	uint64_t io_unit_offset;
1753 	uint64_t io_units_remaining;
1754 	void *curr_payload;
1755 	enum spdk_blob_op_type op_type;
1756 	spdk_bs_sequence_t *seq;
1757 };
1758 
1759 static void
1760 _spdk_blob_request_submit_op_split_next(void *cb_arg, int bserrno)
1761 {
1762 	struct op_split_ctx	*ctx = cb_arg;
1763 	struct spdk_blob	*blob = ctx->blob;
1764 	struct spdk_io_channel	*ch = ctx->channel;
1765 	enum spdk_blob_op_type	op_type = ctx->op_type;
1766 	uint8_t			*buf = ctx->curr_payload;
1767 	uint64_t		offset = ctx->io_unit_offset;
1768 	uint64_t		length = ctx->io_units_remaining;
1769 	uint64_t		op_length;
1770 
1771 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
1772 		spdk_bs_sequence_finish(ctx->seq, bserrno);
1773 		free(ctx);
1774 		return;
1775 	}
1776 
1777 	op_length = spdk_min(length, _spdk_bs_num_io_units_to_cluster_boundary(blob,
1778 			     offset));
1779 
1780 	/* Update length and payload for next operation */
1781 	ctx->io_units_remaining -= op_length;
1782 	ctx->io_unit_offset += op_length;
1783 	if (op_type == SPDK_BLOB_WRITE || op_type == SPDK_BLOB_READ) {
1784 		ctx->curr_payload += op_length * blob->bs->io_unit_size;
1785 	}
1786 
1787 	switch (op_type) {
1788 	case SPDK_BLOB_READ:
1789 		spdk_blob_io_read(blob, ch, buf, offset, op_length,
1790 				  _spdk_blob_request_submit_op_split_next, ctx);
1791 		break;
1792 	case SPDK_BLOB_WRITE:
1793 		spdk_blob_io_write(blob, ch, buf, offset, op_length,
1794 				   _spdk_blob_request_submit_op_split_next, ctx);
1795 		break;
1796 	case SPDK_BLOB_UNMAP:
1797 		spdk_blob_io_unmap(blob, ch, offset, op_length,
1798 				   _spdk_blob_request_submit_op_split_next, ctx);
1799 		break;
1800 	case SPDK_BLOB_WRITE_ZEROES:
1801 		spdk_blob_io_write_zeroes(blob, ch, offset, op_length,
1802 					  _spdk_blob_request_submit_op_split_next, ctx);
1803 		break;
1804 	case SPDK_BLOB_READV:
1805 	case SPDK_BLOB_WRITEV:
1806 		SPDK_ERRLOG("readv/write not valid for %s\n", __func__);
1807 		spdk_bs_sequence_finish(ctx->seq, -EINVAL);
1808 		free(ctx);
1809 		break;
1810 	}
1811 }
1812 
1813 static void
1814 _spdk_blob_request_submit_op_split(struct spdk_io_channel *ch, struct spdk_blob *blob,
1815 				   void *payload, uint64_t offset, uint64_t length,
1816 				   spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1817 {
1818 	struct op_split_ctx *ctx;
1819 	spdk_bs_sequence_t *seq;
1820 	struct spdk_bs_cpl cpl;
1821 
1822 	assert(blob != NULL);
1823 
1824 	ctx = calloc(1, sizeof(struct op_split_ctx));
1825 	if (ctx == NULL) {
1826 		cb_fn(cb_arg, -ENOMEM);
1827 		return;
1828 	}
1829 
1830 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1831 	cpl.u.blob_basic.cb_fn = cb_fn;
1832 	cpl.u.blob_basic.cb_arg = cb_arg;
1833 
1834 	seq = spdk_bs_sequence_start(ch, &cpl);
1835 	if (!seq) {
1836 		free(ctx);
1837 		cb_fn(cb_arg, -ENOMEM);
1838 		return;
1839 	}
1840 
1841 	ctx->blob = blob;
1842 	ctx->channel = ch;
1843 	ctx->curr_payload = payload;
1844 	ctx->io_unit_offset = offset;
1845 	ctx->io_units_remaining = length;
1846 	ctx->op_type = op_type;
1847 	ctx->seq = seq;
1848 
1849 	_spdk_blob_request_submit_op_split_next(ctx, 0);
1850 }
1851 
1852 static void
1853 _spdk_blob_request_submit_op_single(struct spdk_io_channel *_ch, struct spdk_blob *blob,
1854 				    void *payload, uint64_t offset, uint64_t length,
1855 				    spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1856 {
1857 	struct spdk_bs_cpl cpl;
1858 	uint64_t lba;
1859 	uint32_t lba_count;
1860 
1861 	assert(blob != NULL);
1862 
1863 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1864 	cpl.u.blob_basic.cb_fn = cb_fn;
1865 	cpl.u.blob_basic.cb_arg = cb_arg;
1866 
1867 	_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
1868 
1869 	if (blob->frozen_refcnt) {
1870 		/* This blob I/O is frozen */
1871 		spdk_bs_user_op_t *op;
1872 		struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_ch);
1873 
1874 		op = spdk_bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
1875 		if (!op) {
1876 			cb_fn(cb_arg, -ENOMEM);
1877 			return;
1878 		}
1879 
1880 		TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
1881 
1882 		return;
1883 	}
1884 
1885 	switch (op_type) {
1886 	case SPDK_BLOB_READ: {
1887 		spdk_bs_batch_t *batch;
1888 
1889 		batch = spdk_bs_batch_open(_ch, &cpl);
1890 		if (!batch) {
1891 			cb_fn(cb_arg, -ENOMEM);
1892 			return;
1893 		}
1894 
1895 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1896 			/* Read from the blob */
1897 			spdk_bs_batch_read_dev(batch, payload, lba, lba_count);
1898 		} else {
1899 			/* Read from the backing block device */
1900 			spdk_bs_batch_read_bs_dev(batch, blob->back_bs_dev, payload, lba, lba_count);
1901 		}
1902 
1903 		spdk_bs_batch_close(batch);
1904 		break;
1905 	}
1906 	case SPDK_BLOB_WRITE:
1907 	case SPDK_BLOB_WRITE_ZEROES: {
1908 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1909 			/* Write to the blob */
1910 			spdk_bs_batch_t *batch;
1911 
1912 			if (lba_count == 0) {
1913 				cb_fn(cb_arg, 0);
1914 				return;
1915 			}
1916 
1917 			batch = spdk_bs_batch_open(_ch, &cpl);
1918 			if (!batch) {
1919 				cb_fn(cb_arg, -ENOMEM);
1920 				return;
1921 			}
1922 
1923 			if (op_type == SPDK_BLOB_WRITE) {
1924 				spdk_bs_batch_write_dev(batch, payload, lba, lba_count);
1925 			} else {
1926 				spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1927 			}
1928 
1929 			spdk_bs_batch_close(batch);
1930 		} else {
1931 			/* Queue this operation and allocate the cluster */
1932 			spdk_bs_user_op_t *op;
1933 
1934 			op = spdk_bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
1935 			if (!op) {
1936 				cb_fn(cb_arg, -ENOMEM);
1937 				return;
1938 			}
1939 
1940 			_spdk_bs_allocate_and_copy_cluster(blob, _ch, offset, op);
1941 		}
1942 		break;
1943 	}
1944 	case SPDK_BLOB_UNMAP: {
1945 		spdk_bs_batch_t *batch;
1946 
1947 		batch = spdk_bs_batch_open(_ch, &cpl);
1948 		if (!batch) {
1949 			cb_fn(cb_arg, -ENOMEM);
1950 			return;
1951 		}
1952 
1953 		if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
1954 			spdk_bs_batch_unmap_dev(batch, lba, lba_count);
1955 		}
1956 
1957 		spdk_bs_batch_close(batch);
1958 		break;
1959 	}
1960 	case SPDK_BLOB_READV:
1961 	case SPDK_BLOB_WRITEV:
1962 		SPDK_ERRLOG("readv/write not valid\n");
1963 		cb_fn(cb_arg, -EINVAL);
1964 		break;
1965 	}
1966 }
1967 
1968 static void
1969 _spdk_blob_request_submit_op(struct spdk_blob *blob, struct spdk_io_channel *_channel,
1970 			     void *payload, uint64_t offset, uint64_t length,
1971 			     spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1972 {
1973 	assert(blob != NULL);
1974 
1975 	if (blob->data_ro && op_type != SPDK_BLOB_READ) {
1976 		cb_fn(cb_arg, -EPERM);
1977 		return;
1978 	}
1979 
1980 	if (offset + length > _spdk_bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
1981 		cb_fn(cb_arg, -EINVAL);
1982 		return;
1983 	}
1984 	if (length <= _spdk_bs_num_io_units_to_cluster_boundary(blob, offset)) {
1985 		_spdk_blob_request_submit_op_single(_channel, blob, payload, offset, length,
1986 						    cb_fn, cb_arg, op_type);
1987 	} else {
1988 		_spdk_blob_request_submit_op_split(_channel, blob, payload, offset, length,
1989 						   cb_fn, cb_arg, op_type);
1990 	}
1991 }
1992 
1993 struct rw_iov_ctx {
1994 	struct spdk_blob *blob;
1995 	struct spdk_io_channel *channel;
1996 	spdk_blob_op_complete cb_fn;
1997 	void *cb_arg;
1998 	bool read;
1999 	int iovcnt;
2000 	struct iovec *orig_iov;
2001 	uint64_t io_unit_offset;
2002 	uint64_t io_units_remaining;
2003 	uint64_t io_units_done;
2004 	struct iovec iov[0];
2005 };
2006 
2007 static void
2008 _spdk_rw_iov_done(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2009 {
2010 	assert(cb_arg == NULL);
2011 	spdk_bs_sequence_finish(seq, bserrno);
2012 }
2013 
2014 static void
2015 _spdk_rw_iov_split_next(void *cb_arg, int bserrno)
2016 {
2017 	struct rw_iov_ctx *ctx = cb_arg;
2018 	struct spdk_blob *blob = ctx->blob;
2019 	struct iovec *iov, *orig_iov;
2020 	int iovcnt;
2021 	size_t orig_iovoff;
2022 	uint64_t io_units_count, io_units_to_boundary, io_unit_offset;
2023 	uint64_t byte_count;
2024 
2025 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
2026 		ctx->cb_fn(ctx->cb_arg, bserrno);
2027 		free(ctx);
2028 		return;
2029 	}
2030 
2031 	io_unit_offset = ctx->io_unit_offset;
2032 	io_units_to_boundary = _spdk_bs_num_io_units_to_cluster_boundary(blob, io_unit_offset);
2033 	io_units_count = spdk_min(ctx->io_units_remaining, io_units_to_boundary);
2034 	/*
2035 	 * Get index and offset into the original iov array for our current position in the I/O sequence.
2036 	 *  byte_count will keep track of how many bytes remaining until orig_iov and orig_iovoff will
2037 	 *  point to the current position in the I/O sequence.
2038 	 */
2039 	byte_count = ctx->io_units_done * blob->bs->io_unit_size;
2040 	orig_iov = &ctx->orig_iov[0];
2041 	orig_iovoff = 0;
2042 	while (byte_count > 0) {
2043 		if (byte_count >= orig_iov->iov_len) {
2044 			byte_count -= orig_iov->iov_len;
2045 			orig_iov++;
2046 		} else {
2047 			orig_iovoff = byte_count;
2048 			byte_count = 0;
2049 		}
2050 	}
2051 
2052 	/*
2053 	 * Build an iov array for the next I/O in the sequence.  byte_count will keep track of how many
2054 	 *  bytes of this next I/O remain to be accounted for in the new iov array.
2055 	 */
2056 	byte_count = io_units_count * blob->bs->io_unit_size;
2057 	iov = &ctx->iov[0];
2058 	iovcnt = 0;
2059 	while (byte_count > 0) {
2060 		assert(iovcnt < ctx->iovcnt);
2061 		iov->iov_len = spdk_min(byte_count, orig_iov->iov_len - orig_iovoff);
2062 		iov->iov_base = orig_iov->iov_base + orig_iovoff;
2063 		byte_count -= iov->iov_len;
2064 		orig_iovoff = 0;
2065 		orig_iov++;
2066 		iov++;
2067 		iovcnt++;
2068 	}
2069 
2070 	ctx->io_unit_offset += io_units_count;
2071 	ctx->io_units_remaining -= io_units_count;
2072 	ctx->io_units_done += io_units_count;
2073 	iov = &ctx->iov[0];
2074 
2075 	if (ctx->read) {
2076 		spdk_blob_io_readv(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2077 				   io_units_count, _spdk_rw_iov_split_next, ctx);
2078 	} else {
2079 		spdk_blob_io_writev(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2080 				    io_units_count, _spdk_rw_iov_split_next, ctx);
2081 	}
2082 }
2083 
2084 static void
2085 _spdk_blob_request_submit_rw_iov(struct spdk_blob *blob, struct spdk_io_channel *_channel,
2086 				 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
2087 				 spdk_blob_op_complete cb_fn, void *cb_arg, bool read)
2088 {
2089 	struct spdk_bs_cpl	cpl;
2090 
2091 	assert(blob != NULL);
2092 
2093 	if (!read && blob->data_ro) {
2094 		cb_fn(cb_arg, -EPERM);
2095 		return;
2096 	}
2097 
2098 	if (length == 0) {
2099 		cb_fn(cb_arg, 0);
2100 		return;
2101 	}
2102 
2103 	if (offset + length > _spdk_bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
2104 		cb_fn(cb_arg, -EINVAL);
2105 		return;
2106 	}
2107 
2108 	/*
2109 	 * For now, we implement readv/writev using a sequence (instead of a batch) to account for having
2110 	 *  to split a request that spans a cluster boundary.  For I/O that do not span a cluster boundary,
2111 	 *  there will be no noticeable difference compared to using a batch.  For I/O that do span a cluster
2112 	 *  boundary, the target LBAs (after blob offset to LBA translation) may not be contiguous, so we need
2113 	 *  to allocate a separate iov array and split the I/O such that none of the resulting
2114 	 *  smaller I/O cross a cluster boundary.  These smaller I/O will be issued in sequence (not in parallel)
2115 	 *  but since this case happens very infrequently, any performance impact will be negligible.
2116 	 *
2117 	 * This could be optimized in the future to allocate a big enough iov array to account for all of the iovs
2118 	 *  for all of the smaller I/Os, pre-build all of the iov arrays for the smaller I/Os, then issue them
2119 	 *  in a batch.  That would also require creating an intermediate spdk_bs_cpl that would get called
2120 	 *  when the batch was completed, to allow for freeing the memory for the iov arrays.
2121 	 */
2122 	if (spdk_likely(length <= _spdk_bs_num_io_units_to_cluster_boundary(blob, offset))) {
2123 		uint32_t lba_count;
2124 		uint64_t lba;
2125 
2126 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2127 		cpl.u.blob_basic.cb_fn = cb_fn;
2128 		cpl.u.blob_basic.cb_arg = cb_arg;
2129 
2130 		if (blob->frozen_refcnt) {
2131 			/* This blob I/O is frozen */
2132 			enum spdk_blob_op_type op_type;
2133 			spdk_bs_user_op_t *op;
2134 			struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_channel);
2135 
2136 			op_type = read ? SPDK_BLOB_READV : SPDK_BLOB_WRITEV;
2137 			op = spdk_bs_user_op_alloc(_channel, &cpl, op_type, blob, iov, iovcnt, offset, length);
2138 			if (!op) {
2139 				cb_fn(cb_arg, -ENOMEM);
2140 				return;
2141 			}
2142 
2143 			TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
2144 
2145 			return;
2146 		}
2147 
2148 		_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
2149 
2150 		if (read) {
2151 			spdk_bs_sequence_t *seq;
2152 
2153 			seq = spdk_bs_sequence_start(_channel, &cpl);
2154 			if (!seq) {
2155 				cb_fn(cb_arg, -ENOMEM);
2156 				return;
2157 			}
2158 
2159 			if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
2160 				spdk_bs_sequence_readv_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
2161 			} else {
2162 				spdk_bs_sequence_readv_bs_dev(seq, blob->back_bs_dev, iov, iovcnt, lba, lba_count,
2163 							      _spdk_rw_iov_done, NULL);
2164 			}
2165 		} else {
2166 			if (_spdk_bs_io_unit_is_allocated(blob, offset)) {
2167 				spdk_bs_sequence_t *seq;
2168 
2169 				seq = spdk_bs_sequence_start(_channel, &cpl);
2170 				if (!seq) {
2171 					cb_fn(cb_arg, -ENOMEM);
2172 					return;
2173 				}
2174 
2175 				spdk_bs_sequence_writev_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
2176 			} else {
2177 				/* Queue this operation and allocate the cluster */
2178 				spdk_bs_user_op_t *op;
2179 
2180 				op = spdk_bs_user_op_alloc(_channel, &cpl, SPDK_BLOB_WRITEV, blob, iov, iovcnt, offset,
2181 							   length);
2182 				if (!op) {
2183 					cb_fn(cb_arg, -ENOMEM);
2184 					return;
2185 				}
2186 
2187 				_spdk_bs_allocate_and_copy_cluster(blob, _channel, offset, op);
2188 			}
2189 		}
2190 	} else {
2191 		struct rw_iov_ctx *ctx;
2192 
2193 		ctx = calloc(1, sizeof(struct rw_iov_ctx) + iovcnt * sizeof(struct iovec));
2194 		if (ctx == NULL) {
2195 			cb_fn(cb_arg, -ENOMEM);
2196 			return;
2197 		}
2198 
2199 		ctx->blob = blob;
2200 		ctx->channel = _channel;
2201 		ctx->cb_fn = cb_fn;
2202 		ctx->cb_arg = cb_arg;
2203 		ctx->read = read;
2204 		ctx->orig_iov = iov;
2205 		ctx->iovcnt = iovcnt;
2206 		ctx->io_unit_offset = offset;
2207 		ctx->io_units_remaining = length;
2208 		ctx->io_units_done = 0;
2209 
2210 		_spdk_rw_iov_split_next(ctx, 0);
2211 	}
2212 }
2213 
2214 static struct spdk_blob *
2215 _spdk_blob_lookup(struct spdk_blob_store *bs, spdk_blob_id blobid)
2216 {
2217 	struct spdk_blob *blob;
2218 
2219 	TAILQ_FOREACH(blob, &bs->blobs, link) {
2220 		if (blob->id == blobid) {
2221 			return blob;
2222 		}
2223 	}
2224 
2225 	return NULL;
2226 }
2227 
2228 static void
2229 _spdk_blob_get_snapshot_and_clone_entries(struct spdk_blob *blob,
2230 		struct spdk_blob_list **snapshot_entry, struct spdk_blob_list **clone_entry)
2231 {
2232 	assert(blob != NULL);
2233 	*snapshot_entry = NULL;
2234 	*clone_entry = NULL;
2235 
2236 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
2237 		return;
2238 	}
2239 
2240 	TAILQ_FOREACH(*snapshot_entry, &blob->bs->snapshots, link) {
2241 		if ((*snapshot_entry)->id == blob->parent_id) {
2242 			break;
2243 		}
2244 	}
2245 
2246 	if (*snapshot_entry != NULL) {
2247 		TAILQ_FOREACH(*clone_entry, &(*snapshot_entry)->clones, link) {
2248 			if ((*clone_entry)->id == blob->id) {
2249 				break;
2250 			}
2251 		}
2252 
2253 		assert(clone_entry != NULL);
2254 	}
2255 }
2256 
2257 static int
2258 _spdk_bs_channel_create(void *io_device, void *ctx_buf)
2259 {
2260 	struct spdk_blob_store		*bs = io_device;
2261 	struct spdk_bs_channel		*channel = ctx_buf;
2262 	struct spdk_bs_dev		*dev;
2263 	uint32_t			max_ops = bs->max_channel_ops;
2264 	uint32_t			i;
2265 
2266 	dev = bs->dev;
2267 
2268 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_bs_request_set));
2269 	if (!channel->req_mem) {
2270 		return -1;
2271 	}
2272 
2273 	TAILQ_INIT(&channel->reqs);
2274 
2275 	for (i = 0; i < max_ops; i++) {
2276 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
2277 	}
2278 
2279 	channel->bs = bs;
2280 	channel->dev = dev;
2281 	channel->dev_channel = dev->create_channel(dev);
2282 
2283 	if (!channel->dev_channel) {
2284 		SPDK_ERRLOG("Failed to create device channel.\n");
2285 		free(channel->req_mem);
2286 		return -1;
2287 	}
2288 
2289 	TAILQ_INIT(&channel->need_cluster_alloc);
2290 	TAILQ_INIT(&channel->queued_io);
2291 
2292 	return 0;
2293 }
2294 
2295 static void
2296 _spdk_bs_channel_destroy(void *io_device, void *ctx_buf)
2297 {
2298 	struct spdk_bs_channel *channel = ctx_buf;
2299 	spdk_bs_user_op_t *op;
2300 
2301 	while (!TAILQ_EMPTY(&channel->need_cluster_alloc)) {
2302 		op = TAILQ_FIRST(&channel->need_cluster_alloc);
2303 		TAILQ_REMOVE(&channel->need_cluster_alloc, op, link);
2304 		spdk_bs_user_op_abort(op);
2305 	}
2306 
2307 	while (!TAILQ_EMPTY(&channel->queued_io)) {
2308 		op = TAILQ_FIRST(&channel->queued_io);
2309 		TAILQ_REMOVE(&channel->queued_io, op, link);
2310 		spdk_bs_user_op_abort(op);
2311 	}
2312 
2313 	free(channel->req_mem);
2314 	channel->dev->destroy_channel(channel->dev, channel->dev_channel);
2315 }
2316 
2317 static void
2318 _spdk_bs_dev_destroy(void *io_device)
2319 {
2320 	struct spdk_blob_store *bs = io_device;
2321 	struct spdk_blob	*blob, *blob_tmp;
2322 
2323 	bs->dev->destroy(bs->dev);
2324 
2325 	TAILQ_FOREACH_SAFE(blob, &bs->blobs, link, blob_tmp) {
2326 		TAILQ_REMOVE(&bs->blobs, blob, link);
2327 		_spdk_blob_free(blob);
2328 	}
2329 
2330 	pthread_mutex_destroy(&bs->used_clusters_mutex);
2331 
2332 	spdk_bit_array_free(&bs->used_blobids);
2333 	spdk_bit_array_free(&bs->used_md_pages);
2334 	spdk_bit_array_free(&bs->used_clusters);
2335 	/*
2336 	 * If this function is called for any reason except a successful unload,
2337 	 * the unload_cpl type will be NONE and this will be a nop.
2338 	 */
2339 	spdk_bs_call_cpl(&bs->unload_cpl, bs->unload_err);
2340 
2341 	free(bs);
2342 }
2343 
2344 static int
2345 _spdk_bs_blob_list_add(struct spdk_blob *blob)
2346 {
2347 	spdk_blob_id snapshot_id;
2348 	struct spdk_blob_list *snapshot_entry = NULL;
2349 	struct spdk_blob_list *clone_entry = NULL;
2350 
2351 	assert(blob != NULL);
2352 
2353 	snapshot_id = blob->parent_id;
2354 	if (snapshot_id == SPDK_BLOBID_INVALID) {
2355 		return 0;
2356 	}
2357 
2358 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, snapshot_id);
2359 	if (snapshot_entry == NULL) {
2360 		/* Snapshot not found */
2361 		snapshot_entry = calloc(1, sizeof(struct spdk_blob_list));
2362 		if (snapshot_entry == NULL) {
2363 			return -ENOMEM;
2364 		}
2365 		snapshot_entry->id = snapshot_id;
2366 		TAILQ_INIT(&snapshot_entry->clones);
2367 		TAILQ_INSERT_TAIL(&blob->bs->snapshots, snapshot_entry, link);
2368 	} else {
2369 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
2370 			if (clone_entry->id == blob->id) {
2371 				break;
2372 			}
2373 		}
2374 	}
2375 
2376 	if (clone_entry == NULL) {
2377 		/* Clone not found */
2378 		clone_entry = calloc(1, sizeof(struct spdk_blob_list));
2379 		if (clone_entry == NULL) {
2380 			return -ENOMEM;
2381 		}
2382 		clone_entry->id = blob->id;
2383 		TAILQ_INIT(&clone_entry->clones);
2384 		TAILQ_INSERT_TAIL(&snapshot_entry->clones, clone_entry, link);
2385 		snapshot_entry->clone_count++;
2386 	}
2387 
2388 	return 0;
2389 }
2390 
2391 static void
2392 _spdk_bs_blob_list_remove(struct spdk_blob *blob)
2393 {
2394 	struct spdk_blob_list *snapshot_entry = NULL;
2395 	struct spdk_blob_list *clone_entry = NULL;
2396 
2397 	_spdk_blob_get_snapshot_and_clone_entries(blob, &snapshot_entry, &clone_entry);
2398 
2399 	if (snapshot_entry == NULL) {
2400 		return;
2401 	}
2402 
2403 	blob->parent_id = SPDK_BLOBID_INVALID;
2404 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
2405 	free(clone_entry);
2406 
2407 	snapshot_entry->clone_count--;
2408 }
2409 
2410 static int
2411 _spdk_bs_blob_list_free(struct spdk_blob_store *bs)
2412 {
2413 	struct spdk_blob_list *snapshot_entry;
2414 	struct spdk_blob_list *snapshot_entry_tmp;
2415 	struct spdk_blob_list *clone_entry;
2416 	struct spdk_blob_list *clone_entry_tmp;
2417 
2418 	TAILQ_FOREACH_SAFE(snapshot_entry, &bs->snapshots, link, snapshot_entry_tmp) {
2419 		TAILQ_FOREACH_SAFE(clone_entry, &snapshot_entry->clones, link, clone_entry_tmp) {
2420 			TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
2421 			free(clone_entry);
2422 		}
2423 		TAILQ_REMOVE(&bs->snapshots, snapshot_entry, link);
2424 		free(snapshot_entry);
2425 	}
2426 
2427 	return 0;
2428 }
2429 
2430 static void
2431 _spdk_bs_free(struct spdk_blob_store *bs)
2432 {
2433 	_spdk_bs_blob_list_free(bs);
2434 
2435 	spdk_bs_unregister_md_thread(bs);
2436 	spdk_io_device_unregister(bs, _spdk_bs_dev_destroy);
2437 }
2438 
2439 void
2440 spdk_bs_opts_init(struct spdk_bs_opts *opts)
2441 {
2442 	opts->cluster_sz = SPDK_BLOB_OPTS_CLUSTER_SZ;
2443 	opts->num_md_pages = SPDK_BLOB_OPTS_NUM_MD_PAGES;
2444 	opts->max_md_ops = SPDK_BLOB_OPTS_MAX_MD_OPS;
2445 	opts->max_channel_ops = SPDK_BLOB_OPTS_DEFAULT_CHANNEL_OPS;
2446 	opts->clear_method = BS_CLEAR_WITH_UNMAP;
2447 	memset(&opts->bstype, 0, sizeof(opts->bstype));
2448 	opts->iter_cb_fn = NULL;
2449 	opts->iter_cb_arg = NULL;
2450 }
2451 
2452 static int
2453 _spdk_bs_opts_verify(struct spdk_bs_opts *opts)
2454 {
2455 	if (opts->cluster_sz == 0 || opts->num_md_pages == 0 || opts->max_md_ops == 0 ||
2456 	    opts->max_channel_ops == 0) {
2457 		SPDK_ERRLOG("Blobstore options cannot be set to 0\n");
2458 		return -1;
2459 	}
2460 
2461 	return 0;
2462 }
2463 
2464 static int
2465 _spdk_bs_alloc(struct spdk_bs_dev *dev, struct spdk_bs_opts *opts, struct spdk_blob_store **_bs)
2466 {
2467 	struct spdk_blob_store	*bs;
2468 	uint64_t dev_size;
2469 	int rc;
2470 
2471 	dev_size = dev->blocklen * dev->blockcnt;
2472 	if (dev_size < opts->cluster_sz) {
2473 		/* Device size cannot be smaller than cluster size of blobstore */
2474 		SPDK_INFOLOG(SPDK_LOG_BLOB, "Device size %" PRIu64 " is smaller than cluster size %" PRIu32 "\n",
2475 			     dev_size, opts->cluster_sz);
2476 		return -ENOSPC;
2477 	}
2478 	if (opts->cluster_sz < SPDK_BS_PAGE_SIZE) {
2479 		/* Cluster size cannot be smaller than page size */
2480 		SPDK_ERRLOG("Cluster size %" PRIu32 " is smaller than page size %d\n",
2481 			    opts->cluster_sz, SPDK_BS_PAGE_SIZE);
2482 		return -EINVAL;
2483 	}
2484 	bs = calloc(1, sizeof(struct spdk_blob_store));
2485 	if (!bs) {
2486 		return -ENOMEM;
2487 	}
2488 
2489 	TAILQ_INIT(&bs->blobs);
2490 	TAILQ_INIT(&bs->snapshots);
2491 	bs->dev = dev;
2492 	bs->md_thread = spdk_get_thread();
2493 	assert(bs->md_thread != NULL);
2494 
2495 	/*
2496 	 * Do not use _spdk_bs_lba_to_cluster() here since blockcnt may not be an
2497 	 *  even multiple of the cluster size.
2498 	 */
2499 	bs->cluster_sz = opts->cluster_sz;
2500 	bs->total_clusters = dev->blockcnt / (bs->cluster_sz / dev->blocklen);
2501 	bs->pages_per_cluster = bs->cluster_sz / SPDK_BS_PAGE_SIZE;
2502 	bs->num_free_clusters = bs->total_clusters;
2503 	bs->used_clusters = spdk_bit_array_create(bs->total_clusters);
2504 	bs->io_unit_size = dev->blocklen;
2505 	if (bs->used_clusters == NULL) {
2506 		free(bs);
2507 		return -ENOMEM;
2508 	}
2509 
2510 	bs->max_channel_ops = opts->max_channel_ops;
2511 	bs->super_blob = SPDK_BLOBID_INVALID;
2512 	memcpy(&bs->bstype, &opts->bstype, sizeof(opts->bstype));
2513 
2514 	/* The metadata is assumed to be at least 1 page */
2515 	bs->used_md_pages = spdk_bit_array_create(1);
2516 	bs->used_blobids = spdk_bit_array_create(0);
2517 
2518 	pthread_mutex_init(&bs->used_clusters_mutex, NULL);
2519 
2520 	spdk_io_device_register(bs, _spdk_bs_channel_create, _spdk_bs_channel_destroy,
2521 				sizeof(struct spdk_bs_channel), "blobstore");
2522 	rc = spdk_bs_register_md_thread(bs);
2523 	if (rc == -1) {
2524 		spdk_io_device_unregister(bs, NULL);
2525 		pthread_mutex_destroy(&bs->used_clusters_mutex);
2526 		spdk_bit_array_free(&bs->used_blobids);
2527 		spdk_bit_array_free(&bs->used_md_pages);
2528 		spdk_bit_array_free(&bs->used_clusters);
2529 		free(bs);
2530 		/* FIXME: this is a lie but don't know how to get a proper error code here */
2531 		return -ENOMEM;
2532 	}
2533 
2534 	*_bs = bs;
2535 	return 0;
2536 }
2537 
2538 /* START spdk_bs_load, spdk_bs_load_ctx will used for both load and unload. */
2539 
2540 struct spdk_bs_load_ctx {
2541 	struct spdk_blob_store		*bs;
2542 	struct spdk_bs_super_block	*super;
2543 
2544 	struct spdk_bs_md_mask		*mask;
2545 	bool				in_page_chain;
2546 	uint32_t			page_index;
2547 	uint32_t			cur_page;
2548 	struct spdk_blob_md_page	*page;
2549 
2550 	spdk_bs_sequence_t			*seq;
2551 	spdk_blob_op_with_handle_complete	iter_cb_fn;
2552 	void					*iter_cb_arg;
2553 	struct spdk_blob			*blob;
2554 	spdk_blob_id				blobid;
2555 };
2556 
2557 static void
2558 _spdk_bs_load_ctx_fail(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2559 {
2560 	assert(bserrno != 0);
2561 
2562 	spdk_free(ctx->super);
2563 	spdk_bs_sequence_finish(seq, bserrno);
2564 	_spdk_bs_free(ctx->bs);
2565 	free(ctx);
2566 }
2567 
2568 static void
2569 _spdk_bs_set_mask(struct spdk_bit_array *array, struct spdk_bs_md_mask *mask)
2570 {
2571 	uint32_t i = 0;
2572 
2573 	while (true) {
2574 		i = spdk_bit_array_find_first_set(array, i);
2575 		if (i >= mask->length) {
2576 			break;
2577 		}
2578 		mask->mask[i / 8] |= 1U << (i % 8);
2579 		i++;
2580 	}
2581 }
2582 
2583 static int
2584 _spdk_bs_load_mask(struct spdk_bit_array **array_ptr, struct spdk_bs_md_mask *mask)
2585 {
2586 	struct spdk_bit_array *array;
2587 	uint32_t i;
2588 
2589 	if (spdk_bit_array_resize(array_ptr, mask->length) < 0) {
2590 		return -ENOMEM;
2591 	}
2592 
2593 	array = *array_ptr;
2594 	for (i = 0; i < mask->length; i++) {
2595 		if (mask->mask[i / 8] & (1U << (i % 8))) {
2596 			spdk_bit_array_set(array, i);
2597 		}
2598 	}
2599 
2600 	return 0;
2601 }
2602 
2603 static void
2604 _spdk_bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2605 		     struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2606 {
2607 	/* Update the values in the super block */
2608 	super->super_blob = bs->super_blob;
2609 	memcpy(&super->bstype, &bs->bstype, sizeof(bs->bstype));
2610 	super->crc = _spdk_blob_md_page_calc_crc(super);
2611 	spdk_bs_sequence_write_dev(seq, super, _spdk_bs_page_to_lba(bs, 0),
2612 				   _spdk_bs_byte_to_lba(bs, sizeof(*super)),
2613 				   cb_fn, cb_arg);
2614 }
2615 
2616 static void
2617 _spdk_bs_write_used_clusters(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2618 {
2619 	struct spdk_bs_load_ctx	*ctx = arg;
2620 	uint64_t	mask_size, lba, lba_count;
2621 
2622 	/* Write out the used clusters mask */
2623 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2624 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
2625 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2626 	if (!ctx->mask) {
2627 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2628 		return;
2629 	}
2630 
2631 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_CLUSTERS;
2632 	ctx->mask->length = ctx->bs->total_clusters;
2633 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_clusters));
2634 
2635 	_spdk_bs_set_mask(ctx->bs->used_clusters, ctx->mask);
2636 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
2637 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
2638 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2639 }
2640 
2641 static void
2642 _spdk_bs_write_used_md(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2643 {
2644 	struct spdk_bs_load_ctx	*ctx = arg;
2645 	uint64_t	mask_size, lba, lba_count;
2646 
2647 	if (seq->bserrno) {
2648 		_spdk_bs_load_ctx_fail(seq, ctx, seq->bserrno);
2649 		return;
2650 	}
2651 
2652 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
2653 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
2654 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2655 	if (!ctx->mask) {
2656 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2657 		return;
2658 	}
2659 
2660 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_PAGES;
2661 	ctx->mask->length = ctx->super->md_len;
2662 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_md_pages));
2663 
2664 	_spdk_bs_set_mask(ctx->bs->used_md_pages, ctx->mask);
2665 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
2666 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
2667 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2668 }
2669 
2670 static void
2671 _spdk_bs_write_used_blobids(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2672 {
2673 	struct spdk_bs_load_ctx	*ctx = arg;
2674 	uint64_t	mask_size, lba, lba_count;
2675 
2676 	if (ctx->super->used_blobid_mask_len == 0) {
2677 		/*
2678 		 * This is a pre-v3 on-disk format where the blobid mask does not get
2679 		 *  written to disk.
2680 		 */
2681 		cb_fn(seq, arg, 0);
2682 		return;
2683 	}
2684 
2685 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2686 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2687 				 SPDK_MALLOC_DMA);
2688 	if (!ctx->mask) {
2689 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2690 		return;
2691 	}
2692 
2693 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_BLOBIDS;
2694 	ctx->mask->length = ctx->super->md_len;
2695 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_blobids));
2696 
2697 	_spdk_bs_set_mask(ctx->bs->used_blobids, ctx->mask);
2698 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2699 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2700 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2701 }
2702 
2703 static void
2704 _spdk_blob_set_thin_provision(struct spdk_blob *blob)
2705 {
2706 	_spdk_blob_verify_md_op(blob);
2707 	blob->invalid_flags |= SPDK_BLOB_THIN_PROV;
2708 	blob->state = SPDK_BLOB_STATE_DIRTY;
2709 }
2710 
2711 static void _spdk_bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno);
2712 
2713 static void
2714 _spdk_bs_delete_corrupted_blob_cpl(void *cb_arg, int bserrno)
2715 {
2716 	struct spdk_bs_load_ctx *ctx = cb_arg;
2717 	spdk_blob_id id;
2718 	int64_t page_num;
2719 
2720 	/* Iterate to next blob (we can't use spdk_bs_iter_next function as our
2721 	 * last blob has been removed */
2722 	page_num = _spdk_bs_blobid_to_page(ctx->blobid);
2723 	page_num++;
2724 	page_num = spdk_bit_array_find_first_set(ctx->bs->used_blobids, page_num);
2725 	if (page_num >= spdk_bit_array_capacity(ctx->bs->used_blobids)) {
2726 		_spdk_bs_load_iter(ctx, NULL, -ENOENT);
2727 		return;
2728 	}
2729 
2730 	id = _spdk_bs_page_to_blobid(page_num);
2731 
2732 	spdk_bs_open_blob(ctx->bs, id, _spdk_bs_load_iter, ctx);
2733 }
2734 
2735 static void
2736 _spdk_bs_delete_corrupted_close_cb(void *cb_arg, int bserrno)
2737 {
2738 	struct spdk_bs_load_ctx *ctx = cb_arg;
2739 
2740 	if (bserrno != 0) {
2741 		SPDK_ERRLOG("Failed to close corrupted blob\n");
2742 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2743 		return;
2744 	}
2745 
2746 	spdk_bs_delete_blob(ctx->bs, ctx->blobid, _spdk_bs_delete_corrupted_blob_cpl, ctx);
2747 }
2748 
2749 static void
2750 _spdk_bs_delete_corrupted_blob(void *cb_arg, int bserrno)
2751 {
2752 	struct spdk_bs_load_ctx *ctx = cb_arg;
2753 	uint64_t i;
2754 
2755 	if (bserrno != 0) {
2756 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
2757 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2758 		return;
2759 	}
2760 
2761 	/* Snapshot and clone have the same copy of cluster map at this point.
2762 	 * Let's clear cluster map for snpashot now so that it won't be cleared
2763 	 * for clone later when we remove snapshot. Also set thin provision to
2764 	 * pass data corruption check */
2765 	for (i = 0; i < ctx->blob->active.num_clusters; i++) {
2766 		ctx->blob->active.clusters[i] = 0;
2767 	}
2768 
2769 	ctx->blob->md_ro = false;
2770 
2771 	_spdk_blob_set_thin_provision(ctx->blob);
2772 
2773 	ctx->blobid = ctx->blob->id;
2774 
2775 	spdk_blob_close(ctx->blob, _spdk_bs_delete_corrupted_close_cb, ctx);
2776 }
2777 
2778 static void
2779 _spdk_bs_update_corrupted_blob(void *cb_arg, int bserrno)
2780 {
2781 	struct spdk_bs_load_ctx *ctx = cb_arg;
2782 
2783 	if (bserrno != 0) {
2784 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
2785 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2786 		return;
2787 	}
2788 
2789 	ctx->blob->md_ro = false;
2790 	_spdk_blob_remove_xattr(ctx->blob, SNAPSHOT_PENDING_REMOVAL, true);
2791 	_spdk_blob_remove_xattr(ctx->blob, SNAPSHOT_IN_PROGRESS, true);
2792 	spdk_blob_set_read_only(ctx->blob);
2793 
2794 	if (ctx->iter_cb_fn) {
2795 		ctx->iter_cb_fn(ctx->iter_cb_arg, ctx->blob, 0);
2796 	}
2797 	_spdk_bs_blob_list_add(ctx->blob);
2798 
2799 	spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2800 }
2801 
2802 static void
2803 _spdk_bs_examine_clone(void *cb_arg, struct spdk_blob *blob, int bserrno)
2804 {
2805 	struct spdk_bs_load_ctx *ctx = cb_arg;
2806 
2807 	if (bserrno != 0) {
2808 		SPDK_ERRLOG("Failed to open clone of a corrupted blob\n");
2809 		spdk_bs_iter_next(ctx->bs, ctx->blob, _spdk_bs_load_iter, ctx);
2810 		return;
2811 	}
2812 
2813 	if (blob->parent_id == ctx->blob->id) {
2814 		/* Power failure occured before updating clone (snapshot delete case)
2815 		 * or after updating clone (creating snapshot case) - keep snapshot */
2816 		spdk_blob_close(blob, _spdk_bs_update_corrupted_blob, ctx);
2817 	} else {
2818 		/* Power failure occured after updating clone (snapshot delete case)
2819 		 * or before updating clone (creating snapshot case) - remove snapshot */
2820 		spdk_blob_close(blob, _spdk_bs_delete_corrupted_blob, ctx);
2821 	}
2822 }
2823 
2824 static void
2825 _spdk_bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno)
2826 {
2827 	struct spdk_bs_load_ctx *ctx = arg;
2828 	const void *value;
2829 	size_t len;
2830 	int rc = 0;
2831 
2832 	if (bserrno == 0) {
2833 		/* Examine blob if it is corrupted after power failure. Fix
2834 		 * the ones that can be fixed and remove any other corrupted
2835 		 * ones. If it is not corrupted just process it */
2836 		rc = _spdk_blob_get_xattr_value(blob, SNAPSHOT_PENDING_REMOVAL, &value, &len, true);
2837 		if (rc != 0) {
2838 			rc = _spdk_blob_get_xattr_value(blob, SNAPSHOT_IN_PROGRESS, &value, &len, true);
2839 			if (rc != 0) {
2840 				/* Not corrupted - process it and continue with iterating through blobs */
2841 				if (ctx->iter_cb_fn) {
2842 					ctx->iter_cb_fn(ctx->iter_cb_arg, blob, 0);
2843 				}
2844 				_spdk_bs_blob_list_add(blob);
2845 				spdk_bs_iter_next(ctx->bs, blob, _spdk_bs_load_iter, ctx);
2846 				return;
2847 			}
2848 
2849 		}
2850 
2851 		assert(len == sizeof(spdk_blob_id));
2852 
2853 		ctx->blob = blob;
2854 
2855 		/* Open clone to check if we are able to fix this blob or should we remove it */
2856 		spdk_bs_open_blob(ctx->bs, *(spdk_blob_id *)value, _spdk_bs_examine_clone, ctx);
2857 		return;
2858 	} else if (bserrno == -ENOENT) {
2859 		bserrno = 0;
2860 	} else {
2861 		/*
2862 		 * This case needs to be looked at further.  Same problem
2863 		 *  exists with applications that rely on explicit blob
2864 		 *  iteration.  We should just skip the blob that failed
2865 		 *  to load and continue on to the next one.
2866 		 */
2867 		SPDK_ERRLOG("Error in iterating blobs\n");
2868 	}
2869 
2870 	ctx->iter_cb_fn = NULL;
2871 
2872 	spdk_free(ctx->super);
2873 	spdk_free(ctx->mask);
2874 	spdk_bs_sequence_finish(ctx->seq, bserrno);
2875 	free(ctx);
2876 }
2877 
2878 static void
2879 _spdk_bs_load_complete(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2880 {
2881 	ctx->seq = seq;
2882 	spdk_bs_iter_first(ctx->bs, _spdk_bs_load_iter, ctx);
2883 }
2884 
2885 static void
2886 _spdk_bs_load_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2887 {
2888 	struct spdk_bs_load_ctx *ctx = cb_arg;
2889 	int rc;
2890 
2891 	/* The type must be correct */
2892 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_BLOBIDS);
2893 
2894 	/* The length of the mask (in bits) must not be greater than
2895 	 * the length of the buffer (converted to bits) */
2896 	assert(ctx->mask->length <= (ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE * 8));
2897 
2898 	/* The length of the mask must be exactly equal to the size
2899 	 * (in pages) of the metadata region */
2900 	assert(ctx->mask->length == ctx->super->md_len);
2901 
2902 	rc = _spdk_bs_load_mask(&ctx->bs->used_blobids, ctx->mask);
2903 	if (rc < 0) {
2904 		spdk_free(ctx->mask);
2905 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2906 		return;
2907 	}
2908 
2909 	_spdk_bs_load_complete(seq, ctx, bserrno);
2910 }
2911 
2912 static void
2913 _spdk_bs_load_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2914 {
2915 	struct spdk_bs_load_ctx *ctx = cb_arg;
2916 	uint64_t		lba, lba_count, mask_size;
2917 	int			rc;
2918 
2919 	/* The type must be correct */
2920 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
2921 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2922 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
2923 					     struct spdk_blob_md_page) * 8));
2924 	/* The length of the mask must be exactly equal to the total number of clusters */
2925 	assert(ctx->mask->length == ctx->bs->total_clusters);
2926 
2927 	rc = _spdk_bs_load_mask(&ctx->bs->used_clusters, ctx->mask);
2928 	if (rc < 0) {
2929 		spdk_free(ctx->mask);
2930 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2931 		return;
2932 	}
2933 
2934 	ctx->bs->num_free_clusters = spdk_bit_array_count_clear(ctx->bs->used_clusters);
2935 	assert(ctx->bs->num_free_clusters <= ctx->bs->total_clusters);
2936 
2937 	spdk_free(ctx->mask);
2938 
2939 	/* Read the used blobids mask */
2940 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2941 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2942 				 SPDK_MALLOC_DMA);
2943 	if (!ctx->mask) {
2944 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2945 		return;
2946 	}
2947 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2948 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2949 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2950 				  _spdk_bs_load_used_blobids_cpl, ctx);
2951 }
2952 
2953 static void
2954 _spdk_bs_load_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2955 {
2956 	struct spdk_bs_load_ctx *ctx = cb_arg;
2957 	uint64_t		lba, lba_count, mask_size;
2958 	int			rc;
2959 
2960 	/* The type must be correct */
2961 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_PAGES);
2962 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2963 	assert(ctx->mask->length <= (ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE *
2964 				     8));
2965 	/* The length of the mask must be exactly equal to the size (in pages) of the metadata region */
2966 	assert(ctx->mask->length == ctx->super->md_len);
2967 
2968 	rc = _spdk_bs_load_mask(&ctx->bs->used_md_pages, ctx->mask);
2969 	if (rc < 0) {
2970 		spdk_free(ctx->mask);
2971 		_spdk_bs_load_ctx_fail(seq, ctx, rc);
2972 		return;
2973 	}
2974 
2975 	spdk_free(ctx->mask);
2976 
2977 	/* Read the used clusters mask */
2978 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2979 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
2980 				 SPDK_MALLOC_DMA);
2981 	if (!ctx->mask) {
2982 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2983 		return;
2984 	}
2985 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
2986 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
2987 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2988 				  _spdk_bs_load_used_clusters_cpl, ctx);
2989 }
2990 
2991 static void
2992 _spdk_bs_load_read_used_pages(spdk_bs_sequence_t *seq, void *cb_arg)
2993 {
2994 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2995 	uint64_t lba, lba_count, mask_size;
2996 
2997 	/* Read the used pages mask */
2998 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
2999 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3000 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3001 	if (!ctx->mask) {
3002 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3003 		return;
3004 	}
3005 
3006 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
3007 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
3008 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
3009 				  _spdk_bs_load_used_pages_cpl, ctx);
3010 }
3011 
3012 static int
3013 _spdk_bs_load_replay_md_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob_store *bs)
3014 {
3015 	struct spdk_blob_md_descriptor *desc;
3016 	size_t	cur_desc = 0;
3017 
3018 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3019 	while (cur_desc < sizeof(page->descriptors)) {
3020 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
3021 			if (desc->length == 0) {
3022 				/* If padding and length are 0, this terminates the page */
3023 				break;
3024 			}
3025 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT) {
3026 			struct spdk_blob_md_descriptor_extent	*desc_extent;
3027 			unsigned int				i, j;
3028 			unsigned int				cluster_count = 0;
3029 			uint32_t				cluster_idx;
3030 
3031 			desc_extent = (struct spdk_blob_md_descriptor_extent *)desc;
3032 
3033 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->extents[0]); i++) {
3034 				for (j = 0; j < desc_extent->extents[i].length; j++) {
3035 					cluster_idx = desc_extent->extents[i].cluster_idx;
3036 					/*
3037 					 * cluster_idx = 0 means an unallocated cluster - don't mark that
3038 					 * in the used cluster map.
3039 					 */
3040 					if (cluster_idx != 0) {
3041 						spdk_bit_array_set(bs->used_clusters, cluster_idx + j);
3042 						if (bs->num_free_clusters == 0) {
3043 							return -ENOSPC;
3044 						}
3045 						bs->num_free_clusters--;
3046 					}
3047 					cluster_count++;
3048 				}
3049 			}
3050 			if (cluster_count == 0) {
3051 				return -EINVAL;
3052 			}
3053 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
3054 			/* Skip this item */
3055 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
3056 			/* Skip this item */
3057 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
3058 			/* Skip this item */
3059 		} else {
3060 			/* Error */
3061 			return -EINVAL;
3062 		}
3063 		/* Advance to the next descriptor */
3064 		cur_desc += sizeof(*desc) + desc->length;
3065 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
3066 			break;
3067 		}
3068 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
3069 	}
3070 	return 0;
3071 }
3072 
3073 static bool _spdk_bs_load_cur_md_page_valid(struct spdk_bs_load_ctx *ctx)
3074 {
3075 	uint32_t crc;
3076 
3077 	crc = _spdk_blob_md_page_calc_crc(ctx->page);
3078 	if (crc != ctx->page->crc) {
3079 		return false;
3080 	}
3081 
3082 	if (ctx->page->sequence_num == 0 &&
3083 	    _spdk_bs_page_to_blobid(ctx->cur_page) != ctx->page->id) {
3084 		return false;
3085 	}
3086 	return true;
3087 }
3088 
3089 static void
3090 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
3091 
3092 static void
3093 _spdk_bs_load_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3094 {
3095 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3096 
3097 	_spdk_bs_load_complete(seq, ctx, bserrno);
3098 }
3099 
3100 static void
3101 _spdk_bs_load_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3102 {
3103 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3104 
3105 	spdk_free(ctx->mask);
3106 	ctx->mask = NULL;
3107 
3108 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_load_write_used_clusters_cpl);
3109 }
3110 
3111 static void
3112 _spdk_bs_load_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3113 {
3114 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3115 
3116 	spdk_free(ctx->mask);
3117 	ctx->mask = NULL;
3118 
3119 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_load_write_used_blobids_cpl);
3120 }
3121 
3122 static void
3123 _spdk_bs_load_write_used_md(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3124 {
3125 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_load_write_used_pages_cpl);
3126 }
3127 
3128 static void
3129 _spdk_bs_load_replay_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3130 {
3131 	struct spdk_bs_load_ctx *ctx = cb_arg;
3132 	uint64_t num_md_clusters;
3133 	uint64_t i;
3134 	uint32_t page_num;
3135 
3136 	if (bserrno != 0) {
3137 		_spdk_bs_load_ctx_fail(seq, ctx, bserrno);
3138 		return;
3139 	}
3140 
3141 	page_num = ctx->cur_page;
3142 	if (_spdk_bs_load_cur_md_page_valid(ctx) == true) {
3143 		if (ctx->page->sequence_num == 0 || ctx->in_page_chain == true) {
3144 			spdk_bit_array_set(ctx->bs->used_md_pages, page_num);
3145 			if (ctx->page->sequence_num == 0) {
3146 				spdk_bit_array_set(ctx->bs->used_blobids, page_num);
3147 			}
3148 			if (_spdk_bs_load_replay_md_parse_page(ctx->page, ctx->bs)) {
3149 				_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3150 				return;
3151 			}
3152 			if (ctx->page->next != SPDK_INVALID_MD_PAGE) {
3153 				ctx->in_page_chain = true;
3154 				ctx->cur_page = ctx->page->next;
3155 				_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3156 				return;
3157 			}
3158 		}
3159 	}
3160 
3161 	ctx->in_page_chain = false;
3162 
3163 	do {
3164 		ctx->page_index++;
3165 	} while (spdk_bit_array_get(ctx->bs->used_md_pages, ctx->page_index) == true);
3166 
3167 	if (ctx->page_index < ctx->super->md_len) {
3168 		ctx->cur_page = ctx->page_index;
3169 		_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3170 	} else {
3171 		/* Claim all of the clusters used by the metadata */
3172 		num_md_clusters = spdk_divide_round_up(ctx->super->md_len, ctx->bs->pages_per_cluster);
3173 		for (i = 0; i < num_md_clusters; i++) {
3174 			_spdk_bs_claim_cluster(ctx->bs, i);
3175 		}
3176 		spdk_free(ctx->page);
3177 		_spdk_bs_load_write_used_md(seq, ctx, bserrno);
3178 	}
3179 }
3180 
3181 static void
3182 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
3183 {
3184 	struct spdk_bs_load_ctx *ctx = cb_arg;
3185 	uint64_t lba;
3186 
3187 	assert(ctx->cur_page < ctx->super->md_len);
3188 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
3189 	spdk_bs_sequence_read_dev(seq, ctx->page, lba,
3190 				  _spdk_bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
3191 				  _spdk_bs_load_replay_md_cpl, ctx);
3192 }
3193 
3194 static void
3195 _spdk_bs_load_replay_md(spdk_bs_sequence_t *seq, void *cb_arg)
3196 {
3197 	struct spdk_bs_load_ctx *ctx = cb_arg;
3198 
3199 	ctx->page_index = 0;
3200 	ctx->cur_page = 0;
3201 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
3202 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3203 	if (!ctx->page) {
3204 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3205 		return;
3206 	}
3207 	_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
3208 }
3209 
3210 static void
3211 _spdk_bs_recover(spdk_bs_sequence_t *seq, void *cb_arg)
3212 {
3213 	struct spdk_bs_load_ctx *ctx = cb_arg;
3214 	int		rc;
3215 
3216 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->super->md_len);
3217 	if (rc < 0) {
3218 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3219 		return;
3220 	}
3221 
3222 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->super->md_len);
3223 	if (rc < 0) {
3224 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3225 		return;
3226 	}
3227 
3228 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
3229 	if (rc < 0) {
3230 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3231 		return;
3232 	}
3233 
3234 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
3235 	_spdk_bs_load_replay_md(seq, cb_arg);
3236 }
3237 
3238 static void
3239 _spdk_bs_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3240 {
3241 	struct spdk_bs_load_ctx *ctx = cb_arg;
3242 	uint32_t	crc;
3243 	int		rc;
3244 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
3245 
3246 	if (ctx->super->version > SPDK_BS_VERSION ||
3247 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
3248 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3249 		return;
3250 	}
3251 
3252 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3253 		   sizeof(ctx->super->signature)) != 0) {
3254 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3255 		return;
3256 	}
3257 
3258 	crc = _spdk_blob_md_page_calc_crc(ctx->super);
3259 	if (crc != ctx->super->crc) {
3260 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3261 		return;
3262 	}
3263 
3264 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
3265 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype matched - loading blobstore\n");
3266 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
3267 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype wildcard used - loading blobstore regardless bstype\n");
3268 	} else {
3269 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Unexpected bstype\n");
3270 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
3271 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
3272 		_spdk_bs_load_ctx_fail(seq, ctx, -ENXIO);
3273 		return;
3274 	}
3275 
3276 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
3277 		SPDK_NOTICELOG("Size mismatch, dev size: %lu, blobstore size: %lu\n",
3278 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
3279 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
3280 		return;
3281 	}
3282 
3283 	if (ctx->super->size == 0) {
3284 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
3285 	}
3286 
3287 	if (ctx->super->io_unit_size == 0) {
3288 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
3289 	}
3290 
3291 	/* Parse the super block */
3292 	ctx->bs->clean = 1;
3293 	ctx->bs->cluster_sz = ctx->super->cluster_size;
3294 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
3295 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
3296 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
3297 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
3298 	if (rc < 0) {
3299 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
3300 		return;
3301 	}
3302 	ctx->bs->md_start = ctx->super->md_start;
3303 	ctx->bs->md_len = ctx->super->md_len;
3304 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
3305 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
3306 	ctx->bs->super_blob = ctx->super->super_blob;
3307 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
3308 
3309 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0) {
3310 		_spdk_bs_recover(seq, ctx);
3311 	} else {
3312 		_spdk_bs_load_read_used_pages(seq, ctx);
3313 	}
3314 }
3315 
3316 void
3317 spdk_bs_load(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
3318 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
3319 {
3320 	struct spdk_blob_store	*bs;
3321 	struct spdk_bs_cpl	cpl;
3322 	spdk_bs_sequence_t	*seq;
3323 	struct spdk_bs_load_ctx *ctx;
3324 	struct spdk_bs_opts	opts = {};
3325 	int err;
3326 
3327 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Loading blobstore from dev %p\n", dev);
3328 
3329 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
3330 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "unsupported dev block length of %d\n", dev->blocklen);
3331 		dev->destroy(dev);
3332 		cb_fn(cb_arg, NULL, -EINVAL);
3333 		return;
3334 	}
3335 
3336 	if (o) {
3337 		opts = *o;
3338 	} else {
3339 		spdk_bs_opts_init(&opts);
3340 	}
3341 
3342 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
3343 		dev->destroy(dev);
3344 		cb_fn(cb_arg, NULL, -EINVAL);
3345 		return;
3346 	}
3347 
3348 	err = _spdk_bs_alloc(dev, &opts, &bs);
3349 	if (err) {
3350 		dev->destroy(dev);
3351 		cb_fn(cb_arg, NULL, err);
3352 		return;
3353 	}
3354 
3355 	ctx = calloc(1, sizeof(*ctx));
3356 	if (!ctx) {
3357 		_spdk_bs_free(bs);
3358 		cb_fn(cb_arg, NULL, -ENOMEM);
3359 		return;
3360 	}
3361 
3362 	ctx->bs = bs;
3363 	ctx->iter_cb_fn = opts.iter_cb_fn;
3364 	ctx->iter_cb_arg = opts.iter_cb_arg;
3365 
3366 	/* Allocate memory for the super block */
3367 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3368 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3369 	if (!ctx->super) {
3370 		free(ctx);
3371 		_spdk_bs_free(bs);
3372 		cb_fn(cb_arg, NULL, -ENOMEM);
3373 		return;
3374 	}
3375 
3376 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
3377 	cpl.u.bs_handle.cb_fn = cb_fn;
3378 	cpl.u.bs_handle.cb_arg = cb_arg;
3379 	cpl.u.bs_handle.bs = bs;
3380 
3381 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3382 	if (!seq) {
3383 		spdk_free(ctx->super);
3384 		free(ctx);
3385 		_spdk_bs_free(bs);
3386 		cb_fn(cb_arg, NULL, -ENOMEM);
3387 		return;
3388 	}
3389 
3390 	/* Read the super block */
3391 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
3392 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
3393 				  _spdk_bs_load_super_cpl, ctx);
3394 }
3395 
3396 /* END spdk_bs_load */
3397 
3398 /* START spdk_bs_dump */
3399 
3400 struct spdk_bs_dump_ctx {
3401 	struct spdk_blob_store		*bs;
3402 	struct spdk_bs_super_block	*super;
3403 	uint32_t			cur_page;
3404 	struct spdk_blob_md_page	*page;
3405 	spdk_bs_sequence_t		*seq;
3406 	FILE				*fp;
3407 	spdk_bs_dump_print_xattr	print_xattr_fn;
3408 	char				xattr_name[4096];
3409 };
3410 
3411 static void
3412 _spdk_bs_dump_finish(spdk_bs_sequence_t *seq, struct spdk_bs_dump_ctx *ctx, int bserrno)
3413 {
3414 	spdk_free(ctx->super);
3415 
3416 	/*
3417 	 * We need to defer calling spdk_bs_call_cpl() until after
3418 	 * dev destruction, so tuck these away for later use.
3419 	 */
3420 	ctx->bs->unload_err = bserrno;
3421 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3422 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3423 
3424 	spdk_bs_sequence_finish(seq, 0);
3425 	_spdk_bs_free(ctx->bs);
3426 	free(ctx);
3427 }
3428 
3429 static void _spdk_bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
3430 
3431 static void
3432 _spdk_bs_dump_print_md_page(struct spdk_bs_dump_ctx *ctx)
3433 {
3434 	uint32_t page_idx = ctx->cur_page;
3435 	struct spdk_blob_md_page *page = ctx->page;
3436 	struct spdk_blob_md_descriptor *desc;
3437 	size_t cur_desc = 0;
3438 	uint32_t crc;
3439 
3440 	fprintf(ctx->fp, "=========\n");
3441 	fprintf(ctx->fp, "Metadata Page Index: %" PRIu32 " (0x%" PRIx32 ")\n", page_idx, page_idx);
3442 	fprintf(ctx->fp, "Blob ID: 0x%" PRIx64 "\n", page->id);
3443 
3444 	crc = _spdk_blob_md_page_calc_crc(page);
3445 	fprintf(ctx->fp, "CRC: 0x%" PRIx32 " (%s)\n", page->crc, crc == page->crc ? "OK" : "Mismatch");
3446 
3447 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3448 	while (cur_desc < sizeof(page->descriptors)) {
3449 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
3450 			if (desc->length == 0) {
3451 				/* If padding and length are 0, this terminates the page */
3452 				break;
3453 			}
3454 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT) {
3455 			struct spdk_blob_md_descriptor_extent	*desc_extent;
3456 			unsigned int				i;
3457 
3458 			desc_extent = (struct spdk_blob_md_descriptor_extent *)desc;
3459 
3460 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->extents[0]); i++) {
3461 				if (desc_extent->extents[i].cluster_idx != 0) {
3462 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
3463 						desc_extent->extents[i].cluster_idx);
3464 				} else {
3465 					fprintf(ctx->fp, "Unallocated Extent - ");
3466 				}
3467 				fprintf(ctx->fp, " Length: %" PRIu32, desc_extent->extents[i].length);
3468 				fprintf(ctx->fp, "\n");
3469 			}
3470 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
3471 			struct spdk_blob_md_descriptor_xattr *desc_xattr;
3472 			uint32_t i;
3473 
3474 			desc_xattr = (struct spdk_blob_md_descriptor_xattr *)desc;
3475 
3476 			if (desc_xattr->length !=
3477 			    sizeof(desc_xattr->name_length) + sizeof(desc_xattr->value_length) +
3478 			    desc_xattr->name_length + desc_xattr->value_length) {
3479 			}
3480 
3481 			memcpy(ctx->xattr_name, desc_xattr->name, desc_xattr->name_length);
3482 			ctx->xattr_name[desc_xattr->name_length] = '\0';
3483 			fprintf(ctx->fp, "XATTR: name = \"%s\"\n", ctx->xattr_name);
3484 			fprintf(ctx->fp, "       value = \"");
3485 			ctx->print_xattr_fn(ctx->fp, ctx->super->bstype.bstype, ctx->xattr_name,
3486 					    (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
3487 					    desc_xattr->value_length);
3488 			fprintf(ctx->fp, "\"\n");
3489 			for (i = 0; i < desc_xattr->value_length; i++) {
3490 				if (i % 16 == 0) {
3491 					fprintf(ctx->fp, "               ");
3492 				}
3493 				fprintf(ctx->fp, "%02" PRIx8 " ", *((uint8_t *)desc_xattr->name + desc_xattr->name_length + i));
3494 				if ((i + 1) % 16 == 0) {
3495 					fprintf(ctx->fp, "\n");
3496 				}
3497 			}
3498 			if (i % 16 != 0) {
3499 				fprintf(ctx->fp, "\n");
3500 			}
3501 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
3502 			/* TODO */
3503 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
3504 			/* TODO */
3505 		} else {
3506 			/* Error */
3507 		}
3508 		/* Advance to the next descriptor */
3509 		cur_desc += sizeof(*desc) + desc->length;
3510 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
3511 			break;
3512 		}
3513 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
3514 	}
3515 }
3516 
3517 static void
3518 _spdk_bs_dump_read_md_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3519 {
3520 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3521 
3522 	if (bserrno != 0) {
3523 		_spdk_bs_dump_finish(seq, ctx, bserrno);
3524 		return;
3525 	}
3526 
3527 	if (ctx->page->id != 0) {
3528 		_spdk_bs_dump_print_md_page(ctx);
3529 	}
3530 
3531 	ctx->cur_page++;
3532 
3533 	if (ctx->cur_page < ctx->super->md_len) {
3534 		_spdk_bs_dump_read_md_page(seq, cb_arg);
3535 	} else {
3536 		spdk_free(ctx->page);
3537 		_spdk_bs_dump_finish(seq, ctx, 0);
3538 	}
3539 }
3540 
3541 static void
3542 _spdk_bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
3543 {
3544 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3545 	uint64_t lba;
3546 
3547 	assert(ctx->cur_page < ctx->super->md_len);
3548 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
3549 	spdk_bs_sequence_read_dev(seq, ctx->page, lba,
3550 				  _spdk_bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
3551 				  _spdk_bs_dump_read_md_page_cpl, ctx);
3552 }
3553 
3554 static void
3555 _spdk_bs_dump_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3556 {
3557 	struct spdk_bs_dump_ctx *ctx = cb_arg;
3558 
3559 	fprintf(ctx->fp, "Signature: \"%.8s\" ", ctx->super->signature);
3560 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3561 		   sizeof(ctx->super->signature)) != 0) {
3562 		fprintf(ctx->fp, "(Mismatch)\n");
3563 		_spdk_bs_dump_finish(seq, ctx, bserrno);
3564 		return;
3565 	} else {
3566 		fprintf(ctx->fp, "(OK)\n");
3567 	}
3568 	fprintf(ctx->fp, "Version: %" PRIu32 "\n", ctx->super->version);
3569 	fprintf(ctx->fp, "CRC: 0x%x (%s)\n", ctx->super->crc,
3570 		(ctx->super->crc == _spdk_blob_md_page_calc_crc(ctx->super)) ? "OK" : "Mismatch");
3571 	fprintf(ctx->fp, "Blobstore Type: %.*s\n", SPDK_BLOBSTORE_TYPE_LENGTH, ctx->super->bstype.bstype);
3572 	fprintf(ctx->fp, "Cluster Size: %" PRIu32 "\n", ctx->super->cluster_size);
3573 	fprintf(ctx->fp, "Super Blob ID: ");
3574 	if (ctx->super->super_blob == SPDK_BLOBID_INVALID) {
3575 		fprintf(ctx->fp, "(None)\n");
3576 	} else {
3577 		fprintf(ctx->fp, "%" PRIu64 "\n", ctx->super->super_blob);
3578 	}
3579 	fprintf(ctx->fp, "Clean: %" PRIu32 "\n", ctx->super->clean);
3580 	fprintf(ctx->fp, "Used Metadata Page Mask Start: %" PRIu32 "\n", ctx->super->used_page_mask_start);
3581 	fprintf(ctx->fp, "Used Metadata Page Mask Length: %" PRIu32 "\n", ctx->super->used_page_mask_len);
3582 	fprintf(ctx->fp, "Used Cluster Mask Start: %" PRIu32 "\n", ctx->super->used_cluster_mask_start);
3583 	fprintf(ctx->fp, "Used Cluster Mask Length: %" PRIu32 "\n", ctx->super->used_cluster_mask_len);
3584 	fprintf(ctx->fp, "Used Blob ID Mask Start: %" PRIu32 "\n", ctx->super->used_blobid_mask_start);
3585 	fprintf(ctx->fp, "Used Blob ID Mask Length: %" PRIu32 "\n", ctx->super->used_blobid_mask_len);
3586 	fprintf(ctx->fp, "Metadata Start: %" PRIu32 "\n", ctx->super->md_start);
3587 	fprintf(ctx->fp, "Metadata Length: %" PRIu32 "\n", ctx->super->md_len);
3588 
3589 	ctx->cur_page = 0;
3590 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
3591 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3592 	if (!ctx->page) {
3593 		_spdk_bs_dump_finish(seq, ctx, -ENOMEM);
3594 		return;
3595 	}
3596 	_spdk_bs_dump_read_md_page(seq, cb_arg);
3597 }
3598 
3599 void
3600 spdk_bs_dump(struct spdk_bs_dev *dev, FILE *fp, spdk_bs_dump_print_xattr print_xattr_fn,
3601 	     spdk_bs_op_complete cb_fn, void *cb_arg)
3602 {
3603 	struct spdk_blob_store	*bs;
3604 	struct spdk_bs_cpl	cpl;
3605 	spdk_bs_sequence_t	*seq;
3606 	struct spdk_bs_dump_ctx *ctx;
3607 	struct spdk_bs_opts	opts = {};
3608 	int err;
3609 
3610 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Dumping blobstore from dev %p\n", dev);
3611 
3612 	spdk_bs_opts_init(&opts);
3613 
3614 	err = _spdk_bs_alloc(dev, &opts, &bs);
3615 	if (err) {
3616 		dev->destroy(dev);
3617 		cb_fn(cb_arg, err);
3618 		return;
3619 	}
3620 
3621 	ctx = calloc(1, sizeof(*ctx));
3622 	if (!ctx) {
3623 		_spdk_bs_free(bs);
3624 		cb_fn(cb_arg, -ENOMEM);
3625 		return;
3626 	}
3627 
3628 	ctx->bs = bs;
3629 	ctx->fp = fp;
3630 	ctx->print_xattr_fn = print_xattr_fn;
3631 
3632 	/* Allocate memory for the super block */
3633 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3634 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3635 	if (!ctx->super) {
3636 		free(ctx);
3637 		_spdk_bs_free(bs);
3638 		cb_fn(cb_arg, -ENOMEM);
3639 		return;
3640 	}
3641 
3642 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
3643 	cpl.u.bs_basic.cb_fn = cb_fn;
3644 	cpl.u.bs_basic.cb_arg = cb_arg;
3645 
3646 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3647 	if (!seq) {
3648 		spdk_free(ctx->super);
3649 		free(ctx);
3650 		_spdk_bs_free(bs);
3651 		cb_fn(cb_arg, -ENOMEM);
3652 		return;
3653 	}
3654 
3655 	/* Read the super block */
3656 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
3657 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
3658 				  _spdk_bs_dump_super_cpl, ctx);
3659 }
3660 
3661 /* END spdk_bs_dump */
3662 
3663 /* START spdk_bs_init */
3664 
3665 struct spdk_bs_init_ctx {
3666 	struct spdk_blob_store		*bs;
3667 	struct spdk_bs_super_block	*super;
3668 };
3669 
3670 static void
3671 _spdk_bs_init_persist_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3672 {
3673 	struct spdk_bs_init_ctx *ctx = cb_arg;
3674 
3675 	spdk_free(ctx->super);
3676 	free(ctx);
3677 
3678 	spdk_bs_sequence_finish(seq, bserrno);
3679 }
3680 
3681 static void
3682 _spdk_bs_init_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3683 {
3684 	struct spdk_bs_init_ctx *ctx = cb_arg;
3685 
3686 	/* Write super block */
3687 	spdk_bs_sequence_write_dev(seq, ctx->super, _spdk_bs_page_to_lba(ctx->bs, 0),
3688 				   _spdk_bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
3689 				   _spdk_bs_init_persist_super_cpl, ctx);
3690 }
3691 
3692 void
3693 spdk_bs_init(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
3694 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
3695 {
3696 	struct spdk_bs_init_ctx *ctx;
3697 	struct spdk_blob_store	*bs;
3698 	struct spdk_bs_cpl	cpl;
3699 	spdk_bs_sequence_t	*seq;
3700 	spdk_bs_batch_t		*batch;
3701 	uint64_t		num_md_lba;
3702 	uint64_t		num_md_pages;
3703 	uint64_t		num_md_clusters;
3704 	uint32_t		i;
3705 	struct spdk_bs_opts	opts = {};
3706 	int			rc;
3707 
3708 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Initializing blobstore on dev %p\n", dev);
3709 
3710 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
3711 		SPDK_ERRLOG("unsupported dev block length of %d\n",
3712 			    dev->blocklen);
3713 		dev->destroy(dev);
3714 		cb_fn(cb_arg, NULL, -EINVAL);
3715 		return;
3716 	}
3717 
3718 	if (o) {
3719 		opts = *o;
3720 	} else {
3721 		spdk_bs_opts_init(&opts);
3722 	}
3723 
3724 	if (_spdk_bs_opts_verify(&opts) != 0) {
3725 		dev->destroy(dev);
3726 		cb_fn(cb_arg, NULL, -EINVAL);
3727 		return;
3728 	}
3729 
3730 	rc = _spdk_bs_alloc(dev, &opts, &bs);
3731 	if (rc) {
3732 		dev->destroy(dev);
3733 		cb_fn(cb_arg, NULL, rc);
3734 		return;
3735 	}
3736 
3737 	if (opts.num_md_pages == SPDK_BLOB_OPTS_NUM_MD_PAGES) {
3738 		/* By default, allocate 1 page per cluster.
3739 		 * Technically, this over-allocates metadata
3740 		 * because more metadata will reduce the number
3741 		 * of usable clusters. This can be addressed with
3742 		 * more complex math in the future.
3743 		 */
3744 		bs->md_len = bs->total_clusters;
3745 	} else {
3746 		bs->md_len = opts.num_md_pages;
3747 	}
3748 	rc = spdk_bit_array_resize(&bs->used_md_pages, bs->md_len);
3749 	if (rc < 0) {
3750 		_spdk_bs_free(bs);
3751 		cb_fn(cb_arg, NULL, -ENOMEM);
3752 		return;
3753 	}
3754 
3755 	rc = spdk_bit_array_resize(&bs->used_blobids, bs->md_len);
3756 	if (rc < 0) {
3757 		_spdk_bs_free(bs);
3758 		cb_fn(cb_arg, NULL, -ENOMEM);
3759 		return;
3760 	}
3761 
3762 	ctx = calloc(1, sizeof(*ctx));
3763 	if (!ctx) {
3764 		_spdk_bs_free(bs);
3765 		cb_fn(cb_arg, NULL, -ENOMEM);
3766 		return;
3767 	}
3768 
3769 	ctx->bs = bs;
3770 
3771 	/* Allocate memory for the super block */
3772 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
3773 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3774 	if (!ctx->super) {
3775 		free(ctx);
3776 		_spdk_bs_free(bs);
3777 		cb_fn(cb_arg, NULL, -ENOMEM);
3778 		return;
3779 	}
3780 	memcpy(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
3781 	       sizeof(ctx->super->signature));
3782 	ctx->super->version = SPDK_BS_VERSION;
3783 	ctx->super->length = sizeof(*ctx->super);
3784 	ctx->super->super_blob = bs->super_blob;
3785 	ctx->super->clean = 0;
3786 	ctx->super->cluster_size = bs->cluster_sz;
3787 	ctx->super->io_unit_size = bs->io_unit_size;
3788 	memcpy(&ctx->super->bstype, &bs->bstype, sizeof(bs->bstype));
3789 
3790 	/* Calculate how many pages the metadata consumes at the front
3791 	 * of the disk.
3792 	 */
3793 
3794 	/* The super block uses 1 page */
3795 	num_md_pages = 1;
3796 
3797 	/* The used_md_pages mask requires 1 bit per metadata page, rounded
3798 	 * up to the nearest page, plus a header.
3799 	 */
3800 	ctx->super->used_page_mask_start = num_md_pages;
3801 	ctx->super->used_page_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3802 					 spdk_divide_round_up(bs->md_len, 8),
3803 					 SPDK_BS_PAGE_SIZE);
3804 	num_md_pages += ctx->super->used_page_mask_len;
3805 
3806 	/* The used_clusters mask requires 1 bit per cluster, rounded
3807 	 * up to the nearest page, plus a header.
3808 	 */
3809 	ctx->super->used_cluster_mask_start = num_md_pages;
3810 	ctx->super->used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3811 					    spdk_divide_round_up(bs->total_clusters, 8),
3812 					    SPDK_BS_PAGE_SIZE);
3813 	num_md_pages += ctx->super->used_cluster_mask_len;
3814 
3815 	/* The used_blobids mask requires 1 bit per metadata page, rounded
3816 	 * up to the nearest page, plus a header.
3817 	 */
3818 	ctx->super->used_blobid_mask_start = num_md_pages;
3819 	ctx->super->used_blobid_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
3820 					   spdk_divide_round_up(bs->md_len, 8),
3821 					   SPDK_BS_PAGE_SIZE);
3822 	num_md_pages += ctx->super->used_blobid_mask_len;
3823 
3824 	/* The metadata region size was chosen above */
3825 	ctx->super->md_start = bs->md_start = num_md_pages;
3826 	ctx->super->md_len = bs->md_len;
3827 	num_md_pages += bs->md_len;
3828 
3829 	num_md_lba = _spdk_bs_page_to_lba(bs, num_md_pages);
3830 
3831 	ctx->super->size = dev->blockcnt * dev->blocklen;
3832 
3833 	ctx->super->crc = _spdk_blob_md_page_calc_crc(ctx->super);
3834 
3835 	num_md_clusters = spdk_divide_round_up(num_md_pages, bs->pages_per_cluster);
3836 	if (num_md_clusters > bs->total_clusters) {
3837 		SPDK_ERRLOG("Blobstore metadata cannot use more clusters than is available, "
3838 			    "please decrease number of pages reserved for metadata "
3839 			    "or increase cluster size.\n");
3840 		spdk_free(ctx->super);
3841 		free(ctx);
3842 		_spdk_bs_free(bs);
3843 		cb_fn(cb_arg, NULL, -ENOMEM);
3844 		return;
3845 	}
3846 	/* Claim all of the clusters used by the metadata */
3847 	for (i = 0; i < num_md_clusters; i++) {
3848 		_spdk_bs_claim_cluster(bs, i);
3849 	}
3850 
3851 	bs->total_data_clusters = bs->num_free_clusters;
3852 
3853 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
3854 	cpl.u.bs_handle.cb_fn = cb_fn;
3855 	cpl.u.bs_handle.cb_arg = cb_arg;
3856 	cpl.u.bs_handle.bs = bs;
3857 
3858 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3859 	if (!seq) {
3860 		spdk_free(ctx->super);
3861 		free(ctx);
3862 		_spdk_bs_free(bs);
3863 		cb_fn(cb_arg, NULL, -ENOMEM);
3864 		return;
3865 	}
3866 
3867 	batch = spdk_bs_sequence_to_batch(seq, _spdk_bs_init_trim_cpl, ctx);
3868 
3869 	/* Clear metadata space */
3870 	spdk_bs_batch_write_zeroes_dev(batch, 0, num_md_lba);
3871 
3872 	if (opts.clear_method == BS_CLEAR_WITH_UNMAP) {
3873 		/* Trim data clusters */
3874 		spdk_bs_batch_unmap_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
3875 	} else if (opts.clear_method == BS_CLEAR_WITH_WRITE_ZEROES) {
3876 		/* Write_zeroes to data clusters */
3877 		spdk_bs_batch_write_zeroes_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
3878 	}
3879 
3880 	spdk_bs_batch_close(batch);
3881 }
3882 
3883 /* END spdk_bs_init */
3884 
3885 /* START spdk_bs_destroy */
3886 
3887 static void
3888 _spdk_bs_destroy_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3889 {
3890 	struct spdk_bs_init_ctx *ctx = cb_arg;
3891 	struct spdk_blob_store *bs = ctx->bs;
3892 
3893 	/*
3894 	 * We need to defer calling spdk_bs_call_cpl() until after
3895 	 * dev destruction, so tuck these away for later use.
3896 	 */
3897 	bs->unload_err = bserrno;
3898 	memcpy(&bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3899 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3900 
3901 	spdk_bs_sequence_finish(seq, bserrno);
3902 
3903 	_spdk_bs_free(bs);
3904 	free(ctx);
3905 }
3906 
3907 void
3908 spdk_bs_destroy(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn,
3909 		void *cb_arg)
3910 {
3911 	struct spdk_bs_cpl	cpl;
3912 	spdk_bs_sequence_t	*seq;
3913 	struct spdk_bs_init_ctx *ctx;
3914 
3915 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Destroying blobstore\n");
3916 
3917 	if (!TAILQ_EMPTY(&bs->blobs)) {
3918 		SPDK_ERRLOG("Blobstore still has open blobs\n");
3919 		cb_fn(cb_arg, -EBUSY);
3920 		return;
3921 	}
3922 
3923 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
3924 	cpl.u.bs_basic.cb_fn = cb_fn;
3925 	cpl.u.bs_basic.cb_arg = cb_arg;
3926 
3927 	ctx = calloc(1, sizeof(*ctx));
3928 	if (!ctx) {
3929 		cb_fn(cb_arg, -ENOMEM);
3930 		return;
3931 	}
3932 
3933 	ctx->bs = bs;
3934 
3935 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3936 	if (!seq) {
3937 		free(ctx);
3938 		cb_fn(cb_arg, -ENOMEM);
3939 		return;
3940 	}
3941 
3942 	/* Write zeroes to the super block */
3943 	spdk_bs_sequence_write_zeroes_dev(seq,
3944 					  _spdk_bs_page_to_lba(bs, 0),
3945 					  _spdk_bs_byte_to_lba(bs, sizeof(struct spdk_bs_super_block)),
3946 					  _spdk_bs_destroy_trim_cpl, ctx);
3947 }
3948 
3949 /* END spdk_bs_destroy */
3950 
3951 /* START spdk_bs_unload */
3952 
3953 static void
3954 _spdk_bs_unload_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3955 {
3956 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3957 
3958 	spdk_free(ctx->super);
3959 
3960 	/*
3961 	 * We need to defer calling spdk_bs_call_cpl() until after
3962 	 * dev destruction, so tuck these away for later use.
3963 	 */
3964 	ctx->bs->unload_err = bserrno;
3965 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3966 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3967 
3968 	spdk_bs_sequence_finish(seq, bserrno);
3969 
3970 	_spdk_bs_free(ctx->bs);
3971 	free(ctx);
3972 }
3973 
3974 static void
3975 _spdk_bs_unload_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3976 {
3977 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3978 
3979 	spdk_free(ctx->mask);
3980 	ctx->super->clean = 1;
3981 
3982 	_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_unload_write_super_cpl, ctx);
3983 }
3984 
3985 static void
3986 _spdk_bs_unload_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3987 {
3988 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3989 
3990 	spdk_free(ctx->mask);
3991 	ctx->mask = NULL;
3992 
3993 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_unload_write_used_clusters_cpl);
3994 }
3995 
3996 static void
3997 _spdk_bs_unload_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3998 {
3999 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4000 
4001 	spdk_free(ctx->mask);
4002 	ctx->mask = NULL;
4003 
4004 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_unload_write_used_blobids_cpl);
4005 }
4006 
4007 static void
4008 _spdk_bs_unload_read_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4009 {
4010 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_unload_write_used_pages_cpl);
4011 }
4012 
4013 void
4014 spdk_bs_unload(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn, void *cb_arg)
4015 {
4016 	struct spdk_bs_cpl	cpl;
4017 	spdk_bs_sequence_t	*seq;
4018 	struct spdk_bs_load_ctx *ctx;
4019 
4020 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blobstore\n");
4021 
4022 	if (!TAILQ_EMPTY(&bs->blobs)) {
4023 		SPDK_ERRLOG("Blobstore still has open blobs\n");
4024 		cb_fn(cb_arg, -EBUSY);
4025 		return;
4026 	}
4027 
4028 	ctx = calloc(1, sizeof(*ctx));
4029 	if (!ctx) {
4030 		cb_fn(cb_arg, -ENOMEM);
4031 		return;
4032 	}
4033 
4034 	ctx->bs = bs;
4035 
4036 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4037 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4038 	if (!ctx->super) {
4039 		free(ctx);
4040 		cb_fn(cb_arg, -ENOMEM);
4041 		return;
4042 	}
4043 
4044 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4045 	cpl.u.bs_basic.cb_fn = cb_fn;
4046 	cpl.u.bs_basic.cb_arg = cb_arg;
4047 
4048 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4049 	if (!seq) {
4050 		spdk_free(ctx->super);
4051 		free(ctx);
4052 		cb_fn(cb_arg, -ENOMEM);
4053 		return;
4054 	}
4055 
4056 	/* Read super block */
4057 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
4058 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
4059 				  _spdk_bs_unload_read_super_cpl, ctx);
4060 }
4061 
4062 /* END spdk_bs_unload */
4063 
4064 /* START spdk_bs_set_super */
4065 
4066 struct spdk_bs_set_super_ctx {
4067 	struct spdk_blob_store		*bs;
4068 	struct spdk_bs_super_block	*super;
4069 };
4070 
4071 static void
4072 _spdk_bs_set_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4073 {
4074 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
4075 
4076 	if (bserrno != 0) {
4077 		SPDK_ERRLOG("Unable to write to super block of blobstore\n");
4078 	}
4079 
4080 	spdk_free(ctx->super);
4081 
4082 	spdk_bs_sequence_finish(seq, bserrno);
4083 
4084 	free(ctx);
4085 }
4086 
4087 static void
4088 _spdk_bs_set_super_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4089 {
4090 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
4091 
4092 	if (bserrno != 0) {
4093 		SPDK_ERRLOG("Unable to read super block of blobstore\n");
4094 		spdk_free(ctx->super);
4095 		spdk_bs_sequence_finish(seq, bserrno);
4096 		free(ctx);
4097 		return;
4098 	}
4099 
4100 	_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_set_super_write_cpl, ctx);
4101 }
4102 
4103 void
4104 spdk_bs_set_super(struct spdk_blob_store *bs, spdk_blob_id blobid,
4105 		  spdk_bs_op_complete cb_fn, void *cb_arg)
4106 {
4107 	struct spdk_bs_cpl		cpl;
4108 	spdk_bs_sequence_t		*seq;
4109 	struct spdk_bs_set_super_ctx	*ctx;
4110 
4111 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Setting super blob id on blobstore\n");
4112 
4113 	ctx = calloc(1, sizeof(*ctx));
4114 	if (!ctx) {
4115 		cb_fn(cb_arg, -ENOMEM);
4116 		return;
4117 	}
4118 
4119 	ctx->bs = bs;
4120 
4121 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4122 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4123 	if (!ctx->super) {
4124 		free(ctx);
4125 		cb_fn(cb_arg, -ENOMEM);
4126 		return;
4127 	}
4128 
4129 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4130 	cpl.u.bs_basic.cb_fn = cb_fn;
4131 	cpl.u.bs_basic.cb_arg = cb_arg;
4132 
4133 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4134 	if (!seq) {
4135 		spdk_free(ctx->super);
4136 		free(ctx);
4137 		cb_fn(cb_arg, -ENOMEM);
4138 		return;
4139 	}
4140 
4141 	bs->super_blob = blobid;
4142 
4143 	/* Read super block */
4144 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
4145 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
4146 				  _spdk_bs_set_super_read_cpl, ctx);
4147 }
4148 
4149 /* END spdk_bs_set_super */
4150 
4151 void
4152 spdk_bs_get_super(struct spdk_blob_store *bs,
4153 		  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4154 {
4155 	if (bs->super_blob == SPDK_BLOBID_INVALID) {
4156 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOENT);
4157 	} else {
4158 		cb_fn(cb_arg, bs->super_blob, 0);
4159 	}
4160 }
4161 
4162 uint64_t
4163 spdk_bs_get_cluster_size(struct spdk_blob_store *bs)
4164 {
4165 	return bs->cluster_sz;
4166 }
4167 
4168 uint64_t
4169 spdk_bs_get_page_size(struct spdk_blob_store *bs)
4170 {
4171 	return SPDK_BS_PAGE_SIZE;
4172 }
4173 
4174 uint64_t
4175 spdk_bs_get_io_unit_size(struct spdk_blob_store *bs)
4176 {
4177 	return bs->io_unit_size;
4178 }
4179 
4180 uint64_t
4181 spdk_bs_free_cluster_count(struct spdk_blob_store *bs)
4182 {
4183 	return bs->num_free_clusters;
4184 }
4185 
4186 uint64_t
4187 spdk_bs_total_data_cluster_count(struct spdk_blob_store *bs)
4188 {
4189 	return bs->total_data_clusters;
4190 }
4191 
4192 static int
4193 spdk_bs_register_md_thread(struct spdk_blob_store *bs)
4194 {
4195 	bs->md_channel = spdk_get_io_channel(bs);
4196 	if (!bs->md_channel) {
4197 		SPDK_ERRLOG("Failed to get IO channel.\n");
4198 		return -1;
4199 	}
4200 
4201 	return 0;
4202 }
4203 
4204 static int
4205 spdk_bs_unregister_md_thread(struct spdk_blob_store *bs)
4206 {
4207 	spdk_put_io_channel(bs->md_channel);
4208 
4209 	return 0;
4210 }
4211 
4212 spdk_blob_id spdk_blob_get_id(struct spdk_blob *blob)
4213 {
4214 	assert(blob != NULL);
4215 
4216 	return blob->id;
4217 }
4218 
4219 uint64_t spdk_blob_get_num_pages(struct spdk_blob *blob)
4220 {
4221 	assert(blob != NULL);
4222 
4223 	return _spdk_bs_cluster_to_page(blob->bs, blob->active.num_clusters);
4224 }
4225 
4226 uint64_t spdk_blob_get_num_io_units(struct spdk_blob *blob)
4227 {
4228 	assert(blob != NULL);
4229 
4230 	return spdk_blob_get_num_pages(blob) * _spdk_bs_io_unit_per_page(blob->bs);
4231 }
4232 
4233 uint64_t spdk_blob_get_num_clusters(struct spdk_blob *blob)
4234 {
4235 	assert(blob != NULL);
4236 
4237 	return blob->active.num_clusters;
4238 }
4239 
4240 /* START spdk_bs_create_blob */
4241 
4242 static void
4243 _spdk_bs_create_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4244 {
4245 	struct spdk_blob *blob = cb_arg;
4246 
4247 	_spdk_blob_free(blob);
4248 
4249 	spdk_bs_sequence_finish(seq, bserrno);
4250 }
4251 
4252 static int
4253 _spdk_blob_set_xattrs(struct spdk_blob *blob, const struct spdk_blob_xattr_opts *xattrs,
4254 		      bool internal)
4255 {
4256 	uint64_t i;
4257 	size_t value_len = 0;
4258 	int rc;
4259 	const void *value = NULL;
4260 	if (xattrs->count > 0 && xattrs->get_value == NULL) {
4261 		return -EINVAL;
4262 	}
4263 	for (i = 0; i < xattrs->count; i++) {
4264 		xattrs->get_value(xattrs->ctx, xattrs->names[i], &value, &value_len);
4265 		if (value == NULL || value_len == 0) {
4266 			return -EINVAL;
4267 		}
4268 		rc = _spdk_blob_set_xattr(blob, xattrs->names[i], value, value_len, internal);
4269 		if (rc < 0) {
4270 			return rc;
4271 		}
4272 	}
4273 	return 0;
4274 }
4275 
4276 static void
4277 _spdk_bs_create_blob(struct spdk_blob_store *bs,
4278 		     const struct spdk_blob_opts *opts,
4279 		     const struct spdk_blob_xattr_opts *internal_xattrs,
4280 		     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4281 {
4282 	struct spdk_blob	*blob;
4283 	uint32_t		page_idx;
4284 	struct spdk_bs_cpl	cpl;
4285 	struct spdk_blob_opts	opts_default;
4286 	struct spdk_blob_xattr_opts internal_xattrs_default;
4287 	spdk_bs_sequence_t	*seq;
4288 	spdk_blob_id		id;
4289 	int rc;
4290 
4291 	assert(spdk_get_thread() == bs->md_thread);
4292 
4293 	page_idx = spdk_bit_array_find_first_clear(bs->used_md_pages, 0);
4294 	if (page_idx == UINT32_MAX) {
4295 		cb_fn(cb_arg, 0, -ENOMEM);
4296 		return;
4297 	}
4298 	spdk_bit_array_set(bs->used_blobids, page_idx);
4299 	spdk_bit_array_set(bs->used_md_pages, page_idx);
4300 
4301 	id = _spdk_bs_page_to_blobid(page_idx);
4302 
4303 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Creating blob with id %lu at page %u\n", id, page_idx);
4304 
4305 	blob = _spdk_blob_alloc(bs, id);
4306 	if (!blob) {
4307 		cb_fn(cb_arg, 0, -ENOMEM);
4308 		return;
4309 	}
4310 
4311 	if (!opts) {
4312 		spdk_blob_opts_init(&opts_default);
4313 		opts = &opts_default;
4314 	}
4315 	if (!internal_xattrs) {
4316 		_spdk_blob_xattrs_init(&internal_xattrs_default);
4317 		internal_xattrs = &internal_xattrs_default;
4318 	}
4319 
4320 	rc = _spdk_blob_set_xattrs(blob, &opts->xattrs, false);
4321 	if (rc < 0) {
4322 		_spdk_blob_free(blob);
4323 		cb_fn(cb_arg, 0, rc);
4324 		return;
4325 	}
4326 
4327 	rc = _spdk_blob_set_xattrs(blob, internal_xattrs, true);
4328 	if (rc < 0) {
4329 		_spdk_blob_free(blob);
4330 		cb_fn(cb_arg, 0, rc);
4331 		return;
4332 	}
4333 
4334 	if (opts->thin_provision) {
4335 		_spdk_blob_set_thin_provision(blob);
4336 	}
4337 
4338 	rc = _spdk_blob_resize(blob, opts->num_clusters);
4339 	if (rc < 0) {
4340 		_spdk_blob_free(blob);
4341 		cb_fn(cb_arg, 0, rc);
4342 		return;
4343 	}
4344 	cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4345 	cpl.u.blobid.cb_fn = cb_fn;
4346 	cpl.u.blobid.cb_arg = cb_arg;
4347 	cpl.u.blobid.blobid = blob->id;
4348 
4349 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
4350 	if (!seq) {
4351 		_spdk_blob_free(blob);
4352 		cb_fn(cb_arg, 0, -ENOMEM);
4353 		return;
4354 	}
4355 
4356 	_spdk_blob_persist(seq, blob, _spdk_bs_create_blob_cpl, blob);
4357 }
4358 
4359 void spdk_bs_create_blob(struct spdk_blob_store *bs,
4360 			 spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4361 {
4362 	_spdk_bs_create_blob(bs, NULL, NULL, cb_fn, cb_arg);
4363 }
4364 
4365 void spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
4366 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4367 {
4368 	_spdk_bs_create_blob(bs, opts, NULL, cb_fn, cb_arg);
4369 }
4370 
4371 /* END spdk_bs_create_blob */
4372 
4373 /* START blob_cleanup */
4374 
4375 struct spdk_clone_snapshot_ctx {
4376 	struct spdk_bs_cpl      cpl;
4377 	int bserrno;
4378 	bool frozen;
4379 
4380 	struct spdk_io_channel *channel;
4381 
4382 	/* Current cluster for inflate operation */
4383 	uint64_t cluster;
4384 
4385 	/* For inflation force allocation of all unallocated clusters and remove
4386 	 * thin-provisioning. Otherwise only decouple parent and keep clone thin. */
4387 	bool allocate_all;
4388 
4389 	struct {
4390 		spdk_blob_id id;
4391 		struct spdk_blob *blob;
4392 	} original;
4393 	struct {
4394 		spdk_blob_id id;
4395 		struct spdk_blob *blob;
4396 	} new;
4397 
4398 	/* xattrs specified for snapshot/clones only. They have no impact on
4399 	 * the original blobs xattrs. */
4400 	const struct spdk_blob_xattr_opts *xattrs;
4401 };
4402 
4403 static void
4404 _spdk_bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
4405 {
4406 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
4407 	struct spdk_bs_cpl *cpl = &ctx->cpl;
4408 
4409 	if (bserrno != 0) {
4410 		if (ctx->bserrno != 0) {
4411 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4412 		} else {
4413 			ctx->bserrno = bserrno;
4414 		}
4415 	}
4416 
4417 	switch (cpl->type) {
4418 	case SPDK_BS_CPL_TYPE_BLOBID:
4419 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
4420 		break;
4421 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
4422 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
4423 		break;
4424 	default:
4425 		SPDK_UNREACHABLE();
4426 		break;
4427 	}
4428 
4429 	free(ctx);
4430 }
4431 
4432 static void
4433 _spdk_bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
4434 {
4435 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4436 	struct spdk_blob *origblob = ctx->original.blob;
4437 
4438 	if (bserrno != 0) {
4439 		if (ctx->bserrno != 0) {
4440 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
4441 		} else {
4442 			ctx->bserrno = bserrno;
4443 		}
4444 	}
4445 
4446 	ctx->original.id = origblob->id;
4447 	origblob->locked_operation_in_progress = false;
4448 
4449 	spdk_blob_close(origblob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4450 }
4451 
4452 static void
4453 _spdk_bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
4454 {
4455 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4456 	struct spdk_blob *origblob = ctx->original.blob;
4457 
4458 	if (bserrno != 0) {
4459 		if (ctx->bserrno != 0) {
4460 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4461 		} else {
4462 			ctx->bserrno = bserrno;
4463 		}
4464 	}
4465 
4466 	if (ctx->frozen) {
4467 		/* Unfreeze any outstanding I/O */
4468 		_spdk_blob_unfreeze_io(origblob, _spdk_bs_snapshot_unfreeze_cpl, ctx);
4469 	} else {
4470 		_spdk_bs_snapshot_unfreeze_cpl(ctx, 0);
4471 	}
4472 
4473 }
4474 
4475 static void
4476 _spdk_bs_clone_snapshot_newblob_cleanup(void *cb_arg, int bserrno)
4477 {
4478 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4479 	struct spdk_blob *newblob = ctx->new.blob;
4480 
4481 	if (bserrno != 0) {
4482 		if (ctx->bserrno != 0) {
4483 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
4484 		} else {
4485 			ctx->bserrno = bserrno;
4486 		}
4487 	}
4488 
4489 	ctx->new.id = newblob->id;
4490 	spdk_blob_close(newblob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4491 }
4492 
4493 /* END blob_cleanup */
4494 
4495 /* START spdk_bs_create_snapshot */
4496 
4497 static void
4498 _spdk_bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
4499 {
4500 	uint64_t *cluster_temp;
4501 
4502 	cluster_temp = blob1->active.clusters;
4503 	blob1->active.clusters = blob2->active.clusters;
4504 	blob2->active.clusters = cluster_temp;
4505 }
4506 
4507 static void
4508 _spdk_bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
4509 {
4510 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4511 	struct spdk_blob *origblob = ctx->original.blob;
4512 	struct spdk_blob *newblob = ctx->new.blob;
4513 
4514 	if (bserrno != 0) {
4515 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4516 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4517 		return;
4518 	}
4519 
4520 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
4521 	bserrno = _spdk_blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
4522 	if (bserrno != 0) {
4523 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4524 		return;
4525 	}
4526 
4527 	_spdk_bs_blob_list_add(ctx->original.blob);
4528 
4529 	spdk_blob_set_read_only(newblob);
4530 
4531 	/* sync snapshot metadata */
4532 	spdk_blob_sync_md(newblob, _spdk_bs_clone_snapshot_origblob_cleanup, cb_arg);
4533 }
4534 
4535 static void
4536 _spdk_bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
4537 {
4538 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4539 	struct spdk_blob *origblob = ctx->original.blob;
4540 	struct spdk_blob *newblob = ctx->new.blob;
4541 
4542 	if (bserrno != 0) {
4543 		/* return cluster map back to original */
4544 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4545 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4546 		return;
4547 	}
4548 
4549 	/* Set internal xattr for snapshot id */
4550 	bserrno = _spdk_blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
4551 	if (bserrno != 0) {
4552 		/* return cluster map back to original */
4553 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4554 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4555 		return;
4556 	}
4557 
4558 	_spdk_bs_blob_list_remove(origblob);
4559 	origblob->parent_id = newblob->id;
4560 
4561 	/* Create new back_bs_dev for snapshot */
4562 	origblob->back_bs_dev = spdk_bs_create_blob_bs_dev(newblob);
4563 	if (origblob->back_bs_dev == NULL) {
4564 		/* return cluster map back to original */
4565 		_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4566 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
4567 		return;
4568 	}
4569 
4570 	/* set clone blob as thin provisioned */
4571 	_spdk_blob_set_thin_provision(origblob);
4572 
4573 	_spdk_bs_blob_list_add(newblob);
4574 
4575 	/* sync clone metadata */
4576 	spdk_blob_sync_md(origblob, _spdk_bs_snapshot_origblob_sync_cpl, ctx);
4577 }
4578 
4579 static void
4580 _spdk_bs_snapshot_freeze_cpl(void *cb_arg, int rc)
4581 {
4582 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4583 	struct spdk_blob *origblob = ctx->original.blob;
4584 	struct spdk_blob *newblob = ctx->new.blob;
4585 	int bserrno;
4586 
4587 	if (rc != 0) {
4588 		_spdk_bs_clone_snapshot_newblob_cleanup(ctx, rc);
4589 		return;
4590 	}
4591 
4592 	ctx->frozen = true;
4593 
4594 	/* set new back_bs_dev for snapshot */
4595 	newblob->back_bs_dev = origblob->back_bs_dev;
4596 	/* Set invalid flags from origblob */
4597 	newblob->invalid_flags = origblob->invalid_flags;
4598 
4599 	/* inherit parent from original blob if set */
4600 	newblob->parent_id = origblob->parent_id;
4601 	if (origblob->parent_id != SPDK_BLOBID_INVALID) {
4602 		/* Set internal xattr for snapshot id */
4603 		bserrno = _spdk_blob_set_xattr(newblob, BLOB_SNAPSHOT,
4604 					       &origblob->parent_id, sizeof(spdk_blob_id), true);
4605 		if (bserrno != 0) {
4606 			_spdk_bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
4607 			return;
4608 		}
4609 	}
4610 
4611 	/* swap cluster maps */
4612 	_spdk_bs_snapshot_swap_cluster_maps(newblob, origblob);
4613 
4614 	/* sync snapshot metadata */
4615 	spdk_blob_sync_md(newblob, _spdk_bs_snapshot_newblob_sync_cpl, ctx);
4616 }
4617 
4618 static void
4619 _spdk_bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4620 {
4621 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4622 	struct spdk_blob *origblob = ctx->original.blob;
4623 	struct spdk_blob *newblob = _blob;
4624 
4625 	if (bserrno != 0) {
4626 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4627 		return;
4628 	}
4629 
4630 	ctx->new.blob = newblob;
4631 
4632 	/* Zero out newblob cluster map */
4633 	memset(newblob->active.clusters, 0,
4634 	       newblob->active.num_clusters * sizeof(newblob->active.clusters));
4635 
4636 	_spdk_blob_freeze_io(origblob, _spdk_bs_snapshot_freeze_cpl, ctx);
4637 }
4638 
4639 static void
4640 _spdk_bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
4641 {
4642 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4643 	struct spdk_blob *origblob = ctx->original.blob;
4644 
4645 	if (bserrno != 0) {
4646 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4647 		return;
4648 	}
4649 
4650 	ctx->new.id = blobid;
4651 	ctx->cpl.u.blobid.blobid = blobid;
4652 
4653 	spdk_bs_open_blob(origblob->bs, ctx->new.id, _spdk_bs_snapshot_newblob_open_cpl, ctx);
4654 }
4655 
4656 
4657 static void
4658 _spdk_bs_xattr_snapshot(void *arg, const char *name,
4659 			const void **value, size_t *value_len)
4660 {
4661 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
4662 
4663 	struct spdk_blob *blob = (struct spdk_blob *)arg;
4664 	*value = &blob->id;
4665 	*value_len = sizeof(blob->id);
4666 }
4667 
4668 static void
4669 _spdk_bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4670 {
4671 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4672 	struct spdk_blob_opts opts;
4673 	struct spdk_blob_xattr_opts internal_xattrs;
4674 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
4675 
4676 	if (bserrno != 0) {
4677 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
4678 		return;
4679 	}
4680 
4681 	ctx->original.blob = _blob;
4682 
4683 	if (_blob->data_ro || _blob->md_ro) {
4684 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot from read only blob with id %lu\n",
4685 			      _blob->id);
4686 		ctx->bserrno = -EINVAL;
4687 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4688 		return;
4689 	}
4690 
4691 	if (_blob->locked_operation_in_progress) {
4692 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot - another operation in progress\n");
4693 		ctx->bserrno = -EBUSY;
4694 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4695 		return;
4696 	}
4697 
4698 	_blob->locked_operation_in_progress = true;
4699 
4700 	spdk_blob_opts_init(&opts);
4701 	_spdk_blob_xattrs_init(&internal_xattrs);
4702 
4703 	/* Change the size of new blob to the same as in original blob,
4704 	 * but do not allocate clusters */
4705 	opts.thin_provision = true;
4706 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
4707 
4708 	/* If there are any xattrs specified for snapshot, set them now */
4709 	if (ctx->xattrs) {
4710 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
4711 	}
4712 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
4713 	internal_xattrs.count = 1;
4714 	internal_xattrs.ctx = _blob;
4715 	internal_xattrs.names = xattrs_names;
4716 	internal_xattrs.get_value = _spdk_bs_xattr_snapshot;
4717 
4718 	_spdk_bs_create_blob(_blob->bs, &opts, &internal_xattrs,
4719 			     _spdk_bs_snapshot_newblob_create_cpl, ctx);
4720 }
4721 
4722 void spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
4723 			     const struct spdk_blob_xattr_opts *snapshot_xattrs,
4724 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4725 {
4726 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
4727 
4728 	if (!ctx) {
4729 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
4730 		return;
4731 	}
4732 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4733 	ctx->cpl.u.blobid.cb_fn = cb_fn;
4734 	ctx->cpl.u.blobid.cb_arg = cb_arg;
4735 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
4736 	ctx->bserrno = 0;
4737 	ctx->frozen = false;
4738 	ctx->original.id = blobid;
4739 	ctx->xattrs = snapshot_xattrs;
4740 
4741 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_snapshot_origblob_open_cpl, ctx);
4742 }
4743 /* END spdk_bs_create_snapshot */
4744 
4745 /* START spdk_bs_create_clone */
4746 
4747 static void
4748 _spdk_bs_xattr_clone(void *arg, const char *name,
4749 		     const void **value, size_t *value_len)
4750 {
4751 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
4752 
4753 	struct spdk_blob *blob = (struct spdk_blob *)arg;
4754 	*value = &blob->id;
4755 	*value_len = sizeof(blob->id);
4756 }
4757 
4758 static void
4759 _spdk_bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4760 {
4761 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4762 	struct spdk_blob *clone = _blob;
4763 
4764 	ctx->new.blob = clone;
4765 	_spdk_bs_blob_list_add(clone);
4766 
4767 	spdk_blob_close(clone, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4768 }
4769 
4770 static void
4771 _spdk_bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
4772 {
4773 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4774 
4775 	ctx->cpl.u.blobid.blobid = blobid;
4776 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, _spdk_bs_clone_newblob_open_cpl, ctx);
4777 }
4778 
4779 static void
4780 _spdk_bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4781 {
4782 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4783 	struct spdk_blob_opts		opts;
4784 	struct spdk_blob_xattr_opts internal_xattrs;
4785 	char *xattr_names[] = { BLOB_SNAPSHOT };
4786 
4787 	if (bserrno != 0) {
4788 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
4789 		return;
4790 	}
4791 
4792 	ctx->original.blob = _blob;
4793 
4794 	if (!_blob->data_ro || !_blob->md_ro) {
4795 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Clone not from read-only blob\n");
4796 		ctx->bserrno = -EINVAL;
4797 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4798 		return;
4799 	}
4800 
4801 	if (_blob->locked_operation_in_progress) {
4802 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create clone - another operation in progress\n");
4803 		ctx->bserrno = -EBUSY;
4804 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4805 		return;
4806 	}
4807 
4808 	_blob->locked_operation_in_progress = true;
4809 
4810 	spdk_blob_opts_init(&opts);
4811 	_spdk_blob_xattrs_init(&internal_xattrs);
4812 
4813 	opts.thin_provision = true;
4814 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
4815 	if (ctx->xattrs) {
4816 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
4817 	}
4818 
4819 	/* Set internal xattr BLOB_SNAPSHOT */
4820 	internal_xattrs.count = 1;
4821 	internal_xattrs.ctx = _blob;
4822 	internal_xattrs.names = xattr_names;
4823 	internal_xattrs.get_value = _spdk_bs_xattr_clone;
4824 
4825 	_spdk_bs_create_blob(_blob->bs, &opts, &internal_xattrs,
4826 			     _spdk_bs_clone_newblob_create_cpl, ctx);
4827 }
4828 
4829 void spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
4830 			  const struct spdk_blob_xattr_opts *clone_xattrs,
4831 			  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
4832 {
4833 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
4834 
4835 	if (!ctx) {
4836 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
4837 		return;
4838 	}
4839 
4840 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
4841 	ctx->cpl.u.blobid.cb_fn = cb_fn;
4842 	ctx->cpl.u.blobid.cb_arg = cb_arg;
4843 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
4844 	ctx->bserrno = 0;
4845 	ctx->xattrs = clone_xattrs;
4846 	ctx->original.id = blobid;
4847 
4848 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_clone_origblob_open_cpl, ctx);
4849 }
4850 
4851 /* END spdk_bs_create_clone */
4852 
4853 /* START spdk_bs_inflate_blob */
4854 
4855 static void
4856 _spdk_bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
4857 {
4858 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4859 	struct spdk_blob *_blob = ctx->original.blob;
4860 
4861 	if (bserrno != 0) {
4862 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4863 		return;
4864 	}
4865 
4866 	assert(_parent != NULL);
4867 
4868 	_spdk_bs_blob_list_remove(_blob);
4869 	_blob->parent_id = _parent->id;
4870 	_spdk_blob_set_xattr(_blob, BLOB_SNAPSHOT, &_blob->parent_id,
4871 			     sizeof(spdk_blob_id), true);
4872 
4873 	_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4874 	_blob->back_bs_dev = spdk_bs_create_blob_bs_dev(_parent);
4875 	_spdk_bs_blob_list_add(_blob);
4876 
4877 	spdk_blob_sync_md(_blob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4878 }
4879 
4880 static void
4881 _spdk_bs_inflate_blob_done(void *cb_arg, int bserrno)
4882 {
4883 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4884 	struct spdk_blob *_blob = ctx->original.blob;
4885 	struct spdk_blob *_parent;
4886 
4887 	if (bserrno != 0) {
4888 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4889 		return;
4890 	}
4891 
4892 	if (ctx->allocate_all) {
4893 		/* remove thin provisioning */
4894 		_spdk_bs_blob_list_remove(_blob);
4895 		_spdk_blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
4896 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
4897 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4898 		_blob->back_bs_dev = NULL;
4899 		_blob->parent_id = SPDK_BLOBID_INVALID;
4900 	} else {
4901 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
4902 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
4903 			/* We must change the parent of the inflated blob */
4904 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
4905 					  _spdk_bs_inflate_blob_set_parent_cpl, ctx);
4906 			return;
4907 		}
4908 
4909 		_spdk_bs_blob_list_remove(_blob);
4910 		_spdk_blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
4911 		_blob->parent_id = SPDK_BLOBID_INVALID;
4912 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
4913 		_blob->back_bs_dev = spdk_bs_create_zeroes_dev();
4914 	}
4915 
4916 	_blob->state = SPDK_BLOB_STATE_DIRTY;
4917 	spdk_blob_sync_md(_blob, _spdk_bs_clone_snapshot_origblob_cleanup, ctx);
4918 }
4919 
4920 /* Check if cluster needs allocation */
4921 static inline bool
4922 _spdk_bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
4923 {
4924 	struct spdk_blob_bs_dev *b;
4925 
4926 	assert(blob != NULL);
4927 
4928 	if (blob->active.clusters[cluster] != 0) {
4929 		/* Cluster is already allocated */
4930 		return false;
4931 	}
4932 
4933 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
4934 		/* Blob have no parent blob */
4935 		return allocate_all;
4936 	}
4937 
4938 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
4939 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
4940 }
4941 
4942 static void
4943 _spdk_bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
4944 {
4945 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4946 	struct spdk_blob *_blob = ctx->original.blob;
4947 	uint64_t offset;
4948 
4949 	if (bserrno != 0) {
4950 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
4951 		return;
4952 	}
4953 
4954 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
4955 		if (_spdk_bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
4956 			break;
4957 		}
4958 	}
4959 
4960 	if (ctx->cluster < _blob->active.num_clusters) {
4961 		offset = _spdk_bs_cluster_to_lba(_blob->bs, ctx->cluster);
4962 
4963 		/* We may safely increment a cluster before write */
4964 		ctx->cluster++;
4965 
4966 		/* Use zero length write to touch a cluster */
4967 		spdk_blob_io_write(_blob, ctx->channel, NULL, offset, 0,
4968 				   _spdk_bs_inflate_blob_touch_next, ctx);
4969 	} else {
4970 		_spdk_bs_inflate_blob_done(cb_arg, bserrno);
4971 	}
4972 }
4973 
4974 static void
4975 _spdk_bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
4976 {
4977 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
4978 	uint64_t lfc; /* lowest free cluster */
4979 	uint64_t i;
4980 
4981 	if (bserrno != 0) {
4982 		_spdk_bs_clone_snapshot_cleanup_finish(ctx, bserrno);
4983 		return;
4984 	}
4985 
4986 	ctx->original.blob = _blob;
4987 
4988 	if (_blob->locked_operation_in_progress) {
4989 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot inflate blob - another operation in progress\n");
4990 		ctx->bserrno = -EBUSY;
4991 		spdk_blob_close(_blob, _spdk_bs_clone_snapshot_cleanup_finish, ctx);
4992 		return;
4993 	}
4994 
4995 	_blob->locked_operation_in_progress = true;
4996 
4997 	if (!ctx->allocate_all && _blob->parent_id == SPDK_BLOBID_INVALID) {
4998 		/* This blob have no parent, so we cannot decouple it. */
4999 		SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
5000 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
5001 		return;
5002 	}
5003 
5004 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
5005 		/* This is not thin provisioned blob. No need to inflate. */
5006 		_spdk_bs_clone_snapshot_origblob_cleanup(ctx, 0);
5007 		return;
5008 	}
5009 
5010 	/* Do two passes - one to verify that we can obtain enough clusters
5011 	 * and another to actually claim them.
5012 	 */
5013 	lfc = 0;
5014 	for (i = 0; i < _blob->active.num_clusters; i++) {
5015 		if (_spdk_bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
5016 			lfc = spdk_bit_array_find_first_clear(_blob->bs->used_clusters, lfc);
5017 			if (lfc == UINT32_MAX) {
5018 				/* No more free clusters. Cannot satisfy the request */
5019 				_spdk_bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
5020 				return;
5021 			}
5022 			lfc++;
5023 		}
5024 	}
5025 
5026 	ctx->cluster = 0;
5027 	_spdk_bs_inflate_blob_touch_next(ctx, 0);
5028 }
5029 
5030 static void
5031 _spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5032 		      spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
5033 {
5034 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
5035 
5036 	if (!ctx) {
5037 		cb_fn(cb_arg, -ENOMEM);
5038 		return;
5039 	}
5040 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5041 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
5042 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
5043 	ctx->bserrno = 0;
5044 	ctx->original.id = blobid;
5045 	ctx->channel = channel;
5046 	ctx->allocate_all = allocate_all;
5047 
5048 	spdk_bs_open_blob(bs, ctx->original.id, _spdk_bs_inflate_blob_open_cpl, ctx);
5049 }
5050 
5051 void
5052 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5053 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
5054 {
5055 	_spdk_bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
5056 }
5057 
5058 void
5059 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
5060 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
5061 {
5062 	_spdk_bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
5063 }
5064 /* END spdk_bs_inflate_blob */
5065 
5066 /* START spdk_blob_resize */
5067 struct spdk_bs_resize_ctx {
5068 	spdk_blob_op_complete cb_fn;
5069 	void *cb_arg;
5070 	struct spdk_blob *blob;
5071 	uint64_t sz;
5072 	int rc;
5073 };
5074 
5075 static void
5076 _spdk_bs_resize_unfreeze_cpl(void *cb_arg, int rc)
5077 {
5078 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
5079 
5080 	if (rc != 0) {
5081 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
5082 	}
5083 
5084 	if (ctx->rc != 0) {
5085 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
5086 		rc = ctx->rc;
5087 	}
5088 
5089 	ctx->blob->locked_operation_in_progress = false;
5090 
5091 	ctx->cb_fn(ctx->cb_arg, rc);
5092 	free(ctx);
5093 }
5094 
5095 static void
5096 _spdk_bs_resize_freeze_cpl(void *cb_arg, int rc)
5097 {
5098 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
5099 
5100 	if (rc != 0) {
5101 		ctx->blob->locked_operation_in_progress = false;
5102 		ctx->cb_fn(ctx->cb_arg, rc);
5103 		free(ctx);
5104 		return;
5105 	}
5106 
5107 	ctx->rc = _spdk_blob_resize(ctx->blob, ctx->sz);
5108 
5109 	_spdk_blob_unfreeze_io(ctx->blob, _spdk_bs_resize_unfreeze_cpl, ctx);
5110 }
5111 
5112 void
5113 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
5114 {
5115 	struct spdk_bs_resize_ctx *ctx;
5116 
5117 	_spdk_blob_verify_md_op(blob);
5118 
5119 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Resizing blob %lu to %lu clusters\n", blob->id, sz);
5120 
5121 	if (blob->md_ro) {
5122 		cb_fn(cb_arg, -EPERM);
5123 		return;
5124 	}
5125 
5126 	if (sz == blob->active.num_clusters) {
5127 		cb_fn(cb_arg, 0);
5128 		return;
5129 	}
5130 
5131 	if (blob->locked_operation_in_progress) {
5132 		cb_fn(cb_arg, -EBUSY);
5133 		return;
5134 	}
5135 
5136 	ctx = calloc(1, sizeof(*ctx));
5137 	if (!ctx) {
5138 		cb_fn(cb_arg, -ENOMEM);
5139 		return;
5140 	}
5141 
5142 	blob->locked_operation_in_progress = true;
5143 	ctx->cb_fn = cb_fn;
5144 	ctx->cb_arg = cb_arg;
5145 	ctx->blob = blob;
5146 	ctx->sz = sz;
5147 	_spdk_blob_freeze_io(blob, _spdk_bs_resize_freeze_cpl, ctx);
5148 }
5149 
5150 /* END spdk_blob_resize */
5151 
5152 
5153 /* START spdk_bs_delete_blob */
5154 
5155 static void
5156 _spdk_bs_delete_close_cpl(void *cb_arg, int bserrno)
5157 {
5158 	spdk_bs_sequence_t *seq = cb_arg;
5159 
5160 	spdk_bs_sequence_finish(seq, bserrno);
5161 }
5162 
5163 static void
5164 _spdk_bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5165 {
5166 	struct spdk_blob *blob = cb_arg;
5167 
5168 	if (bserrno != 0) {
5169 		/*
5170 		 * We already removed this blob from the blobstore tailq, so
5171 		 *  we need to free it here since this is the last reference
5172 		 *  to it.
5173 		 */
5174 		_spdk_blob_free(blob);
5175 		_spdk_bs_delete_close_cpl(seq, bserrno);
5176 		return;
5177 	}
5178 
5179 	/*
5180 	 * This will immediately decrement the ref_count and call
5181 	 *  the completion routine since the metadata state is clean.
5182 	 *  By calling spdk_blob_close, we reduce the number of call
5183 	 *  points into code that touches the blob->open_ref count
5184 	 *  and the blobstore's blob list.
5185 	 */
5186 	spdk_blob_close(blob, _spdk_bs_delete_close_cpl, seq);
5187 }
5188 
5189 struct delete_snapshot_ctx {
5190 	struct spdk_blob_list *parent_snapshot_entry;
5191 	struct spdk_blob *snapshot;
5192 	bool snapshot_md_ro;
5193 	struct spdk_blob *clone;
5194 	bool clone_md_ro;
5195 	spdk_blob_op_with_handle_complete cb_fn;
5196 	void *cb_arg;
5197 	int bserrno;
5198 };
5199 
5200 static void
5201 _spdk_delete_blob_cleanup_finish(void *cb_arg, int bserrno)
5202 {
5203 	struct delete_snapshot_ctx *ctx = cb_arg;
5204 
5205 	if (bserrno != 0) {
5206 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
5207 	}
5208 
5209 	assert(ctx != NULL);
5210 
5211 	if (bserrno != 0 && ctx->bserrno == 0) {
5212 		ctx->bserrno = bserrno;
5213 	}
5214 
5215 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
5216 	free(ctx);
5217 }
5218 
5219 static void
5220 _spdk_delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
5221 {
5222 	struct delete_snapshot_ctx *ctx = cb_arg;
5223 
5224 	if (bserrno != 0) {
5225 		ctx->bserrno = bserrno;
5226 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
5227 	}
5228 
5229 	/* open_ref == 1 menas that only deletion context has opened this snapshot
5230 	 * open_ref == 2 menas that clone has opened this snapshot as well,
5231 	 * so we have to add it back to the blobs list */
5232 	if (ctx->snapshot->open_ref == 2) {
5233 		TAILQ_INSERT_HEAD(&ctx->snapshot->bs->blobs, ctx->snapshot, link);
5234 	}
5235 
5236 	ctx->snapshot->locked_operation_in_progress = false;
5237 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
5238 
5239 	spdk_blob_close(ctx->snapshot, _spdk_delete_blob_cleanup_finish, ctx);
5240 }
5241 
5242 static void
5243 _spdk_delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
5244 {
5245 	struct delete_snapshot_ctx *ctx = cb_arg;
5246 
5247 	ctx->clone->locked_operation_in_progress = false;
5248 	ctx->clone->md_ro = ctx->clone_md_ro;
5249 
5250 	spdk_blob_close(ctx->clone, _spdk_delete_snapshot_cleanup_snapshot, ctx);
5251 }
5252 
5253 static void
5254 _spdk_delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
5255 {
5256 	struct delete_snapshot_ctx *ctx = cb_arg;
5257 
5258 	if (bserrno) {
5259 		ctx->bserrno = bserrno;
5260 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5261 		return;
5262 	}
5263 
5264 	ctx->clone->locked_operation_in_progress = false;
5265 	spdk_blob_close(ctx->clone, _spdk_delete_blob_cleanup_finish, ctx);
5266 }
5267 
5268 static void
5269 _spdk_delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
5270 {
5271 	struct delete_snapshot_ctx *ctx = cb_arg;
5272 	struct spdk_blob_list *parent_snapshot_entry = NULL;
5273 	struct spdk_blob_list *snapshot_entry = NULL;
5274 	struct spdk_blob_list *clone_entry = NULL;
5275 	struct spdk_blob_list *snapshot_clone_entry = NULL;
5276 
5277 	if (bserrno) {
5278 		SPDK_ERRLOG("Failed to sync MD on blob\n");
5279 		ctx->bserrno = bserrno;
5280 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5281 		return;
5282 	}
5283 
5284 	/* Get snapshot entry for the snapshot we want to remove */
5285 	snapshot_entry = _spdk_bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
5286 
5287 	assert(snapshot_entry != NULL);
5288 
5289 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
5290 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5291 	assert(clone_entry != NULL);
5292 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
5293 	snapshot_entry->clone_count--;
5294 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
5295 
5296 	if (ctx->snapshot->parent_id != SPDK_BLOBID_INVALID) {
5297 		/* This snapshot is at the same time a clone of another snapshot - we need to
5298 		 * update parent snapshot (remove current clone, add new one inherited from
5299 		 * the snapshot that is being removed) */
5300 
5301 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
5302 		 * snapshot that we are removing */
5303 		_spdk_blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
5304 				&snapshot_clone_entry);
5305 
5306 		/* Switch clone entry in parent snapshot */
5307 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
5308 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
5309 		free(snapshot_clone_entry);
5310 	} else {
5311 		/* No parent snapshot - just remove clone entry */
5312 		free(clone_entry);
5313 	}
5314 
5315 	/* Restore md_ro flags */
5316 	ctx->clone->md_ro = ctx->clone_md_ro;
5317 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
5318 
5319 	_spdk_blob_unfreeze_io(ctx->clone, _spdk_delete_snapshot_unfreeze_cpl, ctx);
5320 }
5321 
5322 static void
5323 _spdk_delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
5324 {
5325 	struct delete_snapshot_ctx *ctx = cb_arg;
5326 	uint64_t i;
5327 
5328 	ctx->snapshot->md_ro = false;
5329 
5330 	if (bserrno) {
5331 		SPDK_ERRLOG("Failed to sync MD on clone\n");
5332 		ctx->bserrno = bserrno;
5333 
5334 		/* Restore snapshot to previous state */
5335 		bserrno = _spdk_blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
5336 		if (bserrno != 0) {
5337 			_spdk_delete_snapshot_cleanup_clone(ctx, bserrno);
5338 			return;
5339 		}
5340 
5341 		spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_cleanup_clone, ctx);
5342 		return;
5343 	}
5344 
5345 	/* Clear cluster map entries for snapshot */
5346 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
5347 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
5348 			ctx->snapshot->active.clusters[i] = 0;
5349 		}
5350 	}
5351 
5352 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
5353 
5354 	if (ctx->parent_snapshot_entry != NULL) {
5355 		ctx->snapshot->back_bs_dev = NULL;
5356 	}
5357 
5358 	spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_sync_snapshot_cpl, ctx);
5359 }
5360 
5361 static void
5362 _spdk_delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
5363 {
5364 	struct delete_snapshot_ctx *ctx = cb_arg;
5365 	uint64_t i;
5366 
5367 	/* Temporarily override md_ro flag for clone for MD modification */
5368 	ctx->clone_md_ro = ctx->clone->md_ro;
5369 	ctx->clone->md_ro = false;
5370 
5371 	if (bserrno) {
5372 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
5373 		ctx->bserrno = bserrno;
5374 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5375 		return;
5376 	}
5377 
5378 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
5379 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
5380 		if (ctx->clone->active.clusters[i] == 0) {
5381 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
5382 		}
5383 	}
5384 
5385 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
5386 	ctx->clone->back_bs_dev->destroy(ctx->clone->back_bs_dev);
5387 
5388 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
5389 	if (ctx->parent_snapshot_entry != NULL) {
5390 		/* ...to parent snapshot */
5391 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
5392 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
5393 		_spdk_blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
5394 				     sizeof(spdk_blob_id),
5395 				     true);
5396 	} else {
5397 		/* ...to blobid invalid and zeroes dev */
5398 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
5399 		ctx->clone->back_bs_dev = spdk_bs_create_zeroes_dev();
5400 		_spdk_blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
5401 	}
5402 
5403 	spdk_blob_sync_md(ctx->clone, _spdk_delete_snapshot_sync_clone_cpl, ctx);
5404 }
5405 
5406 static void
5407 _spdk_delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
5408 {
5409 	struct delete_snapshot_ctx *ctx = cb_arg;
5410 
5411 	if (bserrno) {
5412 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
5413 		ctx->bserrno = bserrno;
5414 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5415 		return;
5416 	}
5417 
5418 	/* Temporarily override md_ro flag for snapshot for MD modification */
5419 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
5420 	ctx->snapshot->md_ro = false;
5421 
5422 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
5423 	ctx->bserrno = _spdk_blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
5424 					    sizeof(spdk_blob_id), true);
5425 	if (ctx->bserrno != 0) {
5426 		_spdk_delete_snapshot_cleanup_clone(ctx, 0);
5427 		return;
5428 	}
5429 
5430 	spdk_blob_sync_md(ctx->snapshot, _spdk_delete_snapshot_sync_snapshot_xattr_cpl, ctx);
5431 }
5432 
5433 static void
5434 _spdk_delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
5435 {
5436 	struct delete_snapshot_ctx *ctx = cb_arg;
5437 
5438 	if (bserrno) {
5439 		SPDK_ERRLOG("Failed to open clone\n");
5440 		ctx->bserrno = bserrno;
5441 		_spdk_delete_snapshot_cleanup_snapshot(ctx, 0);
5442 		return;
5443 	}
5444 
5445 	ctx->clone = clone;
5446 
5447 	if (clone->locked_operation_in_progress) {
5448 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress on its clone\n");
5449 		ctx->bserrno = -EBUSY;
5450 		spdk_blob_close(ctx->clone, _spdk_delete_snapshot_cleanup_snapshot, ctx);
5451 		return;
5452 	}
5453 
5454 	clone->locked_operation_in_progress = true;
5455 
5456 	_spdk_blob_freeze_io(clone, _spdk_delete_snapshot_freeze_io_cb, ctx);
5457 }
5458 
5459 static void
5460 _spdk_update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
5461 {
5462 	struct spdk_blob_list *snapshot_entry = NULL;
5463 	struct spdk_blob_list *clone_entry = NULL;
5464 	struct spdk_blob_list *snapshot_clone_entry = NULL;
5465 
5466 	/* Get snapshot entry for the snapshot we want to remove */
5467 	snapshot_entry = _spdk_bs_get_snapshot_entry(snapshot->bs, snapshot->id);
5468 
5469 	assert(snapshot_entry != NULL);
5470 
5471 	/* Get clone of the snapshot (at this point there can be only one clone) */
5472 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5473 	assert(snapshot_entry->clone_count == 1);
5474 	assert(clone_entry != NULL);
5475 
5476 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
5477 	 * snapshot that we are removing */
5478 	_spdk_blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
5479 			&snapshot_clone_entry);
5480 
5481 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, _spdk_delete_snapshot_open_clone_cb, ctx);
5482 }
5483 
5484 static void
5485 _spdk_bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
5486 {
5487 	spdk_bs_sequence_t *seq = cb_arg;
5488 	struct spdk_blob_list *snapshot_entry = NULL;
5489 	uint32_t page_num;
5490 
5491 	if (bserrno) {
5492 		SPDK_ERRLOG("Failed to remove blob\n");
5493 		spdk_bs_sequence_finish(seq, bserrno);
5494 		return;
5495 	}
5496 
5497 	/* Remove snapshot from the list */
5498 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
5499 	if (snapshot_entry != NULL) {
5500 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
5501 		free(snapshot_entry);
5502 	}
5503 
5504 	page_num = _spdk_bs_blobid_to_page(blob->id);
5505 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
5506 	blob->state = SPDK_BLOB_STATE_DIRTY;
5507 	blob->active.num_pages = 0;
5508 	_spdk_blob_resize(blob, 0);
5509 
5510 	_spdk_blob_persist(seq, blob, _spdk_bs_delete_persist_cpl, blob);
5511 }
5512 
5513 static int
5514 _spdk_bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
5515 {
5516 	struct spdk_blob_list *snapshot_entry = NULL;
5517 	struct spdk_blob_list *clone_entry = NULL;
5518 	struct spdk_blob *clone = NULL;
5519 	bool has_one_clone = false;
5520 
5521 	/* Check if this is a snapshot with clones */
5522 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
5523 	if (snapshot_entry != NULL) {
5524 		if (snapshot_entry->clone_count > 1) {
5525 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
5526 			return -EBUSY;
5527 		} else if (snapshot_entry->clone_count == 1) {
5528 			has_one_clone = true;
5529 		}
5530 	}
5531 
5532 	/* Check if someone has this blob open (besides this delete context):
5533 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
5534 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
5535 	 *	and that is ok, because we will update it accordingly */
5536 	if (blob->open_ref <= 2 && has_one_clone) {
5537 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
5538 		assert(clone_entry != NULL);
5539 		clone = _spdk_blob_lookup(blob->bs, clone_entry->id);
5540 
5541 		if (blob->open_ref == 2 && clone == NULL) {
5542 			/* Clone is closed and someone else opened this blob */
5543 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
5544 			return -EBUSY;
5545 		}
5546 
5547 		*update_clone = true;
5548 		return 0;
5549 	}
5550 
5551 	if (blob->open_ref > 1) {
5552 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
5553 		return -EBUSY;
5554 	}
5555 
5556 	assert(has_one_clone == false);
5557 	*update_clone = false;
5558 	return 0;
5559 }
5560 
5561 static void
5562 _spdk_bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
5563 {
5564 	spdk_bs_sequence_t *seq = cb_arg;
5565 
5566 	spdk_bs_sequence_finish(seq, -ENOMEM);
5567 }
5568 
5569 static void
5570 _spdk_bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
5571 {
5572 	spdk_bs_sequence_t *seq = cb_arg;
5573 	struct delete_snapshot_ctx *ctx;
5574 	bool update_clone = false;
5575 
5576 	if (bserrno != 0) {
5577 		spdk_bs_sequence_finish(seq, bserrno);
5578 		return;
5579 	}
5580 
5581 	_spdk_blob_verify_md_op(blob);
5582 
5583 	ctx = calloc(1, sizeof(*ctx));
5584 	if (ctx == NULL) {
5585 		spdk_blob_close(blob, _spdk_bs_delete_enomem_close_cpl, seq);
5586 		return;
5587 	}
5588 
5589 	ctx->snapshot = blob;
5590 	ctx->cb_fn = _spdk_bs_delete_blob_finish;
5591 	ctx->cb_arg = seq;
5592 
5593 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
5594 	ctx->bserrno = _spdk_bs_is_blob_deletable(blob, &update_clone);
5595 	if (ctx->bserrno) {
5596 		spdk_blob_close(blob, _spdk_delete_blob_cleanup_finish, ctx);
5597 		return;
5598 	}
5599 
5600 	if (blob->locked_operation_in_progress) {
5601 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress\n");
5602 		ctx->bserrno = -EBUSY;
5603 		spdk_blob_close(blob, _spdk_delete_blob_cleanup_finish, ctx);
5604 		return;
5605 	}
5606 
5607 	blob->locked_operation_in_progress = true;
5608 
5609 	/*
5610 	 * Remove the blob from the blob_store list now, to ensure it does not
5611 	 *  get returned after this point by _spdk_blob_lookup().
5612 	 */
5613 	TAILQ_REMOVE(&blob->bs->blobs, blob, link);
5614 
5615 	if (update_clone) {
5616 		/* This blob is a snapshot with active clone - update clone first */
5617 		_spdk_update_clone_on_snapshot_deletion(blob, ctx);
5618 	} else {
5619 		/* This blob does not have any clones - just remove it */
5620 		_spdk_bs_blob_list_remove(blob);
5621 		_spdk_bs_delete_blob_finish(seq, blob, 0);
5622 		free(ctx);
5623 	}
5624 }
5625 
5626 void
5627 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5628 		    spdk_blob_op_complete cb_fn, void *cb_arg)
5629 {
5630 	struct spdk_bs_cpl	cpl;
5631 	spdk_bs_sequence_t	*seq;
5632 
5633 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Deleting blob %lu\n", blobid);
5634 
5635 	assert(spdk_get_thread() == bs->md_thread);
5636 
5637 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5638 	cpl.u.blob_basic.cb_fn = cb_fn;
5639 	cpl.u.blob_basic.cb_arg = cb_arg;
5640 
5641 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
5642 	if (!seq) {
5643 		cb_fn(cb_arg, -ENOMEM);
5644 		return;
5645 	}
5646 
5647 	spdk_bs_open_blob(bs, blobid, _spdk_bs_delete_open_cpl, seq);
5648 }
5649 
5650 /* END spdk_bs_delete_blob */
5651 
5652 /* START spdk_bs_open_blob */
5653 
5654 static void
5655 _spdk_bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5656 {
5657 	struct spdk_blob *blob = cb_arg;
5658 
5659 	/* If the blob have crc error, we just return NULL. */
5660 	if (blob == NULL) {
5661 		seq->cpl.u.blob_handle.blob = NULL;
5662 		spdk_bs_sequence_finish(seq, bserrno);
5663 		return;
5664 	}
5665 
5666 	blob->open_ref++;
5667 
5668 	TAILQ_INSERT_HEAD(&blob->bs->blobs, blob, link);
5669 
5670 	spdk_bs_sequence_finish(seq, bserrno);
5671 }
5672 
5673 static void _spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5674 			       struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5675 {
5676 	struct spdk_blob		*blob;
5677 	struct spdk_bs_cpl		cpl;
5678 	struct spdk_blob_open_opts	opts_default;
5679 	spdk_bs_sequence_t		*seq;
5680 	uint32_t			page_num;
5681 
5682 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Opening blob %lu\n", blobid);
5683 	assert(spdk_get_thread() == bs->md_thread);
5684 
5685 	page_num = _spdk_bs_blobid_to_page(blobid);
5686 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
5687 		/* Invalid blobid */
5688 		cb_fn(cb_arg, NULL, -ENOENT);
5689 		return;
5690 	}
5691 
5692 	blob = _spdk_blob_lookup(bs, blobid);
5693 	if (blob) {
5694 		blob->open_ref++;
5695 		cb_fn(cb_arg, blob, 0);
5696 		return;
5697 	}
5698 
5699 	blob = _spdk_blob_alloc(bs, blobid);
5700 	if (!blob) {
5701 		cb_fn(cb_arg, NULL, -ENOMEM);
5702 		return;
5703 	}
5704 
5705 	if (!opts) {
5706 		spdk_blob_open_opts_init(&opts_default);
5707 		opts = &opts_default;
5708 	}
5709 
5710 	blob->clear_method = opts->clear_method;
5711 
5712 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
5713 	cpl.u.blob_handle.cb_fn = cb_fn;
5714 	cpl.u.blob_handle.cb_arg = cb_arg;
5715 	cpl.u.blob_handle.blob = blob;
5716 
5717 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
5718 	if (!seq) {
5719 		_spdk_blob_free(blob);
5720 		cb_fn(cb_arg, NULL, -ENOMEM);
5721 		return;
5722 	}
5723 
5724 	_spdk_blob_load(seq, blob, _spdk_bs_open_blob_cpl, blob);
5725 }
5726 
5727 void spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
5728 		       spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5729 {
5730 	_spdk_bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
5731 }
5732 
5733 void spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
5734 			   struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
5735 {
5736 	_spdk_bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
5737 }
5738 
5739 /* END spdk_bs_open_blob */
5740 
5741 /* START spdk_blob_set_read_only */
5742 int spdk_blob_set_read_only(struct spdk_blob *blob)
5743 {
5744 	_spdk_blob_verify_md_op(blob);
5745 
5746 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
5747 
5748 	blob->state = SPDK_BLOB_STATE_DIRTY;
5749 	return 0;
5750 }
5751 /* END spdk_blob_set_read_only */
5752 
5753 /* START spdk_blob_sync_md */
5754 
5755 static void
5756 _spdk_blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5757 {
5758 	struct spdk_blob *blob = cb_arg;
5759 
5760 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
5761 		blob->data_ro = true;
5762 		blob->md_ro = true;
5763 	}
5764 
5765 	spdk_bs_sequence_finish(seq, bserrno);
5766 }
5767 
5768 static void
5769 _spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5770 {
5771 	struct spdk_bs_cpl	cpl;
5772 	spdk_bs_sequence_t	*seq;
5773 
5774 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5775 	cpl.u.blob_basic.cb_fn = cb_fn;
5776 	cpl.u.blob_basic.cb_arg = cb_arg;
5777 
5778 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
5779 	if (!seq) {
5780 		cb_fn(cb_arg, -ENOMEM);
5781 		return;
5782 	}
5783 
5784 	_spdk_blob_persist(seq, blob, _spdk_blob_sync_md_cpl, blob);
5785 }
5786 
5787 void
5788 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5789 {
5790 	_spdk_blob_verify_md_op(blob);
5791 
5792 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blob %lu\n", blob->id);
5793 
5794 	if (blob->md_ro) {
5795 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
5796 		cb_fn(cb_arg, 0);
5797 		return;
5798 	}
5799 
5800 	_spdk_blob_sync_md(blob, cb_fn, cb_arg);
5801 }
5802 
5803 /* END spdk_blob_sync_md */
5804 
5805 struct spdk_blob_insert_cluster_ctx {
5806 	struct spdk_thread	*thread;
5807 	struct spdk_blob	*blob;
5808 	uint32_t		cluster_num;	/* cluster index in blob */
5809 	uint32_t		cluster;	/* cluster on disk */
5810 	int			rc;
5811 	spdk_blob_op_complete	cb_fn;
5812 	void			*cb_arg;
5813 };
5814 
5815 static void
5816 _spdk_blob_insert_cluster_msg_cpl(void *arg)
5817 {
5818 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5819 
5820 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
5821 	free(ctx);
5822 }
5823 
5824 static void
5825 _spdk_blob_insert_cluster_msg_cb(void *arg, int bserrno)
5826 {
5827 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5828 
5829 	ctx->rc = bserrno;
5830 	spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
5831 }
5832 
5833 static void
5834 _spdk_blob_insert_cluster_msg(void *arg)
5835 {
5836 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
5837 
5838 	ctx->rc = _spdk_blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
5839 	if (ctx->rc != 0) {
5840 		spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
5841 		return;
5842 	}
5843 
5844 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
5845 	_spdk_blob_sync_md(ctx->blob, _spdk_blob_insert_cluster_msg_cb, ctx);
5846 }
5847 
5848 static void
5849 _spdk_blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
5850 				       uint64_t cluster, spdk_blob_op_complete cb_fn, void *cb_arg)
5851 {
5852 	struct spdk_blob_insert_cluster_ctx *ctx;
5853 
5854 	ctx = calloc(1, sizeof(*ctx));
5855 	if (ctx == NULL) {
5856 		cb_fn(cb_arg, -ENOMEM);
5857 		return;
5858 	}
5859 
5860 	ctx->thread = spdk_get_thread();
5861 	ctx->blob = blob;
5862 	ctx->cluster_num = cluster_num;
5863 	ctx->cluster = cluster;
5864 	ctx->cb_fn = cb_fn;
5865 	ctx->cb_arg = cb_arg;
5866 
5867 	spdk_thread_send_msg(blob->bs->md_thread, _spdk_blob_insert_cluster_msg, ctx);
5868 }
5869 
5870 /* START spdk_blob_close */
5871 
5872 static void
5873 _spdk_blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5874 {
5875 	struct spdk_blob *blob = cb_arg;
5876 
5877 	if (bserrno == 0) {
5878 		blob->open_ref--;
5879 		if (blob->open_ref == 0) {
5880 			/*
5881 			 * Blobs with active.num_pages == 0 are deleted blobs.
5882 			 *  these blobs are removed from the blob_store list
5883 			 *  when the deletion process starts - so don't try to
5884 			 *  remove them again.
5885 			 */
5886 			if (blob->active.num_pages > 0) {
5887 				TAILQ_REMOVE(&blob->bs->blobs, blob, link);
5888 			}
5889 			_spdk_blob_free(blob);
5890 		}
5891 	}
5892 
5893 	spdk_bs_sequence_finish(seq, bserrno);
5894 }
5895 
5896 void spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
5897 {
5898 	struct spdk_bs_cpl	cpl;
5899 	spdk_bs_sequence_t	*seq;
5900 
5901 	_spdk_blob_verify_md_op(blob);
5902 
5903 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Closing blob %lu\n", blob->id);
5904 
5905 	if (blob->open_ref == 0) {
5906 		cb_fn(cb_arg, -EBADF);
5907 		return;
5908 	}
5909 
5910 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
5911 	cpl.u.blob_basic.cb_fn = cb_fn;
5912 	cpl.u.blob_basic.cb_arg = cb_arg;
5913 
5914 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
5915 	if (!seq) {
5916 		cb_fn(cb_arg, -ENOMEM);
5917 		return;
5918 	}
5919 
5920 	/* Sync metadata */
5921 	_spdk_blob_persist(seq, blob, _spdk_blob_close_cpl, blob);
5922 }
5923 
5924 /* END spdk_blob_close */
5925 
5926 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
5927 {
5928 	return spdk_get_io_channel(bs);
5929 }
5930 
5931 void spdk_bs_free_io_channel(struct spdk_io_channel *channel)
5932 {
5933 	spdk_put_io_channel(channel);
5934 }
5935 
5936 void spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
5937 			uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
5938 {
5939 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
5940 				     SPDK_BLOB_UNMAP);
5941 }
5942 
5943 void spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
5944 			       uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
5945 {
5946 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
5947 				     SPDK_BLOB_WRITE_ZEROES);
5948 }
5949 
5950 void spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
5951 			void *payload, uint64_t offset, uint64_t length,
5952 			spdk_blob_op_complete cb_fn, void *cb_arg)
5953 {
5954 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
5955 				     SPDK_BLOB_WRITE);
5956 }
5957 
5958 void spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
5959 		       void *payload, uint64_t offset, uint64_t length,
5960 		       spdk_blob_op_complete cb_fn, void *cb_arg)
5961 {
5962 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
5963 				     SPDK_BLOB_READ);
5964 }
5965 
5966 void spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
5967 			 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
5968 			 spdk_blob_op_complete cb_fn, void *cb_arg)
5969 {
5970 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false);
5971 }
5972 
5973 void spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
5974 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
5975 			spdk_blob_op_complete cb_fn, void *cb_arg)
5976 {
5977 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true);
5978 }
5979 
5980 struct spdk_bs_iter_ctx {
5981 	int64_t page_num;
5982 	struct spdk_blob_store *bs;
5983 
5984 	spdk_blob_op_with_handle_complete cb_fn;
5985 	void *cb_arg;
5986 };
5987 
5988 static void
5989 _spdk_bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5990 {
5991 	struct spdk_bs_iter_ctx *ctx = cb_arg;
5992 	struct spdk_blob_store *bs = ctx->bs;
5993 	spdk_blob_id id;
5994 
5995 	if (bserrno == 0) {
5996 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
5997 		free(ctx);
5998 		return;
5999 	}
6000 
6001 	ctx->page_num++;
6002 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
6003 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
6004 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
6005 		free(ctx);
6006 		return;
6007 	}
6008 
6009 	id = _spdk_bs_page_to_blobid(ctx->page_num);
6010 
6011 	spdk_bs_open_blob(bs, id, _spdk_bs_iter_cpl, ctx);
6012 }
6013 
6014 void
6015 spdk_bs_iter_first(struct spdk_blob_store *bs,
6016 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6017 {
6018 	struct spdk_bs_iter_ctx *ctx;
6019 
6020 	ctx = calloc(1, sizeof(*ctx));
6021 	if (!ctx) {
6022 		cb_fn(cb_arg, NULL, -ENOMEM);
6023 		return;
6024 	}
6025 
6026 	ctx->page_num = -1;
6027 	ctx->bs = bs;
6028 	ctx->cb_fn = cb_fn;
6029 	ctx->cb_arg = cb_arg;
6030 
6031 	_spdk_bs_iter_cpl(ctx, NULL, -1);
6032 }
6033 
6034 static void
6035 _spdk_bs_iter_close_cpl(void *cb_arg, int bserrno)
6036 {
6037 	struct spdk_bs_iter_ctx *ctx = cb_arg;
6038 
6039 	_spdk_bs_iter_cpl(ctx, NULL, -1);
6040 }
6041 
6042 void
6043 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
6044 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6045 {
6046 	struct spdk_bs_iter_ctx *ctx;
6047 
6048 	assert(blob != NULL);
6049 
6050 	ctx = calloc(1, sizeof(*ctx));
6051 	if (!ctx) {
6052 		cb_fn(cb_arg, NULL, -ENOMEM);
6053 		return;
6054 	}
6055 
6056 	ctx->page_num = _spdk_bs_blobid_to_page(blob->id);
6057 	ctx->bs = bs;
6058 	ctx->cb_fn = cb_fn;
6059 	ctx->cb_arg = cb_arg;
6060 
6061 	/* Close the existing blob */
6062 	spdk_blob_close(blob, _spdk_bs_iter_close_cpl, ctx);
6063 }
6064 
6065 static int
6066 _spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
6067 		     uint16_t value_len, bool internal)
6068 {
6069 	struct spdk_xattr_tailq *xattrs;
6070 	struct spdk_xattr	*xattr;
6071 	size_t			desc_size;
6072 
6073 	_spdk_blob_verify_md_op(blob);
6074 
6075 	if (blob->md_ro) {
6076 		return -EPERM;
6077 	}
6078 
6079 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
6080 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
6081 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Xattr '%s' of size %ld does not fix into single page %ld\n", name,
6082 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
6083 		return -ENOMEM;
6084 	}
6085 
6086 	if (internal) {
6087 		xattrs = &blob->xattrs_internal;
6088 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
6089 	} else {
6090 		xattrs = &blob->xattrs;
6091 	}
6092 
6093 	TAILQ_FOREACH(xattr, xattrs, link) {
6094 		if (!strcmp(name, xattr->name)) {
6095 			free(xattr->value);
6096 			xattr->value_len = value_len;
6097 			xattr->value = malloc(value_len);
6098 			memcpy(xattr->value, value, value_len);
6099 
6100 			blob->state = SPDK_BLOB_STATE_DIRTY;
6101 
6102 			return 0;
6103 		}
6104 	}
6105 
6106 	xattr = calloc(1, sizeof(*xattr));
6107 	if (!xattr) {
6108 		return -ENOMEM;
6109 	}
6110 	xattr->name = strdup(name);
6111 	xattr->value_len = value_len;
6112 	xattr->value = malloc(value_len);
6113 	memcpy(xattr->value, value, value_len);
6114 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
6115 
6116 	blob->state = SPDK_BLOB_STATE_DIRTY;
6117 
6118 	return 0;
6119 }
6120 
6121 int
6122 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
6123 		    uint16_t value_len)
6124 {
6125 	return _spdk_blob_set_xattr(blob, name, value, value_len, false);
6126 }
6127 
6128 static int
6129 _spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
6130 {
6131 	struct spdk_xattr_tailq *xattrs;
6132 	struct spdk_xattr	*xattr;
6133 
6134 	_spdk_blob_verify_md_op(blob);
6135 
6136 	if (blob->md_ro) {
6137 		return -EPERM;
6138 	}
6139 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
6140 
6141 	TAILQ_FOREACH(xattr, xattrs, link) {
6142 		if (!strcmp(name, xattr->name)) {
6143 			TAILQ_REMOVE(xattrs, xattr, link);
6144 			free(xattr->value);
6145 			free(xattr->name);
6146 			free(xattr);
6147 
6148 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
6149 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
6150 			}
6151 			blob->state = SPDK_BLOB_STATE_DIRTY;
6152 
6153 			return 0;
6154 		}
6155 	}
6156 
6157 	return -ENOENT;
6158 }
6159 
6160 int
6161 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
6162 {
6163 	return _spdk_blob_remove_xattr(blob, name, false);
6164 }
6165 
6166 static int
6167 _spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
6168 			   const void **value, size_t *value_len, bool internal)
6169 {
6170 	struct spdk_xattr	*xattr;
6171 	struct spdk_xattr_tailq *xattrs;
6172 
6173 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
6174 
6175 	TAILQ_FOREACH(xattr, xattrs, link) {
6176 		if (!strcmp(name, xattr->name)) {
6177 			*value = xattr->value;
6178 			*value_len = xattr->value_len;
6179 			return 0;
6180 		}
6181 	}
6182 	return -ENOENT;
6183 }
6184 
6185 int
6186 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
6187 			  const void **value, size_t *value_len)
6188 {
6189 	_spdk_blob_verify_md_op(blob);
6190 
6191 	return _spdk_blob_get_xattr_value(blob, name, value, value_len, false);
6192 }
6193 
6194 struct spdk_xattr_names {
6195 	uint32_t	count;
6196 	const char	*names[0];
6197 };
6198 
6199 static int
6200 _spdk_blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
6201 {
6202 	struct spdk_xattr	*xattr;
6203 	int			count = 0;
6204 
6205 	TAILQ_FOREACH(xattr, xattrs, link) {
6206 		count++;
6207 	}
6208 
6209 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
6210 	if (*names == NULL) {
6211 		return -ENOMEM;
6212 	}
6213 
6214 	TAILQ_FOREACH(xattr, xattrs, link) {
6215 		(*names)->names[(*names)->count++] = xattr->name;
6216 	}
6217 
6218 	return 0;
6219 }
6220 
6221 int
6222 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
6223 {
6224 	_spdk_blob_verify_md_op(blob);
6225 
6226 	return _spdk_blob_get_xattr_names(&blob->xattrs, names);
6227 }
6228 
6229 uint32_t
6230 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
6231 {
6232 	assert(names != NULL);
6233 
6234 	return names->count;
6235 }
6236 
6237 const char *
6238 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
6239 {
6240 	if (index >= names->count) {
6241 		return NULL;
6242 	}
6243 
6244 	return names->names[index];
6245 }
6246 
6247 void
6248 spdk_xattr_names_free(struct spdk_xattr_names *names)
6249 {
6250 	free(names);
6251 }
6252 
6253 struct spdk_bs_type
6254 spdk_bs_get_bstype(struct spdk_blob_store *bs)
6255 {
6256 	return bs->bstype;
6257 }
6258 
6259 void
6260 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
6261 {
6262 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
6263 }
6264 
6265 bool
6266 spdk_blob_is_read_only(struct spdk_blob *blob)
6267 {
6268 	assert(blob != NULL);
6269 	return (blob->data_ro || blob->md_ro);
6270 }
6271 
6272 bool
6273 spdk_blob_is_snapshot(struct spdk_blob *blob)
6274 {
6275 	struct spdk_blob_list *snapshot_entry;
6276 
6277 	assert(blob != NULL);
6278 
6279 	snapshot_entry = _spdk_bs_get_snapshot_entry(blob->bs, blob->id);
6280 	if (snapshot_entry == NULL) {
6281 		return false;
6282 	}
6283 
6284 	return true;
6285 }
6286 
6287 bool
6288 spdk_blob_is_clone(struct spdk_blob *blob)
6289 {
6290 	assert(blob != NULL);
6291 
6292 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
6293 		assert(spdk_blob_is_thin_provisioned(blob));
6294 		return true;
6295 	}
6296 
6297 	return false;
6298 }
6299 
6300 bool
6301 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
6302 {
6303 	assert(blob != NULL);
6304 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
6305 }
6306 
6307 spdk_blob_id
6308 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
6309 {
6310 	struct spdk_blob_list *snapshot_entry = NULL;
6311 	struct spdk_blob_list *clone_entry = NULL;
6312 
6313 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
6314 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
6315 			if (clone_entry->id == blob_id) {
6316 				return snapshot_entry->id;
6317 			}
6318 		}
6319 	}
6320 
6321 	return SPDK_BLOBID_INVALID;
6322 }
6323 
6324 int
6325 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
6326 		     size_t *count)
6327 {
6328 	struct spdk_blob_list *snapshot_entry, *clone_entry;
6329 	size_t n;
6330 
6331 	snapshot_entry = _spdk_bs_get_snapshot_entry(bs, blobid);
6332 	if (snapshot_entry == NULL) {
6333 		*count = 0;
6334 		return 0;
6335 	}
6336 
6337 	if (ids == NULL || *count < snapshot_entry->clone_count) {
6338 		*count = snapshot_entry->clone_count;
6339 		return -ENOMEM;
6340 	}
6341 	*count = snapshot_entry->clone_count;
6342 
6343 	n = 0;
6344 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
6345 		ids[n++] = clone_entry->id;
6346 	}
6347 
6348 	return 0;
6349 }
6350 
6351 SPDK_LOG_REGISTER_COMPONENT("blob", SPDK_LOG_BLOB)
6352