xref: /spdk/lib/blob/blobstore.c (revision 34cbbf3bf06841b4eea3fcafec3f062ff6cc585a)
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 #include "spdk/string.h"
45 
46 #include "spdk_internal/assert.h"
47 #include "spdk_internal/log.h"
48 
49 #include "blobstore.h"
50 
51 #define BLOB_CRC32C_INITIAL    0xffffffffUL
52 
53 static int bs_register_md_thread(struct spdk_blob_store *bs);
54 static int bs_unregister_md_thread(struct spdk_blob_store *bs);
55 static void blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno);
56 static void blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
57 		uint64_t cluster, uint32_t extent, spdk_blob_op_complete cb_fn, void *cb_arg);
58 
59 static int blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
60 			  uint16_t value_len, bool internal);
61 static int blob_get_xattr_value(struct spdk_blob *blob, const char *name,
62 				const void **value, size_t *value_len, bool internal);
63 static int blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal);
64 
65 static void blob_insert_extent(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
66 			       spdk_blob_op_complete cb_fn, void *cb_arg);
67 
68 static void
69 blob_verify_md_op(struct spdk_blob *blob)
70 {
71 	assert(blob != NULL);
72 	assert(spdk_get_thread() == blob->bs->md_thread);
73 	assert(blob->state != SPDK_BLOB_STATE_LOADING);
74 }
75 
76 static struct spdk_blob_list *
77 bs_get_snapshot_entry(struct spdk_blob_store *bs, spdk_blob_id blobid)
78 {
79 	struct spdk_blob_list *snapshot_entry = NULL;
80 
81 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
82 		if (snapshot_entry->id == blobid) {
83 			break;
84 		}
85 	}
86 
87 	return snapshot_entry;
88 }
89 
90 static void
91 bs_claim_md_page(struct spdk_blob_store *bs, uint32_t page)
92 {
93 	assert(page < spdk_bit_array_capacity(bs->used_md_pages));
94 	assert(spdk_bit_array_get(bs->used_md_pages, page) == false);
95 
96 	spdk_bit_array_set(bs->used_md_pages, page);
97 }
98 
99 static void
100 bs_release_md_page(struct spdk_blob_store *bs, uint32_t page)
101 {
102 	assert(page < spdk_bit_array_capacity(bs->used_md_pages));
103 	assert(spdk_bit_array_get(bs->used_md_pages, page) == true);
104 
105 	spdk_bit_array_clear(bs->used_md_pages, page);
106 }
107 
108 static void
109 bs_claim_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
110 {
111 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
112 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == false);
113 	assert(bs->num_free_clusters > 0);
114 
115 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %u\n", cluster_num);
116 
117 	spdk_bit_array_set(bs->used_clusters, cluster_num);
118 	bs->num_free_clusters--;
119 }
120 
121 static int
122 blob_insert_cluster(struct spdk_blob *blob, uint32_t cluster_num, uint64_t cluster)
123 {
124 	uint64_t *cluster_lba = &blob->active.clusters[cluster_num];
125 
126 	blob_verify_md_op(blob);
127 
128 	if (*cluster_lba != 0) {
129 		return -EEXIST;
130 	}
131 
132 	*cluster_lba = bs_cluster_to_lba(blob->bs, cluster);
133 	return 0;
134 }
135 
136 static int
137 bs_allocate_cluster(struct spdk_blob *blob, uint32_t cluster_num,
138 		    uint64_t *lowest_free_cluster, uint32_t *lowest_free_md_page, bool update_map)
139 {
140 	uint32_t *extent_page = 0;
141 
142 	pthread_mutex_lock(&blob->bs->used_clusters_mutex);
143 	*lowest_free_cluster = spdk_bit_array_find_first_clear(blob->bs->used_clusters,
144 			       *lowest_free_cluster);
145 	if (*lowest_free_cluster == UINT32_MAX) {
146 		/* No more free clusters. Cannot satisfy the request */
147 		pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
148 		return -ENOSPC;
149 	}
150 
151 	if (blob->use_extent_table) {
152 		extent_page = bs_cluster_to_extent_page(blob, cluster_num);
153 		if (*extent_page == 0) {
154 			/* No extent_page is allocated for the cluster */
155 			*lowest_free_md_page = spdk_bit_array_find_first_clear(blob->bs->used_md_pages,
156 					       *lowest_free_md_page);
157 			if (*lowest_free_md_page == UINT32_MAX) {
158 				/* No more free md pages. Cannot satisfy the request */
159 				pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
160 				return -ENOSPC;
161 			}
162 			bs_claim_md_page(blob->bs, *lowest_free_md_page);
163 		}
164 	}
165 
166 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming cluster %lu for blob %lu\n", *lowest_free_cluster, blob->id);
167 	bs_claim_cluster(blob->bs, *lowest_free_cluster);
168 
169 	pthread_mutex_unlock(&blob->bs->used_clusters_mutex);
170 
171 	if (update_map) {
172 		blob_insert_cluster(blob, cluster_num, *lowest_free_cluster);
173 		if (blob->use_extent_table && *extent_page == 0) {
174 			*extent_page = *lowest_free_md_page;
175 		}
176 	}
177 
178 	return 0;
179 }
180 
181 static void
182 bs_release_cluster(struct spdk_blob_store *bs, uint32_t cluster_num)
183 {
184 	assert(cluster_num < spdk_bit_array_capacity(bs->used_clusters));
185 	assert(spdk_bit_array_get(bs->used_clusters, cluster_num) == true);
186 	assert(bs->num_free_clusters < bs->total_clusters);
187 
188 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Releasing cluster %u\n", cluster_num);
189 
190 	pthread_mutex_lock(&bs->used_clusters_mutex);
191 	spdk_bit_array_clear(bs->used_clusters, cluster_num);
192 	bs->num_free_clusters++;
193 	pthread_mutex_unlock(&bs->used_clusters_mutex);
194 }
195 
196 static void
197 blob_xattrs_init(struct spdk_blob_xattr_opts *xattrs)
198 {
199 	xattrs->count = 0;
200 	xattrs->names = NULL;
201 	xattrs->ctx = NULL;
202 	xattrs->get_value = NULL;
203 }
204 
205 void
206 spdk_blob_opts_init(struct spdk_blob_opts *opts)
207 {
208 	opts->num_clusters = 0;
209 	opts->thin_provision = false;
210 	opts->clear_method = BLOB_CLEAR_WITH_DEFAULT;
211 	blob_xattrs_init(&opts->xattrs);
212 	opts->use_extent_table = true;
213 }
214 
215 void
216 spdk_blob_open_opts_init(struct spdk_blob_open_opts *opts)
217 {
218 	opts->clear_method = BLOB_CLEAR_WITH_DEFAULT;
219 }
220 
221 static struct spdk_blob *
222 blob_alloc(struct spdk_blob_store *bs, spdk_blob_id id)
223 {
224 	struct spdk_blob *blob;
225 
226 	blob = calloc(1, sizeof(*blob));
227 	if (!blob) {
228 		return NULL;
229 	}
230 
231 	blob->id = id;
232 	blob->bs = bs;
233 
234 	blob->parent_id = SPDK_BLOBID_INVALID;
235 
236 	blob->state = SPDK_BLOB_STATE_DIRTY;
237 	blob->extent_rle_found = false;
238 	blob->extent_table_found = false;
239 	blob->active.num_pages = 1;
240 	blob->active.pages = calloc(1, sizeof(*blob->active.pages));
241 	if (!blob->active.pages) {
242 		free(blob);
243 		return NULL;
244 	}
245 
246 	blob->active.pages[0] = bs_blobid_to_page(id);
247 
248 	TAILQ_INIT(&blob->xattrs);
249 	TAILQ_INIT(&blob->xattrs_internal);
250 	TAILQ_INIT(&blob->pending_persists);
251 
252 	return blob;
253 }
254 
255 static void
256 xattrs_free(struct spdk_xattr_tailq *xattrs)
257 {
258 	struct spdk_xattr	*xattr, *xattr_tmp;
259 
260 	TAILQ_FOREACH_SAFE(xattr, xattrs, link, xattr_tmp) {
261 		TAILQ_REMOVE(xattrs, xattr, link);
262 		free(xattr->name);
263 		free(xattr->value);
264 		free(xattr);
265 	}
266 }
267 
268 static void
269 blob_free(struct spdk_blob *blob)
270 {
271 	assert(blob != NULL);
272 	assert(TAILQ_EMPTY(&blob->pending_persists));
273 
274 	free(blob->active.extent_pages);
275 	free(blob->clean.extent_pages);
276 	free(blob->active.clusters);
277 	free(blob->clean.clusters);
278 	free(blob->active.pages);
279 	free(blob->clean.pages);
280 
281 	xattrs_free(&blob->xattrs);
282 	xattrs_free(&blob->xattrs_internal);
283 
284 	if (blob->back_bs_dev) {
285 		blob->back_bs_dev->destroy(blob->back_bs_dev);
286 	}
287 
288 	free(blob);
289 }
290 
291 struct freeze_io_ctx {
292 	struct spdk_bs_cpl cpl;
293 	struct spdk_blob *blob;
294 };
295 
296 static void
297 blob_io_sync(struct spdk_io_channel_iter *i)
298 {
299 	spdk_for_each_channel_continue(i, 0);
300 }
301 
302 static void
303 blob_execute_queued_io(struct spdk_io_channel_iter *i)
304 {
305 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
306 	struct spdk_bs_channel *ch = spdk_io_channel_get_ctx(_ch);
307 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
308 	struct spdk_bs_request_set	*set;
309 	struct spdk_bs_user_op_args	*args;
310 	spdk_bs_user_op_t *op, *tmp;
311 
312 	TAILQ_FOREACH_SAFE(op, &ch->queued_io, link, tmp) {
313 		set = (struct spdk_bs_request_set *)op;
314 		args = &set->u.user_op;
315 
316 		if (args->blob == ctx->blob) {
317 			TAILQ_REMOVE(&ch->queued_io, op, link);
318 			bs_user_op_execute(op);
319 		}
320 	}
321 
322 	spdk_for_each_channel_continue(i, 0);
323 }
324 
325 static void
326 blob_io_cpl(struct spdk_io_channel_iter *i, int status)
327 {
328 	struct freeze_io_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
329 
330 	ctx->cpl.u.blob_basic.cb_fn(ctx->cpl.u.blob_basic.cb_arg, 0);
331 
332 	free(ctx);
333 }
334 
335 static void
336 blob_freeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
337 {
338 	struct freeze_io_ctx *ctx;
339 
340 	ctx = calloc(1, sizeof(*ctx));
341 	if (!ctx) {
342 		cb_fn(cb_arg, -ENOMEM);
343 		return;
344 	}
345 
346 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
347 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
348 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
349 	ctx->blob = blob;
350 
351 	/* Freeze I/O on blob */
352 	blob->frozen_refcnt++;
353 
354 	if (blob->frozen_refcnt == 1) {
355 		spdk_for_each_channel(blob->bs, blob_io_sync, ctx, blob_io_cpl);
356 	} else {
357 		cb_fn(cb_arg, 0);
358 		free(ctx);
359 	}
360 }
361 
362 static void
363 blob_unfreeze_io(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
364 {
365 	struct freeze_io_ctx *ctx;
366 
367 	ctx = calloc(1, sizeof(*ctx));
368 	if (!ctx) {
369 		cb_fn(cb_arg, -ENOMEM);
370 		return;
371 	}
372 
373 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
374 	ctx->cpl.u.blob_basic.cb_fn = cb_fn;
375 	ctx->cpl.u.blob_basic.cb_arg = cb_arg;
376 	ctx->blob = blob;
377 
378 	assert(blob->frozen_refcnt > 0);
379 
380 	blob->frozen_refcnt--;
381 
382 	if (blob->frozen_refcnt == 0) {
383 		spdk_for_each_channel(blob->bs, blob_execute_queued_io, ctx, blob_io_cpl);
384 	} else {
385 		cb_fn(cb_arg, 0);
386 		free(ctx);
387 	}
388 }
389 
390 static int
391 blob_mark_clean(struct spdk_blob *blob)
392 {
393 	uint32_t *extent_pages = NULL;
394 	uint64_t *clusters = NULL;
395 	uint32_t *pages = NULL;
396 
397 	assert(blob != NULL);
398 
399 	if (blob->active.num_extent_pages) {
400 		assert(blob->active.extent_pages);
401 		extent_pages = calloc(blob->active.num_extent_pages, sizeof(*blob->active.extent_pages));
402 		if (!extent_pages) {
403 			return -ENOMEM;
404 		}
405 		memcpy(extent_pages, blob->active.extent_pages,
406 		       blob->active.num_extent_pages * sizeof(*extent_pages));
407 	}
408 
409 	if (blob->active.num_clusters) {
410 		assert(blob->active.clusters);
411 		clusters = calloc(blob->active.num_clusters, sizeof(*blob->active.clusters));
412 		if (!clusters) {
413 			free(extent_pages);
414 			return -ENOMEM;
415 		}
416 		memcpy(clusters, blob->active.clusters, blob->active.num_clusters * sizeof(*blob->active.clusters));
417 	}
418 
419 	if (blob->active.num_pages) {
420 		assert(blob->active.pages);
421 		pages = calloc(blob->active.num_pages, sizeof(*blob->active.pages));
422 		if (!pages) {
423 			free(extent_pages);
424 			free(clusters);
425 			return -ENOMEM;
426 		}
427 		memcpy(pages, blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
428 	}
429 
430 	free(blob->clean.extent_pages);
431 	free(blob->clean.clusters);
432 	free(blob->clean.pages);
433 
434 	blob->clean.num_extent_pages = blob->active.num_extent_pages;
435 	blob->clean.extent_pages = blob->active.extent_pages;
436 	blob->clean.num_clusters = blob->active.num_clusters;
437 	blob->clean.clusters = blob->active.clusters;
438 	blob->clean.num_pages = blob->active.num_pages;
439 	blob->clean.pages = blob->active.pages;
440 
441 	blob->active.extent_pages = extent_pages;
442 	blob->active.clusters = clusters;
443 	blob->active.pages = pages;
444 
445 	/* If the metadata was dirtied again while the metadata was being written to disk,
446 	 *  we do not want to revert the DIRTY state back to CLEAN here.
447 	 */
448 	if (blob->state == SPDK_BLOB_STATE_LOADING) {
449 		blob->state = SPDK_BLOB_STATE_CLEAN;
450 	}
451 
452 	return 0;
453 }
454 
455 static int
456 blob_deserialize_xattr(struct spdk_blob *blob,
457 		       struct spdk_blob_md_descriptor_xattr *desc_xattr, bool internal)
458 {
459 	struct spdk_xattr                       *xattr;
460 
461 	if (desc_xattr->length != sizeof(desc_xattr->name_length) +
462 	    sizeof(desc_xattr->value_length) +
463 	    desc_xattr->name_length + desc_xattr->value_length) {
464 		return -EINVAL;
465 	}
466 
467 	xattr = calloc(1, sizeof(*xattr));
468 	if (xattr == NULL) {
469 		return -ENOMEM;
470 	}
471 
472 	xattr->name = malloc(desc_xattr->name_length + 1);
473 	if (xattr->name == NULL) {
474 		free(xattr);
475 		return -ENOMEM;
476 	}
477 	memcpy(xattr->name, desc_xattr->name, desc_xattr->name_length);
478 	xattr->name[desc_xattr->name_length] = '\0';
479 
480 	xattr->value = malloc(desc_xattr->value_length);
481 	if (xattr->value == NULL) {
482 		free(xattr->name);
483 		free(xattr);
484 		return -ENOMEM;
485 	}
486 	xattr->value_len = desc_xattr->value_length;
487 	memcpy(xattr->value,
488 	       (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
489 	       desc_xattr->value_length);
490 
491 	TAILQ_INSERT_TAIL(internal ? &blob->xattrs_internal : &blob->xattrs, xattr, link);
492 
493 	return 0;
494 }
495 
496 
497 static int
498 blob_parse_page(const struct spdk_blob_md_page *page, struct spdk_blob *blob)
499 {
500 	struct spdk_blob_md_descriptor *desc;
501 	size_t	cur_desc = 0;
502 	void *tmp;
503 
504 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
505 	while (cur_desc < sizeof(page->descriptors)) {
506 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
507 			if (desc->length == 0) {
508 				/* If padding and length are 0, this terminates the page */
509 				break;
510 			}
511 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
512 			struct spdk_blob_md_descriptor_flags	*desc_flags;
513 
514 			desc_flags = (struct spdk_blob_md_descriptor_flags *)desc;
515 
516 			if (desc_flags->length != sizeof(*desc_flags) - sizeof(*desc)) {
517 				return -EINVAL;
518 			}
519 
520 			if ((desc_flags->invalid_flags | SPDK_BLOB_INVALID_FLAGS_MASK) !=
521 			    SPDK_BLOB_INVALID_FLAGS_MASK) {
522 				return -EINVAL;
523 			}
524 
525 			if ((desc_flags->data_ro_flags | SPDK_BLOB_DATA_RO_FLAGS_MASK) !=
526 			    SPDK_BLOB_DATA_RO_FLAGS_MASK) {
527 				blob->data_ro = true;
528 				blob->md_ro = true;
529 			}
530 
531 			if ((desc_flags->md_ro_flags | SPDK_BLOB_MD_RO_FLAGS_MASK) !=
532 			    SPDK_BLOB_MD_RO_FLAGS_MASK) {
533 				blob->md_ro = true;
534 			}
535 
536 			if ((desc_flags->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
537 				blob->data_ro = true;
538 				blob->md_ro = true;
539 			}
540 
541 			blob->invalid_flags = desc_flags->invalid_flags;
542 			blob->data_ro_flags = desc_flags->data_ro_flags;
543 			blob->md_ro_flags = desc_flags->md_ro_flags;
544 
545 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
546 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
547 			unsigned int				i, j;
548 			unsigned int				cluster_count = blob->active.num_clusters;
549 
550 			if (blob->extent_table_found) {
551 				/* Extent Table already present in the md,
552 				 * both descriptors should never be at the same time. */
553 				return -EINVAL;
554 			}
555 			blob->extent_rle_found = true;
556 
557 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
558 
559 			if (desc_extent_rle->length == 0 ||
560 			    (desc_extent_rle->length % sizeof(desc_extent_rle->extents[0]) != 0)) {
561 				return -EINVAL;
562 			}
563 
564 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
565 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
566 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
567 						if (!spdk_bit_array_get(blob->bs->used_clusters,
568 									desc_extent_rle->extents[i].cluster_idx + j)) {
569 							return -EINVAL;
570 						}
571 					}
572 					cluster_count++;
573 				}
574 			}
575 
576 			if (cluster_count == 0) {
577 				return -EINVAL;
578 			}
579 			tmp = realloc(blob->active.clusters, cluster_count * sizeof(*blob->active.clusters));
580 			if (tmp == NULL) {
581 				return -ENOMEM;
582 			}
583 			blob->active.clusters = tmp;
584 			blob->active.cluster_array_size = cluster_count;
585 
586 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
587 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
588 					if (desc_extent_rle->extents[i].cluster_idx != 0) {
589 						blob->active.clusters[blob->active.num_clusters++] = bs_cluster_to_lba(blob->bs,
590 								desc_extent_rle->extents[i].cluster_idx + j);
591 					} else if (spdk_blob_is_thin_provisioned(blob)) {
592 						blob->active.clusters[blob->active.num_clusters++] = 0;
593 					} else {
594 						return -EINVAL;
595 					}
596 				}
597 			}
598 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE) {
599 			struct spdk_blob_md_descriptor_extent_table *desc_extent_table;
600 			uint32_t num_extent_pages = blob->active.num_extent_pages;
601 			uint32_t i, j;
602 			size_t extent_pages_length;
603 
604 			desc_extent_table = (struct spdk_blob_md_descriptor_extent_table *)desc;
605 			extent_pages_length = desc_extent_table->length - sizeof(desc_extent_table->num_clusters);
606 
607 			if (blob->extent_rle_found) {
608 				/* This means that Extent RLE is present in MD,
609 				 * both should never be at the same time. */
610 				return -EINVAL;
611 			} else if (blob->extent_table_found &&
612 				   desc_extent_table->num_clusters != blob->remaining_clusters_in_et) {
613 				/* Number of clusters in this ET does not match number
614 				 * from previously read EXTENT_TABLE. */
615 				return -EINVAL;
616 			}
617 
618 			blob->extent_table_found = true;
619 
620 			if (desc_extent_table->length == 0 ||
621 			    (extent_pages_length % sizeof(desc_extent_table->extent_page[0]) != 0)) {
622 				return -EINVAL;
623 			}
624 
625 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
626 				num_extent_pages += desc_extent_table->extent_page[i].num_pages;
627 			}
628 
629 			tmp = realloc(blob->active.extent_pages, num_extent_pages * sizeof(uint32_t));
630 			if (tmp == NULL) {
631 				return -ENOMEM;
632 			}
633 			blob->active.extent_pages = tmp;
634 			blob->active.extent_pages_array_size = num_extent_pages;
635 
636 			blob->remaining_clusters_in_et = desc_extent_table->num_clusters;
637 
638 			/* Extent table entries contain md page numbers for extent pages.
639 			 * Zeroes represent unallocated extent pages, those are run-length-encoded.
640 			 */
641 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
642 				if (desc_extent_table->extent_page[i].page_idx != 0) {
643 					assert(desc_extent_table->extent_page[i].num_pages == 1);
644 					blob->active.extent_pages[blob->active.num_extent_pages++] =
645 						desc_extent_table->extent_page[i].page_idx;
646 				} else if (spdk_blob_is_thin_provisioned(blob)) {
647 					for (j = 0; j < desc_extent_table->extent_page[i].num_pages; j++) {
648 						blob->active.extent_pages[blob->active.num_extent_pages++] = 0;
649 					}
650 				} else {
651 					return -EINVAL;
652 				}
653 			}
654 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
655 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
656 			unsigned int					i;
657 			unsigned int					cluster_count = 0;
658 			size_t						cluster_idx_length;
659 
660 			if (blob->extent_rle_found) {
661 				/* This means that Extent RLE is present in MD,
662 				 * both should never be at the same time. */
663 				return -EINVAL;
664 			}
665 
666 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
667 			cluster_idx_length = desc_extent->length - sizeof(desc_extent->start_cluster_idx);
668 
669 			if (desc_extent->length <= sizeof(desc_extent->start_cluster_idx) ||
670 			    (cluster_idx_length % sizeof(desc_extent->cluster_idx[0]) != 0)) {
671 				return -EINVAL;
672 			}
673 
674 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
675 				if (desc_extent->cluster_idx[i] != 0) {
676 					if (!spdk_bit_array_get(blob->bs->used_clusters, desc_extent->cluster_idx[i])) {
677 						return -EINVAL;
678 					}
679 				}
680 				cluster_count++;
681 			}
682 
683 			if (cluster_count == 0) {
684 				return -EINVAL;
685 			}
686 
687 			/* When reading extent pages sequentially starting cluster idx should match
688 			 * current size of a blob.
689 			 * If changed to batch reading, this check shall be removed. */
690 			if (desc_extent->start_cluster_idx != blob->active.num_clusters) {
691 				return -EINVAL;
692 			}
693 
694 			tmp = realloc(blob->active.clusters,
695 				      (cluster_count + blob->active.num_clusters) * sizeof(*blob->active.clusters));
696 			if (tmp == NULL) {
697 				return -ENOMEM;
698 			}
699 			blob->active.clusters = tmp;
700 			blob->active.cluster_array_size = (cluster_count + blob->active.num_clusters);
701 
702 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
703 				if (desc_extent->cluster_idx[i] != 0) {
704 					blob->active.clusters[blob->active.num_clusters++] = bs_cluster_to_lba(blob->bs,
705 							desc_extent->cluster_idx[i]);
706 				} else if (spdk_blob_is_thin_provisioned(blob)) {
707 					blob->active.clusters[blob->active.num_clusters++] = 0;
708 				} else {
709 					return -EINVAL;
710 				}
711 			}
712 			assert(desc_extent->start_cluster_idx + cluster_count == blob->active.num_clusters);
713 			assert(blob->remaining_clusters_in_et >= cluster_count);
714 			blob->remaining_clusters_in_et -= cluster_count;
715 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
716 			int rc;
717 
718 			rc = blob_deserialize_xattr(blob,
719 						    (struct spdk_blob_md_descriptor_xattr *) desc, false);
720 			if (rc != 0) {
721 				return rc;
722 			}
723 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
724 			int rc;
725 
726 			rc = blob_deserialize_xattr(blob,
727 						    (struct spdk_blob_md_descriptor_xattr *) desc, true);
728 			if (rc != 0) {
729 				return rc;
730 			}
731 		} else {
732 			/* Unrecognized descriptor type.  Do not fail - just continue to the
733 			 *  next descriptor.  If this descriptor is associated with some feature
734 			 *  defined in a newer version of blobstore, that version of blobstore
735 			 *  should create and set an associated feature flag to specify if this
736 			 *  blob can be loaded or not.
737 			 */
738 		}
739 
740 		/* Advance to the next descriptor */
741 		cur_desc += sizeof(*desc) + desc->length;
742 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
743 			break;
744 		}
745 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
746 	}
747 
748 	return 0;
749 }
750 
751 static bool bs_load_cur_extent_page_valid(struct spdk_blob_md_page *page);
752 
753 static int
754 blob_parse_extent_page(struct spdk_blob_md_page *extent_page, struct spdk_blob *blob)
755 {
756 	assert(blob != NULL);
757 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
758 
759 	if (bs_load_cur_extent_page_valid(extent_page) == false) {
760 		return -ENOENT;
761 	}
762 
763 	return blob_parse_page(extent_page, blob);
764 }
765 
766 static int
767 blob_parse(const struct spdk_blob_md_page *pages, uint32_t page_count,
768 	   struct spdk_blob *blob)
769 {
770 	const struct spdk_blob_md_page *page;
771 	uint32_t i;
772 	int rc;
773 
774 	assert(page_count > 0);
775 	assert(pages[0].sequence_num == 0);
776 	assert(blob != NULL);
777 	assert(blob->state == SPDK_BLOB_STATE_LOADING);
778 	assert(blob->active.clusters == NULL);
779 
780 	/* The blobid provided doesn't match what's in the MD, this can
781 	 * happen for example if a bogus blobid is passed in through open.
782 	 */
783 	if (blob->id != pages[0].id) {
784 		SPDK_ERRLOG("Blobid (%lu) doesn't match what's in metadata (%lu)\n",
785 			    blob->id, pages[0].id);
786 		return -ENOENT;
787 	}
788 
789 	for (i = 0; i < page_count; i++) {
790 		page = &pages[i];
791 
792 		assert(page->id == blob->id);
793 		assert(page->sequence_num == i);
794 
795 		rc = blob_parse_page(page, blob);
796 		if (rc != 0) {
797 			return rc;
798 		}
799 	}
800 
801 	return 0;
802 }
803 
804 static int
805 blob_serialize_add_page(const struct spdk_blob *blob,
806 			struct spdk_blob_md_page **pages,
807 			uint32_t *page_count,
808 			struct spdk_blob_md_page **last_page)
809 {
810 	struct spdk_blob_md_page *page;
811 
812 	assert(pages != NULL);
813 	assert(page_count != NULL);
814 
815 	if (*page_count == 0) {
816 		assert(*pages == NULL);
817 		*page_count = 1;
818 		*pages = spdk_malloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
819 				     NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
820 	} else {
821 		assert(*pages != NULL);
822 		(*page_count)++;
823 		*pages = spdk_realloc(*pages,
824 				      SPDK_BS_PAGE_SIZE * (*page_count),
825 				      SPDK_BS_PAGE_SIZE);
826 	}
827 
828 	if (*pages == NULL) {
829 		*page_count = 0;
830 		*last_page = NULL;
831 		return -ENOMEM;
832 	}
833 
834 	page = &(*pages)[*page_count - 1];
835 	memset(page, 0, sizeof(*page));
836 	page->id = blob->id;
837 	page->sequence_num = *page_count - 1;
838 	page->next = SPDK_INVALID_MD_PAGE;
839 	*last_page = page;
840 
841 	return 0;
842 }
843 
844 /* Transform the in-memory representation 'xattr' into an on-disk xattr descriptor.
845  * Update required_sz on both success and failure.
846  *
847  */
848 static int
849 blob_serialize_xattr(const struct spdk_xattr *xattr,
850 		     uint8_t *buf, size_t buf_sz,
851 		     size_t *required_sz, bool internal)
852 {
853 	struct spdk_blob_md_descriptor_xattr	*desc;
854 
855 	*required_sz = sizeof(struct spdk_blob_md_descriptor_xattr) +
856 		       strlen(xattr->name) +
857 		       xattr->value_len;
858 
859 	if (buf_sz < *required_sz) {
860 		return -1;
861 	}
862 
863 	desc = (struct spdk_blob_md_descriptor_xattr *)buf;
864 
865 	desc->type = internal ? SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL : SPDK_MD_DESCRIPTOR_TYPE_XATTR;
866 	desc->length = sizeof(desc->name_length) +
867 		       sizeof(desc->value_length) +
868 		       strlen(xattr->name) +
869 		       xattr->value_len;
870 	desc->name_length = strlen(xattr->name);
871 	desc->value_length = xattr->value_len;
872 
873 	memcpy(desc->name, xattr->name, desc->name_length);
874 	memcpy((void *)((uintptr_t)desc->name + desc->name_length),
875 	       xattr->value,
876 	       desc->value_length);
877 
878 	return 0;
879 }
880 
881 static void
882 blob_serialize_extent_table_entry(const struct spdk_blob *blob,
883 				  uint64_t start_ep, uint64_t *next_ep,
884 				  uint8_t **buf, size_t *remaining_sz)
885 {
886 	struct spdk_blob_md_descriptor_extent_table *desc;
887 	size_t cur_sz;
888 	uint64_t i, et_idx;
889 	uint32_t extent_page, ep_len;
890 
891 	/* The buffer must have room for at least num_clusters entry */
892 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc->num_clusters);
893 	if (*remaining_sz < cur_sz) {
894 		*next_ep = start_ep;
895 		return;
896 	}
897 
898 	desc = (struct spdk_blob_md_descriptor_extent_table *)*buf;
899 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE;
900 
901 	desc->num_clusters = blob->active.num_clusters;
902 
903 	ep_len = 1;
904 	et_idx = 0;
905 	for (i = start_ep; i < blob->active.num_extent_pages; i++) {
906 		if (*remaining_sz < cur_sz  + sizeof(desc->extent_page[0])) {
907 			/* If we ran out of buffer space, return */
908 			break;
909 		}
910 
911 		extent_page = blob->active.extent_pages[i];
912 		/* Verify that next extent_page is unallocated */
913 		if (extent_page == 0 &&
914 		    (i + 1 < blob->active.num_extent_pages && blob->active.extent_pages[i + 1] == 0)) {
915 			ep_len++;
916 			continue;
917 		}
918 		desc->extent_page[et_idx].page_idx = extent_page;
919 		desc->extent_page[et_idx].num_pages = ep_len;
920 		et_idx++;
921 
922 		ep_len = 1;
923 		cur_sz += sizeof(desc->extent_page[et_idx]);
924 	}
925 	*next_ep = i;
926 
927 	desc->length = sizeof(desc->num_clusters) + sizeof(desc->extent_page[0]) * et_idx;
928 	*remaining_sz -= sizeof(struct spdk_blob_md_descriptor) + desc->length;
929 	*buf += sizeof(struct spdk_blob_md_descriptor) + desc->length;
930 }
931 
932 static int
933 blob_serialize_extent_table(const struct spdk_blob *blob,
934 			    struct spdk_blob_md_page **pages,
935 			    struct spdk_blob_md_page *cur_page,
936 			    uint32_t *page_count, uint8_t **buf,
937 			    size_t *remaining_sz)
938 {
939 	uint64_t				last_extent_page;
940 	int					rc;
941 
942 	last_extent_page = 0;
943 	/* At least single extent table entry has to be always persisted.
944 	 * Such case occurs with num_extent_pages == 0. */
945 	while (last_extent_page <= blob->active.num_extent_pages) {
946 		blob_serialize_extent_table_entry(blob, last_extent_page, &last_extent_page, buf,
947 						  remaining_sz);
948 
949 		if (last_extent_page == blob->active.num_extent_pages) {
950 			break;
951 		}
952 
953 		rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
954 		if (rc < 0) {
955 			return rc;
956 		}
957 
958 		*buf = (uint8_t *)cur_page->descriptors;
959 		*remaining_sz = sizeof(cur_page->descriptors);
960 	}
961 
962 	return 0;
963 }
964 
965 static void
966 blob_serialize_extent_rle(const struct spdk_blob *blob,
967 			  uint64_t start_cluster, uint64_t *next_cluster,
968 			  uint8_t **buf, size_t *buf_sz)
969 {
970 	struct spdk_blob_md_descriptor_extent_rle *desc_extent_rle;
971 	size_t cur_sz;
972 	uint64_t i, extent_idx;
973 	uint64_t lba, lba_per_cluster, lba_count;
974 
975 	/* The buffer must have room for at least one extent */
976 	cur_sz = sizeof(struct spdk_blob_md_descriptor) + sizeof(desc_extent_rle->extents[0]);
977 	if (*buf_sz < cur_sz) {
978 		*next_cluster = start_cluster;
979 		return;
980 	}
981 
982 	desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)*buf;
983 	desc_extent_rle->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE;
984 
985 	lba_per_cluster = bs_cluster_to_lba(blob->bs, 1);
986 
987 	lba = blob->active.clusters[start_cluster];
988 	lba_count = lba_per_cluster;
989 	extent_idx = 0;
990 	for (i = start_cluster + 1; i < blob->active.num_clusters; i++) {
991 		if ((lba + lba_count) == blob->active.clusters[i] && lba != 0) {
992 			/* Run-length encode sequential non-zero LBA */
993 			lba_count += lba_per_cluster;
994 			continue;
995 		} else if (lba == 0 && blob->active.clusters[i] == 0) {
996 			/* Run-length encode unallocated clusters */
997 			lba_count += lba_per_cluster;
998 			continue;
999 		}
1000 		desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
1001 		desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
1002 		extent_idx++;
1003 
1004 		cur_sz += sizeof(desc_extent_rle->extents[extent_idx]);
1005 
1006 		if (*buf_sz < cur_sz) {
1007 			/* If we ran out of buffer space, return */
1008 			*next_cluster = i;
1009 			break;
1010 		}
1011 
1012 		lba = blob->active.clusters[i];
1013 		lba_count = lba_per_cluster;
1014 	}
1015 
1016 	if (*buf_sz >= cur_sz) {
1017 		desc_extent_rle->extents[extent_idx].cluster_idx = lba / lba_per_cluster;
1018 		desc_extent_rle->extents[extent_idx].length = lba_count / lba_per_cluster;
1019 		extent_idx++;
1020 
1021 		*next_cluster = blob->active.num_clusters;
1022 	}
1023 
1024 	desc_extent_rle->length = sizeof(desc_extent_rle->extents[0]) * extent_idx;
1025 	*buf_sz -= sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
1026 	*buf += sizeof(struct spdk_blob_md_descriptor) + desc_extent_rle->length;
1027 }
1028 
1029 static int
1030 blob_serialize_extents_rle(const struct spdk_blob *blob,
1031 			   struct spdk_blob_md_page **pages,
1032 			   struct spdk_blob_md_page *cur_page,
1033 			   uint32_t *page_count, uint8_t **buf,
1034 			   size_t *remaining_sz)
1035 {
1036 	uint64_t				last_cluster;
1037 	int					rc;
1038 
1039 	last_cluster = 0;
1040 	while (last_cluster < blob->active.num_clusters) {
1041 		blob_serialize_extent_rle(blob, last_cluster, &last_cluster, buf, remaining_sz);
1042 
1043 		if (last_cluster == blob->active.num_clusters) {
1044 			break;
1045 		}
1046 
1047 		rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
1048 		if (rc < 0) {
1049 			return rc;
1050 		}
1051 
1052 		*buf = (uint8_t *)cur_page->descriptors;
1053 		*remaining_sz = sizeof(cur_page->descriptors);
1054 	}
1055 
1056 	return 0;
1057 }
1058 
1059 static void
1060 blob_serialize_extent_page(const struct spdk_blob *blob,
1061 			   uint64_t cluster, struct spdk_blob_md_page *page)
1062 {
1063 	struct spdk_blob_md_descriptor_extent_page *desc_extent;
1064 	uint64_t i, extent_idx;
1065 	uint64_t lba, lba_per_cluster;
1066 	uint64_t start_cluster_idx = (cluster / SPDK_EXTENTS_PER_EP) * SPDK_EXTENTS_PER_EP;
1067 
1068 	desc_extent = (struct spdk_blob_md_descriptor_extent_page *) page->descriptors;
1069 	desc_extent->type = SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE;
1070 
1071 	lba_per_cluster = bs_cluster_to_lba(blob->bs, 1);
1072 
1073 	desc_extent->start_cluster_idx = start_cluster_idx;
1074 	extent_idx = 0;
1075 	for (i = start_cluster_idx; i < blob->active.num_clusters; i++) {
1076 		lba = blob->active.clusters[i];
1077 		desc_extent->cluster_idx[extent_idx++] = lba / lba_per_cluster;
1078 		if (extent_idx >= SPDK_EXTENTS_PER_EP) {
1079 			break;
1080 		}
1081 	}
1082 	desc_extent->length = sizeof(desc_extent->start_cluster_idx) +
1083 			      sizeof(desc_extent->cluster_idx[0]) * extent_idx;
1084 }
1085 
1086 static void
1087 blob_serialize_flags(const struct spdk_blob *blob,
1088 		     uint8_t *buf, size_t *buf_sz)
1089 {
1090 	struct spdk_blob_md_descriptor_flags *desc;
1091 
1092 	/*
1093 	 * Flags get serialized first, so we should always have room for the flags
1094 	 *  descriptor.
1095 	 */
1096 	assert(*buf_sz >= sizeof(*desc));
1097 
1098 	desc = (struct spdk_blob_md_descriptor_flags *)buf;
1099 	desc->type = SPDK_MD_DESCRIPTOR_TYPE_FLAGS;
1100 	desc->length = sizeof(*desc) - sizeof(struct spdk_blob_md_descriptor);
1101 	desc->invalid_flags = blob->invalid_flags;
1102 	desc->data_ro_flags = blob->data_ro_flags;
1103 	desc->md_ro_flags = blob->md_ro_flags;
1104 
1105 	*buf_sz -= sizeof(*desc);
1106 }
1107 
1108 static int
1109 blob_serialize_xattrs(const struct spdk_blob *blob,
1110 		      const struct spdk_xattr_tailq *xattrs, bool internal,
1111 		      struct spdk_blob_md_page **pages,
1112 		      struct spdk_blob_md_page *cur_page,
1113 		      uint32_t *page_count, uint8_t **buf,
1114 		      size_t *remaining_sz)
1115 {
1116 	const struct spdk_xattr	*xattr;
1117 	int	rc;
1118 
1119 	TAILQ_FOREACH(xattr, xattrs, link) {
1120 		size_t required_sz = 0;
1121 
1122 		rc = blob_serialize_xattr(xattr,
1123 					  *buf, *remaining_sz,
1124 					  &required_sz, internal);
1125 		if (rc < 0) {
1126 			/* Need to add a new page to the chain */
1127 			rc = blob_serialize_add_page(blob, pages, page_count,
1128 						     &cur_page);
1129 			if (rc < 0) {
1130 				spdk_free(*pages);
1131 				*pages = NULL;
1132 				*page_count = 0;
1133 				return rc;
1134 			}
1135 
1136 			*buf = (uint8_t *)cur_page->descriptors;
1137 			*remaining_sz = sizeof(cur_page->descriptors);
1138 
1139 			/* Try again */
1140 			required_sz = 0;
1141 			rc = blob_serialize_xattr(xattr,
1142 						  *buf, *remaining_sz,
1143 						  &required_sz, internal);
1144 
1145 			if (rc < 0) {
1146 				spdk_free(*pages);
1147 				*pages = NULL;
1148 				*page_count = 0;
1149 				return rc;
1150 			}
1151 		}
1152 
1153 		*remaining_sz -= required_sz;
1154 		*buf += required_sz;
1155 	}
1156 
1157 	return 0;
1158 }
1159 
1160 static int
1161 blob_serialize(const struct spdk_blob *blob, struct spdk_blob_md_page **pages,
1162 	       uint32_t *page_count)
1163 {
1164 	struct spdk_blob_md_page		*cur_page;
1165 	int					rc;
1166 	uint8_t					*buf;
1167 	size_t					remaining_sz;
1168 
1169 	assert(pages != NULL);
1170 	assert(page_count != NULL);
1171 	assert(blob != NULL);
1172 	assert(blob->state == SPDK_BLOB_STATE_DIRTY);
1173 
1174 	*pages = NULL;
1175 	*page_count = 0;
1176 
1177 	/* A blob always has at least 1 page, even if it has no descriptors */
1178 	rc = blob_serialize_add_page(blob, pages, page_count, &cur_page);
1179 	if (rc < 0) {
1180 		return rc;
1181 	}
1182 
1183 	buf = (uint8_t *)cur_page->descriptors;
1184 	remaining_sz = sizeof(cur_page->descriptors);
1185 
1186 	/* Serialize flags */
1187 	blob_serialize_flags(blob, buf, &remaining_sz);
1188 	buf += sizeof(struct spdk_blob_md_descriptor_flags);
1189 
1190 	/* Serialize xattrs */
1191 	rc = blob_serialize_xattrs(blob, &blob->xattrs, false,
1192 				   pages, cur_page, page_count, &buf, &remaining_sz);
1193 	if (rc < 0) {
1194 		return rc;
1195 	}
1196 
1197 	/* Serialize internal xattrs */
1198 	rc = blob_serialize_xattrs(blob, &blob->xattrs_internal, true,
1199 				   pages, cur_page, page_count, &buf, &remaining_sz);
1200 	if (rc < 0) {
1201 		return rc;
1202 	}
1203 
1204 	if (blob->use_extent_table) {
1205 		/* Serialize extent table */
1206 		rc = blob_serialize_extent_table(blob, pages, cur_page, page_count, &buf, &remaining_sz);
1207 	} else {
1208 		/* Serialize extents */
1209 		rc = blob_serialize_extents_rle(blob, pages, cur_page, page_count, &buf, &remaining_sz);
1210 	}
1211 
1212 	return rc;
1213 }
1214 
1215 struct spdk_blob_load_ctx {
1216 	struct spdk_blob		*blob;
1217 
1218 	struct spdk_blob_md_page	*pages;
1219 	uint32_t			num_pages;
1220 	uint32_t			next_extent_page;
1221 	spdk_bs_sequence_t	        *seq;
1222 
1223 	spdk_bs_sequence_cpl		cb_fn;
1224 	void				*cb_arg;
1225 };
1226 
1227 static uint32_t
1228 blob_md_page_calc_crc(void *page)
1229 {
1230 	uint32_t		crc;
1231 
1232 	crc = BLOB_CRC32C_INITIAL;
1233 	crc = spdk_crc32c_update(page, SPDK_BS_PAGE_SIZE - 4, crc);
1234 	crc ^= BLOB_CRC32C_INITIAL;
1235 
1236 	return crc;
1237 
1238 }
1239 
1240 static void
1241 blob_load_final(void *cb_arg, int bserrno)
1242 {
1243 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1244 	struct spdk_blob		*blob = ctx->blob;
1245 
1246 	if (bserrno == 0) {
1247 		blob_mark_clean(blob);
1248 	}
1249 
1250 	ctx->cb_fn(ctx->seq, ctx->cb_arg, bserrno);
1251 
1252 	/* Free the memory */
1253 	spdk_free(ctx->pages);
1254 	free(ctx);
1255 }
1256 
1257 static void
1258 blob_load_snapshot_cpl(void *cb_arg, struct spdk_blob *snapshot, int bserrno)
1259 {
1260 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1261 	struct spdk_blob		*blob = ctx->blob;
1262 
1263 	if (bserrno == 0) {
1264 		blob->back_bs_dev = bs_create_blob_bs_dev(snapshot);
1265 		if (blob->back_bs_dev == NULL) {
1266 			bserrno = -ENOMEM;
1267 		}
1268 	}
1269 	if (bserrno != 0) {
1270 		SPDK_ERRLOG("Snapshot fail\n");
1271 	}
1272 
1273 	blob_load_final(ctx, bserrno);
1274 }
1275 
1276 static void blob_update_clear_method(struct spdk_blob *blob);
1277 
1278 static void
1279 blob_load_backing_dev(void *cb_arg)
1280 {
1281 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1282 	struct spdk_blob		*blob = ctx->blob;
1283 	const void			*value;
1284 	size_t				len;
1285 	int				rc;
1286 
1287 	if (spdk_blob_is_thin_provisioned(blob)) {
1288 		rc = blob_get_xattr_value(blob, BLOB_SNAPSHOT, &value, &len, true);
1289 		if (rc == 0) {
1290 			if (len != sizeof(spdk_blob_id)) {
1291 				blob_load_final(ctx, -EINVAL);
1292 				return;
1293 			}
1294 			/* open snapshot blob and continue in the callback function */
1295 			blob->parent_id = *(spdk_blob_id *)value;
1296 			spdk_bs_open_blob(blob->bs, blob->parent_id,
1297 					  blob_load_snapshot_cpl, ctx);
1298 			return;
1299 		} else {
1300 			/* add zeroes_dev for thin provisioned blob */
1301 			blob->back_bs_dev = bs_create_zeroes_dev();
1302 		}
1303 	} else {
1304 		/* standard blob */
1305 		blob->back_bs_dev = NULL;
1306 	}
1307 	blob_load_final(ctx, 0);
1308 }
1309 
1310 static void
1311 blob_load_cpl_extents_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1312 {
1313 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1314 	struct spdk_blob		*blob = ctx->blob;
1315 	struct spdk_blob_md_page	*page;
1316 	uint64_t			i;
1317 	uint32_t			crc;
1318 	uint64_t			lba;
1319 	void				*tmp;
1320 	uint64_t			sz;
1321 
1322 	if (bserrno) {
1323 		SPDK_ERRLOG("Extent page read failed: %d\n", bserrno);
1324 		blob_load_final(ctx, bserrno);
1325 		return;
1326 	}
1327 
1328 	if (ctx->pages == NULL) {
1329 		/* First iteration of this function, allocate buffer for single EXTENT_PAGE */
1330 		ctx->pages = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE, NULL, SPDK_ENV_SOCKET_ID_ANY,
1331 					  SPDK_MALLOC_DMA);
1332 		if (!ctx->pages) {
1333 			blob_load_final(ctx, -ENOMEM);
1334 			return;
1335 		}
1336 		ctx->num_pages = 1;
1337 		ctx->next_extent_page = 0;
1338 	} else {
1339 		page = &ctx->pages[0];
1340 		crc = blob_md_page_calc_crc(page);
1341 		if (crc != page->crc) {
1342 			blob_load_final(ctx, -EINVAL);
1343 			return;
1344 		}
1345 
1346 		if (page->next != SPDK_INVALID_MD_PAGE) {
1347 			blob_load_final(ctx, -EINVAL);
1348 			return;
1349 		}
1350 
1351 		bserrno = blob_parse_extent_page(page, blob);
1352 		if (bserrno) {
1353 			blob_load_final(ctx, bserrno);
1354 			return;
1355 		}
1356 	}
1357 
1358 	for (i = ctx->next_extent_page; i < blob->active.num_extent_pages; i++) {
1359 		if (blob->active.extent_pages[i] != 0) {
1360 			/* Extent page was allocated, read and parse it. */
1361 			lba = bs_md_page_to_lba(blob->bs, blob->active.extent_pages[i]);
1362 			ctx->next_extent_page = i + 1;
1363 
1364 			bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1365 					     bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
1366 					     blob_load_cpl_extents_cpl, ctx);
1367 			return;
1368 		} else {
1369 			/* Thin provisioned blobs can point to unallocated extent pages.
1370 			 * In this case blob size should be increased by up to the amount left in remaining_clusters_in_et. */
1371 
1372 			sz = spdk_min(blob->remaining_clusters_in_et, SPDK_EXTENTS_PER_EP);
1373 			blob->active.num_clusters += sz;
1374 			blob->remaining_clusters_in_et -= sz;
1375 
1376 			assert(spdk_blob_is_thin_provisioned(blob));
1377 			assert(i + 1 < blob->active.num_extent_pages || blob->remaining_clusters_in_et == 0);
1378 
1379 			tmp = realloc(blob->active.clusters, blob->active.num_clusters * sizeof(*blob->active.clusters));
1380 			if (tmp == NULL) {
1381 				blob_load_final(ctx, -ENOMEM);
1382 				return;
1383 			}
1384 			memset(tmp + sizeof(*blob->active.clusters) * blob->active.cluster_array_size, 0,
1385 			       sizeof(*blob->active.clusters) * (blob->active.num_clusters - blob->active.cluster_array_size));
1386 			blob->active.clusters = tmp;
1387 			blob->active.cluster_array_size = blob->active.num_clusters;
1388 		}
1389 	}
1390 
1391 	blob_load_backing_dev(ctx);
1392 }
1393 
1394 static void
1395 blob_load_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1396 {
1397 	struct spdk_blob_load_ctx	*ctx = cb_arg;
1398 	struct spdk_blob		*blob = ctx->blob;
1399 	struct spdk_blob_md_page	*page;
1400 	int				rc;
1401 	uint32_t			crc;
1402 	uint32_t			current_page;
1403 
1404 	if (ctx->num_pages == 1) {
1405 		current_page = bs_blobid_to_page(blob->id);
1406 	} else {
1407 		assert(ctx->num_pages != 0);
1408 		page = &ctx->pages[ctx->num_pages - 2];
1409 		current_page = page->next;
1410 	}
1411 
1412 	if (bserrno) {
1413 		SPDK_ERRLOG("Metadata page %d read failed for blobid %lu: %d\n",
1414 			    current_page, blob->id, bserrno);
1415 		blob_load_final(ctx, bserrno);
1416 		return;
1417 	}
1418 
1419 	page = &ctx->pages[ctx->num_pages - 1];
1420 	crc = blob_md_page_calc_crc(page);
1421 	if (crc != page->crc) {
1422 		SPDK_ERRLOG("Metadata page %d crc mismatch for blobid %lu\n",
1423 			    current_page, blob->id);
1424 		blob_load_final(ctx, -EINVAL);
1425 		return;
1426 	}
1427 
1428 	if (page->next != SPDK_INVALID_MD_PAGE) {
1429 		uint32_t next_page = page->next;
1430 		uint64_t next_lba = bs_md_page_to_lba(blob->bs, next_page);
1431 
1432 		/* Read the next page */
1433 		ctx->num_pages++;
1434 		ctx->pages = spdk_realloc(ctx->pages, (sizeof(*page) * ctx->num_pages),
1435 					  sizeof(*page));
1436 		if (ctx->pages == NULL) {
1437 			blob_load_final(ctx, -ENOMEM);
1438 			return;
1439 		}
1440 
1441 		bs_sequence_read_dev(seq, &ctx->pages[ctx->num_pages - 1],
1442 				     next_lba,
1443 				     bs_byte_to_lba(blob->bs, sizeof(*page)),
1444 				     blob_load_cpl, ctx);
1445 		return;
1446 	}
1447 
1448 	/* Parse the pages */
1449 	rc = blob_parse(ctx->pages, ctx->num_pages, blob);
1450 	if (rc) {
1451 		blob_load_final(ctx, rc);
1452 		return;
1453 	}
1454 
1455 	if (blob->extent_table_found == true) {
1456 		/* If EXTENT_TABLE was found, that means support for it should be enabled. */
1457 		assert(blob->extent_rle_found == false);
1458 		blob->use_extent_table = true;
1459 	} else {
1460 		/* If EXTENT_RLE or no extent_* descriptor was found disable support
1461 		 * for extent table. No extent_* descriptors means that blob has length of 0
1462 		 * and no extent_rle descriptors were persisted for it.
1463 		 * EXTENT_TABLE if used, is always present in metadata regardless of length. */
1464 		blob->use_extent_table = false;
1465 	}
1466 
1467 	/* Check the clear_method stored in metadata vs what may have been passed
1468 	 * via spdk_bs_open_blob_ext() and update accordingly.
1469 	 */
1470 	blob_update_clear_method(blob);
1471 
1472 	spdk_free(ctx->pages);
1473 	ctx->pages = NULL;
1474 
1475 	if (blob->extent_table_found) {
1476 		blob_load_cpl_extents_cpl(seq, ctx, 0);
1477 	} else {
1478 		blob_load_backing_dev(ctx);
1479 	}
1480 }
1481 
1482 /* Load a blob from disk given a blobid */
1483 static void
1484 blob_load(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
1485 	  spdk_bs_sequence_cpl cb_fn, void *cb_arg)
1486 {
1487 	struct spdk_blob_load_ctx *ctx;
1488 	struct spdk_blob_store *bs;
1489 	uint32_t page_num;
1490 	uint64_t lba;
1491 
1492 	blob_verify_md_op(blob);
1493 
1494 	bs = blob->bs;
1495 
1496 	ctx = calloc(1, sizeof(*ctx));
1497 	if (!ctx) {
1498 		cb_fn(seq, cb_arg, -ENOMEM);
1499 		return;
1500 	}
1501 
1502 	ctx->blob = blob;
1503 	ctx->pages = spdk_realloc(ctx->pages, SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE);
1504 	if (!ctx->pages) {
1505 		free(ctx);
1506 		cb_fn(seq, cb_arg, -ENOMEM);
1507 		return;
1508 	}
1509 	ctx->num_pages = 1;
1510 	ctx->cb_fn = cb_fn;
1511 	ctx->cb_arg = cb_arg;
1512 	ctx->seq = seq;
1513 
1514 	page_num = bs_blobid_to_page(blob->id);
1515 	lba = bs_md_page_to_lba(blob->bs, page_num);
1516 
1517 	blob->state = SPDK_BLOB_STATE_LOADING;
1518 
1519 	bs_sequence_read_dev(seq, &ctx->pages[0], lba,
1520 			     bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE),
1521 			     blob_load_cpl, ctx);
1522 }
1523 
1524 struct spdk_blob_persist_ctx {
1525 	struct spdk_blob		*blob;
1526 
1527 	struct spdk_bs_super_block	*super;
1528 
1529 	struct spdk_blob_md_page	*pages;
1530 	uint32_t			next_extent_page;
1531 	struct spdk_blob_md_page	*extent_page;
1532 
1533 	spdk_bs_sequence_t		*seq;
1534 	spdk_bs_sequence_cpl		cb_fn;
1535 	void				*cb_arg;
1536 	TAILQ_ENTRY(spdk_blob_persist_ctx) link;
1537 };
1538 
1539 static void
1540 bs_batch_clear_dev(struct spdk_blob_persist_ctx *ctx, spdk_bs_batch_t *batch, uint64_t lba,
1541 		   uint32_t lba_count)
1542 {
1543 	switch (ctx->blob->clear_method) {
1544 	case BLOB_CLEAR_WITH_DEFAULT:
1545 	case BLOB_CLEAR_WITH_UNMAP:
1546 		bs_batch_unmap_dev(batch, lba, lba_count);
1547 		break;
1548 	case BLOB_CLEAR_WITH_WRITE_ZEROES:
1549 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
1550 		break;
1551 	case BLOB_CLEAR_WITH_NONE:
1552 	default:
1553 		break;
1554 	}
1555 }
1556 
1557 static void blob_persist_check_dirty(struct spdk_blob_persist_ctx *ctx);
1558 
1559 static void
1560 blob_persist_complete(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1561 {
1562 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1563 	struct spdk_blob_persist_ctx	*next_persist;
1564 	struct spdk_blob		*blob = ctx->blob;
1565 
1566 	if (bserrno == 0) {
1567 		blob_mark_clean(blob);
1568 	}
1569 
1570 	assert(ctx == TAILQ_FIRST(&blob->pending_persists));
1571 	TAILQ_REMOVE(&blob->pending_persists, ctx, link);
1572 
1573 	next_persist = TAILQ_FIRST(&blob->pending_persists);
1574 
1575 	/* Call user callback */
1576 	ctx->cb_fn(seq, ctx->cb_arg, bserrno);
1577 
1578 	/* Free the memory */
1579 	spdk_free(ctx->pages);
1580 	free(ctx);
1581 
1582 	if (next_persist != NULL) {
1583 		blob_persist_check_dirty(next_persist);
1584 	}
1585 }
1586 
1587 static void
1588 blob_persist_clear_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1589 {
1590 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1591 	struct spdk_blob		*blob = ctx->blob;
1592 	struct spdk_blob_store		*bs = blob->bs;
1593 	size_t				i;
1594 
1595 	if (bserrno != 0) {
1596 		blob_persist_complete(seq, ctx, bserrno);
1597 		return;
1598 	}
1599 
1600 	/* Release all clusters that were truncated */
1601 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1602 		uint32_t cluster_num = bs_lba_to_cluster(bs, blob->active.clusters[i]);
1603 
1604 		/* Nothing to release if it was not allocated */
1605 		if (blob->active.clusters[i] != 0) {
1606 			bs_release_cluster(bs, cluster_num);
1607 		}
1608 	}
1609 
1610 	if (blob->active.num_clusters == 0) {
1611 		free(blob->active.clusters);
1612 		blob->active.clusters = NULL;
1613 		blob->active.cluster_array_size = 0;
1614 	} else if (blob->active.num_clusters != blob->active.cluster_array_size) {
1615 #ifndef __clang_analyzer__
1616 		void *tmp;
1617 
1618 		/* scan-build really can't figure reallocs, workaround it */
1619 		tmp = realloc(blob->active.clusters, sizeof(*blob->active.clusters) * blob->active.num_clusters);
1620 		assert(tmp != NULL);
1621 		blob->active.clusters = tmp;
1622 
1623 		tmp = realloc(blob->active.extent_pages, sizeof(uint32_t) * blob->active.num_extent_pages);
1624 		assert(tmp != NULL);
1625 		blob->active.extent_pages = tmp;
1626 #endif
1627 		blob->active.extent_pages_array_size = blob->active.num_extent_pages;
1628 		blob->active.cluster_array_size = blob->active.num_clusters;
1629 	}
1630 
1631 	/* TODO: Add path to persist clear extent pages. */
1632 	blob_persist_complete(seq, ctx, bserrno);
1633 }
1634 
1635 static void
1636 blob_persist_clear_clusters(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1637 {
1638 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1639 	struct spdk_blob		*blob = ctx->blob;
1640 	struct spdk_blob_store		*bs = blob->bs;
1641 	spdk_bs_batch_t			*batch;
1642 	size_t				i;
1643 	uint64_t			lba;
1644 	uint32_t			lba_count;
1645 
1646 	if (bserrno != 0) {
1647 		blob_persist_complete(seq, ctx, bserrno);
1648 		return;
1649 	}
1650 
1651 	/* Clusters don't move around in blobs. The list shrinks or grows
1652 	 * at the end, but no changes ever occur in the middle of the list.
1653 	 */
1654 
1655 	batch = bs_sequence_to_batch(seq, blob_persist_clear_clusters_cpl, ctx);
1656 
1657 	/* Clear all clusters that were truncated */
1658 	lba = 0;
1659 	lba_count = 0;
1660 	for (i = blob->active.num_clusters; i < blob->active.cluster_array_size; i++) {
1661 		uint64_t next_lba = blob->active.clusters[i];
1662 		uint32_t next_lba_count = bs_cluster_to_lba(bs, 1);
1663 
1664 		if (next_lba > 0 && (lba + lba_count) == next_lba) {
1665 			/* This cluster is contiguous with the previous one. */
1666 			lba_count += next_lba_count;
1667 			continue;
1668 		}
1669 
1670 		/* This cluster is not contiguous with the previous one. */
1671 
1672 		/* If a run of LBAs previously existing, clear them now */
1673 		if (lba_count > 0) {
1674 			bs_batch_clear_dev(ctx, batch, lba, lba_count);
1675 		}
1676 
1677 		/* Start building the next batch */
1678 		lba = next_lba;
1679 		if (next_lba > 0) {
1680 			lba_count = next_lba_count;
1681 		} else {
1682 			lba_count = 0;
1683 		}
1684 	}
1685 
1686 	/* If we ended with a contiguous set of LBAs, clear them now */
1687 	if (lba_count > 0) {
1688 		bs_batch_clear_dev(ctx, batch, lba, lba_count);
1689 	}
1690 
1691 	bs_batch_close(batch);
1692 }
1693 
1694 static void
1695 blob_persist_zero_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1696 {
1697 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1698 	struct spdk_blob		*blob = ctx->blob;
1699 	struct spdk_blob_store		*bs = blob->bs;
1700 	size_t				i;
1701 
1702 	if (bserrno != 0) {
1703 		blob_persist_complete(seq, ctx, bserrno);
1704 		return;
1705 	}
1706 
1707 	/* This loop starts at 1 because the first page is special and handled
1708 	 * below. The pages (except the first) are never written in place,
1709 	 * so any pages in the clean list must be zeroed.
1710 	 */
1711 	for (i = 1; i < blob->clean.num_pages; i++) {
1712 		bs_release_md_page(bs, blob->clean.pages[i]);
1713 	}
1714 
1715 	if (blob->active.num_pages == 0) {
1716 		uint32_t page_num;
1717 
1718 		page_num = bs_blobid_to_page(blob->id);
1719 		bs_release_md_page(bs, page_num);
1720 	}
1721 
1722 	/* Move on to clearing clusters */
1723 	blob_persist_clear_clusters(seq, ctx, 0);
1724 }
1725 
1726 static void
1727 blob_persist_zero_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1728 {
1729 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1730 	struct spdk_blob		*blob = ctx->blob;
1731 	struct spdk_blob_store		*bs = blob->bs;
1732 	uint64_t			lba;
1733 	uint32_t			lba_count;
1734 	spdk_bs_batch_t			*batch;
1735 	size_t				i;
1736 
1737 	if (bserrno != 0) {
1738 		blob_persist_complete(seq, ctx, bserrno);
1739 		return;
1740 	}
1741 
1742 	batch = bs_sequence_to_batch(seq, blob_persist_zero_pages_cpl, ctx);
1743 
1744 	lba_count = bs_byte_to_lba(bs, SPDK_BS_PAGE_SIZE);
1745 
1746 	/* This loop starts at 1 because the first page is special and handled
1747 	 * below. The pages (except the first) are never written in place,
1748 	 * so any pages in the clean list must be zeroed.
1749 	 */
1750 	for (i = 1; i < blob->clean.num_pages; i++) {
1751 		lba = bs_md_page_to_lba(bs, blob->clean.pages[i]);
1752 
1753 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
1754 	}
1755 
1756 	/* The first page will only be zeroed if this is a delete. */
1757 	if (blob->active.num_pages == 0) {
1758 		uint32_t page_num;
1759 
1760 		/* The first page in the metadata goes where the blobid indicates */
1761 		page_num = bs_blobid_to_page(blob->id);
1762 		lba = bs_md_page_to_lba(bs, page_num);
1763 
1764 		bs_batch_write_zeroes_dev(batch, lba, lba_count);
1765 	}
1766 
1767 	bs_batch_close(batch);
1768 }
1769 
1770 static void
1771 blob_persist_write_page_root(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1772 {
1773 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1774 	struct spdk_blob		*blob = ctx->blob;
1775 	struct spdk_blob_store		*bs = blob->bs;
1776 	uint64_t			lba;
1777 	uint32_t			lba_count;
1778 	struct spdk_blob_md_page	*page;
1779 
1780 	if (bserrno != 0) {
1781 		blob_persist_complete(seq, ctx, bserrno);
1782 		return;
1783 	}
1784 
1785 	if (blob->active.num_pages == 0) {
1786 		/* Move on to the next step */
1787 		blob_persist_zero_pages(seq, ctx, 0);
1788 		return;
1789 	}
1790 
1791 	lba_count = bs_byte_to_lba(bs, sizeof(*page));
1792 
1793 	page = &ctx->pages[0];
1794 	/* The first page in the metadata goes where the blobid indicates */
1795 	lba = bs_md_page_to_lba(bs, bs_blobid_to_page(blob->id));
1796 
1797 	bs_sequence_write_dev(seq, page, lba, lba_count,
1798 			      blob_persist_zero_pages, ctx);
1799 }
1800 
1801 static void
1802 blob_persist_write_page_chain(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
1803 {
1804 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
1805 	struct spdk_blob		*blob = ctx->blob;
1806 	struct spdk_blob_store		*bs = blob->bs;
1807 	uint64_t			lba;
1808 	uint32_t			lba_count;
1809 	struct spdk_blob_md_page	*page;
1810 	spdk_bs_batch_t			*batch;
1811 	size_t				i;
1812 
1813 	if (bserrno != 0) {
1814 		blob_persist_complete(seq, ctx, bserrno);
1815 		return;
1816 	}
1817 
1818 	/* Clusters don't move around in blobs. The list shrinks or grows
1819 	 * at the end, but no changes ever occur in the middle of the list.
1820 	 */
1821 
1822 	lba_count = bs_byte_to_lba(bs, sizeof(*page));
1823 
1824 	batch = bs_sequence_to_batch(seq, blob_persist_write_page_root, ctx);
1825 
1826 	/* This starts at 1. The root page is not written until
1827 	 * all of the others are finished
1828 	 */
1829 	for (i = 1; i < blob->active.num_pages; i++) {
1830 		page = &ctx->pages[i];
1831 		assert(page->sequence_num == i);
1832 
1833 		lba = bs_md_page_to_lba(bs, blob->active.pages[i]);
1834 
1835 		bs_batch_write_dev(batch, page, lba, lba_count);
1836 	}
1837 
1838 	bs_batch_close(batch);
1839 }
1840 
1841 static int
1842 blob_resize(struct spdk_blob *blob, uint64_t sz)
1843 {
1844 	uint64_t	i;
1845 	uint64_t	*tmp;
1846 	uint64_t	lfc; /* lowest free cluster */
1847 	uint32_t	lfmd; /*  lowest free md page */
1848 	uint64_t	num_clusters;
1849 	uint32_t	*ep_tmp;
1850 	uint64_t	new_num_ep = 0, current_num_ep = 0;
1851 	struct spdk_blob_store *bs;
1852 
1853 	bs = blob->bs;
1854 
1855 	blob_verify_md_op(blob);
1856 
1857 	if (blob->active.num_clusters == sz) {
1858 		return 0;
1859 	}
1860 
1861 	if (blob->active.num_clusters < blob->active.cluster_array_size) {
1862 		/* If this blob was resized to be larger, then smaller, then
1863 		 * larger without syncing, then the cluster array already
1864 		 * contains spare assigned clusters we can use.
1865 		 */
1866 		num_clusters = spdk_min(blob->active.cluster_array_size,
1867 					sz);
1868 	} else {
1869 		num_clusters = blob->active.num_clusters;
1870 	}
1871 
1872 	if (blob->use_extent_table) {
1873 		/* Round up since every cluster beyond current Extent Table size,
1874 		 * requires new extent page. */
1875 		new_num_ep = spdk_divide_round_up(sz, SPDK_EXTENTS_PER_EP);
1876 		current_num_ep = spdk_divide_round_up(num_clusters, SPDK_EXTENTS_PER_EP);
1877 	}
1878 
1879 	/* Do two passes - one to verify that we can obtain enough clusters
1880 	 * and md pages, another to actually claim them.
1881 	 */
1882 
1883 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1884 		lfc = 0;
1885 		for (i = num_clusters; i < sz; i++) {
1886 			lfc = spdk_bit_array_find_first_clear(bs->used_clusters, lfc);
1887 			if (lfc == UINT32_MAX) {
1888 				/* No more free clusters. Cannot satisfy the request */
1889 				return -ENOSPC;
1890 			}
1891 			lfc++;
1892 		}
1893 		lfmd = 0;
1894 		for (i = current_num_ep; i < new_num_ep ; i++) {
1895 			lfmd = spdk_bit_array_find_first_clear(blob->bs->used_md_pages, lfmd);
1896 			if (lfmd == UINT32_MAX) {
1897 				/* No more free md pages. Cannot satisfy the request */
1898 				return -ENOSPC;
1899 			}
1900 		}
1901 	}
1902 
1903 	if (sz > num_clusters) {
1904 		/* Expand the cluster array if necessary.
1905 		 * We only shrink the array when persisting.
1906 		 */
1907 		tmp = realloc(blob->active.clusters, sizeof(*blob->active.clusters) * sz);
1908 		if (sz > 0 && tmp == NULL) {
1909 			return -ENOMEM;
1910 		}
1911 		memset(tmp + blob->active.cluster_array_size, 0,
1912 		       sizeof(*blob->active.clusters) * (sz - blob->active.cluster_array_size));
1913 		blob->active.clusters = tmp;
1914 		blob->active.cluster_array_size = sz;
1915 
1916 		/* Expand the extents table, only if enough clusters were added */
1917 		if (new_num_ep > current_num_ep && blob->use_extent_table) {
1918 			ep_tmp = realloc(blob->active.extent_pages, sizeof(*blob->active.extent_pages) * new_num_ep);
1919 			if (new_num_ep > 0 && ep_tmp == NULL) {
1920 				return -ENOMEM;
1921 			}
1922 			memset(ep_tmp + blob->active.extent_pages_array_size, 0,
1923 			       sizeof(*blob->active.extent_pages) * (new_num_ep - blob->active.extent_pages_array_size));
1924 			blob->active.extent_pages = ep_tmp;
1925 			blob->active.extent_pages_array_size = new_num_ep;
1926 		}
1927 	}
1928 
1929 	blob->state = SPDK_BLOB_STATE_DIRTY;
1930 
1931 	if (spdk_blob_is_thin_provisioned(blob) == false) {
1932 		lfc = 0;
1933 		lfmd = 0;
1934 		for (i = num_clusters; i < sz; i++) {
1935 			bs_allocate_cluster(blob, i, &lfc, &lfmd, true);
1936 			lfc++;
1937 			lfmd++;
1938 		}
1939 	}
1940 
1941 	blob->active.num_clusters = sz;
1942 	blob->active.num_extent_pages = new_num_ep;
1943 
1944 	return 0;
1945 }
1946 
1947 static void
1948 blob_persist_generate_new_md(struct spdk_blob_persist_ctx *ctx)
1949 {
1950 	spdk_bs_sequence_t *seq = ctx->seq;
1951 	struct spdk_blob *blob = ctx->blob;
1952 	struct spdk_blob_store *bs = blob->bs;
1953 	uint64_t i;
1954 	uint32_t page_num;
1955 	void *tmp;
1956 	int rc;
1957 
1958 	/* Generate the new metadata */
1959 	rc = blob_serialize(blob, &ctx->pages, &blob->active.num_pages);
1960 	if (rc < 0) {
1961 		blob_persist_complete(seq, ctx, rc);
1962 		return;
1963 	}
1964 
1965 	assert(blob->active.num_pages >= 1);
1966 
1967 	/* Resize the cache of page indices */
1968 	tmp = realloc(blob->active.pages, blob->active.num_pages * sizeof(*blob->active.pages));
1969 	if (!tmp) {
1970 		blob_persist_complete(seq, ctx, -ENOMEM);
1971 		return;
1972 	}
1973 	blob->active.pages = tmp;
1974 
1975 	/* Assign this metadata to pages. This requires two passes -
1976 	 * one to verify that there are enough pages and a second
1977 	 * to actually claim them. */
1978 	page_num = 0;
1979 	/* Note that this loop starts at one. The first page location is fixed by the blobid. */
1980 	for (i = 1; i < blob->active.num_pages; i++) {
1981 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1982 		if (page_num == UINT32_MAX) {
1983 			blob_persist_complete(seq, ctx, -ENOMEM);
1984 			return;
1985 		}
1986 		page_num++;
1987 	}
1988 
1989 	page_num = 0;
1990 	blob->active.pages[0] = bs_blobid_to_page(blob->id);
1991 	for (i = 1; i < blob->active.num_pages; i++) {
1992 		page_num = spdk_bit_array_find_first_clear(bs->used_md_pages, page_num);
1993 		ctx->pages[i - 1].next = page_num;
1994 		/* Now that previous metadata page is complete, calculate the crc for it. */
1995 		ctx->pages[i - 1].crc = blob_md_page_calc_crc(&ctx->pages[i - 1]);
1996 		blob->active.pages[i] = page_num;
1997 		bs_claim_md_page(bs, page_num);
1998 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Claiming page %u for blob %lu\n", page_num, blob->id);
1999 		page_num++;
2000 	}
2001 	ctx->pages[i - 1].crc = blob_md_page_calc_crc(&ctx->pages[i - 1]);
2002 	/* Start writing the metadata from last page to first */
2003 	blob->state = SPDK_BLOB_STATE_CLEAN;
2004 	blob_persist_write_page_chain(seq, ctx, 0);
2005 }
2006 
2007 static void
2008 blob_persist_write_extent_pages(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2009 {
2010 	struct spdk_blob_persist_ctx	*ctx = cb_arg;
2011 	struct spdk_blob		*blob = ctx->blob;
2012 	size_t				i;
2013 	uint32_t			extent_page_id;
2014 	uint32_t                        page_count = 0;
2015 	int				rc;
2016 
2017 	if (ctx->extent_page != NULL) {
2018 		spdk_free(ctx->extent_page);
2019 		ctx->extent_page = NULL;
2020 	}
2021 
2022 	if (bserrno != 0) {
2023 		blob_persist_complete(seq, ctx, bserrno);
2024 		return;
2025 	}
2026 
2027 	/* Only write out changed extent pages */
2028 	for (i = ctx->next_extent_page; i < blob->active.num_extent_pages; i++) {
2029 		extent_page_id = blob->active.extent_pages[i];
2030 		if (extent_page_id == 0) {
2031 			/* No Extent Page to persist */
2032 			assert(spdk_blob_is_thin_provisioned(blob));
2033 			continue;
2034 		}
2035 		/* Writing out new extent page for the first time. Either active extent pages is larger
2036 		 * than clean extent pages or there was no extent page assigned due to thin provisioning. */
2037 		if (i >= blob->clean.extent_pages_array_size || blob->clean.extent_pages[i] == 0) {
2038 			blob->state = SPDK_BLOB_STATE_DIRTY;
2039 			assert(spdk_bit_array_get(blob->bs->used_md_pages, extent_page_id));
2040 			ctx->next_extent_page = i + 1;
2041 			rc = blob_serialize_add_page(ctx->blob, &ctx->extent_page, &page_count, &ctx->extent_page);
2042 			if (rc < 0) {
2043 				blob_persist_complete(seq, ctx, rc);
2044 				return;
2045 			}
2046 
2047 			blob_serialize_extent_page(blob, i * SPDK_EXTENTS_PER_EP, ctx->extent_page);
2048 
2049 			ctx->extent_page->crc = blob_md_page_calc_crc(ctx->extent_page);
2050 
2051 			bs_sequence_write_dev(seq, ctx->extent_page, bs_md_page_to_lba(blob->bs, extent_page_id),
2052 					      bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
2053 					      blob_persist_write_extent_pages, ctx);
2054 			return;
2055 		}
2056 		assert(blob->clean.extent_pages[i] != 0);
2057 	}
2058 
2059 	blob_persist_generate_new_md(ctx);
2060 }
2061 
2062 static void
2063 blob_persist_start(struct spdk_blob_persist_ctx *ctx)
2064 {
2065 	spdk_bs_sequence_t *seq = ctx->seq;
2066 	struct spdk_blob *blob = ctx->blob;
2067 
2068 	if (blob->active.num_pages == 0) {
2069 		/* This is the signal that the blob should be deleted.
2070 		 * Immediately jump to the clean up routine. */
2071 		assert(blob->clean.num_pages > 0);
2072 		blob->state = SPDK_BLOB_STATE_CLEAN;
2073 		blob_persist_zero_pages(seq, ctx, 0);
2074 		return;
2075 
2076 	}
2077 
2078 	blob_persist_write_extent_pages(seq, ctx, 0);
2079 }
2080 
2081 static void
2082 blob_persist_dirty_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2083 {
2084 	struct spdk_blob_persist_ctx *ctx = cb_arg;
2085 
2086 	spdk_free(ctx->super);
2087 
2088 	if (bserrno != 0) {
2089 		blob_persist_complete(seq, ctx, bserrno);
2090 		return;
2091 	}
2092 
2093 	ctx->blob->bs->clean = 0;
2094 
2095 	blob_persist_start(ctx);
2096 }
2097 
2098 static void
2099 bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
2100 	       struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg);
2101 
2102 
2103 static void
2104 blob_persist_dirty(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2105 {
2106 	struct spdk_blob_persist_ctx *ctx = cb_arg;
2107 
2108 	if (bserrno != 0) {
2109 		spdk_free(ctx->super);
2110 		blob_persist_complete(seq, ctx, bserrno);
2111 		return;
2112 	}
2113 
2114 	ctx->super->clean = 0;
2115 	if (ctx->super->size == 0) {
2116 		ctx->super->size = ctx->blob->bs->dev->blockcnt * ctx->blob->bs->dev->blocklen;
2117 	}
2118 
2119 	bs_write_super(seq, ctx->blob->bs, ctx->super, blob_persist_dirty_cpl, ctx);
2120 }
2121 
2122 static void
2123 blob_persist_check_dirty(struct spdk_blob_persist_ctx *ctx)
2124 {
2125 	if (ctx->blob->bs->clean) {
2126 		ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
2127 					  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2128 		if (!ctx->super) {
2129 			blob_persist_complete(ctx->seq, ctx, -ENOMEM);
2130 			return;
2131 		}
2132 
2133 		bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(ctx->blob->bs, 0),
2134 				     bs_byte_to_lba(ctx->blob->bs, sizeof(*ctx->super)),
2135 				     blob_persist_dirty, ctx);
2136 	} else {
2137 		blob_persist_start(ctx);
2138 	}
2139 }
2140 
2141 /* Write a blob to disk */
2142 static void
2143 blob_persist(spdk_bs_sequence_t *seq, struct spdk_blob *blob,
2144 	     spdk_bs_sequence_cpl cb_fn, void *cb_arg)
2145 {
2146 	struct spdk_blob_persist_ctx *ctx;
2147 
2148 	blob_verify_md_op(blob);
2149 
2150 	if (blob->state == SPDK_BLOB_STATE_CLEAN && TAILQ_EMPTY(&blob->pending_persists)) {
2151 		cb_fn(seq, cb_arg, 0);
2152 		return;
2153 	}
2154 
2155 	ctx = calloc(1, sizeof(*ctx));
2156 	if (!ctx) {
2157 		cb_fn(seq, cb_arg, -ENOMEM);
2158 		return;
2159 	}
2160 	ctx->blob = blob;
2161 	ctx->seq = seq;
2162 	ctx->cb_fn = cb_fn;
2163 	ctx->cb_arg = cb_arg;
2164 	ctx->next_extent_page = 0;
2165 
2166 	/* Multiple blob persists can affect one another, via blob->state or
2167 	 * blob mutable data changes. To prevent it, queue up the persists. */
2168 	if (!TAILQ_EMPTY(&blob->pending_persists)) {
2169 		TAILQ_INSERT_TAIL(&blob->pending_persists, ctx, link);
2170 		return;
2171 	}
2172 	TAILQ_INSERT_HEAD(&blob->pending_persists, ctx, link);
2173 
2174 	blob_persist_check_dirty(ctx);
2175 }
2176 
2177 struct spdk_blob_copy_cluster_ctx {
2178 	struct spdk_blob *blob;
2179 	uint8_t *buf;
2180 	uint64_t page;
2181 	uint64_t new_cluster;
2182 	uint32_t new_extent_page;
2183 	spdk_bs_sequence_t *seq;
2184 };
2185 
2186 static void
2187 blob_allocate_and_copy_cluster_cpl(void *cb_arg, int bserrno)
2188 {
2189 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2190 	struct spdk_bs_request_set *set = (struct spdk_bs_request_set *)ctx->seq;
2191 	TAILQ_HEAD(, spdk_bs_request_set) requests;
2192 	spdk_bs_user_op_t *op;
2193 
2194 	TAILQ_INIT(&requests);
2195 	TAILQ_SWAP(&set->channel->need_cluster_alloc, &requests, spdk_bs_request_set, link);
2196 
2197 	while (!TAILQ_EMPTY(&requests)) {
2198 		op = TAILQ_FIRST(&requests);
2199 		TAILQ_REMOVE(&requests, op, link);
2200 		if (bserrno == 0) {
2201 			bs_user_op_execute(op);
2202 		} else {
2203 			bs_user_op_abort(op);
2204 		}
2205 	}
2206 
2207 	spdk_free(ctx->buf);
2208 	free(ctx);
2209 }
2210 
2211 static void
2212 blob_insert_cluster_cpl(void *cb_arg, int bserrno)
2213 {
2214 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2215 
2216 	if (bserrno) {
2217 		if (bserrno == -EEXIST) {
2218 			/* The metadata insert failed because another thread
2219 			 * allocated the cluster first. Free our cluster
2220 			 * but continue without error. */
2221 			bserrno = 0;
2222 		}
2223 		bs_release_cluster(ctx->blob->bs, ctx->new_cluster);
2224 		if (ctx->new_extent_page != 0) {
2225 			bs_release_md_page(ctx->blob->bs, ctx->new_extent_page);
2226 		}
2227 	}
2228 
2229 	bs_sequence_finish(ctx->seq, bserrno);
2230 }
2231 
2232 static void
2233 blob_write_copy_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2234 {
2235 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2236 	uint32_t cluster_number;
2237 
2238 	if (bserrno) {
2239 		/* The write failed, so jump to the final completion handler */
2240 		bs_sequence_finish(seq, bserrno);
2241 		return;
2242 	}
2243 
2244 	cluster_number = bs_page_to_cluster(ctx->blob->bs, ctx->page);
2245 
2246 	blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
2247 					 ctx->new_extent_page, blob_insert_cluster_cpl, ctx);
2248 }
2249 
2250 static void
2251 blob_write_copy(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2252 {
2253 	struct spdk_blob_copy_cluster_ctx *ctx = cb_arg;
2254 
2255 	if (bserrno != 0) {
2256 		/* The read failed, so jump to the final completion handler */
2257 		bs_sequence_finish(seq, bserrno);
2258 		return;
2259 	}
2260 
2261 	/* Write whole cluster */
2262 	bs_sequence_write_dev(seq, ctx->buf,
2263 			      bs_cluster_to_lba(ctx->blob->bs, ctx->new_cluster),
2264 			      bs_cluster_to_lba(ctx->blob->bs, 1),
2265 			      blob_write_copy_cpl, ctx);
2266 }
2267 
2268 static void
2269 bs_allocate_and_copy_cluster(struct spdk_blob *blob,
2270 			     struct spdk_io_channel *_ch,
2271 			     uint64_t io_unit, spdk_bs_user_op_t *op)
2272 {
2273 	struct spdk_bs_cpl cpl;
2274 	struct spdk_bs_channel *ch;
2275 	struct spdk_blob_copy_cluster_ctx *ctx;
2276 	uint32_t cluster_start_page;
2277 	uint32_t cluster_number;
2278 	int rc;
2279 
2280 	ch = spdk_io_channel_get_ctx(_ch);
2281 
2282 	if (!TAILQ_EMPTY(&ch->need_cluster_alloc)) {
2283 		/* There are already operations pending. Queue this user op
2284 		 * and return because it will be re-executed when the outstanding
2285 		 * cluster allocation completes. */
2286 		TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
2287 		return;
2288 	}
2289 
2290 	/* Round the io_unit offset down to the first page in the cluster */
2291 	cluster_start_page = bs_io_unit_to_cluster_start(blob, io_unit);
2292 
2293 	/* Calculate which index in the metadata cluster array the corresponding
2294 	 * cluster is supposed to be at. */
2295 	cluster_number = bs_io_unit_to_cluster_number(blob, io_unit);
2296 
2297 	ctx = calloc(1, sizeof(*ctx));
2298 	if (!ctx) {
2299 		bs_user_op_abort(op);
2300 		return;
2301 	}
2302 
2303 	assert(blob->bs->cluster_sz % blob->back_bs_dev->blocklen == 0);
2304 
2305 	ctx->blob = blob;
2306 	ctx->page = cluster_start_page;
2307 
2308 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
2309 		ctx->buf = spdk_malloc(blob->bs->cluster_sz, blob->back_bs_dev->blocklen,
2310 				       NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
2311 		if (!ctx->buf) {
2312 			SPDK_ERRLOG("DMA allocation for cluster of size = %" PRIu32 " failed.\n",
2313 				    blob->bs->cluster_sz);
2314 			free(ctx);
2315 			bs_user_op_abort(op);
2316 			return;
2317 		}
2318 	}
2319 
2320 	rc = bs_allocate_cluster(blob, cluster_number, &ctx->new_cluster, &ctx->new_extent_page,
2321 				 false);
2322 	if (rc != 0) {
2323 		spdk_free(ctx->buf);
2324 		free(ctx);
2325 		bs_user_op_abort(op);
2326 		return;
2327 	}
2328 
2329 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2330 	cpl.u.blob_basic.cb_fn = blob_allocate_and_copy_cluster_cpl;
2331 	cpl.u.blob_basic.cb_arg = ctx;
2332 
2333 	ctx->seq = bs_sequence_start(_ch, &cpl);
2334 	if (!ctx->seq) {
2335 		bs_release_cluster(blob->bs, ctx->new_cluster);
2336 		spdk_free(ctx->buf);
2337 		free(ctx);
2338 		bs_user_op_abort(op);
2339 		return;
2340 	}
2341 
2342 	/* Queue the user op to block other incoming operations */
2343 	TAILQ_INSERT_TAIL(&ch->need_cluster_alloc, op, link);
2344 
2345 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
2346 		/* Read cluster from backing device */
2347 		bs_sequence_read_bs_dev(ctx->seq, blob->back_bs_dev, ctx->buf,
2348 					bs_dev_page_to_lba(blob->back_bs_dev, cluster_start_page),
2349 					bs_dev_byte_to_lba(blob->back_bs_dev, blob->bs->cluster_sz),
2350 					blob_write_copy, ctx);
2351 	} else {
2352 		blob_insert_cluster_on_md_thread(ctx->blob, cluster_number, ctx->new_cluster,
2353 						 ctx->new_extent_page, blob_insert_cluster_cpl, ctx);
2354 	}
2355 }
2356 
2357 static inline bool
2358 blob_calculate_lba_and_lba_count(struct spdk_blob *blob, uint64_t io_unit, uint64_t length,
2359 				 uint64_t *lba,	uint32_t *lba_count)
2360 {
2361 	*lba_count = length;
2362 
2363 	if (!bs_io_unit_is_allocated(blob, io_unit)) {
2364 		assert(blob->back_bs_dev != NULL);
2365 		*lba = bs_io_unit_to_back_dev_lba(blob, io_unit);
2366 		*lba_count = bs_io_unit_to_back_dev_lba(blob, *lba_count);
2367 		return false;
2368 	} else {
2369 		*lba = bs_blob_io_unit_to_lba(blob, io_unit);
2370 		return true;
2371 	}
2372 }
2373 
2374 struct op_split_ctx {
2375 	struct spdk_blob *blob;
2376 	struct spdk_io_channel *channel;
2377 	uint64_t io_unit_offset;
2378 	uint64_t io_units_remaining;
2379 	void *curr_payload;
2380 	enum spdk_blob_op_type op_type;
2381 	spdk_bs_sequence_t *seq;
2382 };
2383 
2384 static void
2385 blob_request_submit_op_split_next(void *cb_arg, int bserrno)
2386 {
2387 	struct op_split_ctx	*ctx = cb_arg;
2388 	struct spdk_blob	*blob = ctx->blob;
2389 	struct spdk_io_channel	*ch = ctx->channel;
2390 	enum spdk_blob_op_type	op_type = ctx->op_type;
2391 	uint8_t			*buf = ctx->curr_payload;
2392 	uint64_t		offset = ctx->io_unit_offset;
2393 	uint64_t		length = ctx->io_units_remaining;
2394 	uint64_t		op_length;
2395 
2396 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
2397 		bs_sequence_finish(ctx->seq, bserrno);
2398 		free(ctx);
2399 		return;
2400 	}
2401 
2402 	op_length = spdk_min(length, bs_num_io_units_to_cluster_boundary(blob,
2403 			     offset));
2404 
2405 	/* Update length and payload for next operation */
2406 	ctx->io_units_remaining -= op_length;
2407 	ctx->io_unit_offset += op_length;
2408 	if (op_type == SPDK_BLOB_WRITE || op_type == SPDK_BLOB_READ) {
2409 		ctx->curr_payload += op_length * blob->bs->io_unit_size;
2410 	}
2411 
2412 	switch (op_type) {
2413 	case SPDK_BLOB_READ:
2414 		spdk_blob_io_read(blob, ch, buf, offset, op_length,
2415 				  blob_request_submit_op_split_next, ctx);
2416 		break;
2417 	case SPDK_BLOB_WRITE:
2418 		spdk_blob_io_write(blob, ch, buf, offset, op_length,
2419 				   blob_request_submit_op_split_next, ctx);
2420 		break;
2421 	case SPDK_BLOB_UNMAP:
2422 		spdk_blob_io_unmap(blob, ch, offset, op_length,
2423 				   blob_request_submit_op_split_next, ctx);
2424 		break;
2425 	case SPDK_BLOB_WRITE_ZEROES:
2426 		spdk_blob_io_write_zeroes(blob, ch, offset, op_length,
2427 					  blob_request_submit_op_split_next, ctx);
2428 		break;
2429 	case SPDK_BLOB_READV:
2430 	case SPDK_BLOB_WRITEV:
2431 		SPDK_ERRLOG("readv/write not valid\n");
2432 		bs_sequence_finish(ctx->seq, -EINVAL);
2433 		free(ctx);
2434 		break;
2435 	}
2436 }
2437 
2438 static void
2439 blob_request_submit_op_split(struct spdk_io_channel *ch, struct spdk_blob *blob,
2440 			     void *payload, uint64_t offset, uint64_t length,
2441 			     spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
2442 {
2443 	struct op_split_ctx *ctx;
2444 	spdk_bs_sequence_t *seq;
2445 	struct spdk_bs_cpl cpl;
2446 
2447 	assert(blob != NULL);
2448 
2449 	ctx = calloc(1, sizeof(struct op_split_ctx));
2450 	if (ctx == NULL) {
2451 		cb_fn(cb_arg, -ENOMEM);
2452 		return;
2453 	}
2454 
2455 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2456 	cpl.u.blob_basic.cb_fn = cb_fn;
2457 	cpl.u.blob_basic.cb_arg = cb_arg;
2458 
2459 	seq = bs_sequence_start(ch, &cpl);
2460 	if (!seq) {
2461 		free(ctx);
2462 		cb_fn(cb_arg, -ENOMEM);
2463 		return;
2464 	}
2465 
2466 	ctx->blob = blob;
2467 	ctx->channel = ch;
2468 	ctx->curr_payload = payload;
2469 	ctx->io_unit_offset = offset;
2470 	ctx->io_units_remaining = length;
2471 	ctx->op_type = op_type;
2472 	ctx->seq = seq;
2473 
2474 	blob_request_submit_op_split_next(ctx, 0);
2475 }
2476 
2477 static void
2478 blob_request_submit_op_single(struct spdk_io_channel *_ch, struct spdk_blob *blob,
2479 			      void *payload, uint64_t offset, uint64_t length,
2480 			      spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
2481 {
2482 	struct spdk_bs_cpl cpl;
2483 	uint64_t lba;
2484 	uint32_t lba_count;
2485 	bool is_allocated;
2486 
2487 	assert(blob != NULL);
2488 
2489 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2490 	cpl.u.blob_basic.cb_fn = cb_fn;
2491 	cpl.u.blob_basic.cb_arg = cb_arg;
2492 
2493 	is_allocated = blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
2494 
2495 	if (blob->frozen_refcnt) {
2496 		/* This blob I/O is frozen */
2497 		spdk_bs_user_op_t *op;
2498 		struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_ch);
2499 
2500 		op = bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
2501 		if (!op) {
2502 			cb_fn(cb_arg, -ENOMEM);
2503 			return;
2504 		}
2505 
2506 		TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
2507 
2508 		return;
2509 	}
2510 
2511 	switch (op_type) {
2512 	case SPDK_BLOB_READ: {
2513 		spdk_bs_batch_t *batch;
2514 
2515 		batch = bs_batch_open(_ch, &cpl);
2516 		if (!batch) {
2517 			cb_fn(cb_arg, -ENOMEM);
2518 			return;
2519 		}
2520 
2521 		if (is_allocated) {
2522 			/* Read from the blob */
2523 			bs_batch_read_dev(batch, payload, lba, lba_count);
2524 		} else {
2525 			/* Read from the backing block device */
2526 			bs_batch_read_bs_dev(batch, blob->back_bs_dev, payload, lba, lba_count);
2527 		}
2528 
2529 		bs_batch_close(batch);
2530 		break;
2531 	}
2532 	case SPDK_BLOB_WRITE:
2533 	case SPDK_BLOB_WRITE_ZEROES: {
2534 		if (is_allocated) {
2535 			/* Write to the blob */
2536 			spdk_bs_batch_t *batch;
2537 
2538 			if (lba_count == 0) {
2539 				cb_fn(cb_arg, 0);
2540 				return;
2541 			}
2542 
2543 			batch = bs_batch_open(_ch, &cpl);
2544 			if (!batch) {
2545 				cb_fn(cb_arg, -ENOMEM);
2546 				return;
2547 			}
2548 
2549 			if (op_type == SPDK_BLOB_WRITE) {
2550 				bs_batch_write_dev(batch, payload, lba, lba_count);
2551 			} else {
2552 				bs_batch_write_zeroes_dev(batch, lba, lba_count);
2553 			}
2554 
2555 			bs_batch_close(batch);
2556 		} else {
2557 			/* Queue this operation and allocate the cluster */
2558 			spdk_bs_user_op_t *op;
2559 
2560 			op = bs_user_op_alloc(_ch, &cpl, op_type, blob, payload, 0, offset, length);
2561 			if (!op) {
2562 				cb_fn(cb_arg, -ENOMEM);
2563 				return;
2564 			}
2565 
2566 			bs_allocate_and_copy_cluster(blob, _ch, offset, op);
2567 		}
2568 		break;
2569 	}
2570 	case SPDK_BLOB_UNMAP: {
2571 		spdk_bs_batch_t *batch;
2572 
2573 		batch = bs_batch_open(_ch, &cpl);
2574 		if (!batch) {
2575 			cb_fn(cb_arg, -ENOMEM);
2576 			return;
2577 		}
2578 
2579 		if (is_allocated) {
2580 			bs_batch_unmap_dev(batch, lba, lba_count);
2581 		}
2582 
2583 		bs_batch_close(batch);
2584 		break;
2585 	}
2586 	case SPDK_BLOB_READV:
2587 	case SPDK_BLOB_WRITEV:
2588 		SPDK_ERRLOG("readv/write not valid\n");
2589 		cb_fn(cb_arg, -EINVAL);
2590 		break;
2591 	}
2592 }
2593 
2594 static void
2595 blob_request_submit_op(struct spdk_blob *blob, struct spdk_io_channel *_channel,
2596 		       void *payload, uint64_t offset, uint64_t length,
2597 		       spdk_blob_op_complete cb_fn, void *cb_arg, enum spdk_blob_op_type op_type)
2598 {
2599 	assert(blob != NULL);
2600 
2601 	if (blob->data_ro && op_type != SPDK_BLOB_READ) {
2602 		cb_fn(cb_arg, -EPERM);
2603 		return;
2604 	}
2605 
2606 	if (offset + length > bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
2607 		cb_fn(cb_arg, -EINVAL);
2608 		return;
2609 	}
2610 	if (length <= bs_num_io_units_to_cluster_boundary(blob, offset)) {
2611 		blob_request_submit_op_single(_channel, blob, payload, offset, length,
2612 					      cb_fn, cb_arg, op_type);
2613 	} else {
2614 		blob_request_submit_op_split(_channel, blob, payload, offset, length,
2615 					     cb_fn, cb_arg, op_type);
2616 	}
2617 }
2618 
2619 struct rw_iov_ctx {
2620 	struct spdk_blob *blob;
2621 	struct spdk_io_channel *channel;
2622 	spdk_blob_op_complete cb_fn;
2623 	void *cb_arg;
2624 	bool read;
2625 	int iovcnt;
2626 	struct iovec *orig_iov;
2627 	uint64_t io_unit_offset;
2628 	uint64_t io_units_remaining;
2629 	uint64_t io_units_done;
2630 	struct iovec iov[0];
2631 };
2632 
2633 static void
2634 rw_iov_done(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
2635 {
2636 	assert(cb_arg == NULL);
2637 	bs_sequence_finish(seq, bserrno);
2638 }
2639 
2640 static void
2641 rw_iov_split_next(void *cb_arg, int bserrno)
2642 {
2643 	struct rw_iov_ctx *ctx = cb_arg;
2644 	struct spdk_blob *blob = ctx->blob;
2645 	struct iovec *iov, *orig_iov;
2646 	int iovcnt;
2647 	size_t orig_iovoff;
2648 	uint64_t io_units_count, io_units_to_boundary, io_unit_offset;
2649 	uint64_t byte_count;
2650 
2651 	if (bserrno != 0 || ctx->io_units_remaining == 0) {
2652 		ctx->cb_fn(ctx->cb_arg, bserrno);
2653 		free(ctx);
2654 		return;
2655 	}
2656 
2657 	io_unit_offset = ctx->io_unit_offset;
2658 	io_units_to_boundary = bs_num_io_units_to_cluster_boundary(blob, io_unit_offset);
2659 	io_units_count = spdk_min(ctx->io_units_remaining, io_units_to_boundary);
2660 	/*
2661 	 * Get index and offset into the original iov array for our current position in the I/O sequence.
2662 	 *  byte_count will keep track of how many bytes remaining until orig_iov and orig_iovoff will
2663 	 *  point to the current position in the I/O sequence.
2664 	 */
2665 	byte_count = ctx->io_units_done * blob->bs->io_unit_size;
2666 	orig_iov = &ctx->orig_iov[0];
2667 	orig_iovoff = 0;
2668 	while (byte_count > 0) {
2669 		if (byte_count >= orig_iov->iov_len) {
2670 			byte_count -= orig_iov->iov_len;
2671 			orig_iov++;
2672 		} else {
2673 			orig_iovoff = byte_count;
2674 			byte_count = 0;
2675 		}
2676 	}
2677 
2678 	/*
2679 	 * Build an iov array for the next I/O in the sequence.  byte_count will keep track of how many
2680 	 *  bytes of this next I/O remain to be accounted for in the new iov array.
2681 	 */
2682 	byte_count = io_units_count * blob->bs->io_unit_size;
2683 	iov = &ctx->iov[0];
2684 	iovcnt = 0;
2685 	while (byte_count > 0) {
2686 		assert(iovcnt < ctx->iovcnt);
2687 		iov->iov_len = spdk_min(byte_count, orig_iov->iov_len - orig_iovoff);
2688 		iov->iov_base = orig_iov->iov_base + orig_iovoff;
2689 		byte_count -= iov->iov_len;
2690 		orig_iovoff = 0;
2691 		orig_iov++;
2692 		iov++;
2693 		iovcnt++;
2694 	}
2695 
2696 	ctx->io_unit_offset += io_units_count;
2697 	ctx->io_units_remaining -= io_units_count;
2698 	ctx->io_units_done += io_units_count;
2699 	iov = &ctx->iov[0];
2700 
2701 	if (ctx->read) {
2702 		spdk_blob_io_readv(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2703 				   io_units_count, rw_iov_split_next, ctx);
2704 	} else {
2705 		spdk_blob_io_writev(ctx->blob, ctx->channel, iov, iovcnt, io_unit_offset,
2706 				    io_units_count, rw_iov_split_next, ctx);
2707 	}
2708 }
2709 
2710 static void
2711 blob_request_submit_rw_iov(struct spdk_blob *blob, struct spdk_io_channel *_channel,
2712 			   struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
2713 			   spdk_blob_op_complete cb_fn, void *cb_arg, bool read)
2714 {
2715 	struct spdk_bs_cpl	cpl;
2716 
2717 	assert(blob != NULL);
2718 
2719 	if (!read && blob->data_ro) {
2720 		cb_fn(cb_arg, -EPERM);
2721 		return;
2722 	}
2723 
2724 	if (length == 0) {
2725 		cb_fn(cb_arg, 0);
2726 		return;
2727 	}
2728 
2729 	if (offset + length > bs_cluster_to_lba(blob->bs, blob->active.num_clusters)) {
2730 		cb_fn(cb_arg, -EINVAL);
2731 		return;
2732 	}
2733 
2734 	/*
2735 	 * For now, we implement readv/writev using a sequence (instead of a batch) to account for having
2736 	 *  to split a request that spans a cluster boundary.  For I/O that do not span a cluster boundary,
2737 	 *  there will be no noticeable difference compared to using a batch.  For I/O that do span a cluster
2738 	 *  boundary, the target LBAs (after blob offset to LBA translation) may not be contiguous, so we need
2739 	 *  to allocate a separate iov array and split the I/O such that none of the resulting
2740 	 *  smaller I/O cross a cluster boundary.  These smaller I/O will be issued in sequence (not in parallel)
2741 	 *  but since this case happens very infrequently, any performance impact will be negligible.
2742 	 *
2743 	 * This could be optimized in the future to allocate a big enough iov array to account for all of the iovs
2744 	 *  for all of the smaller I/Os, pre-build all of the iov arrays for the smaller I/Os, then issue them
2745 	 *  in a batch.  That would also require creating an intermediate spdk_bs_cpl that would get called
2746 	 *  when the batch was completed, to allow for freeing the memory for the iov arrays.
2747 	 */
2748 	if (spdk_likely(length <= bs_num_io_units_to_cluster_boundary(blob, offset))) {
2749 		uint32_t lba_count;
2750 		uint64_t lba;
2751 		bool is_allocated;
2752 
2753 		cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
2754 		cpl.u.blob_basic.cb_fn = cb_fn;
2755 		cpl.u.blob_basic.cb_arg = cb_arg;
2756 
2757 		if (blob->frozen_refcnt) {
2758 			/* This blob I/O is frozen */
2759 			enum spdk_blob_op_type op_type;
2760 			spdk_bs_user_op_t *op;
2761 			struct spdk_bs_channel *bs_channel = spdk_io_channel_get_ctx(_channel);
2762 
2763 			op_type = read ? SPDK_BLOB_READV : SPDK_BLOB_WRITEV;
2764 			op = bs_user_op_alloc(_channel, &cpl, op_type, blob, iov, iovcnt, offset, length);
2765 			if (!op) {
2766 				cb_fn(cb_arg, -ENOMEM);
2767 				return;
2768 			}
2769 
2770 			TAILQ_INSERT_TAIL(&bs_channel->queued_io, op, link);
2771 
2772 			return;
2773 		}
2774 
2775 		is_allocated = blob_calculate_lba_and_lba_count(blob, offset, length, &lba, &lba_count);
2776 
2777 		if (read) {
2778 			spdk_bs_sequence_t *seq;
2779 
2780 			seq = bs_sequence_start(_channel, &cpl);
2781 			if (!seq) {
2782 				cb_fn(cb_arg, -ENOMEM);
2783 				return;
2784 			}
2785 
2786 			if (is_allocated) {
2787 				bs_sequence_readv_dev(seq, iov, iovcnt, lba, lba_count, rw_iov_done, NULL);
2788 			} else {
2789 				bs_sequence_readv_bs_dev(seq, blob->back_bs_dev, iov, iovcnt, lba, lba_count,
2790 							 rw_iov_done, NULL);
2791 			}
2792 		} else {
2793 			if (is_allocated) {
2794 				spdk_bs_sequence_t *seq;
2795 
2796 				seq = bs_sequence_start(_channel, &cpl);
2797 				if (!seq) {
2798 					cb_fn(cb_arg, -ENOMEM);
2799 					return;
2800 				}
2801 
2802 				bs_sequence_writev_dev(seq, iov, iovcnt, lba, lba_count, rw_iov_done, NULL);
2803 			} else {
2804 				/* Queue this operation and allocate the cluster */
2805 				spdk_bs_user_op_t *op;
2806 
2807 				op = bs_user_op_alloc(_channel, &cpl, SPDK_BLOB_WRITEV, blob, iov, iovcnt, offset,
2808 						      length);
2809 				if (!op) {
2810 					cb_fn(cb_arg, -ENOMEM);
2811 					return;
2812 				}
2813 
2814 				bs_allocate_and_copy_cluster(blob, _channel, offset, op);
2815 			}
2816 		}
2817 	} else {
2818 		struct rw_iov_ctx *ctx;
2819 
2820 		ctx = calloc(1, sizeof(struct rw_iov_ctx) + iovcnt * sizeof(struct iovec));
2821 		if (ctx == NULL) {
2822 			cb_fn(cb_arg, -ENOMEM);
2823 			return;
2824 		}
2825 
2826 		ctx->blob = blob;
2827 		ctx->channel = _channel;
2828 		ctx->cb_fn = cb_fn;
2829 		ctx->cb_arg = cb_arg;
2830 		ctx->read = read;
2831 		ctx->orig_iov = iov;
2832 		ctx->iovcnt = iovcnt;
2833 		ctx->io_unit_offset = offset;
2834 		ctx->io_units_remaining = length;
2835 		ctx->io_units_done = 0;
2836 
2837 		rw_iov_split_next(ctx, 0);
2838 	}
2839 }
2840 
2841 static struct spdk_blob *
2842 blob_lookup(struct spdk_blob_store *bs, spdk_blob_id blobid)
2843 {
2844 	struct spdk_blob *blob;
2845 
2846 	if (spdk_bit_array_get(bs->open_blobids, blobid) == 0) {
2847 		return NULL;
2848 	}
2849 
2850 	TAILQ_FOREACH(blob, &bs->blobs, link) {
2851 		if (blob->id == blobid) {
2852 			return blob;
2853 		}
2854 	}
2855 
2856 	return NULL;
2857 }
2858 
2859 static void
2860 blob_get_snapshot_and_clone_entries(struct spdk_blob *blob,
2861 				    struct spdk_blob_list **snapshot_entry, struct spdk_blob_list **clone_entry)
2862 {
2863 	assert(blob != NULL);
2864 	*snapshot_entry = NULL;
2865 	*clone_entry = NULL;
2866 
2867 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
2868 		return;
2869 	}
2870 
2871 	TAILQ_FOREACH(*snapshot_entry, &blob->bs->snapshots, link) {
2872 		if ((*snapshot_entry)->id == blob->parent_id) {
2873 			break;
2874 		}
2875 	}
2876 
2877 	if (*snapshot_entry != NULL) {
2878 		TAILQ_FOREACH(*clone_entry, &(*snapshot_entry)->clones, link) {
2879 			if ((*clone_entry)->id == blob->id) {
2880 				break;
2881 			}
2882 		}
2883 
2884 		assert(clone_entry != NULL);
2885 	}
2886 }
2887 
2888 static int
2889 bs_channel_create(void *io_device, void *ctx_buf)
2890 {
2891 	struct spdk_blob_store		*bs = io_device;
2892 	struct spdk_bs_channel		*channel = ctx_buf;
2893 	struct spdk_bs_dev		*dev;
2894 	uint32_t			max_ops = bs->max_channel_ops;
2895 	uint32_t			i;
2896 
2897 	dev = bs->dev;
2898 
2899 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_bs_request_set));
2900 	if (!channel->req_mem) {
2901 		return -1;
2902 	}
2903 
2904 	TAILQ_INIT(&channel->reqs);
2905 
2906 	for (i = 0; i < max_ops; i++) {
2907 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
2908 	}
2909 
2910 	channel->bs = bs;
2911 	channel->dev = dev;
2912 	channel->dev_channel = dev->create_channel(dev);
2913 
2914 	if (!channel->dev_channel) {
2915 		SPDK_ERRLOG("Failed to create device channel.\n");
2916 		free(channel->req_mem);
2917 		return -1;
2918 	}
2919 
2920 	TAILQ_INIT(&channel->need_cluster_alloc);
2921 	TAILQ_INIT(&channel->queued_io);
2922 
2923 	return 0;
2924 }
2925 
2926 static void
2927 bs_channel_destroy(void *io_device, void *ctx_buf)
2928 {
2929 	struct spdk_bs_channel *channel = ctx_buf;
2930 	spdk_bs_user_op_t *op;
2931 
2932 	while (!TAILQ_EMPTY(&channel->need_cluster_alloc)) {
2933 		op = TAILQ_FIRST(&channel->need_cluster_alloc);
2934 		TAILQ_REMOVE(&channel->need_cluster_alloc, op, link);
2935 		bs_user_op_abort(op);
2936 	}
2937 
2938 	while (!TAILQ_EMPTY(&channel->queued_io)) {
2939 		op = TAILQ_FIRST(&channel->queued_io);
2940 		TAILQ_REMOVE(&channel->queued_io, op, link);
2941 		bs_user_op_abort(op);
2942 	}
2943 
2944 	free(channel->req_mem);
2945 	channel->dev->destroy_channel(channel->dev, channel->dev_channel);
2946 }
2947 
2948 static void
2949 bs_dev_destroy(void *io_device)
2950 {
2951 	struct spdk_blob_store *bs = io_device;
2952 	struct spdk_blob	*blob, *blob_tmp;
2953 
2954 	bs->dev->destroy(bs->dev);
2955 
2956 	TAILQ_FOREACH_SAFE(blob, &bs->blobs, link, blob_tmp) {
2957 		TAILQ_REMOVE(&bs->blobs, blob, link);
2958 		spdk_bit_array_clear(bs->open_blobids, blob->id);
2959 		blob_free(blob);
2960 	}
2961 
2962 	pthread_mutex_destroy(&bs->used_clusters_mutex);
2963 
2964 	spdk_bit_array_free(&bs->open_blobids);
2965 	spdk_bit_array_free(&bs->used_blobids);
2966 	spdk_bit_array_free(&bs->used_md_pages);
2967 	spdk_bit_array_free(&bs->used_clusters);
2968 	/*
2969 	 * If this function is called for any reason except a successful unload,
2970 	 * the unload_cpl type will be NONE and this will be a nop.
2971 	 */
2972 	bs_call_cpl(&bs->unload_cpl, bs->unload_err);
2973 
2974 	free(bs);
2975 }
2976 
2977 static int
2978 bs_blob_list_add(struct spdk_blob *blob)
2979 {
2980 	spdk_blob_id snapshot_id;
2981 	struct spdk_blob_list *snapshot_entry = NULL;
2982 	struct spdk_blob_list *clone_entry = NULL;
2983 
2984 	assert(blob != NULL);
2985 
2986 	snapshot_id = blob->parent_id;
2987 	if (snapshot_id == SPDK_BLOBID_INVALID) {
2988 		return 0;
2989 	}
2990 
2991 	snapshot_entry = bs_get_snapshot_entry(blob->bs, snapshot_id);
2992 	if (snapshot_entry == NULL) {
2993 		/* Snapshot not found */
2994 		snapshot_entry = calloc(1, sizeof(struct spdk_blob_list));
2995 		if (snapshot_entry == NULL) {
2996 			return -ENOMEM;
2997 		}
2998 		snapshot_entry->id = snapshot_id;
2999 		TAILQ_INIT(&snapshot_entry->clones);
3000 		TAILQ_INSERT_TAIL(&blob->bs->snapshots, snapshot_entry, link);
3001 	} else {
3002 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
3003 			if (clone_entry->id == blob->id) {
3004 				break;
3005 			}
3006 		}
3007 	}
3008 
3009 	if (clone_entry == NULL) {
3010 		/* Clone not found */
3011 		clone_entry = calloc(1, sizeof(struct spdk_blob_list));
3012 		if (clone_entry == NULL) {
3013 			return -ENOMEM;
3014 		}
3015 		clone_entry->id = blob->id;
3016 		TAILQ_INIT(&clone_entry->clones);
3017 		TAILQ_INSERT_TAIL(&snapshot_entry->clones, clone_entry, link);
3018 		snapshot_entry->clone_count++;
3019 	}
3020 
3021 	return 0;
3022 }
3023 
3024 static void
3025 bs_blob_list_remove(struct spdk_blob *blob)
3026 {
3027 	struct spdk_blob_list *snapshot_entry = NULL;
3028 	struct spdk_blob_list *clone_entry = NULL;
3029 
3030 	blob_get_snapshot_and_clone_entries(blob, &snapshot_entry, &clone_entry);
3031 
3032 	if (snapshot_entry == NULL) {
3033 		return;
3034 	}
3035 
3036 	blob->parent_id = SPDK_BLOBID_INVALID;
3037 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
3038 	free(clone_entry);
3039 
3040 	snapshot_entry->clone_count--;
3041 }
3042 
3043 static int
3044 bs_blob_list_free(struct spdk_blob_store *bs)
3045 {
3046 	struct spdk_blob_list *snapshot_entry;
3047 	struct spdk_blob_list *snapshot_entry_tmp;
3048 	struct spdk_blob_list *clone_entry;
3049 	struct spdk_blob_list *clone_entry_tmp;
3050 
3051 	TAILQ_FOREACH_SAFE(snapshot_entry, &bs->snapshots, link, snapshot_entry_tmp) {
3052 		TAILQ_FOREACH_SAFE(clone_entry, &snapshot_entry->clones, link, clone_entry_tmp) {
3053 			TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
3054 			free(clone_entry);
3055 		}
3056 		TAILQ_REMOVE(&bs->snapshots, snapshot_entry, link);
3057 		free(snapshot_entry);
3058 	}
3059 
3060 	return 0;
3061 }
3062 
3063 static void
3064 bs_free(struct spdk_blob_store *bs)
3065 {
3066 	bs_blob_list_free(bs);
3067 
3068 	bs_unregister_md_thread(bs);
3069 	spdk_io_device_unregister(bs, bs_dev_destroy);
3070 }
3071 
3072 void
3073 spdk_bs_opts_init(struct spdk_bs_opts *opts)
3074 {
3075 	opts->cluster_sz = SPDK_BLOB_OPTS_CLUSTER_SZ;
3076 	opts->num_md_pages = SPDK_BLOB_OPTS_NUM_MD_PAGES;
3077 	opts->max_md_ops = SPDK_BLOB_OPTS_MAX_MD_OPS;
3078 	opts->max_channel_ops = SPDK_BLOB_OPTS_DEFAULT_CHANNEL_OPS;
3079 	opts->clear_method = BS_CLEAR_WITH_UNMAP;
3080 	memset(&opts->bstype, 0, sizeof(opts->bstype));
3081 	opts->iter_cb_fn = NULL;
3082 	opts->iter_cb_arg = NULL;
3083 }
3084 
3085 static int
3086 bs_opts_verify(struct spdk_bs_opts *opts)
3087 {
3088 	if (opts->cluster_sz == 0 || opts->num_md_pages == 0 || opts->max_md_ops == 0 ||
3089 	    opts->max_channel_ops == 0) {
3090 		SPDK_ERRLOG("Blobstore options cannot be set to 0\n");
3091 		return -1;
3092 	}
3093 
3094 	return 0;
3095 }
3096 
3097 static int
3098 bs_alloc(struct spdk_bs_dev *dev, struct spdk_bs_opts *opts, struct spdk_blob_store **_bs)
3099 {
3100 	struct spdk_blob_store	*bs;
3101 	uint64_t dev_size;
3102 	int rc;
3103 
3104 	dev_size = dev->blocklen * dev->blockcnt;
3105 	if (dev_size < opts->cluster_sz) {
3106 		/* Device size cannot be smaller than cluster size of blobstore */
3107 		SPDK_INFOLOG(SPDK_LOG_BLOB, "Device size %" PRIu64 " is smaller than cluster size %" PRIu32 "\n",
3108 			     dev_size, opts->cluster_sz);
3109 		return -ENOSPC;
3110 	}
3111 	if (opts->cluster_sz < SPDK_BS_PAGE_SIZE) {
3112 		/* Cluster size cannot be smaller than page size */
3113 		SPDK_ERRLOG("Cluster size %" PRIu32 " is smaller than page size %d\n",
3114 			    opts->cluster_sz, SPDK_BS_PAGE_SIZE);
3115 		return -EINVAL;
3116 	}
3117 	bs = calloc(1, sizeof(struct spdk_blob_store));
3118 	if (!bs) {
3119 		return -ENOMEM;
3120 	}
3121 
3122 	TAILQ_INIT(&bs->blobs);
3123 	TAILQ_INIT(&bs->snapshots);
3124 	bs->dev = dev;
3125 	bs->md_thread = spdk_get_thread();
3126 	assert(bs->md_thread != NULL);
3127 
3128 	/*
3129 	 * Do not use bs_lba_to_cluster() here since blockcnt may not be an
3130 	 *  even multiple of the cluster size.
3131 	 */
3132 	bs->cluster_sz = opts->cluster_sz;
3133 	bs->total_clusters = dev->blockcnt / (bs->cluster_sz / dev->blocklen);
3134 	bs->pages_per_cluster = bs->cluster_sz / SPDK_BS_PAGE_SIZE;
3135 	if (spdk_u32_is_pow2(bs->pages_per_cluster)) {
3136 		bs->pages_per_cluster_shift = spdk_u32log2(bs->pages_per_cluster);
3137 	}
3138 	bs->num_free_clusters = bs->total_clusters;
3139 	bs->used_clusters = spdk_bit_array_create(bs->total_clusters);
3140 	bs->io_unit_size = dev->blocklen;
3141 	if (bs->used_clusters == NULL) {
3142 		free(bs);
3143 		return -ENOMEM;
3144 	}
3145 
3146 	bs->max_channel_ops = opts->max_channel_ops;
3147 	bs->super_blob = SPDK_BLOBID_INVALID;
3148 	memcpy(&bs->bstype, &opts->bstype, sizeof(opts->bstype));
3149 
3150 	/* The metadata is assumed to be at least 1 page */
3151 	bs->used_md_pages = spdk_bit_array_create(1);
3152 	bs->used_blobids = spdk_bit_array_create(0);
3153 	bs->open_blobids = spdk_bit_array_create(0);
3154 
3155 	pthread_mutex_init(&bs->used_clusters_mutex, NULL);
3156 
3157 	spdk_io_device_register(bs, bs_channel_create, bs_channel_destroy,
3158 				sizeof(struct spdk_bs_channel), "blobstore");
3159 	rc = bs_register_md_thread(bs);
3160 	if (rc == -1) {
3161 		spdk_io_device_unregister(bs, NULL);
3162 		pthread_mutex_destroy(&bs->used_clusters_mutex);
3163 		spdk_bit_array_free(&bs->open_blobids);
3164 		spdk_bit_array_free(&bs->used_blobids);
3165 		spdk_bit_array_free(&bs->used_md_pages);
3166 		spdk_bit_array_free(&bs->used_clusters);
3167 		free(bs);
3168 		/* FIXME: this is a lie but don't know how to get a proper error code here */
3169 		return -ENOMEM;
3170 	}
3171 
3172 	*_bs = bs;
3173 	return 0;
3174 }
3175 
3176 /* START spdk_bs_load, spdk_bs_load_ctx will used for both load and unload. */
3177 
3178 struct spdk_bs_load_ctx {
3179 	struct spdk_blob_store		*bs;
3180 	struct spdk_bs_super_block	*super;
3181 
3182 	struct spdk_bs_md_mask		*mask;
3183 	bool				in_page_chain;
3184 	uint32_t			page_index;
3185 	uint32_t			cur_page;
3186 	struct spdk_blob_md_page	*page;
3187 
3188 	uint64_t			num_extent_pages;
3189 	uint32_t			*extent_page_num;
3190 	struct spdk_blob_md_page	*extent_pages;
3191 
3192 	spdk_bs_sequence_t			*seq;
3193 	spdk_blob_op_with_handle_complete	iter_cb_fn;
3194 	void					*iter_cb_arg;
3195 	struct spdk_blob			*blob;
3196 	spdk_blob_id				blobid;
3197 };
3198 
3199 static void
3200 bs_load_ctx_fail(struct spdk_bs_load_ctx *ctx, int bserrno)
3201 {
3202 	assert(bserrno != 0);
3203 
3204 	spdk_free(ctx->super);
3205 	bs_sequence_finish(ctx->seq, bserrno);
3206 	bs_free(ctx->bs);
3207 	free(ctx);
3208 }
3209 
3210 static void
3211 bs_set_mask(struct spdk_bit_array *array, struct spdk_bs_md_mask *mask)
3212 {
3213 	uint32_t i = 0;
3214 
3215 	while (true) {
3216 		i = spdk_bit_array_find_first_set(array, i);
3217 		if (i >= mask->length) {
3218 			break;
3219 		}
3220 		mask->mask[i / 8] |= 1U << (i % 8);
3221 		i++;
3222 	}
3223 }
3224 
3225 static int
3226 bs_load_mask(struct spdk_bit_array **array_ptr, struct spdk_bs_md_mask *mask)
3227 {
3228 	struct spdk_bit_array *array;
3229 	uint32_t i;
3230 
3231 	if (spdk_bit_array_resize(array_ptr, mask->length) < 0) {
3232 		return -ENOMEM;
3233 	}
3234 
3235 	array = *array_ptr;
3236 	for (i = 0; i < mask->length; i++) {
3237 		if (mask->mask[i / 8] & (1U << (i % 8))) {
3238 			spdk_bit_array_set(array, i);
3239 		}
3240 	}
3241 
3242 	return 0;
3243 }
3244 
3245 static void
3246 bs_write_super(spdk_bs_sequence_t *seq, struct spdk_blob_store *bs,
3247 	       struct spdk_bs_super_block *super, spdk_bs_sequence_cpl cb_fn, void *cb_arg)
3248 {
3249 	/* Update the values in the super block */
3250 	super->super_blob = bs->super_blob;
3251 	memcpy(&super->bstype, &bs->bstype, sizeof(bs->bstype));
3252 	super->crc = blob_md_page_calc_crc(super);
3253 	bs_sequence_write_dev(seq, super, bs_page_to_lba(bs, 0),
3254 			      bs_byte_to_lba(bs, sizeof(*super)),
3255 			      cb_fn, cb_arg);
3256 }
3257 
3258 static void
3259 bs_write_used_clusters(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3260 {
3261 	struct spdk_bs_load_ctx	*ctx = arg;
3262 	uint64_t	mask_size, lba, lba_count;
3263 
3264 	/* Write out the used clusters mask */
3265 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
3266 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3267 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3268 	if (!ctx->mask) {
3269 		bs_load_ctx_fail(ctx, -ENOMEM);
3270 		return;
3271 	}
3272 
3273 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_CLUSTERS;
3274 	ctx->mask->length = ctx->bs->total_clusters;
3275 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_clusters));
3276 
3277 	bs_set_mask(ctx->bs->used_clusters, ctx->mask);
3278 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
3279 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
3280 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3281 }
3282 
3283 static void
3284 bs_write_used_md(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3285 {
3286 	struct spdk_bs_load_ctx	*ctx = arg;
3287 	uint64_t	mask_size, lba, lba_count;
3288 
3289 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
3290 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3291 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3292 	if (!ctx->mask) {
3293 		bs_load_ctx_fail(ctx, -ENOMEM);
3294 		return;
3295 	}
3296 
3297 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_PAGES;
3298 	ctx->mask->length = ctx->super->md_len;
3299 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_md_pages));
3300 
3301 	bs_set_mask(ctx->bs->used_md_pages, ctx->mask);
3302 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
3303 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
3304 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3305 }
3306 
3307 static void
3308 bs_write_used_blobids(spdk_bs_sequence_t *seq, void *arg, spdk_bs_sequence_cpl cb_fn)
3309 {
3310 	struct spdk_bs_load_ctx	*ctx = arg;
3311 	uint64_t	mask_size, lba, lba_count;
3312 
3313 	if (ctx->super->used_blobid_mask_len == 0) {
3314 		/*
3315 		 * This is a pre-v3 on-disk format where the blobid mask does not get
3316 		 *  written to disk.
3317 		 */
3318 		cb_fn(seq, arg, 0);
3319 		return;
3320 	}
3321 
3322 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
3323 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
3324 				 SPDK_MALLOC_DMA);
3325 	if (!ctx->mask) {
3326 		bs_load_ctx_fail(ctx, -ENOMEM);
3327 		return;
3328 	}
3329 
3330 	ctx->mask->type = SPDK_MD_MASK_TYPE_USED_BLOBIDS;
3331 	ctx->mask->length = ctx->super->md_len;
3332 	assert(ctx->mask->length == spdk_bit_array_capacity(ctx->bs->used_blobids));
3333 
3334 	bs_set_mask(ctx->bs->used_blobids, ctx->mask);
3335 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
3336 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
3337 	bs_sequence_write_dev(seq, ctx->mask, lba, lba_count, cb_fn, arg);
3338 }
3339 
3340 static void
3341 blob_set_thin_provision(struct spdk_blob *blob)
3342 {
3343 	blob_verify_md_op(blob);
3344 	blob->invalid_flags |= SPDK_BLOB_THIN_PROV;
3345 	blob->state = SPDK_BLOB_STATE_DIRTY;
3346 }
3347 
3348 static void
3349 blob_set_clear_method(struct spdk_blob *blob, enum blob_clear_method clear_method)
3350 {
3351 	blob_verify_md_op(blob);
3352 	blob->clear_method = clear_method;
3353 	blob->md_ro_flags |= (clear_method << SPDK_BLOB_CLEAR_METHOD_SHIFT);
3354 	blob->state = SPDK_BLOB_STATE_DIRTY;
3355 }
3356 
3357 static void bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno);
3358 
3359 static void
3360 bs_delete_corrupted_blob_cpl(void *cb_arg, int bserrno)
3361 {
3362 	struct spdk_bs_load_ctx *ctx = cb_arg;
3363 	spdk_blob_id id;
3364 	int64_t page_num;
3365 
3366 	/* Iterate to next blob (we can't use spdk_bs_iter_next function as our
3367 	 * last blob has been removed */
3368 	page_num = bs_blobid_to_page(ctx->blobid);
3369 	page_num++;
3370 	page_num = spdk_bit_array_find_first_set(ctx->bs->used_blobids, page_num);
3371 	if (page_num >= spdk_bit_array_capacity(ctx->bs->used_blobids)) {
3372 		bs_load_iter(ctx, NULL, -ENOENT);
3373 		return;
3374 	}
3375 
3376 	id = bs_page_to_blobid(page_num);
3377 
3378 	spdk_bs_open_blob(ctx->bs, id, bs_load_iter, ctx);
3379 }
3380 
3381 static void
3382 bs_delete_corrupted_close_cb(void *cb_arg, int bserrno)
3383 {
3384 	struct spdk_bs_load_ctx *ctx = cb_arg;
3385 
3386 	if (bserrno != 0) {
3387 		SPDK_ERRLOG("Failed to close corrupted blob\n");
3388 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3389 		return;
3390 	}
3391 
3392 	spdk_bs_delete_blob(ctx->bs, ctx->blobid, bs_delete_corrupted_blob_cpl, ctx);
3393 }
3394 
3395 static void
3396 bs_delete_corrupted_blob(void *cb_arg, int bserrno)
3397 {
3398 	struct spdk_bs_load_ctx *ctx = cb_arg;
3399 	uint64_t i;
3400 
3401 	if (bserrno != 0) {
3402 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
3403 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3404 		return;
3405 	}
3406 
3407 	/* Snapshot and clone have the same copy of cluster map and extent pages
3408 	 * at this point. Let's clear both for snpashot now,
3409 	 * so that it won't be cleared for clone later when we remove snapshot.
3410 	 * Also set thin provision to pass data corruption check */
3411 	for (i = 0; i < ctx->blob->active.num_clusters; i++) {
3412 		ctx->blob->active.clusters[i] = 0;
3413 	}
3414 	for (i = 0; i < ctx->blob->active.num_extent_pages; i++) {
3415 		ctx->blob->active.extent_pages[i] = 0;
3416 	}
3417 
3418 	ctx->blob->md_ro = false;
3419 
3420 	blob_set_thin_provision(ctx->blob);
3421 
3422 	ctx->blobid = ctx->blob->id;
3423 
3424 	spdk_blob_close(ctx->blob, bs_delete_corrupted_close_cb, ctx);
3425 }
3426 
3427 static void
3428 bs_update_corrupted_blob(void *cb_arg, int bserrno)
3429 {
3430 	struct spdk_bs_load_ctx *ctx = cb_arg;
3431 
3432 	if (bserrno != 0) {
3433 		SPDK_ERRLOG("Failed to close clone of a corrupted blob\n");
3434 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3435 		return;
3436 	}
3437 
3438 	ctx->blob->md_ro = false;
3439 	blob_remove_xattr(ctx->blob, SNAPSHOT_PENDING_REMOVAL, true);
3440 	blob_remove_xattr(ctx->blob, SNAPSHOT_IN_PROGRESS, true);
3441 	spdk_blob_set_read_only(ctx->blob);
3442 
3443 	if (ctx->iter_cb_fn) {
3444 		ctx->iter_cb_fn(ctx->iter_cb_arg, ctx->blob, 0);
3445 	}
3446 	bs_blob_list_add(ctx->blob);
3447 
3448 	spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3449 }
3450 
3451 static void
3452 bs_examine_clone(void *cb_arg, struct spdk_blob *blob, int bserrno)
3453 {
3454 	struct spdk_bs_load_ctx *ctx = cb_arg;
3455 
3456 	if (bserrno != 0) {
3457 		SPDK_ERRLOG("Failed to open clone of a corrupted blob\n");
3458 		spdk_bs_iter_next(ctx->bs, ctx->blob, bs_load_iter, ctx);
3459 		return;
3460 	}
3461 
3462 	if (blob->parent_id == ctx->blob->id) {
3463 		/* Power failure occured before updating clone (snapshot delete case)
3464 		 * or after updating clone (creating snapshot case) - keep snapshot */
3465 		spdk_blob_close(blob, bs_update_corrupted_blob, ctx);
3466 	} else {
3467 		/* Power failure occured after updating clone (snapshot delete case)
3468 		 * or before updating clone (creating snapshot case) - remove snapshot */
3469 		spdk_blob_close(blob, bs_delete_corrupted_blob, ctx);
3470 	}
3471 }
3472 
3473 static void
3474 bs_load_iter(void *arg, struct spdk_blob *blob, int bserrno)
3475 {
3476 	struct spdk_bs_load_ctx *ctx = arg;
3477 	const void *value;
3478 	size_t len;
3479 	int rc = 0;
3480 
3481 	if (bserrno == 0) {
3482 		/* Examine blob if it is corrupted after power failure. Fix
3483 		 * the ones that can be fixed and remove any other corrupted
3484 		 * ones. If it is not corrupted just process it */
3485 		rc = blob_get_xattr_value(blob, SNAPSHOT_PENDING_REMOVAL, &value, &len, true);
3486 		if (rc != 0) {
3487 			rc = blob_get_xattr_value(blob, SNAPSHOT_IN_PROGRESS, &value, &len, true);
3488 			if (rc != 0) {
3489 				/* Not corrupted - process it and continue with iterating through blobs */
3490 				if (ctx->iter_cb_fn) {
3491 					ctx->iter_cb_fn(ctx->iter_cb_arg, blob, 0);
3492 				}
3493 				bs_blob_list_add(blob);
3494 				spdk_bs_iter_next(ctx->bs, blob, bs_load_iter, ctx);
3495 				return;
3496 			}
3497 
3498 		}
3499 
3500 		assert(len == sizeof(spdk_blob_id));
3501 
3502 		ctx->blob = blob;
3503 
3504 		/* Open clone to check if we are able to fix this blob or should we remove it */
3505 		spdk_bs_open_blob(ctx->bs, *(spdk_blob_id *)value, bs_examine_clone, ctx);
3506 		return;
3507 	} else if (bserrno == -ENOENT) {
3508 		bserrno = 0;
3509 	} else {
3510 		/*
3511 		 * This case needs to be looked at further.  Same problem
3512 		 *  exists with applications that rely on explicit blob
3513 		 *  iteration.  We should just skip the blob that failed
3514 		 *  to load and continue on to the next one.
3515 		 */
3516 		SPDK_ERRLOG("Error in iterating blobs\n");
3517 	}
3518 
3519 	ctx->iter_cb_fn = NULL;
3520 
3521 	spdk_free(ctx->super);
3522 	spdk_free(ctx->mask);
3523 	bs_sequence_finish(ctx->seq, bserrno);
3524 	free(ctx);
3525 }
3526 
3527 static void
3528 bs_load_complete(struct spdk_bs_load_ctx *ctx)
3529 {
3530 	spdk_bs_iter_first(ctx->bs, bs_load_iter, ctx);
3531 }
3532 
3533 static void
3534 bs_load_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3535 {
3536 	struct spdk_bs_load_ctx *ctx = cb_arg;
3537 	int rc;
3538 
3539 	/* The type must be correct */
3540 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_BLOBIDS);
3541 
3542 	/* The length of the mask (in bits) must not be greater than
3543 	 * the length of the buffer (converted to bits) */
3544 	assert(ctx->mask->length <= (ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE * 8));
3545 
3546 	/* The length of the mask must be exactly equal to the size
3547 	 * (in pages) of the metadata region */
3548 	assert(ctx->mask->length == ctx->super->md_len);
3549 
3550 	rc = bs_load_mask(&ctx->bs->used_blobids, ctx->mask);
3551 	if (rc < 0) {
3552 		spdk_free(ctx->mask);
3553 		bs_load_ctx_fail(ctx, rc);
3554 		return;
3555 	}
3556 
3557 	bs_load_complete(ctx);
3558 }
3559 
3560 static void
3561 bs_load_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3562 {
3563 	struct spdk_bs_load_ctx *ctx = cb_arg;
3564 	uint64_t		lba, lba_count, mask_size;
3565 	int			rc;
3566 
3567 	if (bserrno != 0) {
3568 		bs_load_ctx_fail(ctx, bserrno);
3569 		return;
3570 	}
3571 
3572 	/* The type must be correct */
3573 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_CLUSTERS);
3574 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
3575 	assert(ctx->mask->length <= (ctx->super->used_cluster_mask_len * sizeof(
3576 					     struct spdk_blob_md_page) * 8));
3577 	/* The length of the mask must be exactly equal to the total number of clusters */
3578 	assert(ctx->mask->length == ctx->bs->total_clusters);
3579 
3580 	rc = bs_load_mask(&ctx->bs->used_clusters, ctx->mask);
3581 	if (rc < 0) {
3582 		spdk_free(ctx->mask);
3583 		bs_load_ctx_fail(ctx, rc);
3584 		return;
3585 	}
3586 
3587 	ctx->bs->num_free_clusters = spdk_bit_array_count_clear(ctx->bs->used_clusters);
3588 	assert(ctx->bs->num_free_clusters <= ctx->bs->total_clusters);
3589 
3590 	spdk_free(ctx->mask);
3591 
3592 	/* Read the used blobids mask */
3593 	mask_size = ctx->super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE;
3594 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
3595 				 SPDK_MALLOC_DMA);
3596 	if (!ctx->mask) {
3597 		bs_load_ctx_fail(ctx, -ENOMEM);
3598 		return;
3599 	}
3600 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_start);
3601 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_blobid_mask_len);
3602 	bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
3603 			     bs_load_used_blobids_cpl, ctx);
3604 }
3605 
3606 static void
3607 bs_load_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3608 {
3609 	struct spdk_bs_load_ctx *ctx = cb_arg;
3610 	uint64_t		lba, lba_count, mask_size;
3611 	int			rc;
3612 
3613 	if (bserrno != 0) {
3614 		bs_load_ctx_fail(ctx, bserrno);
3615 		return;
3616 	}
3617 
3618 	/* The type must be correct */
3619 	assert(ctx->mask->type == SPDK_MD_MASK_TYPE_USED_PAGES);
3620 	/* The length of the mask (in bits) must not be greater than the length of the buffer (converted to bits) */
3621 	assert(ctx->mask->length <= (ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE *
3622 				     8));
3623 	/* The length of the mask must be exactly equal to the size (in pages) of the metadata region */
3624 	assert(ctx->mask->length == ctx->super->md_len);
3625 
3626 	rc = bs_load_mask(&ctx->bs->used_md_pages, ctx->mask);
3627 	if (rc < 0) {
3628 		spdk_free(ctx->mask);
3629 		bs_load_ctx_fail(ctx, rc);
3630 		return;
3631 	}
3632 
3633 	spdk_free(ctx->mask);
3634 
3635 	/* Read the used clusters mask */
3636 	mask_size = ctx->super->used_cluster_mask_len * SPDK_BS_PAGE_SIZE;
3637 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY,
3638 				 SPDK_MALLOC_DMA);
3639 	if (!ctx->mask) {
3640 		bs_load_ctx_fail(ctx, -ENOMEM);
3641 		return;
3642 	}
3643 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_start);
3644 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_cluster_mask_len);
3645 	bs_sequence_read_dev(seq, ctx->mask, lba, lba_count,
3646 			     bs_load_used_clusters_cpl, ctx);
3647 }
3648 
3649 static void
3650 bs_load_read_used_pages(struct spdk_bs_load_ctx *ctx)
3651 {
3652 	uint64_t lba, lba_count, mask_size;
3653 
3654 	/* Read the used pages mask */
3655 	mask_size = ctx->super->used_page_mask_len * SPDK_BS_PAGE_SIZE;
3656 	ctx->mask = spdk_zmalloc(mask_size, 0x1000, NULL,
3657 				 SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3658 	if (!ctx->mask) {
3659 		bs_load_ctx_fail(ctx, -ENOMEM);
3660 		return;
3661 	}
3662 
3663 	lba = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_start);
3664 	lba_count = bs_page_to_lba(ctx->bs, ctx->super->used_page_mask_len);
3665 	bs_sequence_read_dev(ctx->seq, ctx->mask, lba, lba_count,
3666 			     bs_load_used_pages_cpl, ctx);
3667 }
3668 
3669 static int
3670 bs_load_replay_md_parse_page(struct spdk_bs_load_ctx *ctx, struct spdk_blob_md_page *page)
3671 {
3672 	struct spdk_blob_store *bs = ctx->bs;
3673 	struct spdk_blob_md_descriptor *desc;
3674 	size_t	cur_desc = 0;
3675 
3676 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3677 	while (cur_desc < sizeof(page->descriptors)) {
3678 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
3679 			if (desc->length == 0) {
3680 				/* If padding and length are 0, this terminates the page */
3681 				break;
3682 			}
3683 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
3684 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
3685 			unsigned int				i, j;
3686 			unsigned int				cluster_count = 0;
3687 			uint32_t				cluster_idx;
3688 
3689 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
3690 
3691 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
3692 				for (j = 0; j < desc_extent_rle->extents[i].length; j++) {
3693 					cluster_idx = desc_extent_rle->extents[i].cluster_idx;
3694 					/*
3695 					 * cluster_idx = 0 means an unallocated cluster - don't mark that
3696 					 * in the used cluster map.
3697 					 */
3698 					if (cluster_idx != 0) {
3699 						spdk_bit_array_set(bs->used_clusters, cluster_idx + j);
3700 						if (bs->num_free_clusters == 0) {
3701 							return -ENOSPC;
3702 						}
3703 						bs->num_free_clusters--;
3704 					}
3705 					cluster_count++;
3706 				}
3707 			}
3708 			if (cluster_count == 0) {
3709 				return -EINVAL;
3710 			}
3711 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
3712 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
3713 			uint32_t					i;
3714 			uint32_t					cluster_count = 0;
3715 			uint32_t					cluster_idx;
3716 			size_t						cluster_idx_length;
3717 
3718 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
3719 			cluster_idx_length = desc_extent->length - sizeof(desc_extent->start_cluster_idx);
3720 
3721 			if (desc_extent->length <= sizeof(desc_extent->start_cluster_idx) ||
3722 			    (cluster_idx_length % sizeof(desc_extent->cluster_idx[0]) != 0)) {
3723 				return -EINVAL;
3724 			}
3725 
3726 			for (i = 0; i < cluster_idx_length / sizeof(desc_extent->cluster_idx[0]); i++) {
3727 				cluster_idx = desc_extent->cluster_idx[i];
3728 				/*
3729 				 * cluster_idx = 0 means an unallocated cluster - don't mark that
3730 				 * in the used cluster map.
3731 				 */
3732 				if (cluster_idx != 0) {
3733 					if (cluster_idx < desc_extent->start_cluster_idx &&
3734 					    cluster_idx >= desc_extent->start_cluster_idx + cluster_count) {
3735 						return -EINVAL;
3736 					}
3737 					spdk_bit_array_set(bs->used_clusters, cluster_idx);
3738 					if (bs->num_free_clusters == 0) {
3739 						return -ENOSPC;
3740 					}
3741 					bs->num_free_clusters--;
3742 				}
3743 				cluster_count++;
3744 			}
3745 
3746 			if (cluster_count == 0) {
3747 				return -EINVAL;
3748 			}
3749 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
3750 			/* Skip this item */
3751 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
3752 			/* Skip this item */
3753 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
3754 			/* Skip this item */
3755 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_TABLE) {
3756 			struct spdk_blob_md_descriptor_extent_table *desc_extent_table;
3757 			uint32_t num_extent_pages = ctx->num_extent_pages;
3758 			uint32_t i;
3759 			size_t extent_pages_length;
3760 			void *tmp;
3761 
3762 			desc_extent_table = (struct spdk_blob_md_descriptor_extent_table *)desc;
3763 			extent_pages_length = desc_extent_table->length - sizeof(desc_extent_table->num_clusters);
3764 
3765 			if (desc_extent_table->length == 0 ||
3766 			    (extent_pages_length % sizeof(desc_extent_table->extent_page[0]) != 0)) {
3767 				return -EINVAL;
3768 			}
3769 
3770 			for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
3771 				if (desc_extent_table->extent_page[i].page_idx != 0) {
3772 					if (desc_extent_table->extent_page[i].num_pages != 1) {
3773 						return -EINVAL;
3774 					}
3775 					num_extent_pages += 1;
3776 				}
3777 			}
3778 
3779 			if (num_extent_pages > 0) {
3780 				tmp = realloc(ctx->extent_page_num, num_extent_pages * sizeof(uint32_t));
3781 				if (tmp == NULL) {
3782 					return -ENOMEM;
3783 				}
3784 				ctx->extent_page_num = tmp;
3785 
3786 				/* Extent table entries contain md page numbers for extent pages.
3787 				 * Zeroes represent unallocated extent pages, those are run-length-encoded.
3788 				 */
3789 				for (i = 0; i < extent_pages_length / sizeof(desc_extent_table->extent_page[0]); i++) {
3790 					if (desc_extent_table->extent_page[i].page_idx != 0) {
3791 						ctx->extent_page_num[ctx->num_extent_pages] = desc_extent_table->extent_page[i].page_idx;
3792 						ctx->num_extent_pages += 1;
3793 					}
3794 				}
3795 			}
3796 		} else {
3797 			/* Error */
3798 			return -EINVAL;
3799 		}
3800 		/* Advance to the next descriptor */
3801 		cur_desc += sizeof(*desc) + desc->length;
3802 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
3803 			break;
3804 		}
3805 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
3806 	}
3807 	return 0;
3808 }
3809 
3810 static bool bs_load_cur_extent_page_valid(struct spdk_blob_md_page *page)
3811 {
3812 	uint32_t crc;
3813 	struct spdk_blob_md_descriptor *desc = (struct spdk_blob_md_descriptor *)page->descriptors;
3814 	size_t desc_len;
3815 
3816 	crc = blob_md_page_calc_crc(page);
3817 	if (crc != page->crc) {
3818 		return false;
3819 	}
3820 
3821 	/* Extent page should always be of sequence num 0. */
3822 	if (page->sequence_num != 0) {
3823 		return false;
3824 	}
3825 
3826 	/* Descriptor type must be EXTENT_PAGE. */
3827 	if (desc->type != SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
3828 		return false;
3829 	}
3830 
3831 	/* Descriptor length cannot exceed the page. */
3832 	desc_len = sizeof(*desc) + desc->length;
3833 	if (desc_len > sizeof(page->descriptors)) {
3834 		return false;
3835 	}
3836 
3837 	/* It has to be the only descriptor in the page. */
3838 	if (desc_len + sizeof(*desc) <= sizeof(page->descriptors)) {
3839 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + desc_len);
3840 		if (desc->length != 0) {
3841 			return false;
3842 		}
3843 	}
3844 
3845 	return true;
3846 }
3847 
3848 static bool bs_load_cur_md_page_valid(struct spdk_bs_load_ctx *ctx)
3849 {
3850 	uint32_t crc;
3851 	struct spdk_blob_md_page *page = ctx->page;
3852 
3853 	crc = blob_md_page_calc_crc(page);
3854 	if (crc != page->crc) {
3855 		return false;
3856 	}
3857 
3858 	/* First page of a sequence should match the blobid. */
3859 	if (page->sequence_num == 0 &&
3860 	    bs_page_to_blobid(ctx->cur_page) != page->id) {
3861 		return false;
3862 	}
3863 	assert(bs_load_cur_extent_page_valid(page) == false);
3864 
3865 	return true;
3866 }
3867 
3868 static void
3869 bs_load_replay_cur_md_page(struct spdk_bs_load_ctx *ctx);
3870 
3871 static void
3872 bs_load_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3873 {
3874 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3875 
3876 	if (bserrno != 0) {
3877 		bs_load_ctx_fail(ctx, bserrno);
3878 		return;
3879 	}
3880 
3881 	bs_load_complete(ctx);
3882 }
3883 
3884 static void
3885 bs_load_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3886 {
3887 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3888 
3889 	spdk_free(ctx->mask);
3890 	ctx->mask = NULL;
3891 
3892 	if (bserrno != 0) {
3893 		bs_load_ctx_fail(ctx, bserrno);
3894 		return;
3895 	}
3896 
3897 	bs_write_used_clusters(seq, ctx, bs_load_write_used_clusters_cpl);
3898 }
3899 
3900 static void
3901 bs_load_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3902 {
3903 	struct spdk_bs_load_ctx	*ctx = cb_arg;
3904 
3905 	spdk_free(ctx->mask);
3906 	ctx->mask = NULL;
3907 
3908 	if (bserrno != 0) {
3909 		bs_load_ctx_fail(ctx, bserrno);
3910 		return;
3911 	}
3912 
3913 	bs_write_used_blobids(seq, ctx, bs_load_write_used_blobids_cpl);
3914 }
3915 
3916 static void
3917 bs_load_write_used_md(struct spdk_bs_load_ctx *ctx)
3918 {
3919 	bs_write_used_md(ctx->seq, ctx, bs_load_write_used_pages_cpl);
3920 }
3921 
3922 static void
3923 bs_load_replay_md_chain_cpl(struct spdk_bs_load_ctx *ctx)
3924 {
3925 	uint64_t num_md_clusters;
3926 	uint64_t i;
3927 
3928 	ctx->in_page_chain = false;
3929 
3930 	do {
3931 		ctx->page_index++;
3932 	} while (spdk_bit_array_get(ctx->bs->used_md_pages, ctx->page_index) == true);
3933 
3934 	if (ctx->page_index < ctx->super->md_len) {
3935 		ctx->cur_page = ctx->page_index;
3936 		bs_load_replay_cur_md_page(ctx);
3937 	} else {
3938 		/* Claim all of the clusters used by the metadata */
3939 		num_md_clusters = spdk_divide_round_up(ctx->super->md_len, ctx->bs->pages_per_cluster);
3940 		for (i = 0; i < num_md_clusters; i++) {
3941 			bs_claim_cluster(ctx->bs, i);
3942 		}
3943 		spdk_free(ctx->page);
3944 		bs_load_write_used_md(ctx);
3945 	}
3946 }
3947 
3948 static void
3949 bs_load_replay_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
3950 {
3951 	struct spdk_bs_load_ctx *ctx = cb_arg;
3952 	uint32_t page_num;
3953 	uint64_t i;
3954 
3955 	if (bserrno != 0) {
3956 		spdk_free(ctx->extent_pages);
3957 		bs_load_ctx_fail(ctx, bserrno);
3958 		return;
3959 	}
3960 
3961 	for (i = 0; i < ctx->num_extent_pages; i++) {
3962 		/* Extent pages are only read when present within in chain md.
3963 		 * Integrity of md is not right if that page was not a valid extent page. */
3964 		if (bs_load_cur_extent_page_valid(&ctx->extent_pages[i]) != true) {
3965 			spdk_free(ctx->extent_pages);
3966 			bs_load_ctx_fail(ctx, -EILSEQ);
3967 			return;
3968 		}
3969 
3970 		page_num = ctx->extent_page_num[i];
3971 		spdk_bit_array_set(ctx->bs->used_md_pages, page_num);
3972 		if (bs_load_replay_md_parse_page(ctx, &ctx->extent_pages[i])) {
3973 			spdk_free(ctx->extent_pages);
3974 			bs_load_ctx_fail(ctx, -EILSEQ);
3975 			return;
3976 		}
3977 	}
3978 
3979 	spdk_free(ctx->extent_pages);
3980 	free(ctx->extent_page_num);
3981 	ctx->extent_page_num = NULL;
3982 	ctx->num_extent_pages = 0;
3983 
3984 	bs_load_replay_md_chain_cpl(ctx);
3985 }
3986 
3987 static void
3988 bs_load_replay_extent_pages(struct spdk_bs_load_ctx *ctx)
3989 {
3990 	spdk_bs_batch_t *batch;
3991 	uint32_t page;
3992 	uint64_t lba;
3993 	uint64_t i;
3994 
3995 	ctx->extent_pages = spdk_zmalloc(SPDK_BS_PAGE_SIZE * ctx->num_extent_pages, SPDK_BS_PAGE_SIZE,
3996 					 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
3997 	if (!ctx->extent_pages) {
3998 		bs_load_ctx_fail(ctx, -ENOMEM);
3999 		return;
4000 	}
4001 
4002 	batch = bs_sequence_to_batch(ctx->seq, bs_load_replay_extent_page_cpl, ctx);
4003 
4004 	for (i = 0; i < ctx->num_extent_pages; i++) {
4005 		page = ctx->extent_page_num[i];
4006 		assert(page < ctx->super->md_len);
4007 		lba = bs_md_page_to_lba(ctx->bs, page);
4008 		bs_batch_read_dev(batch, &ctx->extent_pages[i], lba,
4009 				  bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE));
4010 	}
4011 
4012 	bs_batch_close(batch);
4013 }
4014 
4015 static void
4016 bs_load_replay_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4017 {
4018 	struct spdk_bs_load_ctx *ctx = cb_arg;
4019 	uint32_t page_num;
4020 	struct spdk_blob_md_page *page;
4021 
4022 	if (bserrno != 0) {
4023 		bs_load_ctx_fail(ctx, bserrno);
4024 		return;
4025 	}
4026 
4027 	page_num = ctx->cur_page;
4028 	page = ctx->page;
4029 	if (bs_load_cur_md_page_valid(ctx) == true) {
4030 		if (page->sequence_num == 0 || ctx->in_page_chain == true) {
4031 			bs_claim_md_page(ctx->bs, page_num);
4032 			if (page->sequence_num == 0) {
4033 				spdk_bit_array_set(ctx->bs->used_blobids, page_num);
4034 			}
4035 			if (bs_load_replay_md_parse_page(ctx, page)) {
4036 				bs_load_ctx_fail(ctx, -EILSEQ);
4037 				return;
4038 			}
4039 			if (page->next != SPDK_INVALID_MD_PAGE) {
4040 				ctx->in_page_chain = true;
4041 				ctx->cur_page = page->next;
4042 				bs_load_replay_cur_md_page(ctx);
4043 				return;
4044 			}
4045 			if (ctx->num_extent_pages != 0) {
4046 				bs_load_replay_extent_pages(ctx);
4047 				return;
4048 			}
4049 		}
4050 	}
4051 	bs_load_replay_md_chain_cpl(ctx);
4052 }
4053 
4054 static void
4055 bs_load_replay_cur_md_page(struct spdk_bs_load_ctx *ctx)
4056 {
4057 	uint64_t lba;
4058 
4059 	assert(ctx->cur_page < ctx->super->md_len);
4060 	lba = bs_md_page_to_lba(ctx->bs, ctx->cur_page);
4061 	bs_sequence_read_dev(ctx->seq, ctx->page, lba,
4062 			     bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
4063 			     bs_load_replay_md_cpl, ctx);
4064 }
4065 
4066 static void
4067 bs_load_replay_md(struct spdk_bs_load_ctx *ctx)
4068 {
4069 	ctx->page_index = 0;
4070 	ctx->cur_page = 0;
4071 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
4072 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4073 	if (!ctx->page) {
4074 		bs_load_ctx_fail(ctx, -ENOMEM);
4075 		return;
4076 	}
4077 	bs_load_replay_cur_md_page(ctx);
4078 }
4079 
4080 static void
4081 bs_recover(struct spdk_bs_load_ctx *ctx)
4082 {
4083 	int		rc;
4084 
4085 	rc = spdk_bit_array_resize(&ctx->bs->used_md_pages, ctx->super->md_len);
4086 	if (rc < 0) {
4087 		bs_load_ctx_fail(ctx, -ENOMEM);
4088 		return;
4089 	}
4090 
4091 	rc = spdk_bit_array_resize(&ctx->bs->used_blobids, ctx->super->md_len);
4092 	if (rc < 0) {
4093 		bs_load_ctx_fail(ctx, -ENOMEM);
4094 		return;
4095 	}
4096 
4097 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
4098 	if (rc < 0) {
4099 		bs_load_ctx_fail(ctx, -ENOMEM);
4100 		return;
4101 	}
4102 
4103 	rc = spdk_bit_array_resize(&ctx->bs->open_blobids, ctx->super->md_len);
4104 	if (rc < 0) {
4105 		bs_load_ctx_fail(ctx, -ENOMEM);
4106 		return;
4107 	}
4108 
4109 	ctx->bs->num_free_clusters = ctx->bs->total_clusters;
4110 	bs_load_replay_md(ctx);
4111 }
4112 
4113 static void
4114 bs_load_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4115 {
4116 	struct spdk_bs_load_ctx *ctx = cb_arg;
4117 	uint32_t	crc;
4118 	int		rc;
4119 	static const char zeros[SPDK_BLOBSTORE_TYPE_LENGTH];
4120 
4121 	if (ctx->super->version > SPDK_BS_VERSION ||
4122 	    ctx->super->version < SPDK_BS_INITIAL_VERSION) {
4123 		bs_load_ctx_fail(ctx, -EILSEQ);
4124 		return;
4125 	}
4126 
4127 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
4128 		   sizeof(ctx->super->signature)) != 0) {
4129 		bs_load_ctx_fail(ctx, -EILSEQ);
4130 		return;
4131 	}
4132 
4133 	crc = blob_md_page_calc_crc(ctx->super);
4134 	if (crc != ctx->super->crc) {
4135 		bs_load_ctx_fail(ctx, -EILSEQ);
4136 		return;
4137 	}
4138 
4139 	if (memcmp(&ctx->bs->bstype, &ctx->super->bstype, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
4140 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype matched - loading blobstore\n");
4141 	} else if (memcmp(&ctx->bs->bstype, zeros, SPDK_BLOBSTORE_TYPE_LENGTH) == 0) {
4142 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Bstype wildcard used - loading blobstore regardless bstype\n");
4143 	} else {
4144 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Unexpected bstype\n");
4145 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Expected:", ctx->bs->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
4146 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "Found:", ctx->super->bstype.bstype, SPDK_BLOBSTORE_TYPE_LENGTH);
4147 		bs_load_ctx_fail(ctx, -ENXIO);
4148 		return;
4149 	}
4150 
4151 	if (ctx->super->size > ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen) {
4152 		SPDK_NOTICELOG("Size mismatch, dev size: %lu, blobstore size: %lu\n",
4153 			       ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen, ctx->super->size);
4154 		bs_load_ctx_fail(ctx, -EILSEQ);
4155 		return;
4156 	}
4157 
4158 	if (ctx->super->size == 0) {
4159 		ctx->super->size = ctx->bs->dev->blockcnt * ctx->bs->dev->blocklen;
4160 	}
4161 
4162 	if (ctx->super->io_unit_size == 0) {
4163 		ctx->super->io_unit_size = SPDK_BS_PAGE_SIZE;
4164 	}
4165 
4166 	/* Parse the super block */
4167 	ctx->bs->clean = 1;
4168 	ctx->bs->cluster_sz = ctx->super->cluster_size;
4169 	ctx->bs->total_clusters = ctx->super->size / ctx->super->cluster_size;
4170 	ctx->bs->pages_per_cluster = ctx->bs->cluster_sz / SPDK_BS_PAGE_SIZE;
4171 	if (spdk_u32_is_pow2(ctx->bs->pages_per_cluster)) {
4172 		ctx->bs->pages_per_cluster_shift = spdk_u32log2(ctx->bs->pages_per_cluster);
4173 	}
4174 	ctx->bs->io_unit_size = ctx->super->io_unit_size;
4175 	rc = spdk_bit_array_resize(&ctx->bs->used_clusters, ctx->bs->total_clusters);
4176 	if (rc < 0) {
4177 		bs_load_ctx_fail(ctx, -ENOMEM);
4178 		return;
4179 	}
4180 	ctx->bs->md_start = ctx->super->md_start;
4181 	ctx->bs->md_len = ctx->super->md_len;
4182 	ctx->bs->total_data_clusters = ctx->bs->total_clusters - spdk_divide_round_up(
4183 					       ctx->bs->md_start + ctx->bs->md_len, ctx->bs->pages_per_cluster);
4184 	ctx->bs->super_blob = ctx->super->super_blob;
4185 	memcpy(&ctx->bs->bstype, &ctx->super->bstype, sizeof(ctx->super->bstype));
4186 
4187 	if (ctx->super->used_blobid_mask_len == 0 || ctx->super->clean == 0) {
4188 		bs_recover(ctx);
4189 	} else {
4190 		bs_load_read_used_pages(ctx);
4191 	}
4192 }
4193 
4194 void
4195 spdk_bs_load(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
4196 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
4197 {
4198 	struct spdk_blob_store	*bs;
4199 	struct spdk_bs_cpl	cpl;
4200 	struct spdk_bs_load_ctx *ctx;
4201 	struct spdk_bs_opts	opts = {};
4202 	int err;
4203 
4204 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Loading blobstore from dev %p\n", dev);
4205 
4206 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
4207 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "unsupported dev block length of %d\n", dev->blocklen);
4208 		dev->destroy(dev);
4209 		cb_fn(cb_arg, NULL, -EINVAL);
4210 		return;
4211 	}
4212 
4213 	if (o) {
4214 		opts = *o;
4215 	} else {
4216 		spdk_bs_opts_init(&opts);
4217 	}
4218 
4219 	if (opts.max_md_ops == 0 || opts.max_channel_ops == 0) {
4220 		dev->destroy(dev);
4221 		cb_fn(cb_arg, NULL, -EINVAL);
4222 		return;
4223 	}
4224 
4225 	err = bs_alloc(dev, &opts, &bs);
4226 	if (err) {
4227 		dev->destroy(dev);
4228 		cb_fn(cb_arg, NULL, err);
4229 		return;
4230 	}
4231 
4232 	ctx = calloc(1, sizeof(*ctx));
4233 	if (!ctx) {
4234 		bs_free(bs);
4235 		cb_fn(cb_arg, NULL, -ENOMEM);
4236 		return;
4237 	}
4238 
4239 	ctx->bs = bs;
4240 	ctx->iter_cb_fn = opts.iter_cb_fn;
4241 	ctx->iter_cb_arg = opts.iter_cb_arg;
4242 
4243 	/* Allocate memory for the super block */
4244 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4245 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4246 	if (!ctx->super) {
4247 		free(ctx);
4248 		bs_free(bs);
4249 		cb_fn(cb_arg, NULL, -ENOMEM);
4250 		return;
4251 	}
4252 
4253 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
4254 	cpl.u.bs_handle.cb_fn = cb_fn;
4255 	cpl.u.bs_handle.cb_arg = cb_arg;
4256 	cpl.u.bs_handle.bs = bs;
4257 
4258 	ctx->seq = bs_sequence_start(bs->md_channel, &cpl);
4259 	if (!ctx->seq) {
4260 		spdk_free(ctx->super);
4261 		free(ctx);
4262 		bs_free(bs);
4263 		cb_fn(cb_arg, NULL, -ENOMEM);
4264 		return;
4265 	}
4266 
4267 	/* Read the super block */
4268 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
4269 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
4270 			     bs_load_super_cpl, ctx);
4271 }
4272 
4273 /* END spdk_bs_load */
4274 
4275 /* START spdk_bs_dump */
4276 
4277 struct spdk_bs_dump_ctx {
4278 	struct spdk_blob_store		*bs;
4279 	struct spdk_bs_super_block	*super;
4280 	uint32_t			cur_page;
4281 	struct spdk_blob_md_page	*page;
4282 	spdk_bs_sequence_t		*seq;
4283 	FILE				*fp;
4284 	spdk_bs_dump_print_xattr	print_xattr_fn;
4285 	char				xattr_name[4096];
4286 };
4287 
4288 static void
4289 bs_dump_finish(spdk_bs_sequence_t *seq, struct spdk_bs_dump_ctx *ctx, int bserrno)
4290 {
4291 	spdk_free(ctx->super);
4292 
4293 	/*
4294 	 * We need to defer calling bs_call_cpl() until after
4295 	 * dev destruction, so tuck these away for later use.
4296 	 */
4297 	ctx->bs->unload_err = bserrno;
4298 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
4299 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
4300 
4301 	bs_sequence_finish(seq, 0);
4302 	bs_free(ctx->bs);
4303 	free(ctx);
4304 }
4305 
4306 static void bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg);
4307 
4308 static void
4309 bs_dump_print_md_page(struct spdk_bs_dump_ctx *ctx)
4310 {
4311 	uint32_t page_idx = ctx->cur_page;
4312 	struct spdk_blob_md_page *page = ctx->page;
4313 	struct spdk_blob_md_descriptor *desc;
4314 	size_t cur_desc = 0;
4315 	uint32_t crc;
4316 
4317 	fprintf(ctx->fp, "=========\n");
4318 	fprintf(ctx->fp, "Metadata Page Index: %" PRIu32 " (0x%" PRIx32 ")\n", page_idx, page_idx);
4319 	fprintf(ctx->fp, "Blob ID: 0x%" PRIx64 "\n", page->id);
4320 
4321 	crc = blob_md_page_calc_crc(page);
4322 	fprintf(ctx->fp, "CRC: 0x%" PRIx32 " (%s)\n", page->crc, crc == page->crc ? "OK" : "Mismatch");
4323 
4324 	desc = (struct spdk_blob_md_descriptor *)page->descriptors;
4325 	while (cur_desc < sizeof(page->descriptors)) {
4326 		if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_PADDING) {
4327 			if (desc->length == 0) {
4328 				/* If padding and length are 0, this terminates the page */
4329 				break;
4330 			}
4331 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_RLE) {
4332 			struct spdk_blob_md_descriptor_extent_rle	*desc_extent_rle;
4333 			unsigned int				i;
4334 
4335 			desc_extent_rle = (struct spdk_blob_md_descriptor_extent_rle *)desc;
4336 
4337 			for (i = 0; i < desc_extent_rle->length / sizeof(desc_extent_rle->extents[0]); i++) {
4338 				if (desc_extent_rle->extents[i].cluster_idx != 0) {
4339 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
4340 						desc_extent_rle->extents[i].cluster_idx);
4341 				} else {
4342 					fprintf(ctx->fp, "Unallocated Extent - ");
4343 				}
4344 				fprintf(ctx->fp, " Length: %" PRIu32, desc_extent_rle->extents[i].length);
4345 				fprintf(ctx->fp, "\n");
4346 			}
4347 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_EXTENT_PAGE) {
4348 			struct spdk_blob_md_descriptor_extent_page	*desc_extent;
4349 			unsigned int					i;
4350 
4351 			desc_extent = (struct spdk_blob_md_descriptor_extent_page *)desc;
4352 
4353 			for (i = 0; i < desc_extent->length / sizeof(desc_extent->cluster_idx[0]); i++) {
4354 				if (desc_extent->cluster_idx[i] != 0) {
4355 					fprintf(ctx->fp, "Allocated Extent - Start: %" PRIu32,
4356 						desc_extent->cluster_idx[i]);
4357 				} else {
4358 					fprintf(ctx->fp, "Unallocated Extent");
4359 				}
4360 				fprintf(ctx->fp, "\n");
4361 			}
4362 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR) {
4363 			struct spdk_blob_md_descriptor_xattr *desc_xattr;
4364 			uint32_t i;
4365 
4366 			desc_xattr = (struct spdk_blob_md_descriptor_xattr *)desc;
4367 
4368 			if (desc_xattr->length !=
4369 			    sizeof(desc_xattr->name_length) + sizeof(desc_xattr->value_length) +
4370 			    desc_xattr->name_length + desc_xattr->value_length) {
4371 			}
4372 
4373 			memcpy(ctx->xattr_name, desc_xattr->name, desc_xattr->name_length);
4374 			ctx->xattr_name[desc_xattr->name_length] = '\0';
4375 			fprintf(ctx->fp, "XATTR: name = \"%s\"\n", ctx->xattr_name);
4376 			fprintf(ctx->fp, "       value = \"");
4377 			ctx->print_xattr_fn(ctx->fp, ctx->super->bstype.bstype, ctx->xattr_name,
4378 					    (void *)((uintptr_t)desc_xattr->name + desc_xattr->name_length),
4379 					    desc_xattr->value_length);
4380 			fprintf(ctx->fp, "\"\n");
4381 			for (i = 0; i < desc_xattr->value_length; i++) {
4382 				if (i % 16 == 0) {
4383 					fprintf(ctx->fp, "               ");
4384 				}
4385 				fprintf(ctx->fp, "%02" PRIx8 " ", *((uint8_t *)desc_xattr->name + desc_xattr->name_length + i));
4386 				if ((i + 1) % 16 == 0) {
4387 					fprintf(ctx->fp, "\n");
4388 				}
4389 			}
4390 			if (i % 16 != 0) {
4391 				fprintf(ctx->fp, "\n");
4392 			}
4393 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_XATTR_INTERNAL) {
4394 			/* TODO */
4395 		} else if (desc->type == SPDK_MD_DESCRIPTOR_TYPE_FLAGS) {
4396 			/* TODO */
4397 		} else {
4398 			/* Error */
4399 		}
4400 		/* Advance to the next descriptor */
4401 		cur_desc += sizeof(*desc) + desc->length;
4402 		if (cur_desc + sizeof(*desc) > sizeof(page->descriptors)) {
4403 			break;
4404 		}
4405 		desc = (struct spdk_blob_md_descriptor *)((uintptr_t)page->descriptors + cur_desc);
4406 	}
4407 }
4408 
4409 static void
4410 bs_dump_read_md_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4411 {
4412 	struct spdk_bs_dump_ctx *ctx = cb_arg;
4413 
4414 	if (bserrno != 0) {
4415 		bs_dump_finish(seq, ctx, bserrno);
4416 		return;
4417 	}
4418 
4419 	if (ctx->page->id != 0) {
4420 		bs_dump_print_md_page(ctx);
4421 	}
4422 
4423 	ctx->cur_page++;
4424 
4425 	if (ctx->cur_page < ctx->super->md_len) {
4426 		bs_dump_read_md_page(seq, ctx);
4427 	} else {
4428 		spdk_free(ctx->page);
4429 		bs_dump_finish(seq, ctx, 0);
4430 	}
4431 }
4432 
4433 static void
4434 bs_dump_read_md_page(spdk_bs_sequence_t *seq, void *cb_arg)
4435 {
4436 	struct spdk_bs_dump_ctx *ctx = cb_arg;
4437 	uint64_t lba;
4438 
4439 	assert(ctx->cur_page < ctx->super->md_len);
4440 	lba = bs_page_to_lba(ctx->bs, ctx->super->md_start + ctx->cur_page);
4441 	bs_sequence_read_dev(seq, ctx->page, lba,
4442 			     bs_byte_to_lba(ctx->bs, SPDK_BS_PAGE_SIZE),
4443 			     bs_dump_read_md_page_cpl, ctx);
4444 }
4445 
4446 static void
4447 bs_dump_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4448 {
4449 	struct spdk_bs_dump_ctx *ctx = cb_arg;
4450 
4451 	fprintf(ctx->fp, "Signature: \"%.8s\" ", ctx->super->signature);
4452 	if (memcmp(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
4453 		   sizeof(ctx->super->signature)) != 0) {
4454 		fprintf(ctx->fp, "(Mismatch)\n");
4455 		bs_dump_finish(seq, ctx, bserrno);
4456 		return;
4457 	} else {
4458 		fprintf(ctx->fp, "(OK)\n");
4459 	}
4460 	fprintf(ctx->fp, "Version: %" PRIu32 "\n", ctx->super->version);
4461 	fprintf(ctx->fp, "CRC: 0x%x (%s)\n", ctx->super->crc,
4462 		(ctx->super->crc == blob_md_page_calc_crc(ctx->super)) ? "OK" : "Mismatch");
4463 	fprintf(ctx->fp, "Blobstore Type: %.*s\n", SPDK_BLOBSTORE_TYPE_LENGTH, ctx->super->bstype.bstype);
4464 	fprintf(ctx->fp, "Cluster Size: %" PRIu32 "\n", ctx->super->cluster_size);
4465 	fprintf(ctx->fp, "Super Blob ID: ");
4466 	if (ctx->super->super_blob == SPDK_BLOBID_INVALID) {
4467 		fprintf(ctx->fp, "(None)\n");
4468 	} else {
4469 		fprintf(ctx->fp, "%" PRIu64 "\n", ctx->super->super_blob);
4470 	}
4471 	fprintf(ctx->fp, "Clean: %" PRIu32 "\n", ctx->super->clean);
4472 	fprintf(ctx->fp, "Used Metadata Page Mask Start: %" PRIu32 "\n", ctx->super->used_page_mask_start);
4473 	fprintf(ctx->fp, "Used Metadata Page Mask Length: %" PRIu32 "\n", ctx->super->used_page_mask_len);
4474 	fprintf(ctx->fp, "Used Cluster Mask Start: %" PRIu32 "\n", ctx->super->used_cluster_mask_start);
4475 	fprintf(ctx->fp, "Used Cluster Mask Length: %" PRIu32 "\n", ctx->super->used_cluster_mask_len);
4476 	fprintf(ctx->fp, "Used Blob ID Mask Start: %" PRIu32 "\n", ctx->super->used_blobid_mask_start);
4477 	fprintf(ctx->fp, "Used Blob ID Mask Length: %" PRIu32 "\n", ctx->super->used_blobid_mask_len);
4478 	fprintf(ctx->fp, "Metadata Start: %" PRIu32 "\n", ctx->super->md_start);
4479 	fprintf(ctx->fp, "Metadata Length: %" PRIu32 "\n", ctx->super->md_len);
4480 
4481 	ctx->cur_page = 0;
4482 	ctx->page = spdk_zmalloc(SPDK_BS_PAGE_SIZE, SPDK_BS_PAGE_SIZE,
4483 				 NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4484 	if (!ctx->page) {
4485 		bs_dump_finish(seq, ctx, -ENOMEM);
4486 		return;
4487 	}
4488 	bs_dump_read_md_page(seq, ctx);
4489 }
4490 
4491 void
4492 spdk_bs_dump(struct spdk_bs_dev *dev, FILE *fp, spdk_bs_dump_print_xattr print_xattr_fn,
4493 	     spdk_bs_op_complete cb_fn, void *cb_arg)
4494 {
4495 	struct spdk_blob_store	*bs;
4496 	struct spdk_bs_cpl	cpl;
4497 	spdk_bs_sequence_t	*seq;
4498 	struct spdk_bs_dump_ctx *ctx;
4499 	struct spdk_bs_opts	opts = {};
4500 	int err;
4501 
4502 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Dumping blobstore from dev %p\n", dev);
4503 
4504 	spdk_bs_opts_init(&opts);
4505 
4506 	err = bs_alloc(dev, &opts, &bs);
4507 	if (err) {
4508 		dev->destroy(dev);
4509 		cb_fn(cb_arg, err);
4510 		return;
4511 	}
4512 
4513 	ctx = calloc(1, sizeof(*ctx));
4514 	if (!ctx) {
4515 		bs_free(bs);
4516 		cb_fn(cb_arg, -ENOMEM);
4517 		return;
4518 	}
4519 
4520 	ctx->bs = bs;
4521 	ctx->fp = fp;
4522 	ctx->print_xattr_fn = print_xattr_fn;
4523 
4524 	/* Allocate memory for the super block */
4525 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4526 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4527 	if (!ctx->super) {
4528 		free(ctx);
4529 		bs_free(bs);
4530 		cb_fn(cb_arg, -ENOMEM);
4531 		return;
4532 	}
4533 
4534 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4535 	cpl.u.bs_basic.cb_fn = cb_fn;
4536 	cpl.u.bs_basic.cb_arg = cb_arg;
4537 
4538 	seq = bs_sequence_start(bs->md_channel, &cpl);
4539 	if (!seq) {
4540 		spdk_free(ctx->super);
4541 		free(ctx);
4542 		bs_free(bs);
4543 		cb_fn(cb_arg, -ENOMEM);
4544 		return;
4545 	}
4546 
4547 	/* Read the super block */
4548 	bs_sequence_read_dev(seq, ctx->super, bs_page_to_lba(bs, 0),
4549 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
4550 			     bs_dump_super_cpl, ctx);
4551 }
4552 
4553 /* END spdk_bs_dump */
4554 
4555 /* START spdk_bs_init */
4556 
4557 struct spdk_bs_init_ctx {
4558 	struct spdk_blob_store		*bs;
4559 	struct spdk_bs_super_block	*super;
4560 };
4561 
4562 static void
4563 bs_init_persist_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4564 {
4565 	struct spdk_bs_init_ctx *ctx = cb_arg;
4566 
4567 	spdk_free(ctx->super);
4568 	free(ctx);
4569 
4570 	bs_sequence_finish(seq, bserrno);
4571 }
4572 
4573 static void
4574 bs_init_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4575 {
4576 	struct spdk_bs_init_ctx *ctx = cb_arg;
4577 
4578 	/* Write super block */
4579 	bs_sequence_write_dev(seq, ctx->super, bs_page_to_lba(ctx->bs, 0),
4580 			      bs_byte_to_lba(ctx->bs, sizeof(*ctx->super)),
4581 			      bs_init_persist_super_cpl, ctx);
4582 }
4583 
4584 void
4585 spdk_bs_init(struct spdk_bs_dev *dev, struct spdk_bs_opts *o,
4586 	     spdk_bs_op_with_handle_complete cb_fn, void *cb_arg)
4587 {
4588 	struct spdk_bs_init_ctx *ctx;
4589 	struct spdk_blob_store	*bs;
4590 	struct spdk_bs_cpl	cpl;
4591 	spdk_bs_sequence_t	*seq;
4592 	spdk_bs_batch_t		*batch;
4593 	uint64_t		num_md_lba;
4594 	uint64_t		num_md_pages;
4595 	uint64_t		num_md_clusters;
4596 	uint32_t		i;
4597 	struct spdk_bs_opts	opts = {};
4598 	int			rc;
4599 
4600 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Initializing blobstore on dev %p\n", dev);
4601 
4602 	if ((SPDK_BS_PAGE_SIZE % dev->blocklen) != 0) {
4603 		SPDK_ERRLOG("unsupported dev block length of %d\n",
4604 			    dev->blocklen);
4605 		dev->destroy(dev);
4606 		cb_fn(cb_arg, NULL, -EINVAL);
4607 		return;
4608 	}
4609 
4610 	if (o) {
4611 		opts = *o;
4612 	} else {
4613 		spdk_bs_opts_init(&opts);
4614 	}
4615 
4616 	if (bs_opts_verify(&opts) != 0) {
4617 		dev->destroy(dev);
4618 		cb_fn(cb_arg, NULL, -EINVAL);
4619 		return;
4620 	}
4621 
4622 	rc = bs_alloc(dev, &opts, &bs);
4623 	if (rc) {
4624 		dev->destroy(dev);
4625 		cb_fn(cb_arg, NULL, rc);
4626 		return;
4627 	}
4628 
4629 	if (opts.num_md_pages == SPDK_BLOB_OPTS_NUM_MD_PAGES) {
4630 		/* By default, allocate 1 page per cluster.
4631 		 * Technically, this over-allocates metadata
4632 		 * because more metadata will reduce the number
4633 		 * of usable clusters. This can be addressed with
4634 		 * more complex math in the future.
4635 		 */
4636 		bs->md_len = bs->total_clusters;
4637 	} else {
4638 		bs->md_len = opts.num_md_pages;
4639 	}
4640 	rc = spdk_bit_array_resize(&bs->used_md_pages, bs->md_len);
4641 	if (rc < 0) {
4642 		bs_free(bs);
4643 		cb_fn(cb_arg, NULL, -ENOMEM);
4644 		return;
4645 	}
4646 
4647 	rc = spdk_bit_array_resize(&bs->used_blobids, bs->md_len);
4648 	if (rc < 0) {
4649 		bs_free(bs);
4650 		cb_fn(cb_arg, NULL, -ENOMEM);
4651 		return;
4652 	}
4653 
4654 	rc = spdk_bit_array_resize(&bs->open_blobids, bs->md_len);
4655 	if (rc < 0) {
4656 		bs_free(bs);
4657 		cb_fn(cb_arg, NULL, -ENOMEM);
4658 		return;
4659 	}
4660 
4661 	ctx = calloc(1, sizeof(*ctx));
4662 	if (!ctx) {
4663 		bs_free(bs);
4664 		cb_fn(cb_arg, NULL, -ENOMEM);
4665 		return;
4666 	}
4667 
4668 	ctx->bs = bs;
4669 
4670 	/* Allocate memory for the super block */
4671 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4672 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4673 	if (!ctx->super) {
4674 		free(ctx);
4675 		bs_free(bs);
4676 		cb_fn(cb_arg, NULL, -ENOMEM);
4677 		return;
4678 	}
4679 	memcpy(ctx->super->signature, SPDK_BS_SUPER_BLOCK_SIG,
4680 	       sizeof(ctx->super->signature));
4681 	ctx->super->version = SPDK_BS_VERSION;
4682 	ctx->super->length = sizeof(*ctx->super);
4683 	ctx->super->super_blob = bs->super_blob;
4684 	ctx->super->clean = 0;
4685 	ctx->super->cluster_size = bs->cluster_sz;
4686 	ctx->super->io_unit_size = bs->io_unit_size;
4687 	memcpy(&ctx->super->bstype, &bs->bstype, sizeof(bs->bstype));
4688 
4689 	/* Calculate how many pages the metadata consumes at the front
4690 	 * of the disk.
4691 	 */
4692 
4693 	/* The super block uses 1 page */
4694 	num_md_pages = 1;
4695 
4696 	/* The used_md_pages mask requires 1 bit per metadata page, rounded
4697 	 * up to the nearest page, plus a header.
4698 	 */
4699 	ctx->super->used_page_mask_start = num_md_pages;
4700 	ctx->super->used_page_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
4701 					 spdk_divide_round_up(bs->md_len, 8),
4702 					 SPDK_BS_PAGE_SIZE);
4703 	num_md_pages += ctx->super->used_page_mask_len;
4704 
4705 	/* The used_clusters mask requires 1 bit per cluster, rounded
4706 	 * up to the nearest page, plus a header.
4707 	 */
4708 	ctx->super->used_cluster_mask_start = num_md_pages;
4709 	ctx->super->used_cluster_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
4710 					    spdk_divide_round_up(bs->total_clusters, 8),
4711 					    SPDK_BS_PAGE_SIZE);
4712 	num_md_pages += ctx->super->used_cluster_mask_len;
4713 
4714 	/* The used_blobids mask requires 1 bit per metadata page, rounded
4715 	 * up to the nearest page, plus a header.
4716 	 */
4717 	ctx->super->used_blobid_mask_start = num_md_pages;
4718 	ctx->super->used_blobid_mask_len = spdk_divide_round_up(sizeof(struct spdk_bs_md_mask) +
4719 					   spdk_divide_round_up(bs->md_len, 8),
4720 					   SPDK_BS_PAGE_SIZE);
4721 	num_md_pages += ctx->super->used_blobid_mask_len;
4722 
4723 	/* The metadata region size was chosen above */
4724 	ctx->super->md_start = bs->md_start = num_md_pages;
4725 	ctx->super->md_len = bs->md_len;
4726 	num_md_pages += bs->md_len;
4727 
4728 	num_md_lba = bs_page_to_lba(bs, num_md_pages);
4729 
4730 	ctx->super->size = dev->blockcnt * dev->blocklen;
4731 
4732 	ctx->super->crc = blob_md_page_calc_crc(ctx->super);
4733 
4734 	num_md_clusters = spdk_divide_round_up(num_md_pages, bs->pages_per_cluster);
4735 	if (num_md_clusters > bs->total_clusters) {
4736 		SPDK_ERRLOG("Blobstore metadata cannot use more clusters than is available, "
4737 			    "please decrease number of pages reserved for metadata "
4738 			    "or increase cluster size.\n");
4739 		spdk_free(ctx->super);
4740 		free(ctx);
4741 		bs_free(bs);
4742 		cb_fn(cb_arg, NULL, -ENOMEM);
4743 		return;
4744 	}
4745 	/* Claim all of the clusters used by the metadata */
4746 	for (i = 0; i < num_md_clusters; i++) {
4747 		bs_claim_cluster(bs, i);
4748 	}
4749 
4750 	bs->total_data_clusters = bs->num_free_clusters;
4751 
4752 	cpl.type = SPDK_BS_CPL_TYPE_BS_HANDLE;
4753 	cpl.u.bs_handle.cb_fn = cb_fn;
4754 	cpl.u.bs_handle.cb_arg = cb_arg;
4755 	cpl.u.bs_handle.bs = bs;
4756 
4757 	seq = bs_sequence_start(bs->md_channel, &cpl);
4758 	if (!seq) {
4759 		spdk_free(ctx->super);
4760 		free(ctx);
4761 		bs_free(bs);
4762 		cb_fn(cb_arg, NULL, -ENOMEM);
4763 		return;
4764 	}
4765 
4766 	batch = bs_sequence_to_batch(seq, bs_init_trim_cpl, ctx);
4767 
4768 	/* Clear metadata space */
4769 	bs_batch_write_zeroes_dev(batch, 0, num_md_lba);
4770 
4771 	switch (opts.clear_method) {
4772 	case BS_CLEAR_WITH_UNMAP:
4773 		/* Trim data clusters */
4774 		bs_batch_unmap_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
4775 		break;
4776 	case BS_CLEAR_WITH_WRITE_ZEROES:
4777 		/* Write_zeroes to data clusters */
4778 		bs_batch_write_zeroes_dev(batch, num_md_lba, ctx->bs->dev->blockcnt - num_md_lba);
4779 		break;
4780 	case BS_CLEAR_WITH_NONE:
4781 	default:
4782 		break;
4783 	}
4784 
4785 	bs_batch_close(batch);
4786 }
4787 
4788 /* END spdk_bs_init */
4789 
4790 /* START spdk_bs_destroy */
4791 
4792 static void
4793 bs_destroy_trim_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4794 {
4795 	struct spdk_bs_init_ctx *ctx = cb_arg;
4796 	struct spdk_blob_store *bs = ctx->bs;
4797 
4798 	/*
4799 	 * We need to defer calling bs_call_cpl() until after
4800 	 * dev destruction, so tuck these away for later use.
4801 	 */
4802 	bs->unload_err = bserrno;
4803 	memcpy(&bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
4804 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
4805 
4806 	bs_sequence_finish(seq, bserrno);
4807 
4808 	bs_free(bs);
4809 	free(ctx);
4810 }
4811 
4812 void
4813 spdk_bs_destroy(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn,
4814 		void *cb_arg)
4815 {
4816 	struct spdk_bs_cpl	cpl;
4817 	spdk_bs_sequence_t	*seq;
4818 	struct spdk_bs_init_ctx *ctx;
4819 
4820 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Destroying blobstore\n");
4821 
4822 	if (!TAILQ_EMPTY(&bs->blobs)) {
4823 		SPDK_ERRLOG("Blobstore still has open blobs\n");
4824 		cb_fn(cb_arg, -EBUSY);
4825 		return;
4826 	}
4827 
4828 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4829 	cpl.u.bs_basic.cb_fn = cb_fn;
4830 	cpl.u.bs_basic.cb_arg = cb_arg;
4831 
4832 	ctx = calloc(1, sizeof(*ctx));
4833 	if (!ctx) {
4834 		cb_fn(cb_arg, -ENOMEM);
4835 		return;
4836 	}
4837 
4838 	ctx->bs = bs;
4839 
4840 	seq = bs_sequence_start(bs->md_channel, &cpl);
4841 	if (!seq) {
4842 		free(ctx);
4843 		cb_fn(cb_arg, -ENOMEM);
4844 		return;
4845 	}
4846 
4847 	/* Write zeroes to the super block */
4848 	bs_sequence_write_zeroes_dev(seq,
4849 				     bs_page_to_lba(bs, 0),
4850 				     bs_byte_to_lba(bs, sizeof(struct spdk_bs_super_block)),
4851 				     bs_destroy_trim_cpl, ctx);
4852 }
4853 
4854 /* END spdk_bs_destroy */
4855 
4856 /* START spdk_bs_unload */
4857 
4858 static void
4859 bs_unload_finish(struct spdk_bs_load_ctx *ctx, int bserrno)
4860 {
4861 	spdk_bs_sequence_t *seq = ctx->seq;
4862 
4863 	spdk_free(ctx->super);
4864 
4865 	/*
4866 	 * We need to defer calling bs_call_cpl() until after
4867 	 * dev destruction, so tuck these away for later use.
4868 	 */
4869 	ctx->bs->unload_err = bserrno;
4870 	memcpy(&ctx->bs->unload_cpl, &seq->cpl, sizeof(struct spdk_bs_cpl));
4871 	seq->cpl.type = SPDK_BS_CPL_TYPE_NONE;
4872 
4873 	bs_sequence_finish(seq, bserrno);
4874 
4875 	bs_free(ctx->bs);
4876 	free(ctx);
4877 }
4878 
4879 static void
4880 bs_unload_write_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4881 {
4882 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4883 
4884 	bs_unload_finish(ctx, bserrno);
4885 }
4886 
4887 static void
4888 bs_unload_write_used_clusters_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4889 {
4890 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4891 
4892 	spdk_free(ctx->mask);
4893 
4894 	if (bserrno != 0) {
4895 		bs_unload_finish(ctx, bserrno);
4896 		return;
4897 	}
4898 
4899 	ctx->super->clean = 1;
4900 
4901 	bs_write_super(seq, ctx->bs, ctx->super, bs_unload_write_super_cpl, ctx);
4902 }
4903 
4904 static void
4905 bs_unload_write_used_blobids_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4906 {
4907 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4908 
4909 	spdk_free(ctx->mask);
4910 	ctx->mask = NULL;
4911 
4912 	if (bserrno != 0) {
4913 		bs_unload_finish(ctx, bserrno);
4914 		return;
4915 	}
4916 
4917 	bs_write_used_clusters(seq, ctx, bs_unload_write_used_clusters_cpl);
4918 }
4919 
4920 static void
4921 bs_unload_write_used_pages_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4922 {
4923 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4924 
4925 	spdk_free(ctx->mask);
4926 	ctx->mask = NULL;
4927 
4928 	if (bserrno != 0) {
4929 		bs_unload_finish(ctx, bserrno);
4930 		return;
4931 	}
4932 
4933 	bs_write_used_blobids(seq, ctx, bs_unload_write_used_blobids_cpl);
4934 }
4935 
4936 static void
4937 bs_unload_read_super_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
4938 {
4939 	struct spdk_bs_load_ctx	*ctx = cb_arg;
4940 
4941 	if (bserrno != 0) {
4942 		bs_unload_finish(ctx, bserrno);
4943 		return;
4944 	}
4945 
4946 	bs_write_used_md(seq, cb_arg, bs_unload_write_used_pages_cpl);
4947 }
4948 
4949 void
4950 spdk_bs_unload(struct spdk_blob_store *bs, spdk_bs_op_complete cb_fn, void *cb_arg)
4951 {
4952 	struct spdk_bs_cpl	cpl;
4953 	struct spdk_bs_load_ctx *ctx;
4954 
4955 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blobstore\n");
4956 
4957 	if (!TAILQ_EMPTY(&bs->blobs)) {
4958 		SPDK_ERRLOG("Blobstore still has open blobs\n");
4959 		cb_fn(cb_arg, -EBUSY);
4960 		return;
4961 	}
4962 
4963 	ctx = calloc(1, sizeof(*ctx));
4964 	if (!ctx) {
4965 		cb_fn(cb_arg, -ENOMEM);
4966 		return;
4967 	}
4968 
4969 	ctx->bs = bs;
4970 
4971 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
4972 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
4973 	if (!ctx->super) {
4974 		free(ctx);
4975 		cb_fn(cb_arg, -ENOMEM);
4976 		return;
4977 	}
4978 
4979 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
4980 	cpl.u.bs_basic.cb_fn = cb_fn;
4981 	cpl.u.bs_basic.cb_arg = cb_arg;
4982 
4983 	ctx->seq = bs_sequence_start(bs->md_channel, &cpl);
4984 	if (!ctx->seq) {
4985 		spdk_free(ctx->super);
4986 		free(ctx);
4987 		cb_fn(cb_arg, -ENOMEM);
4988 		return;
4989 	}
4990 
4991 	/* Read super block */
4992 	bs_sequence_read_dev(ctx->seq, ctx->super, bs_page_to_lba(bs, 0),
4993 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
4994 			     bs_unload_read_super_cpl, ctx);
4995 }
4996 
4997 /* END spdk_bs_unload */
4998 
4999 /* START spdk_bs_set_super */
5000 
5001 struct spdk_bs_set_super_ctx {
5002 	struct spdk_blob_store		*bs;
5003 	struct spdk_bs_super_block	*super;
5004 };
5005 
5006 static void
5007 bs_set_super_write_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5008 {
5009 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
5010 
5011 	if (bserrno != 0) {
5012 		SPDK_ERRLOG("Unable to write to super block of blobstore\n");
5013 	}
5014 
5015 	spdk_free(ctx->super);
5016 
5017 	bs_sequence_finish(seq, bserrno);
5018 
5019 	free(ctx);
5020 }
5021 
5022 static void
5023 bs_set_super_read_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5024 {
5025 	struct spdk_bs_set_super_ctx	*ctx = cb_arg;
5026 
5027 	if (bserrno != 0) {
5028 		SPDK_ERRLOG("Unable to read super block of blobstore\n");
5029 		spdk_free(ctx->super);
5030 		bs_sequence_finish(seq, bserrno);
5031 		free(ctx);
5032 		return;
5033 	}
5034 
5035 	bs_write_super(seq, ctx->bs, ctx->super, bs_set_super_write_cpl, ctx);
5036 }
5037 
5038 void
5039 spdk_bs_set_super(struct spdk_blob_store *bs, spdk_blob_id blobid,
5040 		  spdk_bs_op_complete cb_fn, void *cb_arg)
5041 {
5042 	struct spdk_bs_cpl		cpl;
5043 	spdk_bs_sequence_t		*seq;
5044 	struct spdk_bs_set_super_ctx	*ctx;
5045 
5046 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Setting super blob id on blobstore\n");
5047 
5048 	ctx = calloc(1, sizeof(*ctx));
5049 	if (!ctx) {
5050 		cb_fn(cb_arg, -ENOMEM);
5051 		return;
5052 	}
5053 
5054 	ctx->bs = bs;
5055 
5056 	ctx->super = spdk_zmalloc(sizeof(*ctx->super), 0x1000, NULL,
5057 				  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
5058 	if (!ctx->super) {
5059 		free(ctx);
5060 		cb_fn(cb_arg, -ENOMEM);
5061 		return;
5062 	}
5063 
5064 	cpl.type = SPDK_BS_CPL_TYPE_BS_BASIC;
5065 	cpl.u.bs_basic.cb_fn = cb_fn;
5066 	cpl.u.bs_basic.cb_arg = cb_arg;
5067 
5068 	seq = bs_sequence_start(bs->md_channel, &cpl);
5069 	if (!seq) {
5070 		spdk_free(ctx->super);
5071 		free(ctx);
5072 		cb_fn(cb_arg, -ENOMEM);
5073 		return;
5074 	}
5075 
5076 	bs->super_blob = blobid;
5077 
5078 	/* Read super block */
5079 	bs_sequence_read_dev(seq, ctx->super, bs_page_to_lba(bs, 0),
5080 			     bs_byte_to_lba(bs, sizeof(*ctx->super)),
5081 			     bs_set_super_read_cpl, ctx);
5082 }
5083 
5084 /* END spdk_bs_set_super */
5085 
5086 void
5087 spdk_bs_get_super(struct spdk_blob_store *bs,
5088 		  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5089 {
5090 	if (bs->super_blob == SPDK_BLOBID_INVALID) {
5091 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOENT);
5092 	} else {
5093 		cb_fn(cb_arg, bs->super_blob, 0);
5094 	}
5095 }
5096 
5097 uint64_t
5098 spdk_bs_get_cluster_size(struct spdk_blob_store *bs)
5099 {
5100 	return bs->cluster_sz;
5101 }
5102 
5103 uint64_t
5104 spdk_bs_get_page_size(struct spdk_blob_store *bs)
5105 {
5106 	return SPDK_BS_PAGE_SIZE;
5107 }
5108 
5109 uint64_t
5110 spdk_bs_get_io_unit_size(struct spdk_blob_store *bs)
5111 {
5112 	return bs->io_unit_size;
5113 }
5114 
5115 uint64_t
5116 spdk_bs_free_cluster_count(struct spdk_blob_store *bs)
5117 {
5118 	return bs->num_free_clusters;
5119 }
5120 
5121 uint64_t
5122 spdk_bs_total_data_cluster_count(struct spdk_blob_store *bs)
5123 {
5124 	return bs->total_data_clusters;
5125 }
5126 
5127 static int
5128 bs_register_md_thread(struct spdk_blob_store *bs)
5129 {
5130 	bs->md_channel = spdk_get_io_channel(bs);
5131 	if (!bs->md_channel) {
5132 		SPDK_ERRLOG("Failed to get IO channel.\n");
5133 		return -1;
5134 	}
5135 
5136 	return 0;
5137 }
5138 
5139 static int
5140 bs_unregister_md_thread(struct spdk_blob_store *bs)
5141 {
5142 	spdk_put_io_channel(bs->md_channel);
5143 
5144 	return 0;
5145 }
5146 
5147 spdk_blob_id spdk_blob_get_id(struct spdk_blob *blob)
5148 {
5149 	assert(blob != NULL);
5150 
5151 	return blob->id;
5152 }
5153 
5154 uint64_t spdk_blob_get_num_pages(struct spdk_blob *blob)
5155 {
5156 	assert(blob != NULL);
5157 
5158 	return bs_cluster_to_page(blob->bs, blob->active.num_clusters);
5159 }
5160 
5161 uint64_t spdk_blob_get_num_io_units(struct spdk_blob *blob)
5162 {
5163 	assert(blob != NULL);
5164 
5165 	return spdk_blob_get_num_pages(blob) * bs_io_unit_per_page(blob->bs);
5166 }
5167 
5168 uint64_t spdk_blob_get_num_clusters(struct spdk_blob *blob)
5169 {
5170 	assert(blob != NULL);
5171 
5172 	return blob->active.num_clusters;
5173 }
5174 
5175 /* START spdk_bs_create_blob */
5176 
5177 static void
5178 bs_create_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
5179 {
5180 	struct spdk_blob *blob = cb_arg;
5181 	uint32_t page_idx = bs_blobid_to_page(blob->id);
5182 
5183 	if (bserrno != 0) {
5184 		spdk_bit_array_clear(blob->bs->used_blobids, page_idx);
5185 		bs_release_md_page(blob->bs, page_idx);
5186 	}
5187 
5188 	blob_free(blob);
5189 
5190 	bs_sequence_finish(seq, bserrno);
5191 }
5192 
5193 static int
5194 blob_set_xattrs(struct spdk_blob *blob, const struct spdk_blob_xattr_opts *xattrs,
5195 		bool internal)
5196 {
5197 	uint64_t i;
5198 	size_t value_len = 0;
5199 	int rc;
5200 	const void *value = NULL;
5201 	if (xattrs->count > 0 && xattrs->get_value == NULL) {
5202 		return -EINVAL;
5203 	}
5204 	for (i = 0; i < xattrs->count; i++) {
5205 		xattrs->get_value(xattrs->ctx, xattrs->names[i], &value, &value_len);
5206 		if (value == NULL || value_len == 0) {
5207 			return -EINVAL;
5208 		}
5209 		rc = blob_set_xattr(blob, xattrs->names[i], value, value_len, internal);
5210 		if (rc < 0) {
5211 			return rc;
5212 		}
5213 	}
5214 	return 0;
5215 }
5216 
5217 static void
5218 bs_create_blob(struct spdk_blob_store *bs,
5219 	       const struct spdk_blob_opts *opts,
5220 	       const struct spdk_blob_xattr_opts *internal_xattrs,
5221 	       spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5222 {
5223 	struct spdk_blob	*blob;
5224 	uint32_t		page_idx;
5225 	struct spdk_bs_cpl	cpl;
5226 	struct spdk_blob_opts	opts_default;
5227 	struct spdk_blob_xattr_opts internal_xattrs_default;
5228 	spdk_bs_sequence_t	*seq;
5229 	spdk_blob_id		id;
5230 	int rc;
5231 
5232 	assert(spdk_get_thread() == bs->md_thread);
5233 
5234 	page_idx = spdk_bit_array_find_first_clear(bs->used_md_pages, 0);
5235 	if (page_idx == UINT32_MAX) {
5236 		cb_fn(cb_arg, 0, -ENOMEM);
5237 		return;
5238 	}
5239 	spdk_bit_array_set(bs->used_blobids, page_idx);
5240 	bs_claim_md_page(bs, page_idx);
5241 
5242 	id = bs_page_to_blobid(page_idx);
5243 
5244 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Creating blob with id %lu at page %u\n", id, page_idx);
5245 
5246 	blob = blob_alloc(bs, id);
5247 	if (!blob) {
5248 		spdk_bit_array_clear(bs->used_blobids, page_idx);
5249 		bs_release_md_page(bs, page_idx);
5250 		cb_fn(cb_arg, 0, -ENOMEM);
5251 		return;
5252 	}
5253 
5254 	if (!opts) {
5255 		spdk_blob_opts_init(&opts_default);
5256 		opts = &opts_default;
5257 	}
5258 
5259 	blob->use_extent_table = opts->use_extent_table;
5260 	if (blob->use_extent_table) {
5261 		blob->invalid_flags |= SPDK_BLOB_EXTENT_TABLE;
5262 	}
5263 
5264 	if (!internal_xattrs) {
5265 		blob_xattrs_init(&internal_xattrs_default);
5266 		internal_xattrs = &internal_xattrs_default;
5267 	}
5268 
5269 	rc = blob_set_xattrs(blob, &opts->xattrs, false);
5270 	if (rc < 0) {
5271 		blob_free(blob);
5272 		spdk_bit_array_clear(bs->used_blobids, page_idx);
5273 		bs_release_md_page(bs, page_idx);
5274 		cb_fn(cb_arg, 0, rc);
5275 		return;
5276 	}
5277 
5278 	rc = blob_set_xattrs(blob, internal_xattrs, true);
5279 	if (rc < 0) {
5280 		blob_free(blob);
5281 		spdk_bit_array_clear(bs->used_blobids, page_idx);
5282 		bs_release_md_page(bs, page_idx);
5283 		cb_fn(cb_arg, 0, rc);
5284 		return;
5285 	}
5286 
5287 	if (opts->thin_provision) {
5288 		blob_set_thin_provision(blob);
5289 	}
5290 
5291 	blob_set_clear_method(blob, opts->clear_method);
5292 
5293 	rc = blob_resize(blob, opts->num_clusters);
5294 	if (rc < 0) {
5295 		blob_free(blob);
5296 		spdk_bit_array_clear(bs->used_blobids, page_idx);
5297 		bs_release_md_page(bs, page_idx);
5298 		cb_fn(cb_arg, 0, rc);
5299 		return;
5300 	}
5301 	cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
5302 	cpl.u.blobid.cb_fn = cb_fn;
5303 	cpl.u.blobid.cb_arg = cb_arg;
5304 	cpl.u.blobid.blobid = blob->id;
5305 
5306 	seq = bs_sequence_start(bs->md_channel, &cpl);
5307 	if (!seq) {
5308 		blob_free(blob);
5309 		spdk_bit_array_clear(bs->used_blobids, page_idx);
5310 		bs_release_md_page(bs, page_idx);
5311 		cb_fn(cb_arg, 0, -ENOMEM);
5312 		return;
5313 	}
5314 
5315 	blob_persist(seq, blob, bs_create_blob_cpl, blob);
5316 }
5317 
5318 void spdk_bs_create_blob(struct spdk_blob_store *bs,
5319 			 spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5320 {
5321 	bs_create_blob(bs, NULL, NULL, cb_fn, cb_arg);
5322 }
5323 
5324 void spdk_bs_create_blob_ext(struct spdk_blob_store *bs, const struct spdk_blob_opts *opts,
5325 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5326 {
5327 	bs_create_blob(bs, opts, NULL, cb_fn, cb_arg);
5328 }
5329 
5330 /* END spdk_bs_create_blob */
5331 
5332 /* START blob_cleanup */
5333 
5334 struct spdk_clone_snapshot_ctx {
5335 	struct spdk_bs_cpl      cpl;
5336 	int bserrno;
5337 	bool frozen;
5338 
5339 	struct spdk_io_channel *channel;
5340 
5341 	/* Current cluster for inflate operation */
5342 	uint64_t cluster;
5343 
5344 	/* For inflation force allocation of all unallocated clusters and remove
5345 	 * thin-provisioning. Otherwise only decouple parent and keep clone thin. */
5346 	bool allocate_all;
5347 
5348 	struct {
5349 		spdk_blob_id id;
5350 		struct spdk_blob *blob;
5351 	} original;
5352 	struct {
5353 		spdk_blob_id id;
5354 		struct spdk_blob *blob;
5355 	} new;
5356 
5357 	/* xattrs specified for snapshot/clones only. They have no impact on
5358 	 * the original blobs xattrs. */
5359 	const struct spdk_blob_xattr_opts *xattrs;
5360 };
5361 
5362 static void
5363 bs_clone_snapshot_cleanup_finish(void *cb_arg, int bserrno)
5364 {
5365 	struct spdk_clone_snapshot_ctx *ctx = cb_arg;
5366 	struct spdk_bs_cpl *cpl = &ctx->cpl;
5367 
5368 	if (bserrno != 0) {
5369 		if (ctx->bserrno != 0) {
5370 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5371 		} else {
5372 			ctx->bserrno = bserrno;
5373 		}
5374 	}
5375 
5376 	switch (cpl->type) {
5377 	case SPDK_BS_CPL_TYPE_BLOBID:
5378 		cpl->u.blobid.cb_fn(cpl->u.blobid.cb_arg, cpl->u.blobid.blobid, ctx->bserrno);
5379 		break;
5380 	case SPDK_BS_CPL_TYPE_BLOB_BASIC:
5381 		cpl->u.blob_basic.cb_fn(cpl->u.blob_basic.cb_arg, ctx->bserrno);
5382 		break;
5383 	default:
5384 		SPDK_UNREACHABLE();
5385 		break;
5386 	}
5387 
5388 	free(ctx);
5389 }
5390 
5391 static void
5392 bs_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
5393 {
5394 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5395 	struct spdk_blob *origblob = ctx->original.blob;
5396 
5397 	if (bserrno != 0) {
5398 		if (ctx->bserrno != 0) {
5399 			SPDK_ERRLOG("Unfreeze error %d\n", bserrno);
5400 		} else {
5401 			ctx->bserrno = bserrno;
5402 		}
5403 	}
5404 
5405 	ctx->original.id = origblob->id;
5406 	origblob->locked_operation_in_progress = false;
5407 
5408 	spdk_blob_close(origblob, bs_clone_snapshot_cleanup_finish, ctx);
5409 }
5410 
5411 static void
5412 bs_clone_snapshot_origblob_cleanup(void *cb_arg, int bserrno)
5413 {
5414 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5415 	struct spdk_blob *origblob = ctx->original.blob;
5416 
5417 	if (bserrno != 0) {
5418 		if (ctx->bserrno != 0) {
5419 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5420 		} else {
5421 			ctx->bserrno = bserrno;
5422 		}
5423 	}
5424 
5425 	if (ctx->frozen) {
5426 		/* Unfreeze any outstanding I/O */
5427 		blob_unfreeze_io(origblob, bs_snapshot_unfreeze_cpl, ctx);
5428 	} else {
5429 		bs_snapshot_unfreeze_cpl(ctx, 0);
5430 	}
5431 
5432 }
5433 
5434 static void
5435 bs_clone_snapshot_newblob_cleanup(void *cb_arg, int bserrno)
5436 {
5437 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5438 	struct spdk_blob *newblob = ctx->new.blob;
5439 
5440 	if (bserrno != 0) {
5441 		if (ctx->bserrno != 0) {
5442 			SPDK_ERRLOG("Cleanup error %d\n", bserrno);
5443 		} else {
5444 			ctx->bserrno = bserrno;
5445 		}
5446 	}
5447 
5448 	ctx->new.id = newblob->id;
5449 	spdk_blob_close(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
5450 }
5451 
5452 /* END blob_cleanup */
5453 
5454 /* START spdk_bs_create_snapshot */
5455 
5456 static void
5457 bs_snapshot_swap_cluster_maps(struct spdk_blob *blob1, struct spdk_blob *blob2)
5458 {
5459 	uint64_t *cluster_temp;
5460 	uint32_t *extent_page_temp;
5461 
5462 	cluster_temp = blob1->active.clusters;
5463 	blob1->active.clusters = blob2->active.clusters;
5464 	blob2->active.clusters = cluster_temp;
5465 
5466 	extent_page_temp = blob1->active.extent_pages;
5467 	blob1->active.extent_pages = blob2->active.extent_pages;
5468 	blob2->active.extent_pages = extent_page_temp;
5469 }
5470 
5471 static void
5472 bs_snapshot_origblob_sync_cpl(void *cb_arg, int bserrno)
5473 {
5474 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5475 	struct spdk_blob *origblob = ctx->original.blob;
5476 	struct spdk_blob *newblob = ctx->new.blob;
5477 
5478 	if (bserrno != 0) {
5479 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5480 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5481 		return;
5482 	}
5483 
5484 	/* Remove metadata descriptor SNAPSHOT_IN_PROGRESS */
5485 	bserrno = blob_remove_xattr(newblob, SNAPSHOT_IN_PROGRESS, true);
5486 	if (bserrno != 0) {
5487 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5488 		return;
5489 	}
5490 
5491 	bs_blob_list_add(ctx->original.blob);
5492 
5493 	spdk_blob_set_read_only(newblob);
5494 
5495 	/* sync snapshot metadata */
5496 	spdk_blob_sync_md(newblob, bs_clone_snapshot_origblob_cleanup, ctx);
5497 }
5498 
5499 static void
5500 bs_snapshot_newblob_sync_cpl(void *cb_arg, int bserrno)
5501 {
5502 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5503 	struct spdk_blob *origblob = ctx->original.blob;
5504 	struct spdk_blob *newblob = ctx->new.blob;
5505 
5506 	if (bserrno != 0) {
5507 		/* return cluster map back to original */
5508 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5509 
5510 		/* Newblob md sync failed. Valid clusters are only present in origblob.
5511 		 * Since I/O is frozen on origblob, not changes to zeroed out cluster map should have occured.
5512 		 * Newblob needs to be reverted to thin_provisioned state at creation to properly close. */
5513 		blob_set_thin_provision(newblob);
5514 		assert(spdk_mem_all_zero(newblob->active.clusters,
5515 					 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
5516 		assert(spdk_mem_all_zero(newblob->active.extent_pages,
5517 					 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
5518 
5519 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5520 		return;
5521 	}
5522 
5523 	/* Set internal xattr for snapshot id */
5524 	bserrno = blob_set_xattr(origblob, BLOB_SNAPSHOT, &newblob->id, sizeof(spdk_blob_id), true);
5525 	if (bserrno != 0) {
5526 		/* return cluster map back to original */
5527 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5528 		bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5529 		return;
5530 	}
5531 
5532 	bs_blob_list_remove(origblob);
5533 	origblob->parent_id = newblob->id;
5534 
5535 	/* Create new back_bs_dev for snapshot */
5536 	origblob->back_bs_dev = bs_create_blob_bs_dev(newblob);
5537 	if (origblob->back_bs_dev == NULL) {
5538 		/* return cluster map back to original */
5539 		bs_snapshot_swap_cluster_maps(newblob, origblob);
5540 		bs_clone_snapshot_newblob_cleanup(ctx, -EINVAL);
5541 		return;
5542 	}
5543 
5544 	/* set clone blob as thin provisioned */
5545 	blob_set_thin_provision(origblob);
5546 
5547 	bs_blob_list_add(newblob);
5548 
5549 	/* sync clone metadata */
5550 	spdk_blob_sync_md(origblob, bs_snapshot_origblob_sync_cpl, ctx);
5551 }
5552 
5553 static void
5554 bs_snapshot_freeze_cpl(void *cb_arg, int rc)
5555 {
5556 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5557 	struct spdk_blob *origblob = ctx->original.blob;
5558 	struct spdk_blob *newblob = ctx->new.blob;
5559 	int bserrno;
5560 
5561 	if (rc != 0) {
5562 		bs_clone_snapshot_newblob_cleanup(ctx, rc);
5563 		return;
5564 	}
5565 
5566 	ctx->frozen = true;
5567 
5568 	/* set new back_bs_dev for snapshot */
5569 	newblob->back_bs_dev = origblob->back_bs_dev;
5570 	/* Set invalid flags from origblob */
5571 	newblob->invalid_flags = origblob->invalid_flags;
5572 
5573 	/* inherit parent from original blob if set */
5574 	newblob->parent_id = origblob->parent_id;
5575 	if (origblob->parent_id != SPDK_BLOBID_INVALID) {
5576 		/* Set internal xattr for snapshot id */
5577 		bserrno = blob_set_xattr(newblob, BLOB_SNAPSHOT,
5578 					 &origblob->parent_id, sizeof(spdk_blob_id), true);
5579 		if (bserrno != 0) {
5580 			bs_clone_snapshot_newblob_cleanup(ctx, bserrno);
5581 			return;
5582 		}
5583 	}
5584 
5585 	/* swap cluster maps */
5586 	bs_snapshot_swap_cluster_maps(newblob, origblob);
5587 
5588 	/* Set the clear method on the new blob to match the original. */
5589 	blob_set_clear_method(newblob, origblob->clear_method);
5590 
5591 	/* sync snapshot metadata */
5592 	spdk_blob_sync_md(newblob, bs_snapshot_newblob_sync_cpl, ctx);
5593 }
5594 
5595 static void
5596 bs_snapshot_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5597 {
5598 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5599 	struct spdk_blob *origblob = ctx->original.blob;
5600 	struct spdk_blob *newblob = _blob;
5601 
5602 	if (bserrno != 0) {
5603 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5604 		return;
5605 	}
5606 
5607 	ctx->new.blob = newblob;
5608 	assert(spdk_blob_is_thin_provisioned(newblob));
5609 	assert(spdk_mem_all_zero(newblob->active.clusters,
5610 				 newblob->active.num_clusters * sizeof(*newblob->active.clusters)));
5611 	assert(spdk_mem_all_zero(newblob->active.extent_pages,
5612 				 newblob->active.num_extent_pages * sizeof(*newblob->active.extent_pages)));
5613 
5614 	blob_freeze_io(origblob, bs_snapshot_freeze_cpl, ctx);
5615 }
5616 
5617 static void
5618 bs_snapshot_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
5619 {
5620 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5621 	struct spdk_blob *origblob = ctx->original.blob;
5622 
5623 	if (bserrno != 0) {
5624 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5625 		return;
5626 	}
5627 
5628 	ctx->new.id = blobid;
5629 	ctx->cpl.u.blobid.blobid = blobid;
5630 
5631 	spdk_bs_open_blob(origblob->bs, ctx->new.id, bs_snapshot_newblob_open_cpl, ctx);
5632 }
5633 
5634 
5635 static void
5636 bs_xattr_snapshot(void *arg, const char *name,
5637 		  const void **value, size_t *value_len)
5638 {
5639 	assert(strncmp(name, SNAPSHOT_IN_PROGRESS, sizeof(SNAPSHOT_IN_PROGRESS)) == 0);
5640 
5641 	struct spdk_blob *blob = (struct spdk_blob *)arg;
5642 	*value = &blob->id;
5643 	*value_len = sizeof(blob->id);
5644 }
5645 
5646 static void
5647 bs_snapshot_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5648 {
5649 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5650 	struct spdk_blob_opts opts;
5651 	struct spdk_blob_xattr_opts internal_xattrs;
5652 	char *xattrs_names[] = { SNAPSHOT_IN_PROGRESS };
5653 
5654 	if (bserrno != 0) {
5655 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5656 		return;
5657 	}
5658 
5659 	ctx->original.blob = _blob;
5660 
5661 	if (_blob->data_ro || _blob->md_ro) {
5662 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot from read only blob with id %lu\n",
5663 			      _blob->id);
5664 		ctx->bserrno = -EINVAL;
5665 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5666 		return;
5667 	}
5668 
5669 	if (_blob->locked_operation_in_progress) {
5670 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create snapshot - another operation in progress\n");
5671 		ctx->bserrno = -EBUSY;
5672 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5673 		return;
5674 	}
5675 
5676 	_blob->locked_operation_in_progress = true;
5677 
5678 	spdk_blob_opts_init(&opts);
5679 	blob_xattrs_init(&internal_xattrs);
5680 
5681 	/* Change the size of new blob to the same as in original blob,
5682 	 * but do not allocate clusters */
5683 	opts.thin_provision = true;
5684 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
5685 	opts.use_extent_table = _blob->use_extent_table;
5686 
5687 	/* If there are any xattrs specified for snapshot, set them now */
5688 	if (ctx->xattrs) {
5689 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
5690 	}
5691 	/* Set internal xattr SNAPSHOT_IN_PROGRESS */
5692 	internal_xattrs.count = 1;
5693 	internal_xattrs.ctx = _blob;
5694 	internal_xattrs.names = xattrs_names;
5695 	internal_xattrs.get_value = bs_xattr_snapshot;
5696 
5697 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
5698 		       bs_snapshot_newblob_create_cpl, ctx);
5699 }
5700 
5701 void spdk_bs_create_snapshot(struct spdk_blob_store *bs, spdk_blob_id blobid,
5702 			     const struct spdk_blob_xattr_opts *snapshot_xattrs,
5703 			     spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5704 {
5705 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
5706 
5707 	if (!ctx) {
5708 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
5709 		return;
5710 	}
5711 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
5712 	ctx->cpl.u.blobid.cb_fn = cb_fn;
5713 	ctx->cpl.u.blobid.cb_arg = cb_arg;
5714 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
5715 	ctx->bserrno = 0;
5716 	ctx->frozen = false;
5717 	ctx->original.id = blobid;
5718 	ctx->xattrs = snapshot_xattrs;
5719 
5720 	spdk_bs_open_blob(bs, ctx->original.id, bs_snapshot_origblob_open_cpl, ctx);
5721 }
5722 /* END spdk_bs_create_snapshot */
5723 
5724 /* START spdk_bs_create_clone */
5725 
5726 static void
5727 bs_xattr_clone(void *arg, const char *name,
5728 	       const void **value, size_t *value_len)
5729 {
5730 	assert(strncmp(name, BLOB_SNAPSHOT, sizeof(BLOB_SNAPSHOT)) == 0);
5731 
5732 	struct spdk_blob *blob = (struct spdk_blob *)arg;
5733 	*value = &blob->id;
5734 	*value_len = sizeof(blob->id);
5735 }
5736 
5737 static void
5738 bs_clone_newblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5739 {
5740 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5741 	struct spdk_blob *clone = _blob;
5742 
5743 	ctx->new.blob = clone;
5744 	bs_blob_list_add(clone);
5745 
5746 	spdk_blob_close(clone, bs_clone_snapshot_origblob_cleanup, ctx);
5747 }
5748 
5749 static void
5750 bs_clone_newblob_create_cpl(void *cb_arg, spdk_blob_id blobid, int bserrno)
5751 {
5752 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5753 
5754 	ctx->cpl.u.blobid.blobid = blobid;
5755 	spdk_bs_open_blob(ctx->original.blob->bs, blobid, bs_clone_newblob_open_cpl, ctx);
5756 }
5757 
5758 static void
5759 bs_clone_origblob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5760 {
5761 	struct spdk_clone_snapshot_ctx	*ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5762 	struct spdk_blob_opts		opts;
5763 	struct spdk_blob_xattr_opts internal_xattrs;
5764 	char *xattr_names[] = { BLOB_SNAPSHOT };
5765 
5766 	if (bserrno != 0) {
5767 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5768 		return;
5769 	}
5770 
5771 	ctx->original.blob = _blob;
5772 
5773 	if (!_blob->data_ro || !_blob->md_ro) {
5774 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Clone not from read-only blob\n");
5775 		ctx->bserrno = -EINVAL;
5776 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5777 		return;
5778 	}
5779 
5780 	if (_blob->locked_operation_in_progress) {
5781 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot create clone - another operation in progress\n");
5782 		ctx->bserrno = -EBUSY;
5783 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5784 		return;
5785 	}
5786 
5787 	_blob->locked_operation_in_progress = true;
5788 
5789 	spdk_blob_opts_init(&opts);
5790 	blob_xattrs_init(&internal_xattrs);
5791 
5792 	opts.thin_provision = true;
5793 	opts.num_clusters = spdk_blob_get_num_clusters(_blob);
5794 	opts.use_extent_table = _blob->use_extent_table;
5795 	if (ctx->xattrs) {
5796 		memcpy(&opts.xattrs, ctx->xattrs, sizeof(*ctx->xattrs));
5797 	}
5798 
5799 	/* Set internal xattr BLOB_SNAPSHOT */
5800 	internal_xattrs.count = 1;
5801 	internal_xattrs.ctx = _blob;
5802 	internal_xattrs.names = xattr_names;
5803 	internal_xattrs.get_value = bs_xattr_clone;
5804 
5805 	bs_create_blob(_blob->bs, &opts, &internal_xattrs,
5806 		       bs_clone_newblob_create_cpl, ctx);
5807 }
5808 
5809 void spdk_bs_create_clone(struct spdk_blob_store *bs, spdk_blob_id blobid,
5810 			  const struct spdk_blob_xattr_opts *clone_xattrs,
5811 			  spdk_blob_op_with_id_complete cb_fn, void *cb_arg)
5812 {
5813 	struct spdk_clone_snapshot_ctx	*ctx = calloc(1, sizeof(*ctx));
5814 
5815 	if (!ctx) {
5816 		cb_fn(cb_arg, SPDK_BLOBID_INVALID, -ENOMEM);
5817 		return;
5818 	}
5819 
5820 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOBID;
5821 	ctx->cpl.u.blobid.cb_fn = cb_fn;
5822 	ctx->cpl.u.blobid.cb_arg = cb_arg;
5823 	ctx->cpl.u.blobid.blobid = SPDK_BLOBID_INVALID;
5824 	ctx->bserrno = 0;
5825 	ctx->xattrs = clone_xattrs;
5826 	ctx->original.id = blobid;
5827 
5828 	spdk_bs_open_blob(bs, ctx->original.id, bs_clone_origblob_open_cpl, ctx);
5829 }
5830 
5831 /* END spdk_bs_create_clone */
5832 
5833 /* START spdk_bs_inflate_blob */
5834 
5835 static void
5836 bs_inflate_blob_set_parent_cpl(void *cb_arg, struct spdk_blob *_parent, int bserrno)
5837 {
5838 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5839 	struct spdk_blob *_blob = ctx->original.blob;
5840 
5841 	if (bserrno != 0) {
5842 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5843 		return;
5844 	}
5845 
5846 	assert(_parent != NULL);
5847 
5848 	bs_blob_list_remove(_blob);
5849 	_blob->parent_id = _parent->id;
5850 	blob_set_xattr(_blob, BLOB_SNAPSHOT, &_blob->parent_id,
5851 		       sizeof(spdk_blob_id), true);
5852 
5853 	_blob->back_bs_dev->destroy(_blob->back_bs_dev);
5854 	_blob->back_bs_dev = bs_create_blob_bs_dev(_parent);
5855 	bs_blob_list_add(_blob);
5856 
5857 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
5858 }
5859 
5860 static void
5861 bs_inflate_blob_done(void *cb_arg, int bserrno)
5862 {
5863 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5864 	struct spdk_blob *_blob = ctx->original.blob;
5865 	struct spdk_blob *_parent;
5866 
5867 	if (bserrno != 0) {
5868 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5869 		return;
5870 	}
5871 
5872 	if (ctx->allocate_all) {
5873 		/* remove thin provisioning */
5874 		bs_blob_list_remove(_blob);
5875 		blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
5876 		_blob->invalid_flags = _blob->invalid_flags & ~SPDK_BLOB_THIN_PROV;
5877 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
5878 		_blob->back_bs_dev = NULL;
5879 		_blob->parent_id = SPDK_BLOBID_INVALID;
5880 	} else {
5881 		_parent = ((struct spdk_blob_bs_dev *)(_blob->back_bs_dev))->blob;
5882 		if (_parent->parent_id != SPDK_BLOBID_INVALID) {
5883 			/* We must change the parent of the inflated blob */
5884 			spdk_bs_open_blob(_blob->bs, _parent->parent_id,
5885 					  bs_inflate_blob_set_parent_cpl, ctx);
5886 			return;
5887 		}
5888 
5889 		bs_blob_list_remove(_blob);
5890 		blob_remove_xattr(_blob, BLOB_SNAPSHOT, true);
5891 		_blob->parent_id = SPDK_BLOBID_INVALID;
5892 		_blob->back_bs_dev->destroy(_blob->back_bs_dev);
5893 		_blob->back_bs_dev = bs_create_zeroes_dev();
5894 	}
5895 
5896 	_blob->state = SPDK_BLOB_STATE_DIRTY;
5897 	spdk_blob_sync_md(_blob, bs_clone_snapshot_origblob_cleanup, ctx);
5898 }
5899 
5900 /* Check if cluster needs allocation */
5901 static inline bool
5902 bs_cluster_needs_allocation(struct spdk_blob *blob, uint64_t cluster, bool allocate_all)
5903 {
5904 	struct spdk_blob_bs_dev *b;
5905 
5906 	assert(blob != NULL);
5907 
5908 	if (blob->active.clusters[cluster] != 0) {
5909 		/* Cluster is already allocated */
5910 		return false;
5911 	}
5912 
5913 	if (blob->parent_id == SPDK_BLOBID_INVALID) {
5914 		/* Blob have no parent blob */
5915 		return allocate_all;
5916 	}
5917 
5918 	b = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
5919 	return (allocate_all || b->blob->active.clusters[cluster] != 0);
5920 }
5921 
5922 static void
5923 bs_inflate_blob_touch_next(void *cb_arg, int bserrno)
5924 {
5925 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5926 	struct spdk_blob *_blob = ctx->original.blob;
5927 	uint64_t offset;
5928 
5929 	if (bserrno != 0) {
5930 		bs_clone_snapshot_origblob_cleanup(ctx, bserrno);
5931 		return;
5932 	}
5933 
5934 	for (; ctx->cluster < _blob->active.num_clusters; ctx->cluster++) {
5935 		if (bs_cluster_needs_allocation(_blob, ctx->cluster, ctx->allocate_all)) {
5936 			break;
5937 		}
5938 	}
5939 
5940 	if (ctx->cluster < _blob->active.num_clusters) {
5941 		offset = bs_cluster_to_lba(_blob->bs, ctx->cluster);
5942 
5943 		/* We may safely increment a cluster before write */
5944 		ctx->cluster++;
5945 
5946 		/* Use zero length write to touch a cluster */
5947 		spdk_blob_io_write(_blob, ctx->channel, NULL, offset, 0,
5948 				   bs_inflate_blob_touch_next, ctx);
5949 	} else {
5950 		bs_inflate_blob_done(cb_arg, bserrno);
5951 	}
5952 }
5953 
5954 static void
5955 bs_inflate_blob_open_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
5956 {
5957 	struct spdk_clone_snapshot_ctx *ctx = (struct spdk_clone_snapshot_ctx *)cb_arg;
5958 	uint64_t lfc; /* lowest free cluster */
5959 	uint64_t i;
5960 
5961 	if (bserrno != 0) {
5962 		bs_clone_snapshot_cleanup_finish(ctx, bserrno);
5963 		return;
5964 	}
5965 
5966 	ctx->original.blob = _blob;
5967 
5968 	if (_blob->locked_operation_in_progress) {
5969 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot inflate blob - another operation in progress\n");
5970 		ctx->bserrno = -EBUSY;
5971 		spdk_blob_close(_blob, bs_clone_snapshot_cleanup_finish, ctx);
5972 		return;
5973 	}
5974 
5975 	_blob->locked_operation_in_progress = true;
5976 
5977 	if (!ctx->allocate_all && _blob->parent_id == SPDK_BLOBID_INVALID) {
5978 		/* This blob have no parent, so we cannot decouple it. */
5979 		SPDK_ERRLOG("Cannot decouple parent of blob with no parent.\n");
5980 		bs_clone_snapshot_origblob_cleanup(ctx, -EINVAL);
5981 		return;
5982 	}
5983 
5984 	if (spdk_blob_is_thin_provisioned(_blob) == false) {
5985 		/* This is not thin provisioned blob. No need to inflate. */
5986 		bs_clone_snapshot_origblob_cleanup(ctx, 0);
5987 		return;
5988 	}
5989 
5990 	/* Do two passes - one to verify that we can obtain enough clusters
5991 	 * and another to actually claim them.
5992 	 */
5993 	lfc = 0;
5994 	for (i = 0; i < _blob->active.num_clusters; i++) {
5995 		if (bs_cluster_needs_allocation(_blob, i, ctx->allocate_all)) {
5996 			lfc = spdk_bit_array_find_first_clear(_blob->bs->used_clusters, lfc);
5997 			if (lfc == UINT32_MAX) {
5998 				/* No more free clusters. Cannot satisfy the request */
5999 				bs_clone_snapshot_origblob_cleanup(ctx, -ENOSPC);
6000 				return;
6001 			}
6002 			lfc++;
6003 		}
6004 	}
6005 
6006 	ctx->cluster = 0;
6007 	bs_inflate_blob_touch_next(ctx, 0);
6008 }
6009 
6010 static void
6011 bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6012 		spdk_blob_id blobid, bool allocate_all, spdk_blob_op_complete cb_fn, void *cb_arg)
6013 {
6014 	struct spdk_clone_snapshot_ctx *ctx = calloc(1, sizeof(*ctx));
6015 
6016 	if (!ctx) {
6017 		cb_fn(cb_arg, -ENOMEM);
6018 		return;
6019 	}
6020 	ctx->cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6021 	ctx->cpl.u.bs_basic.cb_fn = cb_fn;
6022 	ctx->cpl.u.bs_basic.cb_arg = cb_arg;
6023 	ctx->bserrno = 0;
6024 	ctx->original.id = blobid;
6025 	ctx->channel = channel;
6026 	ctx->allocate_all = allocate_all;
6027 
6028 	spdk_bs_open_blob(bs, ctx->original.id, bs_inflate_blob_open_cpl, ctx);
6029 }
6030 
6031 void
6032 spdk_bs_inflate_blob(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6033 		     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6034 {
6035 	bs_inflate_blob(bs, channel, blobid, true, cb_fn, cb_arg);
6036 }
6037 
6038 void
6039 spdk_bs_blob_decouple_parent(struct spdk_blob_store *bs, struct spdk_io_channel *channel,
6040 			     spdk_blob_id blobid, spdk_blob_op_complete cb_fn, void *cb_arg)
6041 {
6042 	bs_inflate_blob(bs, channel, blobid, false, cb_fn, cb_arg);
6043 }
6044 /* END spdk_bs_inflate_blob */
6045 
6046 /* START spdk_blob_resize */
6047 struct spdk_bs_resize_ctx {
6048 	spdk_blob_op_complete cb_fn;
6049 	void *cb_arg;
6050 	struct spdk_blob *blob;
6051 	uint64_t sz;
6052 	int rc;
6053 };
6054 
6055 static void
6056 bs_resize_unfreeze_cpl(void *cb_arg, int rc)
6057 {
6058 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6059 
6060 	if (rc != 0) {
6061 		SPDK_ERRLOG("Unfreeze failed, rc=%d\n", rc);
6062 	}
6063 
6064 	if (ctx->rc != 0) {
6065 		SPDK_ERRLOG("Unfreeze failed, ctx->rc=%d\n", ctx->rc);
6066 		rc = ctx->rc;
6067 	}
6068 
6069 	ctx->blob->locked_operation_in_progress = false;
6070 
6071 	ctx->cb_fn(ctx->cb_arg, rc);
6072 	free(ctx);
6073 }
6074 
6075 static void
6076 bs_resize_freeze_cpl(void *cb_arg, int rc)
6077 {
6078 	struct spdk_bs_resize_ctx *ctx = (struct spdk_bs_resize_ctx *)cb_arg;
6079 
6080 	if (rc != 0) {
6081 		ctx->blob->locked_operation_in_progress = false;
6082 		ctx->cb_fn(ctx->cb_arg, rc);
6083 		free(ctx);
6084 		return;
6085 	}
6086 
6087 	ctx->rc = blob_resize(ctx->blob, ctx->sz);
6088 
6089 	blob_unfreeze_io(ctx->blob, bs_resize_unfreeze_cpl, ctx);
6090 }
6091 
6092 void
6093 spdk_blob_resize(struct spdk_blob *blob, uint64_t sz, spdk_blob_op_complete cb_fn, void *cb_arg)
6094 {
6095 	struct spdk_bs_resize_ctx *ctx;
6096 
6097 	blob_verify_md_op(blob);
6098 
6099 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Resizing blob %lu to %lu clusters\n", blob->id, sz);
6100 
6101 	if (blob->md_ro) {
6102 		cb_fn(cb_arg, -EPERM);
6103 		return;
6104 	}
6105 
6106 	if (sz == blob->active.num_clusters) {
6107 		cb_fn(cb_arg, 0);
6108 		return;
6109 	}
6110 
6111 	if (blob->locked_operation_in_progress) {
6112 		cb_fn(cb_arg, -EBUSY);
6113 		return;
6114 	}
6115 
6116 	ctx = calloc(1, sizeof(*ctx));
6117 	if (!ctx) {
6118 		cb_fn(cb_arg, -ENOMEM);
6119 		return;
6120 	}
6121 
6122 	blob->locked_operation_in_progress = true;
6123 	ctx->cb_fn = cb_fn;
6124 	ctx->cb_arg = cb_arg;
6125 	ctx->blob = blob;
6126 	ctx->sz = sz;
6127 	blob_freeze_io(blob, bs_resize_freeze_cpl, ctx);
6128 }
6129 
6130 /* END spdk_blob_resize */
6131 
6132 
6133 /* START spdk_bs_delete_blob */
6134 
6135 static void
6136 bs_delete_close_cpl(void *cb_arg, int bserrno)
6137 {
6138 	spdk_bs_sequence_t *seq = cb_arg;
6139 
6140 	bs_sequence_finish(seq, bserrno);
6141 }
6142 
6143 static void
6144 bs_delete_persist_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6145 {
6146 	struct spdk_blob *blob = cb_arg;
6147 
6148 	if (bserrno != 0) {
6149 		/*
6150 		 * We already removed this blob from the blobstore tailq, so
6151 		 *  we need to free it here since this is the last reference
6152 		 *  to it.
6153 		 */
6154 		blob_free(blob);
6155 		bs_delete_close_cpl(seq, bserrno);
6156 		return;
6157 	}
6158 
6159 	/*
6160 	 * This will immediately decrement the ref_count and call
6161 	 *  the completion routine since the metadata state is clean.
6162 	 *  By calling spdk_blob_close, we reduce the number of call
6163 	 *  points into code that touches the blob->open_ref count
6164 	 *  and the blobstore's blob list.
6165 	 */
6166 	spdk_blob_close(blob, bs_delete_close_cpl, seq);
6167 }
6168 
6169 struct delete_snapshot_ctx {
6170 	struct spdk_blob_list *parent_snapshot_entry;
6171 	struct spdk_blob *snapshot;
6172 	bool snapshot_md_ro;
6173 	struct spdk_blob *clone;
6174 	bool clone_md_ro;
6175 	spdk_blob_op_with_handle_complete cb_fn;
6176 	void *cb_arg;
6177 	int bserrno;
6178 };
6179 
6180 static void
6181 delete_blob_cleanup_finish(void *cb_arg, int bserrno)
6182 {
6183 	struct delete_snapshot_ctx *ctx = cb_arg;
6184 
6185 	if (bserrno != 0) {
6186 		SPDK_ERRLOG("Snapshot cleanup error %d\n", bserrno);
6187 	}
6188 
6189 	assert(ctx != NULL);
6190 
6191 	if (bserrno != 0 && ctx->bserrno == 0) {
6192 		ctx->bserrno = bserrno;
6193 	}
6194 
6195 	ctx->cb_fn(ctx->cb_arg, ctx->snapshot, ctx->bserrno);
6196 	free(ctx);
6197 }
6198 
6199 static void
6200 delete_snapshot_cleanup_snapshot(void *cb_arg, int bserrno)
6201 {
6202 	struct delete_snapshot_ctx *ctx = cb_arg;
6203 
6204 	if (bserrno != 0) {
6205 		ctx->bserrno = bserrno;
6206 		SPDK_ERRLOG("Clone cleanup error %d\n", bserrno);
6207 	}
6208 
6209 	if (ctx->bserrno != 0) {
6210 		assert(blob_lookup(ctx->snapshot->bs, ctx->snapshot->id) == NULL);
6211 		TAILQ_INSERT_HEAD(&ctx->snapshot->bs->blobs, ctx->snapshot, link);
6212 		spdk_bit_array_set(ctx->snapshot->bs->open_blobids, ctx->snapshot->id);
6213 	}
6214 
6215 	ctx->snapshot->locked_operation_in_progress = false;
6216 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6217 
6218 	spdk_blob_close(ctx->snapshot, delete_blob_cleanup_finish, ctx);
6219 }
6220 
6221 static void
6222 delete_snapshot_cleanup_clone(void *cb_arg, int bserrno)
6223 {
6224 	struct delete_snapshot_ctx *ctx = cb_arg;
6225 
6226 	ctx->clone->locked_operation_in_progress = false;
6227 	ctx->clone->md_ro = ctx->clone_md_ro;
6228 
6229 	spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
6230 }
6231 
6232 static void
6233 delete_snapshot_unfreeze_cpl(void *cb_arg, int bserrno)
6234 {
6235 	struct delete_snapshot_ctx *ctx = cb_arg;
6236 
6237 	if (bserrno) {
6238 		ctx->bserrno = bserrno;
6239 		delete_snapshot_cleanup_clone(ctx, 0);
6240 		return;
6241 	}
6242 
6243 	ctx->clone->locked_operation_in_progress = false;
6244 	spdk_blob_close(ctx->clone, delete_blob_cleanup_finish, ctx);
6245 }
6246 
6247 static void
6248 delete_snapshot_sync_snapshot_cpl(void *cb_arg, int bserrno)
6249 {
6250 	struct delete_snapshot_ctx *ctx = cb_arg;
6251 	struct spdk_blob_list *parent_snapshot_entry = NULL;
6252 	struct spdk_blob_list *snapshot_entry = NULL;
6253 	struct spdk_blob_list *clone_entry = NULL;
6254 	struct spdk_blob_list *snapshot_clone_entry = NULL;
6255 
6256 	if (bserrno) {
6257 		SPDK_ERRLOG("Failed to sync MD on blob\n");
6258 		ctx->bserrno = bserrno;
6259 		delete_snapshot_cleanup_clone(ctx, 0);
6260 		return;
6261 	}
6262 
6263 	/* Get snapshot entry for the snapshot we want to remove */
6264 	snapshot_entry = bs_get_snapshot_entry(ctx->snapshot->bs, ctx->snapshot->id);
6265 
6266 	assert(snapshot_entry != NULL);
6267 
6268 	/* Remove clone entry in this snapshot (at this point there can be only one clone) */
6269 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6270 	assert(clone_entry != NULL);
6271 	TAILQ_REMOVE(&snapshot_entry->clones, clone_entry, link);
6272 	snapshot_entry->clone_count--;
6273 	assert(TAILQ_EMPTY(&snapshot_entry->clones));
6274 
6275 	if (ctx->snapshot->parent_id != SPDK_BLOBID_INVALID) {
6276 		/* This snapshot is at the same time a clone of another snapshot - we need to
6277 		 * update parent snapshot (remove current clone, add new one inherited from
6278 		 * the snapshot that is being removed) */
6279 
6280 		/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
6281 		 * snapshot that we are removing */
6282 		blob_get_snapshot_and_clone_entries(ctx->snapshot, &parent_snapshot_entry,
6283 						    &snapshot_clone_entry);
6284 
6285 		/* Switch clone entry in parent snapshot */
6286 		TAILQ_INSERT_TAIL(&parent_snapshot_entry->clones, clone_entry, link);
6287 		TAILQ_REMOVE(&parent_snapshot_entry->clones, snapshot_clone_entry, link);
6288 		free(snapshot_clone_entry);
6289 	} else {
6290 		/* No parent snapshot - just remove clone entry */
6291 		free(clone_entry);
6292 	}
6293 
6294 	/* Restore md_ro flags */
6295 	ctx->clone->md_ro = ctx->clone_md_ro;
6296 	ctx->snapshot->md_ro = ctx->snapshot_md_ro;
6297 
6298 	blob_unfreeze_io(ctx->clone, delete_snapshot_unfreeze_cpl, ctx);
6299 }
6300 
6301 static void
6302 delete_snapshot_sync_clone_cpl(void *cb_arg, int bserrno)
6303 {
6304 	struct delete_snapshot_ctx *ctx = cb_arg;
6305 	uint64_t i;
6306 
6307 	ctx->snapshot->md_ro = false;
6308 
6309 	if (bserrno) {
6310 		SPDK_ERRLOG("Failed to sync MD on clone\n");
6311 		ctx->bserrno = bserrno;
6312 
6313 		/* Restore snapshot to previous state */
6314 		bserrno = blob_remove_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, true);
6315 		if (bserrno != 0) {
6316 			delete_snapshot_cleanup_clone(ctx, bserrno);
6317 			return;
6318 		}
6319 
6320 		spdk_blob_sync_md(ctx->snapshot, delete_snapshot_cleanup_clone, ctx);
6321 		return;
6322 	}
6323 
6324 	/* Clear cluster map entries for snapshot */
6325 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
6326 		if (ctx->clone->active.clusters[i] == ctx->snapshot->active.clusters[i]) {
6327 			ctx->snapshot->active.clusters[i] = 0;
6328 		}
6329 	}
6330 	for (i = 0; i < ctx->snapshot->active.num_extent_pages &&
6331 	     i < ctx->clone->active.num_extent_pages; i++) {
6332 		if (ctx->clone->active.extent_pages[i] == ctx->snapshot->active.extent_pages[i]) {
6333 			ctx->snapshot->active.extent_pages[i] = 0;
6334 		}
6335 	}
6336 
6337 	blob_set_thin_provision(ctx->snapshot);
6338 	ctx->snapshot->state = SPDK_BLOB_STATE_DIRTY;
6339 
6340 	if (ctx->parent_snapshot_entry != NULL) {
6341 		ctx->snapshot->back_bs_dev = NULL;
6342 	}
6343 
6344 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_cpl, ctx);
6345 }
6346 
6347 static void
6348 delete_snapshot_sync_snapshot_xattr_cpl(void *cb_arg, int bserrno)
6349 {
6350 	struct delete_snapshot_ctx *ctx = cb_arg;
6351 	uint64_t i;
6352 
6353 	/* Temporarily override md_ro flag for clone for MD modification */
6354 	ctx->clone_md_ro = ctx->clone->md_ro;
6355 	ctx->clone->md_ro = false;
6356 
6357 	if (bserrno) {
6358 		SPDK_ERRLOG("Failed to sync MD with xattr on blob\n");
6359 		ctx->bserrno = bserrno;
6360 		delete_snapshot_cleanup_clone(ctx, 0);
6361 		return;
6362 	}
6363 
6364 	/* Copy snapshot map to clone map (only unallocated clusters in clone) */
6365 	for (i = 0; i < ctx->snapshot->active.num_clusters && i < ctx->clone->active.num_clusters; i++) {
6366 		if (ctx->clone->active.clusters[i] == 0) {
6367 			ctx->clone->active.clusters[i] = ctx->snapshot->active.clusters[i];
6368 		}
6369 	}
6370 	for (i = 0; i < ctx->snapshot->active.num_extent_pages &&
6371 	     i < ctx->clone->active.num_extent_pages; i++) {
6372 		if (ctx->clone->active.extent_pages[i] == 0) {
6373 			ctx->clone->active.extent_pages[i] = ctx->snapshot->active.extent_pages[i];
6374 		}
6375 	}
6376 
6377 	/* Delete old backing bs_dev from clone (related to snapshot that will be removed) */
6378 	ctx->clone->back_bs_dev->destroy(ctx->clone->back_bs_dev);
6379 
6380 	/* Set/remove snapshot xattr and switch parent ID and backing bs_dev on clone... */
6381 	if (ctx->parent_snapshot_entry != NULL) {
6382 		/* ...to parent snapshot */
6383 		ctx->clone->parent_id = ctx->parent_snapshot_entry->id;
6384 		ctx->clone->back_bs_dev = ctx->snapshot->back_bs_dev;
6385 		blob_set_xattr(ctx->clone, BLOB_SNAPSHOT, &ctx->parent_snapshot_entry->id,
6386 			       sizeof(spdk_blob_id),
6387 			       true);
6388 	} else {
6389 		/* ...to blobid invalid and zeroes dev */
6390 		ctx->clone->parent_id = SPDK_BLOBID_INVALID;
6391 		ctx->clone->back_bs_dev = bs_create_zeroes_dev();
6392 		blob_remove_xattr(ctx->clone, BLOB_SNAPSHOT, true);
6393 	}
6394 
6395 	spdk_blob_sync_md(ctx->clone, delete_snapshot_sync_clone_cpl, ctx);
6396 }
6397 
6398 static void
6399 delete_snapshot_freeze_io_cb(void *cb_arg, int bserrno)
6400 {
6401 	struct delete_snapshot_ctx *ctx = cb_arg;
6402 
6403 	if (bserrno) {
6404 		SPDK_ERRLOG("Failed to freeze I/O on clone\n");
6405 		ctx->bserrno = bserrno;
6406 		delete_snapshot_cleanup_clone(ctx, 0);
6407 		return;
6408 	}
6409 
6410 	/* Temporarily override md_ro flag for snapshot for MD modification */
6411 	ctx->snapshot_md_ro = ctx->snapshot->md_ro;
6412 	ctx->snapshot->md_ro = false;
6413 
6414 	/* Mark blob as pending for removal for power failure safety, use clone id for recovery */
6415 	ctx->bserrno = blob_set_xattr(ctx->snapshot, SNAPSHOT_PENDING_REMOVAL, &ctx->clone->id,
6416 				      sizeof(spdk_blob_id), true);
6417 	if (ctx->bserrno != 0) {
6418 		delete_snapshot_cleanup_clone(ctx, 0);
6419 		return;
6420 	}
6421 
6422 	spdk_blob_sync_md(ctx->snapshot, delete_snapshot_sync_snapshot_xattr_cpl, ctx);
6423 }
6424 
6425 static void
6426 delete_snapshot_open_clone_cb(void *cb_arg, struct spdk_blob *clone, int bserrno)
6427 {
6428 	struct delete_snapshot_ctx *ctx = cb_arg;
6429 
6430 	if (bserrno) {
6431 		SPDK_ERRLOG("Failed to open clone\n");
6432 		ctx->bserrno = bserrno;
6433 		delete_snapshot_cleanup_snapshot(ctx, 0);
6434 		return;
6435 	}
6436 
6437 	ctx->clone = clone;
6438 
6439 	if (clone->locked_operation_in_progress) {
6440 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress on its clone\n");
6441 		ctx->bserrno = -EBUSY;
6442 		spdk_blob_close(ctx->clone, delete_snapshot_cleanup_snapshot, ctx);
6443 		return;
6444 	}
6445 
6446 	clone->locked_operation_in_progress = true;
6447 
6448 	blob_freeze_io(clone, delete_snapshot_freeze_io_cb, ctx);
6449 }
6450 
6451 static void
6452 update_clone_on_snapshot_deletion(struct spdk_blob *snapshot, struct delete_snapshot_ctx *ctx)
6453 {
6454 	struct spdk_blob_list *snapshot_entry = NULL;
6455 	struct spdk_blob_list *clone_entry = NULL;
6456 	struct spdk_blob_list *snapshot_clone_entry = NULL;
6457 
6458 	/* Get snapshot entry for the snapshot we want to remove */
6459 	snapshot_entry = bs_get_snapshot_entry(snapshot->bs, snapshot->id);
6460 
6461 	assert(snapshot_entry != NULL);
6462 
6463 	/* Get clone of the snapshot (at this point there can be only one clone) */
6464 	clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6465 	assert(snapshot_entry->clone_count == 1);
6466 	assert(clone_entry != NULL);
6467 
6468 	/* Get snapshot entry for parent snapshot and clone entry within that snapshot for
6469 	 * snapshot that we are removing */
6470 	blob_get_snapshot_and_clone_entries(snapshot, &ctx->parent_snapshot_entry,
6471 					    &snapshot_clone_entry);
6472 
6473 	spdk_bs_open_blob(snapshot->bs, clone_entry->id, delete_snapshot_open_clone_cb, ctx);
6474 }
6475 
6476 static void
6477 bs_delete_blob_finish(void *cb_arg, struct spdk_blob *blob, int bserrno)
6478 {
6479 	spdk_bs_sequence_t *seq = cb_arg;
6480 	struct spdk_blob_list *snapshot_entry = NULL;
6481 	uint32_t page_num;
6482 
6483 	if (bserrno) {
6484 		SPDK_ERRLOG("Failed to remove blob\n");
6485 		bs_sequence_finish(seq, bserrno);
6486 		return;
6487 	}
6488 
6489 	/* Remove snapshot from the list */
6490 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
6491 	if (snapshot_entry != NULL) {
6492 		TAILQ_REMOVE(&blob->bs->snapshots, snapshot_entry, link);
6493 		free(snapshot_entry);
6494 	}
6495 
6496 	page_num = bs_blobid_to_page(blob->id);
6497 	spdk_bit_array_clear(blob->bs->used_blobids, page_num);
6498 	blob->state = SPDK_BLOB_STATE_DIRTY;
6499 	blob->active.num_pages = 0;
6500 	blob_resize(blob, 0);
6501 
6502 	blob_persist(seq, blob, bs_delete_persist_cpl, blob);
6503 }
6504 
6505 static int
6506 bs_is_blob_deletable(struct spdk_blob *blob, bool *update_clone)
6507 {
6508 	struct spdk_blob_list *snapshot_entry = NULL;
6509 	struct spdk_blob_list *clone_entry = NULL;
6510 	struct spdk_blob *clone = NULL;
6511 	bool has_one_clone = false;
6512 
6513 	/* Check if this is a snapshot with clones */
6514 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
6515 	if (snapshot_entry != NULL) {
6516 		if (snapshot_entry->clone_count > 1) {
6517 			SPDK_ERRLOG("Cannot remove snapshot with more than one clone\n");
6518 			return -EBUSY;
6519 		} else if (snapshot_entry->clone_count == 1) {
6520 			has_one_clone = true;
6521 		}
6522 	}
6523 
6524 	/* Check if someone has this blob open (besides this delete context):
6525 	 * - open_ref = 1 - only this context opened blob, so it is ok to remove it
6526 	 * - open_ref <= 2 && has_one_clone = true - clone is holding snapshot
6527 	 *	and that is ok, because we will update it accordingly */
6528 	if (blob->open_ref <= 2 && has_one_clone) {
6529 		clone_entry = TAILQ_FIRST(&snapshot_entry->clones);
6530 		assert(clone_entry != NULL);
6531 		clone = blob_lookup(blob->bs, clone_entry->id);
6532 
6533 		if (blob->open_ref == 2 && clone == NULL) {
6534 			/* Clone is closed and someone else opened this blob */
6535 			SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
6536 			return -EBUSY;
6537 		}
6538 
6539 		*update_clone = true;
6540 		return 0;
6541 	}
6542 
6543 	if (blob->open_ref > 1) {
6544 		SPDK_ERRLOG("Cannot remove snapshot because it is open\n");
6545 		return -EBUSY;
6546 	}
6547 
6548 	assert(has_one_clone == false);
6549 	*update_clone = false;
6550 	return 0;
6551 }
6552 
6553 static void
6554 bs_delete_enomem_close_cpl(void *cb_arg, int bserrno)
6555 {
6556 	spdk_bs_sequence_t *seq = cb_arg;
6557 
6558 	bs_sequence_finish(seq, -ENOMEM);
6559 }
6560 
6561 static void
6562 bs_delete_open_cpl(void *cb_arg, struct spdk_blob *blob, int bserrno)
6563 {
6564 	spdk_bs_sequence_t *seq = cb_arg;
6565 	struct delete_snapshot_ctx *ctx;
6566 	bool update_clone = false;
6567 
6568 	if (bserrno != 0) {
6569 		bs_sequence_finish(seq, bserrno);
6570 		return;
6571 	}
6572 
6573 	blob_verify_md_op(blob);
6574 
6575 	ctx = calloc(1, sizeof(*ctx));
6576 	if (ctx == NULL) {
6577 		spdk_blob_close(blob, bs_delete_enomem_close_cpl, seq);
6578 		return;
6579 	}
6580 
6581 	ctx->snapshot = blob;
6582 	ctx->cb_fn = bs_delete_blob_finish;
6583 	ctx->cb_arg = seq;
6584 
6585 	/* Check if blob can be removed and if it is a snapshot with clone on top of it */
6586 	ctx->bserrno = bs_is_blob_deletable(blob, &update_clone);
6587 	if (ctx->bserrno) {
6588 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
6589 		return;
6590 	}
6591 
6592 	if (blob->locked_operation_in_progress) {
6593 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Cannot remove blob - another operation in progress\n");
6594 		ctx->bserrno = -EBUSY;
6595 		spdk_blob_close(blob, delete_blob_cleanup_finish, ctx);
6596 		return;
6597 	}
6598 
6599 	blob->locked_operation_in_progress = true;
6600 
6601 	/*
6602 	 * Remove the blob from the blob_store list now, to ensure it does not
6603 	 *  get returned after this point by blob_lookup().
6604 	 */
6605 	spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
6606 	TAILQ_REMOVE(&blob->bs->blobs, blob, link);
6607 
6608 	if (update_clone) {
6609 		/* This blob is a snapshot with active clone - update clone first */
6610 		update_clone_on_snapshot_deletion(blob, ctx);
6611 	} else {
6612 		/* This blob does not have any clones - just remove it */
6613 		bs_blob_list_remove(blob);
6614 		bs_delete_blob_finish(seq, blob, 0);
6615 		free(ctx);
6616 	}
6617 }
6618 
6619 void
6620 spdk_bs_delete_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
6621 		    spdk_blob_op_complete cb_fn, void *cb_arg)
6622 {
6623 	struct spdk_bs_cpl	cpl;
6624 	spdk_bs_sequence_t	*seq;
6625 
6626 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Deleting blob %lu\n", blobid);
6627 
6628 	assert(spdk_get_thread() == bs->md_thread);
6629 
6630 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6631 	cpl.u.blob_basic.cb_fn = cb_fn;
6632 	cpl.u.blob_basic.cb_arg = cb_arg;
6633 
6634 	seq = bs_sequence_start(bs->md_channel, &cpl);
6635 	if (!seq) {
6636 		cb_fn(cb_arg, -ENOMEM);
6637 		return;
6638 	}
6639 
6640 	spdk_bs_open_blob(bs, blobid, bs_delete_open_cpl, seq);
6641 }
6642 
6643 /* END spdk_bs_delete_blob */
6644 
6645 /* START spdk_bs_open_blob */
6646 
6647 static void
6648 bs_open_blob_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6649 {
6650 	struct spdk_blob *blob = cb_arg;
6651 	struct spdk_blob *existing;
6652 
6653 	if (bserrno != 0) {
6654 		blob_free(blob);
6655 		seq->cpl.u.blob_handle.blob = NULL;
6656 		bs_sequence_finish(seq, bserrno);
6657 		return;
6658 	}
6659 
6660 	existing = blob_lookup(blob->bs, blob->id);
6661 	if (existing) {
6662 		blob_free(blob);
6663 		existing->open_ref++;
6664 		seq->cpl.u.blob_handle.blob = existing;
6665 		bs_sequence_finish(seq, 0);
6666 		return;
6667 	}
6668 
6669 	blob->open_ref++;
6670 
6671 	spdk_bit_array_set(blob->bs->open_blobids, blob->id);
6672 	TAILQ_INSERT_HEAD(&blob->bs->blobs, blob, link);
6673 
6674 	bs_sequence_finish(seq, bserrno);
6675 }
6676 
6677 static void
6678 bs_open_blob(struct spdk_blob_store *bs,
6679 	     spdk_blob_id blobid,
6680 	     struct spdk_blob_open_opts *opts,
6681 	     spdk_blob_op_with_handle_complete cb_fn,
6682 	     void *cb_arg)
6683 {
6684 	struct spdk_blob		*blob;
6685 	struct spdk_bs_cpl		cpl;
6686 	struct spdk_blob_open_opts	opts_default;
6687 	spdk_bs_sequence_t		*seq;
6688 	uint32_t			page_num;
6689 
6690 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Opening blob %lu\n", blobid);
6691 	assert(spdk_get_thread() == bs->md_thread);
6692 
6693 	page_num = bs_blobid_to_page(blobid);
6694 	if (spdk_bit_array_get(bs->used_blobids, page_num) == false) {
6695 		/* Invalid blobid */
6696 		cb_fn(cb_arg, NULL, -ENOENT);
6697 		return;
6698 	}
6699 
6700 	blob = blob_lookup(bs, blobid);
6701 	if (blob) {
6702 		blob->open_ref++;
6703 		cb_fn(cb_arg, blob, 0);
6704 		return;
6705 	}
6706 
6707 	blob = blob_alloc(bs, blobid);
6708 	if (!blob) {
6709 		cb_fn(cb_arg, NULL, -ENOMEM);
6710 		return;
6711 	}
6712 
6713 	if (!opts) {
6714 		spdk_blob_open_opts_init(&opts_default);
6715 		opts = &opts_default;
6716 	}
6717 
6718 	blob->clear_method = opts->clear_method;
6719 
6720 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_HANDLE;
6721 	cpl.u.blob_handle.cb_fn = cb_fn;
6722 	cpl.u.blob_handle.cb_arg = cb_arg;
6723 	cpl.u.blob_handle.blob = blob;
6724 
6725 	seq = bs_sequence_start(bs->md_channel, &cpl);
6726 	if (!seq) {
6727 		blob_free(blob);
6728 		cb_fn(cb_arg, NULL, -ENOMEM);
6729 		return;
6730 	}
6731 
6732 	blob_load(seq, blob, bs_open_blob_cpl, blob);
6733 }
6734 
6735 void spdk_bs_open_blob(struct spdk_blob_store *bs, spdk_blob_id blobid,
6736 		       spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6737 {
6738 	bs_open_blob(bs, blobid, NULL, cb_fn, cb_arg);
6739 }
6740 
6741 void spdk_bs_open_blob_ext(struct spdk_blob_store *bs, spdk_blob_id blobid,
6742 			   struct spdk_blob_open_opts *opts, spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
6743 {
6744 	bs_open_blob(bs, blobid, opts, cb_fn, cb_arg);
6745 }
6746 
6747 /* END spdk_bs_open_blob */
6748 
6749 /* START spdk_blob_set_read_only */
6750 int spdk_blob_set_read_only(struct spdk_blob *blob)
6751 {
6752 	blob_verify_md_op(blob);
6753 
6754 	blob->data_ro_flags |= SPDK_BLOB_READ_ONLY;
6755 
6756 	blob->state = SPDK_BLOB_STATE_DIRTY;
6757 	return 0;
6758 }
6759 /* END spdk_blob_set_read_only */
6760 
6761 /* START spdk_blob_sync_md */
6762 
6763 static void
6764 blob_sync_md_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6765 {
6766 	struct spdk_blob *blob = cb_arg;
6767 
6768 	if (bserrno == 0 && (blob->data_ro_flags & SPDK_BLOB_READ_ONLY)) {
6769 		blob->data_ro = true;
6770 		blob->md_ro = true;
6771 	}
6772 
6773 	bs_sequence_finish(seq, bserrno);
6774 }
6775 
6776 static void
6777 blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
6778 {
6779 	struct spdk_bs_cpl	cpl;
6780 	spdk_bs_sequence_t	*seq;
6781 
6782 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6783 	cpl.u.blob_basic.cb_fn = cb_fn;
6784 	cpl.u.blob_basic.cb_arg = cb_arg;
6785 
6786 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
6787 	if (!seq) {
6788 		cb_fn(cb_arg, -ENOMEM);
6789 		return;
6790 	}
6791 
6792 	blob_persist(seq, blob, blob_sync_md_cpl, blob);
6793 }
6794 
6795 void
6796 spdk_blob_sync_md(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
6797 {
6798 	blob_verify_md_op(blob);
6799 
6800 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Syncing blob %lu\n", blob->id);
6801 
6802 	if (blob->md_ro) {
6803 		assert(blob->state == SPDK_BLOB_STATE_CLEAN);
6804 		cb_fn(cb_arg, 0);
6805 		return;
6806 	}
6807 
6808 	blob_sync_md(blob, cb_fn, cb_arg);
6809 }
6810 
6811 /* END spdk_blob_sync_md */
6812 
6813 struct spdk_blob_insert_cluster_ctx {
6814 	struct spdk_thread	*thread;
6815 	struct spdk_blob	*blob;
6816 	uint32_t		cluster_num;	/* cluster index in blob */
6817 	uint32_t		cluster;	/* cluster on disk */
6818 	uint32_t		extent_page;	/* extent page on disk */
6819 	int			rc;
6820 	spdk_blob_op_complete	cb_fn;
6821 	void			*cb_arg;
6822 };
6823 
6824 static void
6825 blob_insert_cluster_msg_cpl(void *arg)
6826 {
6827 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
6828 
6829 	ctx->cb_fn(ctx->cb_arg, ctx->rc);
6830 	free(ctx);
6831 }
6832 
6833 static void
6834 blob_insert_cluster_msg_cb(void *arg, int bserrno)
6835 {
6836 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
6837 
6838 	ctx->rc = bserrno;
6839 	spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
6840 }
6841 
6842 static void
6843 blob_persist_extent_page_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6844 {
6845 	struct spdk_blob_md_page        *page = cb_arg;
6846 
6847 	bs_sequence_finish(seq, bserrno);
6848 	spdk_free(page);
6849 }
6850 
6851 static void
6852 blob_insert_extent(struct spdk_blob *blob, uint32_t extent, uint64_t cluster_num,
6853 		   spdk_blob_op_complete cb_fn, void *cb_arg)
6854 {
6855 	spdk_bs_sequence_t		*seq;
6856 	struct spdk_bs_cpl		cpl;
6857 	struct spdk_blob_md_page	*page = NULL;
6858 	uint32_t			page_count = 0;
6859 	int				rc;
6860 
6861 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6862 	cpl.u.blob_basic.cb_fn = cb_fn;
6863 	cpl.u.blob_basic.cb_arg = cb_arg;
6864 
6865 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
6866 	if (!seq) {
6867 		cb_fn(cb_arg, -ENOMEM);
6868 		return;
6869 	}
6870 	rc = blob_serialize_add_page(blob, &page, &page_count, &page);
6871 	if (rc < 0) {
6872 		bs_sequence_finish(seq, rc);
6873 		return;
6874 	}
6875 
6876 	blob_serialize_extent_page(blob, cluster_num, page);
6877 
6878 	page->crc = blob_md_page_calc_crc(page);
6879 
6880 	assert(spdk_bit_array_get(blob->bs->used_md_pages, extent) == true);
6881 
6882 	bs_sequence_write_dev(seq, page, bs_md_page_to_lba(blob->bs, extent),
6883 			      bs_byte_to_lba(blob->bs, SPDK_BS_PAGE_SIZE),
6884 			      blob_persist_extent_page_cpl, page);
6885 }
6886 
6887 static void
6888 blob_insert_cluster_msg(void *arg)
6889 {
6890 	struct spdk_blob_insert_cluster_ctx *ctx = arg;
6891 	uint32_t *extent_page;
6892 
6893 	ctx->rc = blob_insert_cluster(ctx->blob, ctx->cluster_num, ctx->cluster);
6894 	if (ctx->rc != 0) {
6895 		spdk_thread_send_msg(ctx->thread, blob_insert_cluster_msg_cpl, ctx);
6896 		return;
6897 	}
6898 
6899 	if (ctx->blob->use_extent_table == false) {
6900 		/* Extent table is not used, proceed with sync of md that will only use extents_rle. */
6901 		ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
6902 		blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
6903 		return;
6904 	}
6905 
6906 	extent_page = bs_cluster_to_extent_page(ctx->blob, ctx->cluster_num);
6907 	if (*extent_page == 0) {
6908 		/* Extent page requires allocation.
6909 		 * It was already claimed in the used_md_pages map and placed in ctx.
6910 		 * Blob persist will take care of writing out new extent page on disk. */
6911 		assert(ctx->extent_page != 0);
6912 		assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
6913 		*extent_page = ctx->extent_page;
6914 		ctx->blob->state = SPDK_BLOB_STATE_DIRTY;
6915 		blob_sync_md(ctx->blob, blob_insert_cluster_msg_cb, ctx);
6916 	} else {
6917 		/* It is possible for original thread to allocate extent page for
6918 		 * different cluster in the same extent page. In such case proceed with
6919 		 * updating the existing extent page, but release the additional one. */
6920 		if (ctx->extent_page != 0) {
6921 			assert(spdk_bit_array_get(ctx->blob->bs->used_md_pages, ctx->extent_page) == true);
6922 			bs_release_md_page(ctx->blob->bs, ctx->extent_page);
6923 			ctx->extent_page = 0;
6924 		}
6925 		/* Extent page already allocated.
6926 		 * Every cluster allocation, requires just an update of single extent page. */
6927 		blob_insert_extent(ctx->blob, *extent_page, ctx->cluster_num,
6928 				   blob_insert_cluster_msg_cb, ctx);
6929 	}
6930 }
6931 
6932 static void
6933 blob_insert_cluster_on_md_thread(struct spdk_blob *blob, uint32_t cluster_num,
6934 				 uint64_t cluster, uint32_t extent_page, spdk_blob_op_complete cb_fn, void *cb_arg)
6935 {
6936 	struct spdk_blob_insert_cluster_ctx *ctx;
6937 
6938 	ctx = calloc(1, sizeof(*ctx));
6939 	if (ctx == NULL) {
6940 		cb_fn(cb_arg, -ENOMEM);
6941 		return;
6942 	}
6943 
6944 	ctx->thread = spdk_get_thread();
6945 	ctx->blob = blob;
6946 	ctx->cluster_num = cluster_num;
6947 	ctx->cluster = cluster;
6948 	ctx->extent_page = extent_page;
6949 	ctx->cb_fn = cb_fn;
6950 	ctx->cb_arg = cb_arg;
6951 
6952 	spdk_thread_send_msg(blob->bs->md_thread, blob_insert_cluster_msg, ctx);
6953 }
6954 
6955 /* START spdk_blob_close */
6956 
6957 static void
6958 blob_close_cpl(spdk_bs_sequence_t *seq, void *cb_arg, int bserrno)
6959 {
6960 	struct spdk_blob *blob = cb_arg;
6961 
6962 	if (bserrno == 0) {
6963 		blob->open_ref--;
6964 		if (blob->open_ref == 0) {
6965 			/*
6966 			 * Blobs with active.num_pages == 0 are deleted blobs.
6967 			 *  these blobs are removed from the blob_store list
6968 			 *  when the deletion process starts - so don't try to
6969 			 *  remove them again.
6970 			 */
6971 			if (blob->active.num_pages > 0) {
6972 				spdk_bit_array_clear(blob->bs->open_blobids, blob->id);
6973 				TAILQ_REMOVE(&blob->bs->blobs, blob, link);
6974 			}
6975 			blob_free(blob);
6976 		}
6977 	}
6978 
6979 	bs_sequence_finish(seq, bserrno);
6980 }
6981 
6982 void spdk_blob_close(struct spdk_blob *blob, spdk_blob_op_complete cb_fn, void *cb_arg)
6983 {
6984 	struct spdk_bs_cpl	cpl;
6985 	spdk_bs_sequence_t	*seq;
6986 
6987 	blob_verify_md_op(blob);
6988 
6989 	SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Closing blob %lu\n", blob->id);
6990 
6991 	if (blob->open_ref == 0) {
6992 		cb_fn(cb_arg, -EBADF);
6993 		return;
6994 	}
6995 
6996 	cpl.type = SPDK_BS_CPL_TYPE_BLOB_BASIC;
6997 	cpl.u.blob_basic.cb_fn = cb_fn;
6998 	cpl.u.blob_basic.cb_arg = cb_arg;
6999 
7000 	seq = bs_sequence_start(blob->bs->md_channel, &cpl);
7001 	if (!seq) {
7002 		cb_fn(cb_arg, -ENOMEM);
7003 		return;
7004 	}
7005 
7006 	/* Sync metadata */
7007 	blob_persist(seq, blob, blob_close_cpl, blob);
7008 }
7009 
7010 /* END spdk_blob_close */
7011 
7012 struct spdk_io_channel *spdk_bs_alloc_io_channel(struct spdk_blob_store *bs)
7013 {
7014 	return spdk_get_io_channel(bs);
7015 }
7016 
7017 void spdk_bs_free_io_channel(struct spdk_io_channel *channel)
7018 {
7019 	spdk_put_io_channel(channel);
7020 }
7021 
7022 void spdk_blob_io_unmap(struct spdk_blob *blob, struct spdk_io_channel *channel,
7023 			uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7024 {
7025 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7026 			       SPDK_BLOB_UNMAP);
7027 }
7028 
7029 void spdk_blob_io_write_zeroes(struct spdk_blob *blob, struct spdk_io_channel *channel,
7030 			       uint64_t offset, uint64_t length, spdk_blob_op_complete cb_fn, void *cb_arg)
7031 {
7032 	blob_request_submit_op(blob, channel, NULL, offset, length, cb_fn, cb_arg,
7033 			       SPDK_BLOB_WRITE_ZEROES);
7034 }
7035 
7036 void spdk_blob_io_write(struct spdk_blob *blob, struct spdk_io_channel *channel,
7037 			void *payload, uint64_t offset, uint64_t length,
7038 			spdk_blob_op_complete cb_fn, void *cb_arg)
7039 {
7040 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7041 			       SPDK_BLOB_WRITE);
7042 }
7043 
7044 void spdk_blob_io_read(struct spdk_blob *blob, struct spdk_io_channel *channel,
7045 		       void *payload, uint64_t offset, uint64_t length,
7046 		       spdk_blob_op_complete cb_fn, void *cb_arg)
7047 {
7048 	blob_request_submit_op(blob, channel, payload, offset, length, cb_fn, cb_arg,
7049 			       SPDK_BLOB_READ);
7050 }
7051 
7052 void spdk_blob_io_writev(struct spdk_blob *blob, struct spdk_io_channel *channel,
7053 			 struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7054 			 spdk_blob_op_complete cb_fn, void *cb_arg)
7055 {
7056 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, false);
7057 }
7058 
7059 void spdk_blob_io_readv(struct spdk_blob *blob, struct spdk_io_channel *channel,
7060 			struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
7061 			spdk_blob_op_complete cb_fn, void *cb_arg)
7062 {
7063 	blob_request_submit_rw_iov(blob, channel, iov, iovcnt, offset, length, cb_fn, cb_arg, true);
7064 }
7065 
7066 struct spdk_bs_iter_ctx {
7067 	int64_t page_num;
7068 	struct spdk_blob_store *bs;
7069 
7070 	spdk_blob_op_with_handle_complete cb_fn;
7071 	void *cb_arg;
7072 };
7073 
7074 static void
7075 bs_iter_cpl(void *cb_arg, struct spdk_blob *_blob, int bserrno)
7076 {
7077 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7078 	struct spdk_blob_store *bs = ctx->bs;
7079 	spdk_blob_id id;
7080 
7081 	if (bserrno == 0) {
7082 		ctx->cb_fn(ctx->cb_arg, _blob, bserrno);
7083 		free(ctx);
7084 		return;
7085 	}
7086 
7087 	ctx->page_num++;
7088 	ctx->page_num = spdk_bit_array_find_first_set(bs->used_blobids, ctx->page_num);
7089 	if (ctx->page_num >= spdk_bit_array_capacity(bs->used_blobids)) {
7090 		ctx->cb_fn(ctx->cb_arg, NULL, -ENOENT);
7091 		free(ctx);
7092 		return;
7093 	}
7094 
7095 	id = bs_page_to_blobid(ctx->page_num);
7096 
7097 	spdk_bs_open_blob(bs, id, bs_iter_cpl, ctx);
7098 }
7099 
7100 void
7101 spdk_bs_iter_first(struct spdk_blob_store *bs,
7102 		   spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7103 {
7104 	struct spdk_bs_iter_ctx *ctx;
7105 
7106 	ctx = calloc(1, sizeof(*ctx));
7107 	if (!ctx) {
7108 		cb_fn(cb_arg, NULL, -ENOMEM);
7109 		return;
7110 	}
7111 
7112 	ctx->page_num = -1;
7113 	ctx->bs = bs;
7114 	ctx->cb_fn = cb_fn;
7115 	ctx->cb_arg = cb_arg;
7116 
7117 	bs_iter_cpl(ctx, NULL, -1);
7118 }
7119 
7120 static void
7121 bs_iter_close_cpl(void *cb_arg, int bserrno)
7122 {
7123 	struct spdk_bs_iter_ctx *ctx = cb_arg;
7124 
7125 	bs_iter_cpl(ctx, NULL, -1);
7126 }
7127 
7128 void
7129 spdk_bs_iter_next(struct spdk_blob_store *bs, struct spdk_blob *blob,
7130 		  spdk_blob_op_with_handle_complete cb_fn, void *cb_arg)
7131 {
7132 	struct spdk_bs_iter_ctx *ctx;
7133 
7134 	assert(blob != NULL);
7135 
7136 	ctx = calloc(1, sizeof(*ctx));
7137 	if (!ctx) {
7138 		cb_fn(cb_arg, NULL, -ENOMEM);
7139 		return;
7140 	}
7141 
7142 	ctx->page_num = bs_blobid_to_page(blob->id);
7143 	ctx->bs = bs;
7144 	ctx->cb_fn = cb_fn;
7145 	ctx->cb_arg = cb_arg;
7146 
7147 	/* Close the existing blob */
7148 	spdk_blob_close(blob, bs_iter_close_cpl, ctx);
7149 }
7150 
7151 static int
7152 blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7153 	       uint16_t value_len, bool internal)
7154 {
7155 	struct spdk_xattr_tailq *xattrs;
7156 	struct spdk_xattr	*xattr;
7157 	size_t			desc_size;
7158 	void			*tmp;
7159 
7160 	blob_verify_md_op(blob);
7161 
7162 	if (blob->md_ro) {
7163 		return -EPERM;
7164 	}
7165 
7166 	desc_size = sizeof(struct spdk_blob_md_descriptor_xattr) + strlen(name) + value_len;
7167 	if (desc_size > SPDK_BS_MAX_DESC_SIZE) {
7168 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "Xattr '%s' of size %ld does not fix into single page %ld\n", name,
7169 			      desc_size, SPDK_BS_MAX_DESC_SIZE);
7170 		return -ENOMEM;
7171 	}
7172 
7173 	if (internal) {
7174 		xattrs = &blob->xattrs_internal;
7175 		blob->invalid_flags |= SPDK_BLOB_INTERNAL_XATTR;
7176 	} else {
7177 		xattrs = &blob->xattrs;
7178 	}
7179 
7180 	TAILQ_FOREACH(xattr, xattrs, link) {
7181 		if (!strcmp(name, xattr->name)) {
7182 			tmp = malloc(value_len);
7183 			if (!tmp) {
7184 				return -ENOMEM;
7185 			}
7186 
7187 			free(xattr->value);
7188 			xattr->value_len = value_len;
7189 			xattr->value = tmp;
7190 			memcpy(xattr->value, value, value_len);
7191 
7192 			blob->state = SPDK_BLOB_STATE_DIRTY;
7193 
7194 			return 0;
7195 		}
7196 	}
7197 
7198 	xattr = calloc(1, sizeof(*xattr));
7199 	if (!xattr) {
7200 		return -ENOMEM;
7201 	}
7202 
7203 	xattr->name = strdup(name);
7204 	if (!xattr->name) {
7205 		free(xattr);
7206 		return -ENOMEM;
7207 	}
7208 
7209 	xattr->value_len = value_len;
7210 	xattr->value = malloc(value_len);
7211 	if (!xattr->value) {
7212 		free(xattr->name);
7213 		free(xattr);
7214 		return -ENOMEM;
7215 	}
7216 	memcpy(xattr->value, value, value_len);
7217 	TAILQ_INSERT_TAIL(xattrs, xattr, link);
7218 
7219 	blob->state = SPDK_BLOB_STATE_DIRTY;
7220 
7221 	return 0;
7222 }
7223 
7224 int
7225 spdk_blob_set_xattr(struct spdk_blob *blob, const char *name, const void *value,
7226 		    uint16_t value_len)
7227 {
7228 	return blob_set_xattr(blob, name, value, value_len, false);
7229 }
7230 
7231 static int
7232 blob_remove_xattr(struct spdk_blob *blob, const char *name, bool internal)
7233 {
7234 	struct spdk_xattr_tailq *xattrs;
7235 	struct spdk_xattr	*xattr;
7236 
7237 	blob_verify_md_op(blob);
7238 
7239 	if (blob->md_ro) {
7240 		return -EPERM;
7241 	}
7242 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
7243 
7244 	TAILQ_FOREACH(xattr, xattrs, link) {
7245 		if (!strcmp(name, xattr->name)) {
7246 			TAILQ_REMOVE(xattrs, xattr, link);
7247 			free(xattr->value);
7248 			free(xattr->name);
7249 			free(xattr);
7250 
7251 			if (internal && TAILQ_EMPTY(&blob->xattrs_internal)) {
7252 				blob->invalid_flags &= ~SPDK_BLOB_INTERNAL_XATTR;
7253 			}
7254 			blob->state = SPDK_BLOB_STATE_DIRTY;
7255 
7256 			return 0;
7257 		}
7258 	}
7259 
7260 	return -ENOENT;
7261 }
7262 
7263 int
7264 spdk_blob_remove_xattr(struct spdk_blob *blob, const char *name)
7265 {
7266 	return blob_remove_xattr(blob, name, false);
7267 }
7268 
7269 static int
7270 blob_get_xattr_value(struct spdk_blob *blob, const char *name,
7271 		     const void **value, size_t *value_len, bool internal)
7272 {
7273 	struct spdk_xattr	*xattr;
7274 	struct spdk_xattr_tailq *xattrs;
7275 
7276 	xattrs = internal ? &blob->xattrs_internal : &blob->xattrs;
7277 
7278 	TAILQ_FOREACH(xattr, xattrs, link) {
7279 		if (!strcmp(name, xattr->name)) {
7280 			*value = xattr->value;
7281 			*value_len = xattr->value_len;
7282 			return 0;
7283 		}
7284 	}
7285 	return -ENOENT;
7286 }
7287 
7288 int
7289 spdk_blob_get_xattr_value(struct spdk_blob *blob, const char *name,
7290 			  const void **value, size_t *value_len)
7291 {
7292 	blob_verify_md_op(blob);
7293 
7294 	return blob_get_xattr_value(blob, name, value, value_len, false);
7295 }
7296 
7297 struct spdk_xattr_names {
7298 	uint32_t	count;
7299 	const char	*names[0];
7300 };
7301 
7302 static int
7303 blob_get_xattr_names(struct spdk_xattr_tailq *xattrs, struct spdk_xattr_names **names)
7304 {
7305 	struct spdk_xattr	*xattr;
7306 	int			count = 0;
7307 
7308 	TAILQ_FOREACH(xattr, xattrs, link) {
7309 		count++;
7310 	}
7311 
7312 	*names = calloc(1, sizeof(struct spdk_xattr_names) + count * sizeof(char *));
7313 	if (*names == NULL) {
7314 		return -ENOMEM;
7315 	}
7316 
7317 	TAILQ_FOREACH(xattr, xattrs, link) {
7318 		(*names)->names[(*names)->count++] = xattr->name;
7319 	}
7320 
7321 	return 0;
7322 }
7323 
7324 int
7325 spdk_blob_get_xattr_names(struct spdk_blob *blob, struct spdk_xattr_names **names)
7326 {
7327 	blob_verify_md_op(blob);
7328 
7329 	return blob_get_xattr_names(&blob->xattrs, names);
7330 }
7331 
7332 uint32_t
7333 spdk_xattr_names_get_count(struct spdk_xattr_names *names)
7334 {
7335 	assert(names != NULL);
7336 
7337 	return names->count;
7338 }
7339 
7340 const char *
7341 spdk_xattr_names_get_name(struct spdk_xattr_names *names, uint32_t index)
7342 {
7343 	if (index >= names->count) {
7344 		return NULL;
7345 	}
7346 
7347 	return names->names[index];
7348 }
7349 
7350 void
7351 spdk_xattr_names_free(struct spdk_xattr_names *names)
7352 {
7353 	free(names);
7354 }
7355 
7356 struct spdk_bs_type
7357 spdk_bs_get_bstype(struct spdk_blob_store *bs)
7358 {
7359 	return bs->bstype;
7360 }
7361 
7362 void
7363 spdk_bs_set_bstype(struct spdk_blob_store *bs, struct spdk_bs_type bstype)
7364 {
7365 	memcpy(&bs->bstype, &bstype, sizeof(bstype));
7366 }
7367 
7368 bool
7369 spdk_blob_is_read_only(struct spdk_blob *blob)
7370 {
7371 	assert(blob != NULL);
7372 	return (blob->data_ro || blob->md_ro);
7373 }
7374 
7375 bool
7376 spdk_blob_is_snapshot(struct spdk_blob *blob)
7377 {
7378 	struct spdk_blob_list *snapshot_entry;
7379 
7380 	assert(blob != NULL);
7381 
7382 	snapshot_entry = bs_get_snapshot_entry(blob->bs, blob->id);
7383 	if (snapshot_entry == NULL) {
7384 		return false;
7385 	}
7386 
7387 	return true;
7388 }
7389 
7390 bool
7391 spdk_blob_is_clone(struct spdk_blob *blob)
7392 {
7393 	assert(blob != NULL);
7394 
7395 	if (blob->parent_id != SPDK_BLOBID_INVALID) {
7396 		assert(spdk_blob_is_thin_provisioned(blob));
7397 		return true;
7398 	}
7399 
7400 	return false;
7401 }
7402 
7403 bool
7404 spdk_blob_is_thin_provisioned(struct spdk_blob *blob)
7405 {
7406 	assert(blob != NULL);
7407 	return !!(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
7408 }
7409 
7410 static void
7411 blob_update_clear_method(struct spdk_blob *blob)
7412 {
7413 	enum blob_clear_method stored_cm;
7414 
7415 	assert(blob != NULL);
7416 
7417 	/* If BLOB_CLEAR_WITH_DEFAULT was passed in, use the setting stored
7418 	 * in metadata previously.  If something other than the default was
7419 	 * specified, ignore stored value and used what was passed in.
7420 	 */
7421 	stored_cm = ((blob->md_ro_flags & SPDK_BLOB_CLEAR_METHOD) >> SPDK_BLOB_CLEAR_METHOD_SHIFT);
7422 
7423 	if (blob->clear_method == BLOB_CLEAR_WITH_DEFAULT) {
7424 		blob->clear_method = stored_cm;
7425 	} else if (blob->clear_method != stored_cm) {
7426 		SPDK_WARNLOG("Using passed in clear method 0x%x instead of stored value of 0x%x\n",
7427 			     blob->clear_method, stored_cm);
7428 	}
7429 }
7430 
7431 spdk_blob_id
7432 spdk_blob_get_parent_snapshot(struct spdk_blob_store *bs, spdk_blob_id blob_id)
7433 {
7434 	struct spdk_blob_list *snapshot_entry = NULL;
7435 	struct spdk_blob_list *clone_entry = NULL;
7436 
7437 	TAILQ_FOREACH(snapshot_entry, &bs->snapshots, link) {
7438 		TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
7439 			if (clone_entry->id == blob_id) {
7440 				return snapshot_entry->id;
7441 			}
7442 		}
7443 	}
7444 
7445 	return SPDK_BLOBID_INVALID;
7446 }
7447 
7448 int
7449 spdk_blob_get_clones(struct spdk_blob_store *bs, spdk_blob_id blobid, spdk_blob_id *ids,
7450 		     size_t *count)
7451 {
7452 	struct spdk_blob_list *snapshot_entry, *clone_entry;
7453 	size_t n;
7454 
7455 	snapshot_entry = bs_get_snapshot_entry(bs, blobid);
7456 	if (snapshot_entry == NULL) {
7457 		*count = 0;
7458 		return 0;
7459 	}
7460 
7461 	if (ids == NULL || *count < snapshot_entry->clone_count) {
7462 		*count = snapshot_entry->clone_count;
7463 		return -ENOMEM;
7464 	}
7465 	*count = snapshot_entry->clone_count;
7466 
7467 	n = 0;
7468 	TAILQ_FOREACH(clone_entry, &snapshot_entry->clones, link) {
7469 		ids[n++] = clone_entry->id;
7470 	}
7471 
7472 	return 0;
7473 }
7474 
7475 SPDK_LOG_REGISTER_COMPONENT("blob", SPDK_LOG_BLOB)
7476