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