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