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