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