xref: /spdk/lib/blob/blobstore.c (revision 97cb1713ffd23594904e38b2636aa491b7d9ab51)
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_data *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_data *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_data *blob, const char *name,
59 				      const void **value, size_t *value_len, bool internal);
60 static int _spdk_blob_remove_xattr(struct spdk_blob_data *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_data *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_data *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_data *
147 _spdk_blob_alloc(struct spdk_blob_store *bs, spdk_blob_id id)
148 {
149 	struct spdk_blob_data *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_data *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_data *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_data *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_data *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_data *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_data *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_data *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_data *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_data *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_data *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_data 		*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_data 		*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_data *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_data 		*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_data 		*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_data 		*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_data 		*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_data 		*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_data 		*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_data		*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_data 		*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_data *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_data *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_data *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_data *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_data *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 	struct spdk_blob_data	*blob = __blob_to_data(_blob);
1481 	uint64_t		op_length;
1482 	uint8_t			*buf;
1483 
1484 	assert(blob != NULL);
1485 
1486 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1487 	cpl.u.blob_basic.cb_fn = cb_fn;
1488 	cpl.u.blob_basic.cb_arg = cb_arg;
1489 
1490 	batch = spdk_bs_batch_open(ch, &cpl);
1491 	if (!batch) {
1492 		cb_fn(cb_arg, -ENOMEM);
1493 		return;
1494 	}
1495 
1496 	buf = payload;
1497 	while (length > 0) {
1498 		op_length = spdk_min(length, _spdk_bs_num_pages_to_cluster_boundary(blob, offset));
1499 
1500 		switch (op_type) {
1501 		case SPDK_BLOB_READ:
1502 			spdk_bs_batch_read_blob(batch, _blob, buf, offset, op_length);
1503 			break;
1504 		case SPDK_BLOB_WRITE:
1505 			spdk_bs_batch_write_blob(batch, _blob, buf, offset, op_length);
1506 			break;
1507 		case SPDK_BLOB_UNMAP:
1508 			spdk_bs_batch_unmap_blob(batch, _blob, offset, op_length);
1509 			break;
1510 		case SPDK_BLOB_WRITE_ZEROES:
1511 			spdk_bs_batch_write_zeroes_blob(batch, _blob, offset, op_length);
1512 			break;
1513 		case SPDK_BLOB_READV:
1514 		case SPDK_BLOB_WRITEV:
1515 			SPDK_ERRLOG("readv/write not valid for %s\n", __func__);
1516 			break;
1517 		}
1518 
1519 		length -= op_length;
1520 		offset += op_length;
1521 		if (op_type == SPDK_BLOB_WRITE || op_type == SPDK_BLOB_READ) {
1522 			buf += op_length * SPDK_BS_PAGE_SIZE;
1523 		}
1524 	}
1525 
1526 	spdk_bs_batch_close(batch);
1527 }
1528 
1529 static void
1530 _spdk_blob_request_submit_op_single(struct spdk_io_channel *_ch, struct spdk_blob *_blob,
1531 				    void *payload, uint64_t offset, uint64_t length,
1532 				    spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1533 {
1534 	struct spdk_blob_data *blob = __blob_to_data(_blob);
1535 	struct spdk_bs_cpl cpl;
1536 	uint64_t lba;
1537 	uint32_t lba_count;
1538 
1539 	assert(blob != NULL);
1540 
1541 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1542 	cpl.u.blob_basic.cb_fn = cb_fn;
1543 	cpl.u.blob_basic.cb_arg = cb_arg;
1544 
1545 	_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
1546 
1547 	switch (op_type) {
1548 	case SPDK_BLOB_READ: {
1549 		spdk_bs_batch_t *batch;
1550 
1551 		batch = spdk_bs_batch_open(_ch, &cpl);
1552 		if (!batch) {
1553 			cb_fn(cb_arg, -ENOMEM);
1554 			return;
1555 		}
1556 
1557 		if (_spdk_bs_page_is_allocated(blob, offset)) {
1558 			/* Read from the blob */
1559 			spdk_bs_batch_read_dev(batch, payload, lba, lba_count);
1560 		} else {
1561 			/* Read from the backing block device */
1562 			spdk_bs_batch_read_bs_dev(batch, blob->back_bs_dev, payload, lba, lba_count);
1563 		}
1564 
1565 		spdk_bs_batch_close(batch);
1566 		break;
1567 	}
1568 	case SPDK_BLOB_WRITE:
1569 	case SPDK_BLOB_WRITE_ZEROES: {
1570 		if (_spdk_bs_page_is_allocated(blob, offset)) {
1571 			/* Write to the blob */
1572 			spdk_bs_batch_t *batch;
1573 
1574 			batch = spdk_bs_batch_open(_ch, &cpl);
1575 			if (!batch) {
1576 				cb_fn(cb_arg, -ENOMEM);
1577 				return;
1578 			}
1579 
1580 			if (op_type == SPDK_BLOB_WRITE) {
1581 				spdk_bs_batch_write_dev(batch, payload, lba, lba_count);
1582 			} else {
1583 				spdk_bs_batch_write_zeroes_dev(batch, lba, lba_count);
1584 			}
1585 
1586 			spdk_bs_batch_close(batch);
1587 		} else {
1588 			/* Queue this operation and allocate the cluster */
1589 			spdk_bs_user_op_t *op;
1590 
1591 			op = spdk_bs_user_op_alloc(_ch, &cpl, op_type, _blob, payload, 0, offset, length);
1592 			if (!op) {
1593 				cb_fn(cb_arg, -ENOMEM);
1594 				return;
1595 			}
1596 
1597 			_spdk_bs_allocate_and_copy_cluster(blob, _ch, offset, op);
1598 		}
1599 		break;
1600 	}
1601 	case SPDK_BLOB_UNMAP: {
1602 		spdk_bs_batch_t *batch;
1603 
1604 		batch = spdk_bs_batch_open(_ch, &cpl);
1605 		if (!batch) {
1606 			cb_fn(cb_arg, -ENOMEM);
1607 			return;
1608 		}
1609 
1610 		if (_spdk_bs_page_is_allocated(blob, offset)) {
1611 			spdk_bs_batch_unmap_dev(batch, lba, lba_count);
1612 		}
1613 
1614 		spdk_bs_batch_close(batch);
1615 		break;
1616 	}
1617 	case SPDK_BLOB_READV:
1618 	case SPDK_BLOB_WRITEV:
1619 		SPDK_ERRLOG("readv/write not valid\n");
1620 		cb_fn(cb_arg, -EINVAL);
1621 		break;
1622 	}
1623 }
1624 
1625 static void
1626 _spdk_blob_request_submit_op(struct spdk_blob *_blob, struct spdk_io_channel *_channel,
1627 			     void *payload, uint64_t offset, uint64_t length,
1628 			     spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
1629 {
1630 	struct spdk_blob_data		*blob = __blob_to_data(_blob);
1631 
1632 	assert(blob != NULL);
1633 
1634 	if (blob->data_ro && op_type != SPDK_BLOB_READ) {
1635 		cb_fn(cb_arg, -EPERM);
1636 		return;
1637 	}
1638 
1639 	if (offset + length > blob->active.num_clusters * blob->bs->pages_per_cluster) {
1640 		cb_fn(cb_arg, -EINVAL);
1641 		return;
1642 	}
1643 
1644 	if (length <= _spdk_bs_num_pages_to_cluster_boundary(blob, offset)) {
1645 		_spdk_blob_request_submit_op_single(_channel, _blob, payload, offset, length,
1646 						    cb_fn, cb_arg, op_type);
1647 	} else {
1648 		_spdk_blob_request_submit_op_split(_channel, _blob, payload, offset, length,
1649 						   cb_fn, cb_arg, op_type);
1650 	}
1651 }
1652 
1653 struct rw_iov_ctx {
1654 	struct spdk_blob *blob;
1655 	struct spdk_io_channel *channel;
1656 	spdk_blob_op_complete cb_fn;
1657 	void *cb_arg;
1658 	bool read;
1659 	int iovcnt;
1660 	struct iovec *orig_iov;
1661 	uint64_t page_offset;
1662 	uint64_t pages_remaining;
1663 	uint64_t pages_done;
1664 	struct iovec iov[0];
1665 };
1666 
1667 static void
1668 _spdk_rw_iov_done(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1669 {
1670 	assert(cb_arg == NULL);
1671 	spdk_bs_sequence_finish(seq, bserrno);
1672 }
1673 
1674 static void
1675 _spdk_rw_iov_split_next(void *cb_arg, int bserrno)
1676 {
1677 	struct rw_iov_ctx *ctx = cb_arg;
1678 	struct spdk_blob_data *blob = __blob_to_data(ctx->blob);
1679 	struct iovec *iov, *orig_iov;
1680 	int iovcnt;
1681 	size_t orig_iovoff;
1682 	uint64_t page_count, pages_to_boundary, page_offset;
1683 	uint64_t byte_count;
1684 
1685 	if (bserrno != 0 || ctx->pages_remaining == 0) {
1686 		ctx->cb_fn(ctx->cb_arg, bserrno);
1687 		free(ctx);
1688 		return;
1689 	}
1690 
1691 	page_offset = ctx->page_offset;
1692 	pages_to_boundary = _spdk_bs_num_pages_to_cluster_boundary(blob, page_offset);
1693 	page_count = spdk_min(ctx->pages_remaining, pages_to_boundary);
1694 
1695 	/*
1696 	 * Get index and offset into the original iov array for our current position in the I/O sequence.
1697 	 *  byte_count will keep track of how many bytes remaining until orig_iov and orig_iovoff will
1698 	 *  point to the current position in the I/O sequence.
1699 	 */
1700 	byte_count = ctx->pages_done * sizeof(struct spdk_blob_md_page);
1701 	orig_iov = &ctx->orig_iov[0];
1702 	orig_iovoff = 0;
1703 	while (byte_count > 0) {
1704 		if (byte_count >= orig_iov->iov_len) {
1705 			byte_count -= orig_iov->iov_len;
1706 			orig_iov++;
1707 		} else {
1708 			orig_iovoff = byte_count;
1709 			byte_count = 0;
1710 		}
1711 	}
1712 
1713 	/*
1714 	 * Build an iov array for the next I/O in the sequence.  byte_count will keep track of how many
1715 	 *  bytes of this next I/O remain to be accounted for in the new iov array.
1716 	 */
1717 	byte_count = page_count * sizeof(struct spdk_blob_md_page);
1718 	iov = &ctx->iov[0];
1719 	iovcnt = 0;
1720 	while (byte_count > 0) {
1721 		iov->iov_len = spdk_min(byte_count, orig_iov->iov_len - orig_iovoff);
1722 		iov->iov_base = orig_iov->iov_base + orig_iovoff;
1723 		byte_count -= iov->iov_len;
1724 		orig_iovoff = 0;
1725 		orig_iov++;
1726 		iov++;
1727 		iovcnt++;
1728 	}
1729 
1730 	ctx->page_offset += page_count;
1731 	ctx->pages_done += page_count;
1732 	ctx->pages_remaining -= page_count;
1733 	iov = &ctx->iov[0];
1734 
1735 	if (ctx->read) {
1736 		spdk_bs_io_readv_blob(ctx->blob, ctx->channel, iov, iovcnt, page_offset,
1737 				      page_count, _spdk_rw_iov_split_next, ctx);
1738 	} else {
1739 		spdk_bs_io_writev_blob(ctx->blob, ctx->channel, iov, iovcnt, page_offset,
1740 				       page_count, _spdk_rw_iov_split_next, ctx);
1741 	}
1742 }
1743 
1744 static void
1745 _spdk_blob_request_submit_rw_iov(struct spdk_blob *_blob, struct spdk_io_channel *_channel,
1746 				 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
1747 				 spdk_blob_op_complete cb_fn, void *cb_arg, bool read)
1748 {
1749 	struct spdk_blob_data	*blob = __blob_to_data(_blob);
1750 	struct spdk_bs_cpl	cpl;
1751 
1752 	assert(blob != NULL);
1753 
1754 	if (!read && blob->data_ro) {
1755 		cb_fn(cb_arg, -EPERM);
1756 		return;
1757 	}
1758 
1759 	if (length == 0) {
1760 		cb_fn(cb_arg, 0);
1761 		return;
1762 	}
1763 
1764 	if (offset + length > blob->active.num_clusters * blob->bs->pages_per_cluster) {
1765 		cb_fn(cb_arg, -EINVAL);
1766 		return;
1767 	}
1768 
1769 	/*
1770 	 * For now, we implement readv/writev using a sequence (instead of a batch) to account for having
1771 	 *  to split a request that spans a cluster boundary.  For I/O that do not span a cluster boundary,
1772 	 *  there will be no noticeable difference compared to using a batch.  For I/O that do span a cluster
1773 	 *  boundary, the target LBAs (after blob offset to LBA translation) may not be contiguous, so we need
1774 	 *  to allocate a separate iov array and split the I/O such that none of the resulting
1775 	 *  smaller I/O cross a cluster boundary.  These smaller I/O will be issued in sequence (not in parallel)
1776 	 *  but since this case happens very infrequently, any performance impact will be negligible.
1777 	 *
1778 	 * This could be optimized in the future to allocate a big enough iov array to account for all of the iovs
1779 	 *  for all of the smaller I/Os, pre-build all of the iov arrays for the smaller I/Os, then issue them
1780 	 *  in a batch.  That would also require creating an intermediate spdk_bs_cpl that would get called
1781 	 *  when the batch was completed, to allow for freeing the memory for the iov arrays.
1782 	 */
1783 	if (spdk_likely(length <= _spdk_bs_num_pages_to_cluster_boundary(blob, offset))) {
1784 		uint32_t lba_count;
1785 		uint64_t lba;
1786 
1787 		_spdk_blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
1788 
1789 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
1790 		cpl.u.blob_basic.cb_fn = cb_fn;
1791 		cpl.u.blob_basic.cb_arg = cb_arg;
1792 
1793 		if (read) {
1794 			spdk_bs_sequence_t *seq;
1795 
1796 			seq = spdk_bs_sequence_start(_channel, &cpl);
1797 			if (!seq) {
1798 				cb_fn(cb_arg, -ENOMEM);
1799 				return;
1800 			}
1801 
1802 			if (_spdk_bs_page_is_allocated(blob, offset)) {
1803 				spdk_bs_sequence_readv_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
1804 			} else {
1805 				spdk_bs_sequence_readv_bs_dev(seq, blob->back_bs_dev, iov, iovcnt, lba, lba_count,
1806 							      _spdk_rw_iov_done, NULL);
1807 			}
1808 		} else {
1809 			if (_spdk_bs_page_is_allocated(blob, offset)) {
1810 				spdk_bs_sequence_t *seq;
1811 
1812 				seq = spdk_bs_sequence_start(_channel, &cpl);
1813 				if (!seq) {
1814 					cb_fn(cb_arg, -ENOMEM);
1815 					return;
1816 				}
1817 
1818 				spdk_bs_sequence_writev_dev(seq, iov, iovcnt, lba, lba_count, _spdk_rw_iov_done, NULL);
1819 			} else {
1820 				/* Queue this operation and allocate the cluster */
1821 				spdk_bs_user_op_t *op;
1822 
1823 				op = spdk_bs_user_op_alloc(_channel, &cpl, SPDK_BLOB_WRITEV, _blob, iov, iovcnt, offset, length);
1824 				if (!op) {
1825 					cb_fn(cb_arg, -ENOMEM);
1826 					return;
1827 				}
1828 
1829 				_spdk_bs_allocate_and_copy_cluster(blob, _channel, offset, op);
1830 			}
1831 		}
1832 	} else {
1833 		struct rw_iov_ctx *ctx;
1834 
1835 		ctx = calloc(1, sizeof(struct rw_iov_ctx) + iovcnt * sizeof(struct iovec));
1836 		if (ctx == NULL) {
1837 			cb_fn(cb_arg, -ENOMEM);
1838 			return;
1839 		}
1840 
1841 		ctx->blob = _blob;
1842 		ctx->channel = _channel;
1843 		ctx->cb_fn = cb_fn;
1844 		ctx->cb_arg = cb_arg;
1845 		ctx->read = read;
1846 		ctx->orig_iov = iov;
1847 		ctx->iovcnt = iovcnt;
1848 		ctx->page_offset = offset;
1849 		ctx->pages_remaining = length;
1850 		ctx->pages_done = 0;
1851 
1852 		_spdk_rw_iov_split_next(ctx, 0);
1853 	}
1854 }
1855 
1856 static struct spdk_blob_data *
1857 _spdk_blob_lookup(struct spdk_blob_store *bs, spdk_blob_id blobid)
1858 {
1859 	struct spdk_blob_data *blob;
1860 
1861 	TAILQ_FOREACH(blob, &bs->blobs, link) {
1862 		if (blob->id == blobid) {
1863 			return blob;
1864 		}
1865 	}
1866 
1867 	return NULL;
1868 }
1869 
1870 static int
1871 _spdk_bs_channel_create(void *io_device, void *ctx_buf)
1872 {
1873 	struct spdk_blob_store		*bs = io_device;
1874 	struct spdk_bs_channel		*channel = ctx_buf;
1875 	struct spdk_bs_dev		*dev;
1876 	uint32_t			max_ops = bs->max_channel_ops;
1877 	uint32_t			i;
1878 
1879 	dev = bs->dev;
1880 
1881 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_bs_request_set));
1882 	if (!channel->req_mem) {
1883 		return -1;
1884 	}
1885 
1886 	TAILQ_INIT(&channel->reqs);
1887 
1888 	for (i = 0; i < max_ops; i++) {
1889 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
1890 	}
1891 
1892 	channel->bs = bs;
1893 	channel->dev = dev;
1894 	channel->dev_channel = dev->create_channel(dev);
1895 
1896 	if (!channel->dev_channel) {
1897 		SPDK_ERRLOG("Failed to create device channel.\n");
1898 		free(channel->req_mem);
1899 		return -1;
1900 	}
1901 
1902 	TAILQ_INIT(&channel->need_cluster_alloc);
1903 
1904 	return 0;
1905 }
1906 
1907 static void
1908 _spdk_bs_channel_destroy(void *io_device, void *ctx_buf)
1909 {
1910 	struct spdk_bs_channel *channel = ctx_buf;
1911 	spdk_bs_user_op_t *op;
1912 
1913 	while (!TAILQ_EMPTY(&channel->need_cluster_alloc)) {
1914 		op = TAILQ_FIRST(&channel->need_cluster_alloc);
1915 		TAILQ_REMOVE(&channel->need_cluster_alloc, op, link);
1916 		spdk_bs_user_op_abort(op);
1917 	}
1918 
1919 	free(channel->req_mem);
1920 	channel->dev->destroy_channel(channel->dev, channel->dev_channel);
1921 }
1922 
1923 static void
1924 _spdk_bs_dev_destroy(void *io_device)
1925 {
1926 	struct spdk_blob_store *bs = io_device;
1927 	struct spdk_blob_data	*blob, *blob_tmp;
1928 
1929 	bs->dev->destroy(bs->dev);
1930 
1931 	TAILQ_FOREACH_SAFE(blob, &bs->blobs, link, blob_tmp) {
1932 		TAILQ_REMOVE(&bs->blobs, blob, link);
1933 		_spdk_blob_free(blob);
1934 	}
1935 
1936 	pthread_mutex_destroy(&bs->used_clusters_mutex);
1937 
1938 	spdk_bit_array_free(&bs->used_blobids);
1939 	spdk_bit_array_free(&bs->used_md_pages);
1940 	spdk_bit_array_free(&bs->used_clusters);
1941 	/*
1942 	 * If this function is called for any reason except a successful unload,
1943 	 * the unload_cpl type will be NONE and this will be a nop.
1944 	 */
1945 	spdk_bs_call_cpl(&bs->unload_cpl, bs->unload_err);
1946 
1947 	free(bs);
1948 }
1949 
1950 static void
1951 _spdk_bs_free(struct spdk_blob_store *bs)
1952 {
1953 	spdk_bs_unregister_md_thread(bs);
1954 	spdk_io_device_unregister(bs, _spdk_bs_dev_destroy);
1955 }
1956 
1957 void
1958 spdk_bs_opts_init(struct spdk_bs_opts *opts)
1959 {
1960 	opts->cluster_sz = SPDK_BLOB_OPTS_CLUSTER_SZ;
1961 	opts->num_md_pages = SPDK_BLOB_OPTS_NUM_MD_PAGES;
1962 	opts->max_md_ops = SPDK_BLOB_OPTS_MAX_MD_OPS;
1963 	opts->max_channel_ops = SPDK_BLOB_OPTS_DEFAULT_CHANNEL_OPS;
1964 	memset(&opts->bstype, 0, sizeof(opts->bstype));
1965 }
1966 
1967 static int
1968 _spdk_bs_opts_verify(struct spdk_bs_opts *opts)
1969 {
1970 	if (opts->cluster_sz == 0 || opts->num_md_pages == 0 || opts->max_md_ops == 0 ||
1971 	    opts->max_channel_ops == 0) {
1972 		SPDK_ERRLOG("Blobstore options cannot be set to 0\n");
1973 		return -1;
1974 	}
1975 
1976 	return 0;
1977 }
1978 
1979 static struct spdk_blob_store *
1980 _spdk_bs_alloc(struct spdk_bs_dev *dev, struct spdk_bs_opts *opts)
1981 {
1982 	struct spdk_blob_store	*bs;
1983 	uint64_t dev_size;
1984 	int rc;
1985 
1986 	dev_size = dev->blocklen * dev->blockcnt;
1987 	if (dev_size < opts->cluster_sz) {
1988 		/* Device size cannot be smaller than cluster size of blobstore */
1989 		SPDK_ERRLOG("Device size %" PRIu64 " is smaller than cluster size %" PRIu32 "\n",
1990 			    dev_size, opts->cluster_sz);
1991 		return NULL;
1992 	}
1993 	if (opts->cluster_sz < SPDK_BS_PAGE_SIZE) {
1994 		/* Cluster size cannot be smaller than page size */
1995 		SPDK_ERRLOG("Cluster size %" PRIu32 " is smaller than page size %d\n",
1996 			    opts->cluster_sz, SPDK_BS_PAGE_SIZE);
1997 		return NULL;
1998 	}
1999 	bs = calloc(1, sizeof(struct spdk_blob_store));
2000 	if (!bs) {
2001 		return NULL;
2002 	}
2003 
2004 	TAILQ_INIT(&bs->blobs);
2005 	bs->dev = dev;
2006 	bs->md_thread = spdk_get_thread();
2007 	assert(bs->md_thread != NULL);
2008 
2009 	/*
2010 	 * Do not use _spdk_bs_lba_to_cluster() here since blockcnt may not be an
2011 	 *  even multiple of the cluster size.
2012 	 */
2013 	bs->cluster_sz = opts->cluster_sz;
2014 	bs->total_clusters = dev->blockcnt / (bs->cluster_sz / dev->blocklen);
2015 	bs->pages_per_cluster = bs->cluster_sz / SPDK_BS_PAGE_SIZE;
2016 	bs->num_free_clusters = bs->total_clusters;
2017 	bs->used_clusters = spdk_bit_array_create(bs->total_clusters);
2018 	if (bs->used_clusters == NULL) {
2019 		free(bs);
2020 		return NULL;
2021 	}
2022 
2023 	bs->max_channel_ops = opts->max_channel_ops;
2024 	bs->super_blob = SPDK_BLOBID_INVALID;
2025 	memcpy(&bs->bstype, &opts->bstype, sizeof(opts->bstype));
2026 
2027 	/* The metadata is assumed to be at least 1 page */
2028 	bs->used_md_pages = spdk_bit_array_create(1);
2029 	bs->used_blobids = spdk_bit_array_create(0);
2030 
2031 	pthread_mutex_init(&bs->used_clusters_mutex, NULL);
2032 
2033 	spdk_io_device_register(bs, _spdk_bs_channel_create, _spdk_bs_channel_destroy,
2034 				sizeof(struct spdk_bs_channel));
2035 	rc = spdk_bs_register_md_thread(bs);
2036 	if (rc == -1) {
2037 		spdk_io_device_unregister(bs, NULL);
2038 		pthread_mutex_destroy(&bs->used_clusters_mutex);
2039 		spdk_bit_array_free(&bs->used_blobids);
2040 		spdk_bit_array_free(&bs->used_md_pages);
2041 		spdk_bit_array_free(&bs->used_clusters);
2042 		free(bs);
2043 		return NULL;
2044 	}
2045 
2046 	return bs;
2047 }
2048 
2049 /* START spdk_bs_load, spdk_bs_load_ctx will used for both load and unload. */
2050 
2051 struct spdk_bs_load_ctx {
2052 	struct spdk_blob_store		*bs;
2053 	struct spdk_bs_super_block	*super;
2054 
2055 	struct spdk_bs_md_mask		*mask;
2056 	bool				in_page_chain;
2057 	uint32_t			page_index;
2058 	uint32_t			cur_page;
2059 	struct spdk_blob_md_page	*page;
2060 	bool				is_load;
2061 };
2062 
2063 static void
2064 _spdk_bs_load_ctx_fail(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2065 {
2066 	assert(bserrno != 0);
2067 
2068 	spdk_dma_free(ctx->super);
2069 	/*
2070 	 * Only free the blobstore when a load fails.  If an unload fails (for some reason)
2071 	 *  we want to keep the blobstore in case the caller wants to try again.
2072 	 */
2073 	if (ctx->is_load) {
2074 		_spdk_bs_free(ctx->bs);
2075 	}
2076 	free(ctx);
2077 	spdk_bs_sequence_finish(seq, bserrno);
2078 }
2079 
2080 static void
2081 _spdk_bs_set_mask(struct spdk_bit_array *array, struct spdk_bs_md_mask *mask)
2082 {
2083 	uint32_t i = 0;
2084 
2085 	while (true) {
2086 		i = spdk_bit_array_find_first_set(array, i);
2087 		if (i >= mask->length) {
2088 			break;
2089 		}
2090 		mask->mask[i / 8] |= 1U << (i % 8);
2091 		i++;
2092 	}
2093 }
2094 
2095 static void
2096 _spdk_bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2097 		     struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2098 {
2099 	/* Update the values in the super block */
2100 	super->super_blob = bs->super_blob;
2101 	memcpy(&super->bstype, &bs->bstype, sizeof(bs->bstype));
2102 	super->crc = _spdk_blob_md_page_calc_crc(super);
2103 	spdk_bs_sequence_write_dev(seq, super, _spdk_bs_page_to_lba(bs, 0),
2104 				   _spdk_bs_byte_to_lba(bs, sizeof(*super)),
2105 				   cb_fn, cb_arg);
2106 }
2107 
2108 static void
2109 _spdk_bs_write_used_clusters(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2110 {
2111 	struct spdk_bs_load_ctx	*ctx = arg;
2112 	uint64_t	mask_size, lba, lba_count;
2113 
2114 	/* Write out the used clusters mask */
2115 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2116 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2117 	if (!ctx->mask) {
2118 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2119 		return;
2120 	}
2121 
2122 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_CLUSTERS;
2123 	ctx->mask->length = ctx->bs->total_clusters;
2124 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_clusters));
2125 
2126 	_spdk_bs_set_mask(ctx->bs->used_clusters, ctx->mask);
2127 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
2128 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
2129 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2130 }
2131 
2132 static void
2133 _spdk_bs_write_used_md(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2134 {
2135 	struct spdk_bs_load_ctx	*ctx = arg;
2136 	uint64_t	mask_size, lba, lba_count;
2137 
2138 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
2139 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2140 	if (!ctx->mask) {
2141 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2142 		return;
2143 	}
2144 
2145 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_PAGES;
2146 	ctx->mask->length = ctx->super->md_len;
2147 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_md_pages));
2148 
2149 	_spdk_bs_set_mask(ctx->bs->used_md_pages, ctx->mask);
2150 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
2151 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
2152 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2153 }
2154 
2155 static void
2156 _spdk_bs_write_used_blobids(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
2157 {
2158 	struct spdk_bs_load_ctx	*ctx = arg;
2159 	uint64_t	mask_size, lba, lba_count;
2160 
2161 	if (ctx->super->used_blobid_mask_len == 0) {
2162 		/*
2163 		 * This is a pre-v3 on-disk format where the blobid mask does not get
2164 		 *  written to disk.
2165 		 */
2166 		cb_fn(seq, arg, 0);
2167 		return;
2168 	}
2169 
2170 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2171 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2172 	if (!ctx->mask) {
2173 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2174 		return;
2175 	}
2176 
2177 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_BLOBIDS;
2178 	ctx->mask->length = ctx->super->md_len;
2179 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_blobids));
2180 
2181 	_spdk_bs_set_mask(ctx->bs->used_blobids, ctx->mask);
2182 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2183 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2184 	spdk_bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
2185 }
2186 
2187 static void
2188 _spdk_bs_load_complete(spdk_bs_sequence_t *seq, struct spdk_bs_load_ctx *ctx, int bserrno)
2189 {
2190 	spdk_dma_free(ctx->super);
2191 	spdk_dma_free(ctx->mask);
2192 	free(ctx);
2193 	spdk_bs_sequence_finish(seq, bserrno);
2194 }
2195 
2196 static void
2197 _spdk_bs_load_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2198 {
2199 	struct spdk_bs_load_ctx *ctx = cb_arg;
2200 	uint32_t i, j;
2201 	int rc;
2202 
2203 	/* The type must be correct */
2204 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_BLOBIDS);
2205 
2206 	/* The length of the mask (in bits) must not be greater than
2207 	 * the length of the buffer (converted to bits) */
2208 	assert(ctx->mask->length <= (ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE * 8));
2209 
2210 	/* The length of the mask must be exactly equal to the size
2211 	 * (in pages) of the metadata region */
2212 	assert(ctx->mask->length == ctx->super->md_len);
2213 
2214 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->mask->length);
2215 	if (rc < 0) {
2216 		spdk_dma_free(ctx->mask);
2217 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2218 		return;
2219 	}
2220 
2221 	for (i = 0; i < ctx->mask->length / 8; i++) {
2222 		uint8_t segment = ctx->mask->mask[i];
2223 		for (j = 0; segment; j++) {
2224 			if (segment & 1U) {
2225 				spdk_bit_array_set(ctx->bs->used_blobids, (i * 8) + j);
2226 			}
2227 			segment >>= 1U;
2228 		}
2229 	}
2230 
2231 	_spdk_bs_load_complete(seq, ctx, bserrno);
2232 }
2233 
2234 static void
2235 _spdk_bs_load_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2236 {
2237 	struct spdk_bs_load_ctx *ctx = cb_arg;
2238 	uint64_t		lba, lba_count, mask_size;
2239 	uint32_t		i, j;
2240 	int			rc;
2241 
2242 	/* The type must be correct */
2243 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
2244 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2245 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
2246 					     struct spdk_blob_md_page) * 8));
2247 	/* The length of the mask must be exactly equal to the total number of clusters */
2248 	assert(ctx->mask->length == ctx->bs->total_clusters);
2249 
2250 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
2251 	if (rc < 0) {
2252 		spdk_dma_free(ctx->mask);
2253 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2254 		return;
2255 	}
2256 
2257 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
2258 	for (i = 0; i < ctx->mask->length / 8; i++) {
2259 		uint8_t segment = ctx->mask->mask[i];
2260 		for (j = 0; segment && (j < 8); j++) {
2261 			if (segment & 1U) {
2262 				spdk_bit_array_set(ctx->bs->used_clusters, (i * 8) + j);
2263 				assert(ctx->bs->num_free_clusters > 0);
2264 				ctx->bs->num_free_clusters--;
2265 			}
2266 			segment >>= 1U;
2267 		}
2268 	}
2269 
2270 	spdk_dma_free(ctx->mask);
2271 
2272 	/* Read the used blobids mask */
2273 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
2274 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2275 	if (!ctx->mask) {
2276 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2277 		return;
2278 	}
2279 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
2280 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
2281 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2282 				  _spdk_bs_load_used_blobids_cpl, ctx);
2283 }
2284 
2285 static void
2286 _spdk_bs_load_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2287 {
2288 	struct spdk_bs_load_ctx *ctx = cb_arg;
2289 	uint64_t		lba, lba_count, mask_size;
2290 	uint32_t		i, j;
2291 	int			rc;
2292 
2293 	/* The type must be correct */
2294 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_PAGES);
2295 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
2296 	assert(ctx->mask->length <= (ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE *
2297 				     8));
2298 	/* The length of the mask must be exactly equal to the size (in pages) of the metadata region */
2299 	assert(ctx->mask->length == ctx->super->md_len);
2300 
2301 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->mask->length);
2302 	if (rc < 0) {
2303 		spdk_dma_free(ctx->mask);
2304 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2305 		return;
2306 	}
2307 
2308 	for (i = 0; i < ctx->mask->length / 8; i++) {
2309 		uint8_t segment = ctx->mask->mask[i];
2310 		for (j = 0; segment && (j < 8); j++) {
2311 			if (segment & 1U) {
2312 				spdk_bit_array_set(ctx->bs->used_md_pages, (i * 8) + j);
2313 			}
2314 			segment >>= 1U;
2315 		}
2316 	}
2317 	spdk_dma_free(ctx->mask);
2318 
2319 	/* Read the used clusters mask */
2320 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
2321 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2322 	if (!ctx->mask) {
2323 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2324 		return;
2325 	}
2326 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
2327 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
2328 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2329 				  _spdk_bs_load_used_clusters_cpl, ctx);
2330 }
2331 
2332 static void
2333 _spdk_bs_load_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2334 {
2335 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2336 	uint64_t lba, lba_count, mask_size;
2337 
2338 	/* Read the used pages mask */
2339 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
2340 	ctx->mask = spdk_dma_zmalloc(mask_size, 0x1000, NULL);
2341 	if (!ctx->mask) {
2342 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2343 		return;
2344 	}
2345 
2346 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
2347 	lba_count = _spdk_bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
2348 	spdk_bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
2349 				  _spdk_bs_load_used_pages_cpl, ctx);
2350 }
2351 
2352 static int
2353 _spdk_bs_load_replay_md_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob_store *bs)
2354 {
2355 	struct spdk_blob_md_descriptor *desc;
2356 	size_t	cur_desc = 0;
2357 
2358 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
2359 	while (cur_desc < sizeof(page->descriptors)) {
2360 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
2361 			if (desc->length == 0) {
2362 				/* If padding and length are 0, this terminates the page */
2363 				break;
2364 			}
2365 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT) {
2366 			struct spdk_blob_md_descriptor_extent	*desc_extent;
2367 			unsigned int				i, j;
2368 			unsigned int				cluster_count = 0;
2369 
2370 			desc_extent = (struct spdk_blob_md_descriptor_extent *)desc;
2371 
2372 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->extents[0]); i++) {
2373 				for (j = 0; j < desc_extent->extents[i].length; j++) {
2374 					spdk_bit_array_set(bs->used_clusters, desc_extent->extents[i].cluster_idx + j);
2375 					if (bs->num_free_clusters == 0) {
2376 						return -1;
2377 					}
2378 					bs->num_free_clusters--;
2379 					cluster_count++;
2380 				}
2381 			}
2382 			if (cluster_count == 0) {
2383 				return -1;
2384 			}
2385 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
2386 			/* Skip this item */
2387 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
2388 			/* Skip this item */
2389 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
2390 			/* Skip this item */
2391 		} else {
2392 			/* Error */
2393 			return -1;
2394 		}
2395 		/* Advance to the next descriptor */
2396 		cur_desc += sizeof(*desc) + desc->length;
2397 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
2398 			break;
2399 		}
2400 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
2401 	}
2402 	return 0;
2403 }
2404 
2405 static bool _spdk_bs_load_cur_md_page_valid(struct spdk_bs_load_ctx *ctx)
2406 {
2407 	uint32_t crc;
2408 
2409 	crc = _spdk_blob_md_page_calc_crc(ctx->page);
2410 	if (crc != ctx->page->crc) {
2411 		return false;
2412 	}
2413 
2414 	if (_spdk_bs_page_to_blobid(ctx->cur_page) != ctx->page->id) {
2415 		return false;
2416 	}
2417 	return true;
2418 }
2419 
2420 static void
2421 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
2422 
2423 static void
2424 _spdk_bs_load_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2425 {
2426 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2427 
2428 	_spdk_bs_load_complete(seq, ctx, bserrno);
2429 }
2430 
2431 static void
2432 _spdk_bs_load_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2433 {
2434 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2435 
2436 	spdk_dma_free(ctx->mask);
2437 	ctx->mask = NULL;
2438 
2439 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_load_write_used_clusters_cpl);
2440 }
2441 
2442 static void
2443 _spdk_bs_load_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2444 {
2445 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2446 
2447 	spdk_dma_free(ctx->mask);
2448 	ctx->mask = NULL;
2449 
2450 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_load_write_used_blobids_cpl);
2451 }
2452 
2453 static void
2454 _spdk_bs_load_write_used_md(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2455 {
2456 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_load_write_used_pages_cpl);
2457 }
2458 
2459 static void
2460 _spdk_bs_load_replay_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2461 {
2462 	struct spdk_bs_load_ctx *ctx = cb_arg;
2463 	uint64_t num_md_clusters;
2464 	uint64_t i;
2465 	uint32_t page_num;
2466 
2467 	if (bserrno != 0) {
2468 		_spdk_bs_load_ctx_fail(seq, ctx, bserrno);
2469 		return;
2470 	}
2471 
2472 	page_num = ctx->cur_page;
2473 	if (_spdk_bs_load_cur_md_page_valid(ctx) == true) {
2474 		if (ctx->page->sequence_num == 0 || ctx->in_page_chain == true) {
2475 			spdk_bit_array_set(ctx->bs->used_md_pages, page_num);
2476 			if (ctx->page->sequence_num == 0) {
2477 				spdk_bit_array_set(ctx->bs->used_blobids, page_num);
2478 			}
2479 			if (_spdk_bs_load_replay_md_parse_page(ctx->page, ctx->bs)) {
2480 				_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
2481 				return;
2482 			}
2483 			if (ctx->page->next != SPDK_INVALID_MD_PAGE) {
2484 				ctx->in_page_chain = true;
2485 				ctx->cur_page = ctx->page->next;
2486 				_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
2487 				return;
2488 			}
2489 		}
2490 	}
2491 
2492 	ctx->in_page_chain = false;
2493 
2494 	do {
2495 		ctx->page_index++;
2496 	} while (spdk_bit_array_get(ctx->bs->used_md_pages, ctx->page_index) == true);
2497 
2498 	if (ctx->page_index < ctx->super->md_len) {
2499 		ctx->cur_page = ctx->page_index;
2500 		_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
2501 	} else {
2502 		/* Claim all of the clusters used by the metadata */
2503 		num_md_clusters = divide_round_up(ctx->super->md_len, ctx->bs->pages_per_cluster);
2504 		for (i = 0; i < num_md_clusters; i++) {
2505 			_spdk_bs_claim_cluster(ctx->bs, i);
2506 		}
2507 		spdk_dma_free(ctx->page);
2508 		_spdk_bs_load_write_used_md(seq, ctx, bserrno);
2509 	}
2510 }
2511 
2512 static void
2513 _spdk_bs_load_replay_cur_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
2514 {
2515 	struct spdk_bs_load_ctx *ctx = cb_arg;
2516 	uint64_t lba;
2517 
2518 	assert(ctx->cur_page < ctx->super->md_len);
2519 	lba = _spdk_bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
2520 	spdk_bs_sequence_read_dev(seq, ctx->page, lba,
2521 				  _spdk_bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
2522 				  _spdk_bs_load_replay_md_cpl, ctx);
2523 }
2524 
2525 static void
2526 _spdk_bs_load_replay_md(spdk_bs_sequence_t *seq, void *cb_arg)
2527 {
2528 	struct spdk_bs_load_ctx *ctx = cb_arg;
2529 
2530 	ctx->page_index = 0;
2531 	ctx->cur_page = 0;
2532 	ctx->page = spdk_dma_zmalloc(SPDK_BS_PAGE_SIZE,
2533 				     SPDK_BS_PAGE_SIZE,
2534 				     NULL);
2535 	if (!ctx->page) {
2536 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2537 		return;
2538 	}
2539 	_spdk_bs_load_replay_cur_md_page(seq, cb_arg);
2540 }
2541 
2542 static void
2543 _spdk_bs_recover(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2544 {
2545 	struct spdk_bs_load_ctx *ctx = cb_arg;
2546 	int 		rc;
2547 
2548 	if (bserrno != 0) {
2549 		_spdk_bs_load_ctx_fail(seq, ctx, -EIO);
2550 		return;
2551 	}
2552 
2553 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->super->md_len);
2554 	if (rc < 0) {
2555 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2556 		return;
2557 	}
2558 
2559 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->super->md_len);
2560 	if (rc < 0) {
2561 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2562 		return;
2563 	}
2564 
2565 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
2566 	if (rc < 0) {
2567 		_spdk_bs_load_ctx_fail(seq, ctx, -ENOMEM);
2568 		return;
2569 	}
2570 
2571 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
2572 	_spdk_bs_load_replay_md(seq, cb_arg);
2573 }
2574 
2575 static void
2576 _spdk_bs_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2577 {
2578 	struct spdk_bs_load_ctx *ctx = cb_arg;
2579 	uint32_t	crc;
2580 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
2581 
2582 	if (ctx->super->version > SPDK_BS_VERSION ||
2583 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
2584 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
2585 		return;
2586 	}
2587 
2588 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
2589 		   sizeof(ctx->super->signature)) != 0) {
2590 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
2591 		return;
2592 	}
2593 
2594 	crc = _spdk_blob_md_page_calc_crc(ctx->super);
2595 	if (crc != ctx->super->crc) {
2596 		_spdk_bs_load_ctx_fail(seq, ctx, -EILSEQ);
2597 		return;
2598 	}
2599 
2600 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
2601 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype matched - loading blobstore\n");
2602 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
2603 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype wildcard used - loading blobstore regardless bstype\n");
2604 	} else {
2605 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Unexpected bstype\n");
2606 		SPDK_TRACEDUMP(SPDK_LOG_BLOB, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
2607 		SPDK_TRACEDUMP(SPDK_LOG_BLOB, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
2608 		_spdk_bs_load_ctx_fail(seq, ctx, -ENXIO);
2609 		return;
2610 	}
2611 
2612 	/* Parse the super block */
2613 	ctx->bs->cluster_sz = ctx->super->cluster_size;
2614 	ctx->bs->total_clusters = ctx->bs->dev->blockcnt / (ctx->bs->cluster_sz / ctx->bs->dev->blocklen);
2615 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
2616 	ctx->bs->md_start = ctx->super->md_start;
2617 	ctx->bs->md_len = ctx->super->md_len;
2618 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - divide_round_up(
2619 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
2620 	ctx->bs->super_blob = ctx->super->super_blob;
2621 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
2622 
2623 	if (ctx->super->clean == 0) {
2624 		_spdk_bs_recover(seq, ctx, 0);
2625 	} else if (ctx->super->used_blobid_mask_len == 0) {
2626 		/*
2627 		 * Metadata is clean, but this is an old metadata format without
2628 		 *  a blobid mask.  Clear the clean bit and then build the masks
2629 		 *  using _spdk_bs_recover.
2630 		 */
2631 		ctx->super->clean = 0;
2632 		_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_recover, ctx);
2633 	} else {
2634 		ctx->super->clean = 0;
2635 		_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_load_write_super_cpl, ctx);
2636 	}
2637 }
2638 
2639 void
2640 spdk_bs_load(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
2641 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
2642 {
2643 	struct spdk_blob_store	*bs;
2644 	struct spdk_bs_cpl	cpl;
2645 	spdk_bs_sequence_t	*seq;
2646 	struct spdk_bs_load_ctx *ctx;
2647 	struct spdk_bs_opts	opts = {};
2648 
2649 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Loading blobstore from dev %p\n", dev);
2650 
2651 	if (o) {
2652 		opts = *o;
2653 	} else {
2654 		spdk_bs_opts_init(&opts);
2655 	}
2656 
2657 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
2658 		cb_fn(cb_arg, NULL, -EINVAL);
2659 		return;
2660 	}
2661 
2662 	bs = _spdk_bs_alloc(dev, &opts);
2663 	if (!bs) {
2664 		cb_fn(cb_arg, NULL, -ENOMEM);
2665 		return;
2666 	}
2667 
2668 	ctx = calloc(1, sizeof(*ctx));
2669 	if (!ctx) {
2670 		_spdk_bs_free(bs);
2671 		cb_fn(cb_arg, NULL, -ENOMEM);
2672 		return;
2673 	}
2674 
2675 	ctx->bs = bs;
2676 	ctx->is_load = true;
2677 
2678 	/* Allocate memory for the super block */
2679 	ctx->super = spdk_dma_zmalloc(sizeof(*ctx->super), 0x1000, NULL);
2680 	if (!ctx->super) {
2681 		free(ctx);
2682 		_spdk_bs_free(bs);
2683 		return;
2684 	}
2685 
2686 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
2687 	cpl.u.bs_handle.cb_fn = cb_fn;
2688 	cpl.u.bs_handle.cb_arg = cb_arg;
2689 	cpl.u.bs_handle.bs = bs;
2690 
2691 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
2692 	if (!seq) {
2693 		spdk_dma_free(ctx->super);
2694 		free(ctx);
2695 		_spdk_bs_free(bs);
2696 		cb_fn(cb_arg, NULL, -ENOMEM);
2697 		return;
2698 	}
2699 
2700 	/* Read the super block */
2701 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
2702 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
2703 				  _spdk_bs_load_super_cpl, ctx);
2704 }
2705 
2706 /* END spdk_bs_load */
2707 
2708 /* START spdk_bs_init */
2709 
2710 struct spdk_bs_init_ctx {
2711 	struct spdk_blob_store		*bs;
2712 	struct spdk_bs_super_block	*super;
2713 };
2714 
2715 static void
2716 _spdk_bs_init_persist_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2717 {
2718 	struct spdk_bs_init_ctx *ctx = cb_arg;
2719 
2720 	spdk_dma_free(ctx->super);
2721 	free(ctx);
2722 
2723 	spdk_bs_sequence_finish(seq, bserrno);
2724 }
2725 
2726 static void
2727 _spdk_bs_init_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2728 {
2729 	struct spdk_bs_init_ctx *ctx = cb_arg;
2730 
2731 	/* Write super block */
2732 	spdk_bs_sequence_write_dev(seq, ctx->super, _spdk_bs_page_to_lba(ctx->bs, 0),
2733 				   _spdk_bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
2734 				   _spdk_bs_init_persist_super_cpl, ctx);
2735 }
2736 
2737 void
2738 spdk_bs_init(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
2739 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
2740 {
2741 	struct spdk_bs_init_ctx *ctx;
2742 	struct spdk_blob_store	*bs;
2743 	struct spdk_bs_cpl	cpl;
2744 	spdk_bs_sequence_t	*seq;
2745 	spdk_bs_batch_t		*batch;
2746 	uint64_t		num_md_lba;
2747 	uint64_t		num_md_pages;
2748 	uint64_t		num_md_clusters;
2749 	uint32_t		i;
2750 	struct spdk_bs_opts	opts = {};
2751 	int			rc;
2752 
2753 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Initializing blobstore on dev %p\n", dev);
2754 
2755 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
2756 		SPDK_ERRLOG("unsupported dev block length of %d\n",
2757 			    dev->blocklen);
2758 		dev->destroy(dev);
2759 		cb_fn(cb_arg, NULL, -EINVAL);
2760 		return;
2761 	}
2762 
2763 	if (o) {
2764 		opts = *o;
2765 	} else {
2766 		spdk_bs_opts_init(&opts);
2767 	}
2768 
2769 	if (_spdk_bs_opts_verify(&opts) != 0) {
2770 		dev->destroy(dev);
2771 		cb_fn(cb_arg, NULL, -EINVAL);
2772 		return;
2773 	}
2774 
2775 	bs = _spdk_bs_alloc(dev, &opts);
2776 	if (!bs) {
2777 		dev->destroy(dev);
2778 		cb_fn(cb_arg, NULL, -ENOMEM);
2779 		return;
2780 	}
2781 
2782 	if (opts.num_md_pages == SPDK_BLOB_OPTS_NUM_MD_PAGES) {
2783 		/* By default, allocate 1 page per cluster.
2784 		 * Technically, this over-allocates metadata
2785 		 * because more metadata will reduce the number
2786 		 * of usable clusters. This can be addressed with
2787 		 * more complex math in the future.
2788 		 */
2789 		bs->md_len = bs->total_clusters;
2790 	} else {
2791 		bs->md_len = opts.num_md_pages;
2792 	}
2793 
2794 	rc = spdk_bit_array_resize(&bs->used_md_pages, bs->md_len);
2795 	if (rc < 0) {
2796 		_spdk_bs_free(bs);
2797 		cb_fn(cb_arg, NULL, -ENOMEM);
2798 		return;
2799 	}
2800 
2801 	rc = spdk_bit_array_resize(&bs->used_blobids, bs->md_len);
2802 	if (rc < 0) {
2803 		_spdk_bs_free(bs);
2804 		cb_fn(cb_arg, NULL, -ENOMEM);
2805 		return;
2806 	}
2807 
2808 	ctx = calloc(1, sizeof(*ctx));
2809 	if (!ctx) {
2810 		_spdk_bs_free(bs);
2811 		cb_fn(cb_arg, NULL, -ENOMEM);
2812 		return;
2813 	}
2814 
2815 	ctx->bs = bs;
2816 
2817 	/* Allocate memory for the super block */
2818 	ctx->super = spdk_dma_zmalloc(sizeof(*ctx->super), 0x1000, NULL);
2819 	if (!ctx->super) {
2820 		free(ctx);
2821 		_spdk_bs_free(bs);
2822 		return;
2823 	}
2824 	memcpy(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
2825 	       sizeof(ctx->super->signature));
2826 	ctx->super->version = SPDK_BS_VERSION;
2827 	ctx->super->length = sizeof(*ctx->super);
2828 	ctx->super->super_blob = bs->super_blob;
2829 	ctx->super->clean = 0;
2830 	ctx->super->cluster_size = bs->cluster_sz;
2831 	memcpy(&ctx->super->bstype, &bs->bstype, sizeof(bs->bstype));
2832 
2833 	/* Calculate how many pages the metadata consumes at the front
2834 	 * of the disk.
2835 	 */
2836 
2837 	/* The super block uses 1 page */
2838 	num_md_pages = 1;
2839 
2840 	/* The used_md_pages mask requires 1 bit per metadata page, rounded
2841 	 * up to the nearest page, plus a header.
2842 	 */
2843 	ctx->super->used_page_mask_start = num_md_pages;
2844 	ctx->super->used_page_mask_len = divide_round_up(sizeof(struct spdk_bs_md_mask) +
2845 					 divide_round_up(bs->md_len, 8),
2846 					 SPDK_BS_PAGE_SIZE);
2847 	num_md_pages += ctx->super->used_page_mask_len;
2848 
2849 	/* The used_clusters mask requires 1 bit per cluster, rounded
2850 	 * up to the nearest page, plus a header.
2851 	 */
2852 	ctx->super->used_cluster_mask_start = num_md_pages;
2853 	ctx->super->used_cluster_mask_len = divide_round_up(sizeof(struct spdk_bs_md_mask) +
2854 					    divide_round_up(bs->total_clusters, 8),
2855 					    SPDK_BS_PAGE_SIZE);
2856 	num_md_pages += ctx->super->used_cluster_mask_len;
2857 
2858 	/* The used_blobids mask requires 1 bit per metadata page, rounded
2859 	 * up to the nearest page, plus a header.
2860 	 */
2861 	ctx->super->used_blobid_mask_start = num_md_pages;
2862 	ctx->super->used_blobid_mask_len = divide_round_up(sizeof(struct spdk_bs_md_mask) +
2863 					   divide_round_up(bs->md_len, 8),
2864 					   SPDK_BS_PAGE_SIZE);
2865 	num_md_pages += ctx->super->used_blobid_mask_len;
2866 
2867 	/* The metadata region size was chosen above */
2868 	ctx->super->md_start = bs->md_start = num_md_pages;
2869 	ctx->super->md_len = bs->md_len;
2870 	num_md_pages += bs->md_len;
2871 
2872 	num_md_lba = _spdk_bs_page_to_lba(bs, num_md_pages);
2873 
2874 	ctx->super->crc = _spdk_blob_md_page_calc_crc(ctx->super);
2875 
2876 	num_md_clusters = divide_round_up(num_md_pages, bs->pages_per_cluster);
2877 	if (num_md_clusters > bs->total_clusters) {
2878 		SPDK_ERRLOG("Blobstore metadata cannot use more clusters than is available, "
2879 			    "please decrease number of pages reserved for metadata "
2880 			    "or increase cluster size.\n");
2881 		spdk_dma_free(ctx->super);
2882 		free(ctx);
2883 		_spdk_bs_free(bs);
2884 		cb_fn(cb_arg, NULL, -ENOMEM);
2885 		return;
2886 	}
2887 	/* Claim all of the clusters used by the metadata */
2888 	for (i = 0; i < num_md_clusters; i++) {
2889 		_spdk_bs_claim_cluster(bs, i);
2890 	}
2891 
2892 	bs->total_data_clusters = bs->num_free_clusters;
2893 
2894 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
2895 	cpl.u.bs_handle.cb_fn = cb_fn;
2896 	cpl.u.bs_handle.cb_arg = cb_arg;
2897 	cpl.u.bs_handle.bs = bs;
2898 
2899 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
2900 	if (!seq) {
2901 		spdk_dma_free(ctx->super);
2902 		free(ctx);
2903 		_spdk_bs_free(bs);
2904 		cb_fn(cb_arg, NULL, -ENOMEM);
2905 		return;
2906 	}
2907 
2908 	batch = spdk_bs_sequence_to_batch(seq, _spdk_bs_init_trim_cpl, ctx);
2909 
2910 	/* Clear metadata space */
2911 	spdk_bs_batch_write_zeroes_dev(batch, 0, num_md_lba);
2912 	/* Trim data clusters */
2913 	spdk_bs_batch_unmap_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
2914 
2915 	spdk_bs_batch_close(batch);
2916 }
2917 
2918 /* END spdk_bs_init */
2919 
2920 /* START spdk_bs_destroy */
2921 
2922 static void
2923 _spdk_bs_destroy_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2924 {
2925 	struct spdk_bs_init_ctx *ctx = cb_arg;
2926 	struct spdk_blob_store *bs = ctx->bs;
2927 
2928 	/*
2929 	 * We need to defer calling spdk_bs_call_cpl() until after
2930 	 * dev destruction, so tuck these away for later use.
2931 	 */
2932 	bs->unload_err = bserrno;
2933 	memcpy(&bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
2934 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
2935 
2936 	spdk_bs_sequence_finish(seq, bserrno);
2937 
2938 	_spdk_bs_free(bs);
2939 	free(ctx);
2940 }
2941 
2942 void
2943 spdk_bs_destroy(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn,
2944 		void *cb_arg)
2945 {
2946 	struct spdk_bs_cpl	cpl;
2947 	spdk_bs_sequence_t	*seq;
2948 	struct spdk_bs_init_ctx *ctx;
2949 
2950 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Destroying blobstore\n");
2951 
2952 	if (!TAILQ_EMPTY(&bs->blobs)) {
2953 		SPDK_ERRLOG("Blobstore still has open blobs\n");
2954 		cb_fn(cb_arg, -EBUSY);
2955 		return;
2956 	}
2957 
2958 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
2959 	cpl.u.bs_basic.cb_fn = cb_fn;
2960 	cpl.u.bs_basic.cb_arg = cb_arg;
2961 
2962 	ctx = calloc(1, sizeof(*ctx));
2963 	if (!ctx) {
2964 		cb_fn(cb_arg, -ENOMEM);
2965 		return;
2966 	}
2967 
2968 	ctx->bs = bs;
2969 
2970 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
2971 	if (!seq) {
2972 		free(ctx);
2973 		cb_fn(cb_arg, -ENOMEM);
2974 		return;
2975 	}
2976 
2977 	/* Write zeroes to the super block */
2978 	spdk_bs_sequence_write_zeroes_dev(seq,
2979 					  _spdk_bs_page_to_lba(bs, 0),
2980 					  _spdk_bs_byte_to_lba(bs, sizeof(struct spdk_bs_super_block)),
2981 					  _spdk_bs_destroy_trim_cpl, ctx);
2982 }
2983 
2984 /* END spdk_bs_destroy */
2985 
2986 /* START spdk_bs_unload */
2987 
2988 static void
2989 _spdk_bs_unload_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2990 {
2991 	struct spdk_bs_load_ctx	*ctx = cb_arg;
2992 
2993 	spdk_dma_free(ctx->super);
2994 
2995 	/*
2996 	 * We need to defer calling spdk_bs_call_cpl() until after
2997 	 * dev destuction, so tuck these away for later use.
2998 	 */
2999 	ctx->bs->unload_err = bserrno;
3000 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
3001 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
3002 
3003 	spdk_bs_sequence_finish(seq, bserrno);
3004 
3005 	_spdk_bs_free(ctx->bs);
3006 	free(ctx);
3007 }
3008 
3009 static void
3010 _spdk_bs_unload_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3011 {
3012 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3013 
3014 	spdk_dma_free(ctx->mask);
3015 	ctx->super->clean = 1;
3016 
3017 	_spdk_bs_write_super(seq, ctx->bs, ctx->super, _spdk_bs_unload_write_super_cpl, ctx);
3018 }
3019 
3020 static void
3021 _spdk_bs_unload_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3022 {
3023 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3024 
3025 	spdk_dma_free(ctx->mask);
3026 	ctx->mask = NULL;
3027 
3028 	_spdk_bs_write_used_clusters(seq, cb_arg, _spdk_bs_unload_write_used_clusters_cpl);
3029 }
3030 
3031 static void
3032 _spdk_bs_unload_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3033 {
3034 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3035 
3036 	spdk_dma_free(ctx->mask);
3037 	ctx->mask = NULL;
3038 
3039 	_spdk_bs_write_used_blobids(seq, cb_arg, _spdk_bs_unload_write_used_blobids_cpl);
3040 }
3041 
3042 static void
3043 _spdk_bs_unload_read_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3044 {
3045 	_spdk_bs_write_used_md(seq, cb_arg, _spdk_bs_unload_write_used_pages_cpl);
3046 }
3047 
3048 void
3049 spdk_bs_unload(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn, void *cb_arg)
3050 {
3051 	struct spdk_bs_cpl	cpl;
3052 	spdk_bs_sequence_t	*seq;
3053 	struct spdk_bs_load_ctx *ctx;
3054 
3055 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blobstore\n");
3056 
3057 	if (!TAILQ_EMPTY(&bs->blobs)) {
3058 		SPDK_ERRLOG("Blobstore still has open blobs\n");
3059 		cb_fn(cb_arg, -EBUSY);
3060 		return;
3061 	}
3062 
3063 	ctx = calloc(1, sizeof(*ctx));
3064 	if (!ctx) {
3065 		cb_fn(cb_arg, -ENOMEM);
3066 		return;
3067 	}
3068 
3069 	ctx->bs = bs;
3070 	ctx->is_load = false;
3071 
3072 	ctx->super = spdk_dma_zmalloc(sizeof(*ctx->super), 0x1000, NULL);
3073 	if (!ctx->super) {
3074 		free(ctx);
3075 		cb_fn(cb_arg, -ENOMEM);
3076 		return;
3077 	}
3078 
3079 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
3080 	cpl.u.bs_basic.cb_fn = cb_fn;
3081 	cpl.u.bs_basic.cb_arg = cb_arg;
3082 
3083 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3084 	if (!seq) {
3085 		spdk_dma_free(ctx->super);
3086 		free(ctx);
3087 		cb_fn(cb_arg, -ENOMEM);
3088 		return;
3089 	}
3090 
3091 	/* Read super block */
3092 	spdk_bs_sequence_read_dev(seq, ctx->super, _spdk_bs_page_to_lba(bs, 0),
3093 				  _spdk_bs_byte_to_lba(bs, sizeof(*ctx->super)),
3094 				  _spdk_bs_unload_read_super_cpl, ctx);
3095 }
3096 
3097 /* END spdk_bs_unload */
3098 
3099 void
3100 spdk_bs_set_super(struct spdk_blob_store *bs, spdk_blob_id blobid,
3101 		  spdk_bs_op_complete cb_fn, void *cb_arg)
3102 {
3103 	bs->super_blob = blobid;
3104 	cb_fn(cb_arg, 0);
3105 }
3106 
3107 void
3108 spdk_bs_get_super(struct spdk_blob_store *bs,
3109 		  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
3110 {
3111 	if (bs->super_blob == SPDK_BLOBID_INVALID) {
3112 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOENT);
3113 	} else {
3114 		cb_fn(cb_arg, bs->super_blob, 0);
3115 	}
3116 }
3117 
3118 uint64_t
3119 spdk_bs_get_cluster_size(struct spdk_blob_store *bs)
3120 {
3121 	return bs->cluster_sz;
3122 }
3123 
3124 uint64_t
3125 spdk_bs_get_page_size(struct spdk_blob_store *bs)
3126 {
3127 	return SPDK_BS_PAGE_SIZE;
3128 }
3129 
3130 uint64_t
3131 spdk_bs_free_cluster_count(struct spdk_blob_store *bs)
3132 {
3133 	return bs->num_free_clusters;
3134 }
3135 
3136 uint64_t
3137 spdk_bs_total_data_cluster_count(struct spdk_blob_store *bs)
3138 {
3139 	return bs->total_data_clusters;
3140 }
3141 
3142 static int
3143 spdk_bs_register_md_thread(struct spdk_blob_store *bs)
3144 {
3145 	bs->md_channel = spdk_get_io_channel(bs);
3146 	if (!bs->md_channel) {
3147 		SPDK_ERRLOG("Failed to get IO channel.\n");
3148 		return -1;
3149 	}
3150 
3151 	return 0;
3152 }
3153 
3154 static int
3155 spdk_bs_unregister_md_thread(struct spdk_blob_store *bs)
3156 {
3157 	spdk_put_io_channel(bs->md_channel);
3158 
3159 	return 0;
3160 }
3161 
3162 spdk_blob_id spdk_blob_get_id(struct spdk_blob *_blob)
3163 {
3164 	struct spdk_blob_data *blob = __blob_to_data(_blob);
3165 
3166 	assert(blob != NULL);
3167 
3168 	return blob->id;
3169 }
3170 
3171 uint64_t spdk_blob_get_num_pages(struct spdk_blob *_blob)
3172 {
3173 	struct spdk_blob_data *blob = __blob_to_data(_blob);
3174 
3175 	assert(blob != NULL);
3176 
3177 	return _spdk_bs_cluster_to_page(blob->bs, blob->active.num_clusters);
3178 }
3179 
3180 uint64_t spdk_blob_get_num_clusters(struct spdk_blob *_blob)
3181 {
3182 	struct spdk_blob_data *blob = __blob_to_data(_blob);
3183 
3184 	assert(blob != NULL);
3185 
3186 	return blob->active.num_clusters;
3187 }
3188 
3189 /* START spdk_bs_create_blob */
3190 
3191 static void
3192 _spdk_bs_create_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3193 {
3194 	struct spdk_blob_data *blob = cb_arg;
3195 
3196 	_spdk_blob_free(blob);
3197 
3198 	spdk_bs_sequence_finish(seq, bserrno);
3199 }
3200 
3201 static int
3202 _spdk_blob_set_xattrs(struct spdk_blob_data *blob, const struct spdk_blob_xattr_opts *xattrs,
3203 		      bool internal)
3204 {
3205 	uint64_t i;
3206 	size_t value_len = 0;
3207 	int rc;
3208 	const void *value = NULL;
3209 	if (xattrs->count > 0 && xattrs->get_value == NULL) {
3210 		return -EINVAL;
3211 	}
3212 	for (i = 0; i < xattrs->count; i++) {
3213 		xattrs->get_value(xattrs->ctx, xattrs->names[i], &value, &value_len);
3214 		if (value == NULL || value_len == 0) {
3215 			return -EINVAL;
3216 		}
3217 		rc = _spdk_blob_set_xattr(blob, xattrs->names[i], value, value_len, internal);
3218 		if (rc < 0) {
3219 			return rc;
3220 		}
3221 	}
3222 	return 0;
3223 }
3224 
3225 static void
3226 _spdk_blob_set_thin_provision(struct spdk_blob_data *blob)
3227 {
3228 	blob->invalid_flags |= SPDK_BLOB_THIN_PROV;
3229 	blob->state = SPDK_BLOB_STATE_DIRTY;
3230 }
3231 
3232 void spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
3233 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
3234 {
3235 	struct spdk_blob_data	*blob;
3236 	uint32_t		page_idx;
3237 	struct spdk_bs_cpl 	cpl;
3238 	struct spdk_blob_opts	opts_default;
3239 	spdk_bs_sequence_t	*seq;
3240 	spdk_blob_id		id;
3241 	int rc;
3242 
3243 	page_idx = spdk_bit_array_find_first_clear(bs->used_md_pages, 0);
3244 	if (page_idx >= spdk_bit_array_capacity(bs->used_md_pages)) {
3245 		cb_fn(cb_arg, 0, -ENOMEM);
3246 		return;
3247 	}
3248 	spdk_bit_array_set(bs->used_blobids, page_idx);
3249 	spdk_bit_array_set(bs->used_md_pages, page_idx);
3250 
3251 	id = _spdk_bs_page_to_blobid(page_idx);
3252 
3253 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Creating blob with id %lu at page %u\n", id, page_idx);
3254 
3255 	blob = _spdk_blob_alloc(bs, id);
3256 	if (!blob) {
3257 		cb_fn(cb_arg, 0, -ENOMEM);
3258 		return;
3259 	}
3260 
3261 	if (!opts) {
3262 		spdk_blob_opts_init(&opts_default);
3263 		opts = &opts_default;
3264 	}
3265 
3266 	rc = _spdk_blob_set_xattrs(blob, &opts->xattrs, false);
3267 	if (rc < 0) {
3268 		_spdk_blob_free(blob);
3269 		cb_fn(cb_arg, 0, rc);
3270 		return;
3271 	}
3272 	if (opts->thin_provision) {
3273 		_spdk_blob_set_thin_provision(blob);
3274 	}
3275 
3276 	rc = spdk_blob_resize(__data_to_blob(blob), opts->num_clusters);
3277 	if (rc < 0) {
3278 		_spdk_blob_free(blob);
3279 		cb_fn(cb_arg, 0, rc);
3280 		return;
3281 	}
3282 	cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
3283 	cpl.u.blobid.cb_fn = cb_fn;
3284 	cpl.u.blobid.cb_arg = cb_arg;
3285 	cpl.u.blobid.blobid = blob->id;
3286 
3287 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3288 	if (!seq) {
3289 		_spdk_blob_free(blob);
3290 		cb_fn(cb_arg, 0, -ENOMEM);
3291 		return;
3292 	}
3293 
3294 	_spdk_blob_persist(seq, blob, _spdk_bs_create_blob_cpl, blob);
3295 }
3296 
3297 void spdk_bs_create_blob(struct spdk_blob_store *bs,
3298 			 spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
3299 {
3300 	spdk_bs_create_blob_ext(bs, NULL, cb_fn, cb_arg);
3301 }
3302 
3303 /* END spdk_bs_create_blob */
3304 
3305 /* START spdk_blob_resize */
3306 int
3307 spdk_blob_resize(struct spdk_blob *_blob, uint64_t sz)
3308 {
3309 	struct spdk_blob_data	*blob = __blob_to_data(_blob);
3310 	int			rc;
3311 
3312 	assert(blob != NULL);
3313 	assert(spdk_get_thread() == blob->bs->md_thread);
3314 
3315 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Resizing blob %lu to %lu clusters\n", blob->id, sz);
3316 
3317 	if (blob->md_ro) {
3318 		return -EPERM;
3319 	}
3320 
3321 	if (sz == blob->active.num_clusters) {
3322 		return 0;
3323 	}
3324 
3325 	rc = _spdk_resize_blob(blob, sz);
3326 	if (rc < 0) {
3327 		return rc;
3328 	}
3329 
3330 	return 0;
3331 }
3332 
3333 /* END spdk_blob_resize */
3334 
3335 
3336 /* START spdk_bs_delete_blob */
3337 
3338 static void
3339 _spdk_bs_delete_close_cpl(void *cb_arg, int bserrno)
3340 {
3341 	spdk_bs_sequence_t *seq = cb_arg;
3342 
3343 	spdk_bs_sequence_finish(seq, bserrno);
3344 }
3345 
3346 static void
3347 _spdk_bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3348 {
3349 	struct spdk_blob *_blob = cb_arg;
3350 	struct spdk_blob_data *blob = __blob_to_data(_blob);
3351 
3352 	if (bserrno != 0) {
3353 		/*
3354 		 * We already removed this blob from the blobstore tailq, so
3355 		 *  we need to free it here since this is the last reference
3356 		 *  to it.
3357 		 */
3358 		_spdk_blob_free(blob);
3359 		_spdk_bs_delete_close_cpl(seq, bserrno);
3360 		return;
3361 	}
3362 
3363 	/*
3364 	 * This will immediately decrement the ref_count and call
3365 	 *  the completion routine since the metadata state is clean.
3366 	 *  By calling spdk_blob_close, we reduce the number of call
3367 	 *  points into code that touches the blob->open_ref count
3368 	 *  and the blobstore's blob list.
3369 	 */
3370 	spdk_blob_close(_blob, _spdk_bs_delete_close_cpl, seq);
3371 }
3372 
3373 static void
3374 _spdk_bs_delete_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
3375 {
3376 	spdk_bs_sequence_t *seq = cb_arg;
3377 	struct spdk_blob_data *blob = __blob_to_data(_blob);
3378 	uint32_t page_num;
3379 
3380 	if (bserrno != 0) {
3381 		spdk_bs_sequence_finish(seq, bserrno);
3382 		return;
3383 	}
3384 
3385 	if (blob->open_ref > 1) {
3386 		/*
3387 		 * Someone has this blob open (besides this delete context).
3388 		 *  Decrement the ref count directly and return -EBUSY.
3389 		 */
3390 		blob->open_ref--;
3391 		spdk_bs_sequence_finish(seq, -EBUSY);
3392 		return;
3393 	}
3394 
3395 	/*
3396 	 * Remove the blob from the blob_store list now, to ensure it does not
3397 	 *  get returned after this point by _spdk_blob_lookup().
3398 	 */
3399 	TAILQ_REMOVE(&blob->bs->blobs, blob, link);
3400 	page_num = _spdk_bs_blobid_to_page(blob->id);
3401 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
3402 	blob->state = SPDK_BLOB_STATE_DIRTY;
3403 	blob->active.num_pages = 0;
3404 	_spdk_resize_blob(blob, 0);
3405 
3406 	_spdk_blob_persist(seq, blob, _spdk_bs_delete_persist_cpl, _blob);
3407 }
3408 
3409 void
3410 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
3411 		    spdk_blob_op_complete cb_fn, void *cb_arg)
3412 {
3413 	struct spdk_bs_cpl	cpl;
3414 	spdk_bs_sequence_t 	*seq;
3415 
3416 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Deleting blob %lu\n", blobid);
3417 
3418 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
3419 	cpl.u.blob_basic.cb_fn = cb_fn;
3420 	cpl.u.blob_basic.cb_arg = cb_arg;
3421 
3422 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3423 	if (!seq) {
3424 		cb_fn(cb_arg, -ENOMEM);
3425 		return;
3426 	}
3427 
3428 	spdk_bs_open_blob(bs, blobid, _spdk_bs_delete_open_cpl, seq);
3429 }
3430 
3431 /* END spdk_bs_delete_blob */
3432 
3433 /* START spdk_bs_open_blob */
3434 
3435 static void
3436 _spdk_bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3437 {
3438 	struct spdk_blob_data *blob = cb_arg;
3439 
3440 	/* If the blob have crc error, we just return NULL. */
3441 	if (blob == NULL) {
3442 		seq->cpl.u.blob_handle.blob = NULL;
3443 		spdk_bs_sequence_finish(seq, bserrno);
3444 		return;
3445 	}
3446 
3447 	blob->open_ref++;
3448 
3449 	TAILQ_INSERT_HEAD(&blob->bs->blobs, blob, link);
3450 
3451 	spdk_bs_sequence_finish(seq, bserrno);
3452 }
3453 
3454 void spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
3455 		       spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
3456 {
3457 	struct spdk_blob_data		*blob;
3458 	struct spdk_bs_cpl		cpl;
3459 	spdk_bs_sequence_t		*seq;
3460 	uint32_t			page_num;
3461 
3462 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Opening blob %lu\n", blobid);
3463 
3464 	page_num = _spdk_bs_blobid_to_page(blobid);
3465 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
3466 		/* Invalid blobid */
3467 		cb_fn(cb_arg, NULL, -ENOENT);
3468 		return;
3469 	}
3470 
3471 	blob = _spdk_blob_lookup(bs, blobid);
3472 	if (blob) {
3473 		blob->open_ref++;
3474 		cb_fn(cb_arg, __data_to_blob(blob), 0);
3475 		return;
3476 	}
3477 
3478 	blob = _spdk_blob_alloc(bs, blobid);
3479 	if (!blob) {
3480 		cb_fn(cb_arg, NULL, -ENOMEM);
3481 		return;
3482 	}
3483 
3484 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
3485 	cpl.u.blob_handle.cb_fn = cb_fn;
3486 	cpl.u.blob_handle.cb_arg = cb_arg;
3487 	cpl.u.blob_handle.blob = __data_to_blob(blob);
3488 
3489 	seq = spdk_bs_sequence_start(bs->md_channel, &cpl);
3490 	if (!seq) {
3491 		_spdk_blob_free(blob);
3492 		cb_fn(cb_arg, NULL, -ENOMEM);
3493 		return;
3494 	}
3495 
3496 	_spdk_blob_load(seq, blob, _spdk_bs_open_blob_cpl, blob);
3497 }
3498 /* END spdk_bs_open_blob */
3499 
3500 /* START spdk_blob_set_read_only */
3501 void spdk_blob_set_read_only(struct spdk_blob *b)
3502 {
3503 	struct spdk_blob_data *blob = __blob_to_data(b);
3504 
3505 	assert(spdk_get_thread() == blob->bs->md_thread);
3506 
3507 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
3508 
3509 	blob->state = SPDK_BLOB_STATE_DIRTY;
3510 }
3511 /* END spdk_blob_set_read_only */
3512 
3513 /* START spdk_blob_sync_md */
3514 
3515 static void
3516 _spdk_blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3517 {
3518 	struct spdk_blob_data *blob = __blob_to_data(cb_arg);
3519 
3520 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
3521 		blob->data_ro = true;
3522 		blob->md_ro = true;
3523 	}
3524 
3525 	spdk_bs_sequence_finish(seq, bserrno);
3526 }
3527 
3528 static void
3529 _spdk_blob_sync_md(struct spdk_blob_data *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
3530 {
3531 	struct spdk_bs_cpl	cpl;
3532 	spdk_bs_sequence_t	*seq;
3533 
3534 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
3535 	cpl.u.blob_basic.cb_fn = cb_fn;
3536 	cpl.u.blob_basic.cb_arg = cb_arg;
3537 
3538 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
3539 	if (!seq) {
3540 		cb_fn(cb_arg, -ENOMEM);
3541 		return;
3542 	}
3543 
3544 	_spdk_blob_persist(seq, blob, _spdk_blob_sync_md_cpl, blob);
3545 }
3546 
3547 void
3548 spdk_blob_sync_md(struct spdk_blob *_blob, spdk_blob_op_complete cb_fn, void *cb_arg)
3549 {
3550 	struct spdk_blob_data	*blob = __blob_to_data(_blob);
3551 
3552 	assert(blob != NULL);
3553 	assert(spdk_get_thread() == blob->bs->md_thread);
3554 
3555 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blob %lu\n", blob->id);
3556 
3557 	assert(blob->state != SPDK_BLOB_STATE_LOADING &&
3558 	       blob->state != SPDK_BLOB_STATE_SYNCING);
3559 
3560 	if (blob->md_ro) {
3561 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
3562 		cb_fn(cb_arg, 0);
3563 		return;
3564 	}
3565 
3566 	if (blob->state == SPDK_BLOB_STATE_CLEAN) {
3567 		cb_fn(cb_arg, 0);
3568 		return;
3569 	}
3570 
3571 	_spdk_blob_sync_md(blob, cb_fn, cb_arg);
3572 }
3573 
3574 /* END spdk_blob_sync_md */
3575 
3576 struct spdk_blob_insert_cluster_ctx {
3577 	struct spdk_thread	*thread;
3578 	struct spdk_blob_data	*blob;
3579 	uint32_t		cluster_num;	/* cluster index in blob */
3580 	uint32_t		cluster;	/* cluster on disk */
3581 	int			rc;
3582 	spdk_blob_op_complete	cb_fn;
3583 	void			*cb_arg;
3584 };
3585 
3586 static void
3587 _spdk_blob_insert_cluster_msg_cpl(void *arg)
3588 {
3589 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
3590 
3591 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
3592 	free(ctx);
3593 }
3594 
3595 static void
3596 _spdk_blob_insert_cluster_msg_cb(void *arg, int bserrno)
3597 {
3598 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
3599 
3600 	ctx->rc = bserrno;
3601 	spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
3602 }
3603 
3604 static void
3605 _spdk_blob_insert_cluster_msg(void *arg)
3606 {
3607 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
3608 
3609 	ctx->rc = _spdk_blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
3610 	if (ctx->rc != 0) {
3611 		spdk_thread_send_msg(ctx->thread, _spdk_blob_insert_cluster_msg_cpl, ctx);
3612 		return;
3613 	}
3614 
3615 	ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
3616 	_spdk_blob_sync_md(ctx->blob, _spdk_blob_insert_cluster_msg_cb, ctx);
3617 }
3618 
3619 void
3620 _spdk_blob_insert_cluster_on_md_thread(struct spdk_blob_data *blob, uint32_t cluster_num,
3621 				       uint64_t cluster, spdk_blob_op_complete cb_fn, void *cb_arg)
3622 {
3623 	struct spdk_blob_insert_cluster_ctx *ctx;
3624 
3625 	ctx = calloc(1, sizeof(*ctx));
3626 	if (ctx == NULL) {
3627 		cb_fn(cb_arg, -ENOMEM);
3628 		return;
3629 	}
3630 
3631 	ctx->thread = spdk_get_thread();
3632 	ctx->blob = blob;
3633 	ctx->cluster_num = cluster_num;
3634 	ctx->cluster = cluster;
3635 	ctx->cb_fn = cb_fn;
3636 	ctx->cb_arg = cb_arg;
3637 
3638 	spdk_thread_send_msg(blob->bs->md_thread, _spdk_blob_insert_cluster_msg, ctx);
3639 }
3640 
3641 /* START spdk_blob_close */
3642 
3643 static void
3644 _spdk_blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3645 {
3646 	struct spdk_blob_data *blob = cb_arg;
3647 
3648 	if (bserrno == 0) {
3649 		blob->open_ref--;
3650 		if (blob->open_ref == 0) {
3651 			/*
3652 			 * Blobs with active.num_pages == 0 are deleted blobs.
3653 			 *  these blobs are removed from the blob_store list
3654 			 *  when the deletion process starts - so don't try to
3655 			 *  remove them again.
3656 			 */
3657 			if (blob->active.num_pages > 0) {
3658 				TAILQ_REMOVE(&blob->bs->blobs, blob, link);
3659 			}
3660 			_spdk_blob_free(blob);
3661 		}
3662 	}
3663 
3664 	spdk_bs_sequence_finish(seq, bserrno);
3665 }
3666 
3667 void spdk_blob_close(struct spdk_blob *b, spdk_blob_op_complete cb_fn, void *cb_arg)
3668 {
3669 	struct spdk_bs_cpl	cpl;
3670 	struct spdk_blob_data	*blob;
3671 	spdk_bs_sequence_t	*seq;
3672 
3673 	assert(b != NULL);
3674 	blob = __blob_to_data(b);
3675 	assert(blob != NULL);
3676 	assert(spdk_get_thread() == blob->bs->md_thread);
3677 
3678 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Closing blob %lu\n", blob->id);
3679 
3680 	assert(blob->state != SPDK_BLOB_STATE_LOADING &&
3681 	       blob->state != SPDK_BLOB_STATE_SYNCING);
3682 
3683 	if (blob->open_ref == 0) {
3684 		cb_fn(cb_arg, -EBADF);
3685 		return;
3686 	}
3687 
3688 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
3689 	cpl.u.blob_basic.cb_fn = cb_fn;
3690 	cpl.u.blob_basic.cb_arg = cb_arg;
3691 
3692 	seq = spdk_bs_sequence_start(blob->bs->md_channel, &cpl);
3693 	if (!seq) {
3694 		cb_fn(cb_arg, -ENOMEM);
3695 		return;
3696 	}
3697 
3698 	if (blob->state == SPDK_BLOB_STATE_CLEAN) {
3699 		_spdk_blob_close_cpl(seq, blob, 0);
3700 		return;
3701 	}
3702 
3703 	/* Sync metadata */
3704 	_spdk_blob_persist(seq, blob, _spdk_blob_close_cpl, blob);
3705 }
3706 
3707 /* END spdk_blob_close */
3708 
3709 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
3710 {
3711 	return spdk_get_io_channel(bs);
3712 }
3713 
3714 void spdk_bs_free_io_channel(struct spdk_io_channel *channel)
3715 {
3716 	spdk_put_io_channel(channel);
3717 }
3718 
3719 void spdk_bs_io_unmap_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3720 			   uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
3721 {
3722 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
3723 				     SPDK_BLOB_UNMAP);
3724 }
3725 
3726 void spdk_bs_io_write_zeroes_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3727 				  uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
3728 {
3729 	_spdk_blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
3730 				     SPDK_BLOB_WRITE_ZEROES);
3731 }
3732 
3733 void spdk_bs_io_write_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3734 			   void *payload, uint64_t offset, uint64_t length,
3735 			   spdk_blob_op_complete cb_fn, void *cb_arg)
3736 {
3737 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
3738 				     SPDK_BLOB_WRITE);
3739 }
3740 
3741 void spdk_bs_io_read_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3742 			  void *payload, uint64_t offset, uint64_t length,
3743 			  spdk_blob_op_complete cb_fn, void *cb_arg)
3744 {
3745 	_spdk_blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
3746 				     SPDK_BLOB_READ);
3747 }
3748 
3749 void spdk_bs_io_writev_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3750 			    struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
3751 			    spdk_blob_op_complete cb_fn, void *cb_arg)
3752 {
3753 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false);
3754 }
3755 
3756 void spdk_bs_io_readv_blob(struct spdk_blob *blob, struct spdk_io_channel *channel,
3757 			   struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
3758 			   spdk_blob_op_complete cb_fn, void *cb_arg)
3759 {
3760 	_spdk_blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true);
3761 }
3762 
3763 struct spdk_bs_iter_ctx {
3764 	int64_t page_num;
3765 	struct spdk_blob_store *bs;
3766 
3767 	spdk_blob_op_with_handle_complete cb_fn;
3768 	void *cb_arg;
3769 };
3770 
3771 static void
3772 _spdk_bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
3773 {
3774 	struct spdk_bs_iter_ctx *ctx = cb_arg;
3775 	struct spdk_blob_store *bs = ctx->bs;
3776 	spdk_blob_id id;
3777 
3778 	if (bserrno == 0) {
3779 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
3780 		free(ctx);
3781 		return;
3782 	}
3783 
3784 	ctx->page_num++;
3785 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
3786 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
3787 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
3788 		free(ctx);
3789 		return;
3790 	}
3791 
3792 	id = _spdk_bs_page_to_blobid(ctx->page_num);
3793 
3794 	spdk_bs_open_blob(bs, id, _spdk_bs_iter_cpl, ctx);
3795 }
3796 
3797 void
3798 spdk_bs_iter_first(struct spdk_blob_store *bs,
3799 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
3800 {
3801 	struct spdk_bs_iter_ctx *ctx;
3802 
3803 	ctx = calloc(1, sizeof(*ctx));
3804 	if (!ctx) {
3805 		cb_fn(cb_arg, NULL, -ENOMEM);
3806 		return;
3807 	}
3808 
3809 	ctx->page_num = -1;
3810 	ctx->bs = bs;
3811 	ctx->cb_fn = cb_fn;
3812 	ctx->cb_arg = cb_arg;
3813 
3814 	_spdk_bs_iter_cpl(ctx, NULL, -1);
3815 }
3816 
3817 static void
3818 _spdk_bs_iter_close_cpl(void *cb_arg, int bserrno)
3819 {
3820 	struct spdk_bs_iter_ctx *ctx = cb_arg;
3821 
3822 	_spdk_bs_iter_cpl(ctx, NULL, -1);
3823 }
3824 
3825 void
3826 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *b,
3827 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
3828 {
3829 	struct spdk_bs_iter_ctx *ctx;
3830 	struct spdk_blob_data	*blob;
3831 
3832 	assert(b != NULL);
3833 	blob = __blob_to_data(b);
3834 	assert(blob != NULL);
3835 
3836 	ctx = calloc(1, sizeof(*ctx));
3837 	if (!ctx) {
3838 		cb_fn(cb_arg, NULL, -ENOMEM);
3839 		return;
3840 	}
3841 
3842 	ctx->page_num = _spdk_bs_blobid_to_page(blob->id);
3843 	ctx->bs = bs;
3844 	ctx->cb_fn = cb_fn;
3845 	ctx->cb_arg = cb_arg;
3846 
3847 	/* Close the existing blob */
3848 	spdk_blob_close(b, _spdk_bs_iter_close_cpl, ctx);
3849 }
3850 
3851 static int
3852 _spdk_blob_set_xattr(struct spdk_blob_data *blob, const char *name, const void *value,
3853 		     uint16_t value_len, bool internal)
3854 {
3855 	struct spdk_xattr_tailq *xattrs;
3856 	struct spdk_xattr 	*xattr;
3857 
3858 	assert(blob != NULL);
3859 
3860 	assert(blob->state != SPDK_BLOB_STATE_LOADING &&
3861 	       blob->state != SPDK_BLOB_STATE_SYNCING);
3862 
3863 	if (blob->md_ro) {
3864 		return -EPERM;
3865 	}
3866 
3867 	if (internal) {
3868 		xattrs = &blob->xattrs_internal;
3869 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
3870 	} else {
3871 		xattrs = &blob->xattrs;
3872 	}
3873 
3874 	TAILQ_FOREACH(xattr, xattrs, link) {
3875 		if (!strcmp(name, xattr->name)) {
3876 			free(xattr->value);
3877 			xattr->value_len = value_len;
3878 			xattr->value = malloc(value_len);
3879 			memcpy(xattr->value, value, value_len);
3880 
3881 			blob->state = SPDK_BLOB_STATE_DIRTY;
3882 
3883 			return 0;
3884 		}
3885 	}
3886 
3887 	xattr = calloc(1, sizeof(*xattr));
3888 	if (!xattr) {
3889 		return -1;
3890 	}
3891 	xattr->name = strdup(name);
3892 	xattr->value_len = value_len;
3893 	xattr->value = malloc(value_len);
3894 	memcpy(xattr->value, value, value_len);
3895 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
3896 
3897 	blob->state = SPDK_BLOB_STATE_DIRTY;
3898 
3899 	return 0;
3900 }
3901 
3902 int
3903 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
3904 		    uint16_t value_len)
3905 {
3906 	return _spdk_blob_set_xattr(__blob_to_data(blob), name, value, value_len, false);
3907 }
3908 
3909 static int
3910 _spdk_blob_remove_xattr(struct spdk_blob_data *blob, const char *name, bool internal)
3911 {
3912 	struct spdk_xattr_tailq *xattrs;
3913 	struct spdk_xattr	*xattr;
3914 
3915 	assert(blob != NULL);
3916 
3917 	assert(blob->state != SPDK_BLOB_STATE_LOADING &&
3918 	       blob->state != SPDK_BLOB_STATE_SYNCING);
3919 
3920 	if (blob->md_ro) {
3921 		return -EPERM;
3922 	}
3923 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
3924 
3925 	TAILQ_FOREACH(xattr, xattrs, link) {
3926 		if (!strcmp(name, xattr->name)) {
3927 			TAILQ_REMOVE(xattrs, xattr, link);
3928 			free(xattr->value);
3929 			free(xattr->name);
3930 			free(xattr);
3931 
3932 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
3933 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
3934 			}
3935 			blob->state = SPDK_BLOB_STATE_DIRTY;
3936 
3937 			return 0;
3938 		}
3939 	}
3940 
3941 	return -ENOENT;
3942 }
3943 
3944 int
3945 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
3946 {
3947 	return _spdk_blob_remove_xattr(__blob_to_data(blob), name, false);
3948 }
3949 
3950 static int
3951 _spdk_blob_get_xattr_value(struct spdk_blob_data *blob, const char *name,
3952 			   const void **value, size_t *value_len, bool internal)
3953 {
3954 	struct spdk_xattr	*xattr;
3955 	struct spdk_xattr_tailq *xattrs;
3956 
3957 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
3958 
3959 	TAILQ_FOREACH(xattr, xattrs, link) {
3960 		if (!strcmp(name, xattr->name)) {
3961 			*value = xattr->value;
3962 			*value_len = xattr->value_len;
3963 			return 0;
3964 		}
3965 	}
3966 	return -ENOENT;
3967 }
3968 
3969 int
3970 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
3971 			  const void **value, size_t *value_len)
3972 {
3973 	return _spdk_blob_get_xattr_value(__blob_to_data(blob), name, value, value_len, false);
3974 }
3975 
3976 struct spdk_xattr_names {
3977 	uint32_t	count;
3978 	const char	*names[0];
3979 };
3980 
3981 static int
3982 _spdk_blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
3983 {
3984 	struct spdk_xattr	*xattr;
3985 	int			count = 0;
3986 
3987 	TAILQ_FOREACH(xattr, xattrs, link) {
3988 		count++;
3989 	}
3990 
3991 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
3992 	if (*names == NULL) {
3993 		return -ENOMEM;
3994 	}
3995 
3996 	TAILQ_FOREACH(xattr, xattrs, link) {
3997 		(*names)->names[(*names)->count++] = xattr->name;
3998 	}
3999 
4000 	return 0;
4001 }
4002 
4003 int
4004 spdk_blob_get_xattr_names(struct spdk_blob *_blob, struct spdk_xattr_names **names)
4005 {
4006 	return _spdk_blob_get_xattr_names(&__blob_to_data(_blob)->xattrs, names);
4007 }
4008 
4009 uint32_t
4010 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
4011 {
4012 	assert(names != NULL);
4013 
4014 	return names->count;
4015 }
4016 
4017 const char *
4018 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
4019 {
4020 	if (index >= names->count) {
4021 		return NULL;
4022 	}
4023 
4024 	return names->names[index];
4025 }
4026 
4027 void
4028 spdk_xattr_names_free(struct spdk_xattr_names *names)
4029 {
4030 	free(names);
4031 }
4032 
4033 struct spdk_bs_type
4034 spdk_bs_get_bstype(struct spdk_blob_store *bs)
4035 {
4036 	return bs->bstype;
4037 }
4038 
4039 void
4040 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
4041 {
4042 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
4043 }
4044 
4045 SPDK_LOG_REGISTER_COMPONENT("blob", SPDK_LOG_BLOB)
4046