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