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