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