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