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