xref: /spdk/lib/bdev/bdev.c (revision 8dd1cd2104ea4001e4a0da2a4851ccd62c82f8e8)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (c) Intel Corporation. All rights reserved.
3  *   Copyright (c) 2019 Mellanox Technologies LTD. All rights reserved.
4  *   Copyright (c) 2021, 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/bdev.h"
10 
11 #include "spdk/config.h"
12 #include "spdk/env.h"
13 #include "spdk/thread.h"
14 #include "spdk/likely.h"
15 #include "spdk/queue.h"
16 #include "spdk/nvme_spec.h"
17 #include "spdk/scsi_spec.h"
18 #include "spdk/notify.h"
19 #include "spdk/util.h"
20 #include "spdk/trace.h"
21 #include "spdk/dma.h"
22 
23 #include "spdk/bdev_module.h"
24 #include "spdk/log.h"
25 #include "spdk/string.h"
26 
27 #include "bdev_internal.h"
28 #include "spdk_internal/trace_defs.h"
29 
30 #ifdef SPDK_CONFIG_VTUNE
31 #include "ittnotify.h"
32 #include "ittnotify_types.h"
33 int __itt_init_ittlib(const char *, __itt_group_id);
34 #endif
35 
36 #define SPDK_BDEV_IO_POOL_SIZE			(64 * 1024 - 1)
37 #define SPDK_BDEV_IO_CACHE_SIZE			256
38 #define SPDK_BDEV_AUTO_EXAMINE			true
39 #define BUF_SMALL_POOL_SIZE			8191
40 #define BUF_LARGE_POOL_SIZE			1023
41 #define NOMEM_THRESHOLD_COUNT			8
42 
43 #define SPDK_BDEV_QOS_TIMESLICE_IN_USEC		1000
44 #define SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE	1
45 #define SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE	512
46 #define SPDK_BDEV_QOS_MIN_IOS_PER_SEC		1000
47 #define SPDK_BDEV_QOS_MIN_BYTES_PER_SEC		(1024 * 1024)
48 #define SPDK_BDEV_QOS_LIMIT_NOT_DEFINED		UINT64_MAX
49 #define SPDK_BDEV_IO_POLL_INTERVAL_IN_MSEC	1000
50 
51 #define SPDK_BDEV_POOL_ALIGNMENT 512
52 
53 /* The maximum number of children requests for a UNMAP or WRITE ZEROES command
54  * when splitting into children requests at a time.
55  */
56 #define SPDK_BDEV_MAX_CHILDREN_UNMAP_WRITE_ZEROES_REQS (8)
57 
58 static const char *qos_rpc_type[] = {"rw_ios_per_sec",
59 				     "rw_mbytes_per_sec", "r_mbytes_per_sec", "w_mbytes_per_sec"
60 				    };
61 
62 TAILQ_HEAD(spdk_bdev_list, spdk_bdev);
63 
64 RB_HEAD(bdev_name_tree, spdk_bdev_name);
65 
66 static int
67 bdev_name_cmp(struct spdk_bdev_name *name1, struct spdk_bdev_name *name2)
68 {
69 	return strcmp(name1->name, name2->name);
70 }
71 
72 RB_GENERATE_STATIC(bdev_name_tree, spdk_bdev_name, node, bdev_name_cmp);
73 
74 struct spdk_bdev_mgr {
75 	struct spdk_mempool *bdev_io_pool;
76 
77 	struct spdk_mempool *buf_small_pool;
78 	struct spdk_mempool *buf_large_pool;
79 
80 	void *zero_buffer;
81 
82 	TAILQ_HEAD(bdev_module_list, spdk_bdev_module) bdev_modules;
83 
84 	struct spdk_bdev_list bdevs;
85 	struct bdev_name_tree bdev_names;
86 
87 	bool init_complete;
88 	bool module_init_complete;
89 
90 	pthread_mutex_t mutex;
91 
92 #ifdef SPDK_CONFIG_VTUNE
93 	__itt_domain	*domain;
94 #endif
95 };
96 
97 static struct spdk_bdev_mgr g_bdev_mgr = {
98 	.bdev_modules = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdev_modules),
99 	.bdevs = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdevs),
100 	.bdev_names = RB_INITIALIZER(g_bdev_mgr.bdev_names),
101 	.init_complete = false,
102 	.module_init_complete = false,
103 	.mutex = PTHREAD_MUTEX_INITIALIZER,
104 };
105 
106 typedef void (*lock_range_cb)(void *ctx, int status);
107 
108 typedef void (*bdev_copy_bounce_buffer_cpl)(void *ctx, int rc);
109 
110 struct lba_range {
111 	uint64_t			offset;
112 	uint64_t			length;
113 	void				*locked_ctx;
114 	struct spdk_bdev_channel	*owner_ch;
115 	TAILQ_ENTRY(lba_range)		tailq;
116 };
117 
118 static struct spdk_bdev_opts	g_bdev_opts = {
119 	.bdev_io_pool_size = SPDK_BDEV_IO_POOL_SIZE,
120 	.bdev_io_cache_size = SPDK_BDEV_IO_CACHE_SIZE,
121 	.bdev_auto_examine = SPDK_BDEV_AUTO_EXAMINE,
122 	.small_buf_pool_size = BUF_SMALL_POOL_SIZE,
123 	.large_buf_pool_size = BUF_LARGE_POOL_SIZE,
124 };
125 
126 static spdk_bdev_init_cb	g_init_cb_fn = NULL;
127 static void			*g_init_cb_arg = NULL;
128 
129 static spdk_bdev_fini_cb	g_fini_cb_fn = NULL;
130 static void			*g_fini_cb_arg = NULL;
131 static struct spdk_thread	*g_fini_thread = NULL;
132 
133 struct spdk_bdev_qos_limit {
134 	/** IOs or bytes allowed per second (i.e., 1s). */
135 	uint64_t limit;
136 
137 	/** Remaining IOs or bytes allowed in current timeslice (e.g., 1ms).
138 	 *  For remaining bytes, allowed to run negative if an I/O is submitted when
139 	 *  some bytes are remaining, but the I/O is bigger than that amount. The
140 	 *  excess will be deducted from the next timeslice.
141 	 */
142 	int64_t remaining_this_timeslice;
143 
144 	/** Minimum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
145 	uint32_t min_per_timeslice;
146 
147 	/** Maximum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
148 	uint32_t max_per_timeslice;
149 
150 	/** Function to check whether to queue the IO. */
151 	bool (*queue_io)(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
152 
153 	/** Function to update for the submitted IO. */
154 	void (*update_quota)(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
155 };
156 
157 struct spdk_bdev_qos {
158 	/** Types of structure of rate limits. */
159 	struct spdk_bdev_qos_limit rate_limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
160 
161 	/** The channel that all I/O are funneled through. */
162 	struct spdk_bdev_channel *ch;
163 
164 	/** The thread on which the poller is running. */
165 	struct spdk_thread *thread;
166 
167 	/** Queue of I/O waiting to be issued. */
168 	bdev_io_tailq_t queued;
169 
170 	/** Size of a timeslice in tsc ticks. */
171 	uint64_t timeslice_size;
172 
173 	/** Timestamp of start of last timeslice. */
174 	uint64_t last_timeslice;
175 
176 	/** Poller that processes queued I/O commands each time slice. */
177 	struct spdk_poller *poller;
178 };
179 
180 struct spdk_bdev_mgmt_channel {
181 	bdev_io_stailq_t need_buf_small;
182 	bdev_io_stailq_t need_buf_large;
183 
184 	/*
185 	 * Each thread keeps a cache of bdev_io - this allows
186 	 *  bdev threads which are *not* DPDK threads to still
187 	 *  benefit from a per-thread bdev_io cache.  Without
188 	 *  this, non-DPDK threads fetching from the mempool
189 	 *  incur a cmpxchg on get and put.
190 	 */
191 	bdev_io_stailq_t per_thread_cache;
192 	uint32_t	per_thread_cache_count;
193 	uint32_t	bdev_io_cache_size;
194 
195 	TAILQ_HEAD(, spdk_bdev_shared_resource)	shared_resources;
196 	TAILQ_HEAD(, spdk_bdev_io_wait_entry)	io_wait_queue;
197 };
198 
199 /*
200  * Per-module (or per-io_device) data. Multiple bdevs built on the same io_device
201  * will queue here their IO that awaits retry. It makes it possible to retry sending
202  * IO to one bdev after IO from other bdev completes.
203  */
204 struct spdk_bdev_shared_resource {
205 	/* The bdev management channel */
206 	struct spdk_bdev_mgmt_channel *mgmt_ch;
207 
208 	/*
209 	 * Count of I/O submitted to bdev module and waiting for completion.
210 	 * Incremented before submit_request() is called on an spdk_bdev_io.
211 	 */
212 	uint64_t		io_outstanding;
213 
214 	/*
215 	 * Queue of IO awaiting retry because of a previous NOMEM status returned
216 	 *  on this channel.
217 	 */
218 	bdev_io_tailq_t		nomem_io;
219 
220 	/*
221 	 * Threshold which io_outstanding must drop to before retrying nomem_io.
222 	 */
223 	uint64_t		nomem_threshold;
224 
225 	/* I/O channel allocated by a bdev module */
226 	struct spdk_io_channel	*shared_ch;
227 
228 	/* Refcount of bdev channels using this resource */
229 	uint32_t		ref;
230 
231 	TAILQ_ENTRY(spdk_bdev_shared_resource) link;
232 };
233 
234 #define BDEV_CH_RESET_IN_PROGRESS	(1 << 0)
235 #define BDEV_CH_QOS_ENABLED		(1 << 1)
236 
237 struct spdk_bdev_channel {
238 	struct spdk_bdev	*bdev;
239 
240 	/* The channel for the underlying device */
241 	struct spdk_io_channel	*channel;
242 
243 	/* Per io_device per thread data */
244 	struct spdk_bdev_shared_resource *shared_resource;
245 
246 	struct spdk_bdev_io_stat stat;
247 
248 	/*
249 	 * Count of I/O submitted to the underlying dev module through this channel
250 	 * and waiting for completion.
251 	 */
252 	uint64_t		io_outstanding;
253 
254 	/*
255 	 * List of all submitted I/Os including I/O that are generated via splitting.
256 	 */
257 	bdev_io_tailq_t		io_submitted;
258 
259 	/*
260 	 * List of spdk_bdev_io that are currently queued because they write to a locked
261 	 * LBA range.
262 	 */
263 	bdev_io_tailq_t		io_locked;
264 
265 	uint32_t		flags;
266 
267 	struct spdk_histogram_data *histogram;
268 
269 #ifdef SPDK_CONFIG_VTUNE
270 	uint64_t		start_tsc;
271 	uint64_t		interval_tsc;
272 	__itt_string_handle	*handle;
273 	struct spdk_bdev_io_stat prev_stat;
274 #endif
275 
276 	bdev_io_tailq_t		queued_resets;
277 
278 	lba_range_tailq_t	locked_ranges;
279 };
280 
281 struct media_event_entry {
282 	struct spdk_bdev_media_event	event;
283 	TAILQ_ENTRY(media_event_entry)	tailq;
284 };
285 
286 #define MEDIA_EVENT_POOL_SIZE 64
287 
288 struct spdk_bdev_desc {
289 	struct spdk_bdev		*bdev;
290 	struct spdk_thread		*thread;
291 	struct {
292 		spdk_bdev_event_cb_t event_fn;
293 		void *ctx;
294 	}				callback;
295 	bool				closed;
296 	bool				write;
297 	bool				memory_domains_supported;
298 	pthread_mutex_t			mutex;
299 	uint32_t			refs;
300 	TAILQ_HEAD(, media_event_entry)	pending_media_events;
301 	TAILQ_HEAD(, media_event_entry)	free_media_events;
302 	struct media_event_entry	*media_events_buffer;
303 	TAILQ_ENTRY(spdk_bdev_desc)	link;
304 
305 	uint64_t		timeout_in_sec;
306 	spdk_bdev_io_timeout_cb	cb_fn;
307 	void			*cb_arg;
308 	struct spdk_poller	*io_timeout_poller;
309 };
310 
311 struct spdk_bdev_iostat_ctx {
312 	struct spdk_bdev_io_stat *stat;
313 	spdk_bdev_get_device_stat_cb cb;
314 	void *cb_arg;
315 };
316 
317 struct set_qos_limit_ctx {
318 	void (*cb_fn)(void *cb_arg, int status);
319 	void *cb_arg;
320 	struct spdk_bdev *bdev;
321 };
322 
323 #define __bdev_to_io_dev(bdev)		(((char *)bdev) + 1)
324 #define __bdev_from_io_dev(io_dev)	((struct spdk_bdev *)(((char *)io_dev) - 1))
325 
326 static inline void bdev_io_complete(void *ctx);
327 
328 static void bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
329 static void bdev_write_zero_buffer_next(void *_bdev_io);
330 
331 static void bdev_enable_qos_msg(struct spdk_io_channel_iter *i);
332 static void bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status);
333 
334 static int bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
335 				     struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
336 				     uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg,
337 				     struct spdk_bdev_ext_io_opts *opts, bool copy_opts);
338 static int bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
339 				      struct iovec *iov, int iovcnt, void *md_buf,
340 				      uint64_t offset_blocks, uint64_t num_blocks,
341 				      spdk_bdev_io_completion_cb cb, void *cb_arg,
342 				      struct spdk_bdev_ext_io_opts *opts, bool copy_opts);
343 
344 static int bdev_lock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
345 			       uint64_t offset, uint64_t length,
346 			       lock_range_cb cb_fn, void *cb_arg);
347 
348 static int bdev_unlock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
349 				 uint64_t offset, uint64_t length,
350 				 lock_range_cb cb_fn, void *cb_arg);
351 
352 static inline void bdev_io_complete(void *ctx);
353 
354 static bool bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_io *bio_to_abort);
355 static bool bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_io *bio_to_abort);
356 
357 void
358 spdk_bdev_get_opts(struct spdk_bdev_opts *opts, size_t opts_size)
359 {
360 	if (!opts) {
361 		SPDK_ERRLOG("opts should not be NULL\n");
362 		return;
363 	}
364 
365 	if (!opts_size) {
366 		SPDK_ERRLOG("opts_size should not be zero value\n");
367 		return;
368 	}
369 
370 	opts->opts_size = opts_size;
371 
372 #define SET_FIELD(field) \
373 	if (offsetof(struct spdk_bdev_opts, field) + sizeof(opts->field) <= opts_size) { \
374 		opts->field = g_bdev_opts.field; \
375 	} \
376 
377 	SET_FIELD(bdev_io_pool_size);
378 	SET_FIELD(bdev_io_cache_size);
379 	SET_FIELD(bdev_auto_examine);
380 	SET_FIELD(small_buf_pool_size);
381 	SET_FIELD(large_buf_pool_size);
382 
383 	/* Do not remove this statement, you should always update this statement when you adding a new field,
384 	 * and do not forget to add the SET_FIELD statement for your added field. */
385 	SPDK_STATIC_ASSERT(sizeof(struct spdk_bdev_opts) == 32, "Incorrect size");
386 
387 #undef SET_FIELD
388 }
389 
390 int
391 spdk_bdev_set_opts(struct spdk_bdev_opts *opts)
392 {
393 	uint32_t min_pool_size;
394 
395 	if (!opts) {
396 		SPDK_ERRLOG("opts cannot be NULL\n");
397 		return -1;
398 	}
399 
400 	if (!opts->opts_size) {
401 		SPDK_ERRLOG("opts_size inside opts cannot be zero value\n");
402 		return -1;
403 	}
404 
405 	/*
406 	 * Add 1 to the thread count to account for the extra mgmt_ch that gets created during subsystem
407 	 *  initialization.  A second mgmt_ch will be created on the same thread when the application starts
408 	 *  but before the deferred put_io_channel event is executed for the first mgmt_ch.
409 	 */
410 	min_pool_size = opts->bdev_io_cache_size * (spdk_thread_get_count() + 1);
411 	if (opts->bdev_io_pool_size < min_pool_size) {
412 		SPDK_ERRLOG("bdev_io_pool_size %" PRIu32 " is not compatible with bdev_io_cache_size %" PRIu32
413 			    " and %" PRIu32 " threads\n", opts->bdev_io_pool_size, opts->bdev_io_cache_size,
414 			    spdk_thread_get_count());
415 		SPDK_ERRLOG("bdev_io_pool_size must be at least %" PRIu32 "\n", min_pool_size);
416 		return -1;
417 	}
418 
419 	if (opts->small_buf_pool_size < BUF_SMALL_POOL_SIZE) {
420 		SPDK_ERRLOG("small_buf_pool_size must be at least %" PRIu32 "\n", BUF_SMALL_POOL_SIZE);
421 		return -1;
422 	}
423 
424 	if (opts->large_buf_pool_size < BUF_LARGE_POOL_SIZE) {
425 		SPDK_ERRLOG("large_buf_pool_size must be at least %" PRIu32 "\n", BUF_LARGE_POOL_SIZE);
426 		return -1;
427 	}
428 
429 #define SET_FIELD(field) \
430         if (offsetof(struct spdk_bdev_opts, field) + sizeof(opts->field) <= opts->opts_size) { \
431                 g_bdev_opts.field = opts->field; \
432         } \
433 
434 	SET_FIELD(bdev_io_pool_size);
435 	SET_FIELD(bdev_io_cache_size);
436 	SET_FIELD(bdev_auto_examine);
437 	SET_FIELD(small_buf_pool_size);
438 	SET_FIELD(large_buf_pool_size);
439 
440 	g_bdev_opts.opts_size = opts->opts_size;
441 
442 #undef SET_FIELD
443 
444 	return 0;
445 }
446 
447 static struct spdk_bdev *
448 bdev_get_by_name(const char *bdev_name)
449 {
450 	struct spdk_bdev_name find;
451 	struct spdk_bdev_name *res;
452 
453 	find.name = (char *)bdev_name;
454 	res = RB_FIND(bdev_name_tree, &g_bdev_mgr.bdev_names, &find);
455 	if (res != NULL) {
456 		return res->bdev;
457 	}
458 
459 	return NULL;
460 }
461 
462 struct spdk_bdev *
463 spdk_bdev_get_by_name(const char *bdev_name)
464 {
465 	struct spdk_bdev *bdev;
466 
467 	pthread_mutex_lock(&g_bdev_mgr.mutex);
468 	bdev = bdev_get_by_name(bdev_name);
469 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
470 
471 	return bdev;
472 }
473 
474 struct spdk_bdev_wait_for_examine_ctx {
475 	struct spdk_poller              *poller;
476 	spdk_bdev_wait_for_examine_cb	cb_fn;
477 	void				*cb_arg;
478 };
479 
480 static bool bdev_module_all_actions_completed(void);
481 
482 static int
483 bdev_wait_for_examine_cb(void *arg)
484 {
485 	struct spdk_bdev_wait_for_examine_ctx *ctx = arg;
486 
487 	if (!bdev_module_all_actions_completed()) {
488 		return SPDK_POLLER_IDLE;
489 	}
490 
491 	spdk_poller_unregister(&ctx->poller);
492 	ctx->cb_fn(ctx->cb_arg);
493 	free(ctx);
494 
495 	return SPDK_POLLER_BUSY;
496 }
497 
498 int
499 spdk_bdev_wait_for_examine(spdk_bdev_wait_for_examine_cb cb_fn, void *cb_arg)
500 {
501 	struct spdk_bdev_wait_for_examine_ctx *ctx;
502 
503 	ctx = calloc(1, sizeof(*ctx));
504 	if (ctx == NULL) {
505 		return -ENOMEM;
506 	}
507 	ctx->cb_fn = cb_fn;
508 	ctx->cb_arg = cb_arg;
509 	ctx->poller = SPDK_POLLER_REGISTER(bdev_wait_for_examine_cb, ctx, 0);
510 
511 	return 0;
512 }
513 
514 struct spdk_bdev_examine_item {
515 	char *name;
516 	TAILQ_ENTRY(spdk_bdev_examine_item) link;
517 };
518 
519 TAILQ_HEAD(spdk_bdev_examine_allowlist, spdk_bdev_examine_item);
520 
521 struct spdk_bdev_examine_allowlist g_bdev_examine_allowlist = TAILQ_HEAD_INITIALIZER(
522 			g_bdev_examine_allowlist);
523 
524 static inline bool
525 bdev_examine_allowlist_check(const char *name)
526 {
527 	struct spdk_bdev_examine_item *item;
528 	TAILQ_FOREACH(item, &g_bdev_examine_allowlist, link) {
529 		if (strcmp(name, item->name) == 0) {
530 			return true;
531 		}
532 	}
533 	return false;
534 }
535 
536 static inline void
537 bdev_examine_allowlist_free(void)
538 {
539 	struct spdk_bdev_examine_item *item;
540 	while (!TAILQ_EMPTY(&g_bdev_examine_allowlist)) {
541 		item = TAILQ_FIRST(&g_bdev_examine_allowlist);
542 		TAILQ_REMOVE(&g_bdev_examine_allowlist, item, link);
543 		free(item->name);
544 		free(item);
545 	}
546 }
547 
548 static inline bool
549 bdev_in_examine_allowlist(struct spdk_bdev *bdev)
550 {
551 	struct spdk_bdev_alias *tmp;
552 	if (bdev_examine_allowlist_check(bdev->name)) {
553 		return true;
554 	}
555 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
556 		if (bdev_examine_allowlist_check(tmp->alias.name)) {
557 			return true;
558 		}
559 	}
560 	return false;
561 }
562 
563 static inline bool
564 bdev_ok_to_examine(struct spdk_bdev *bdev)
565 {
566 	if (g_bdev_opts.bdev_auto_examine) {
567 		return true;
568 	} else {
569 		return bdev_in_examine_allowlist(bdev);
570 	}
571 }
572 
573 static void
574 bdev_examine(struct spdk_bdev *bdev)
575 {
576 	struct spdk_bdev_module *module;
577 	uint32_t action;
578 
579 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
580 		if (module->examine_config && bdev_ok_to_examine(bdev)) {
581 			action = module->internal.action_in_progress;
582 			module->internal.action_in_progress++;
583 			module->examine_config(bdev);
584 			if (action != module->internal.action_in_progress) {
585 				SPDK_ERRLOG("examine_config for module %s did not call spdk_bdev_module_examine_done()\n",
586 					    module->name);
587 			}
588 		}
589 	}
590 
591 	if (bdev->internal.claim_module && bdev_ok_to_examine(bdev)) {
592 		if (bdev->internal.claim_module->examine_disk) {
593 			bdev->internal.claim_module->internal.action_in_progress++;
594 			bdev->internal.claim_module->examine_disk(bdev);
595 		}
596 		return;
597 	}
598 
599 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
600 		if (module->examine_disk && bdev_ok_to_examine(bdev)) {
601 			module->internal.action_in_progress++;
602 			module->examine_disk(bdev);
603 		}
604 	}
605 }
606 
607 int
608 spdk_bdev_examine(const char *name)
609 {
610 	struct spdk_bdev *bdev;
611 	struct spdk_bdev_examine_item *item;
612 
613 	if (g_bdev_opts.bdev_auto_examine) {
614 		SPDK_ERRLOG("Manual examine is not allowed if auto examine is enabled");
615 		return -EINVAL;
616 	}
617 
618 	if (bdev_examine_allowlist_check(name)) {
619 		SPDK_ERRLOG("Duplicate bdev name for manual examine: %s\n", name);
620 		return -EEXIST;
621 	}
622 
623 	item = calloc(1, sizeof(*item));
624 	if (!item) {
625 		return -ENOMEM;
626 	}
627 	item->name = strdup(name);
628 	if (!item->name) {
629 		free(item);
630 		return -ENOMEM;
631 	}
632 	TAILQ_INSERT_TAIL(&g_bdev_examine_allowlist, item, link);
633 
634 	bdev = spdk_bdev_get_by_name(name);
635 	if (bdev) {
636 		bdev_examine(bdev);
637 	}
638 	return 0;
639 }
640 
641 static inline void
642 bdev_examine_allowlist_config_json(struct spdk_json_write_ctx *w)
643 {
644 	struct spdk_bdev_examine_item *item;
645 	TAILQ_FOREACH(item, &g_bdev_examine_allowlist, link) {
646 		spdk_json_write_object_begin(w);
647 		spdk_json_write_named_string(w, "method", "bdev_examine");
648 		spdk_json_write_named_object_begin(w, "params");
649 		spdk_json_write_named_string(w, "name", item->name);
650 		spdk_json_write_object_end(w);
651 		spdk_json_write_object_end(w);
652 	}
653 }
654 
655 struct spdk_bdev *
656 spdk_bdev_first(void)
657 {
658 	struct spdk_bdev *bdev;
659 
660 	bdev = TAILQ_FIRST(&g_bdev_mgr.bdevs);
661 	if (bdev) {
662 		SPDK_DEBUGLOG(bdev, "Starting bdev iteration at %s\n", bdev->name);
663 	}
664 
665 	return bdev;
666 }
667 
668 struct spdk_bdev *
669 spdk_bdev_next(struct spdk_bdev *prev)
670 {
671 	struct spdk_bdev *bdev;
672 
673 	bdev = TAILQ_NEXT(prev, internal.link);
674 	if (bdev) {
675 		SPDK_DEBUGLOG(bdev, "Continuing bdev iteration at %s\n", bdev->name);
676 	}
677 
678 	return bdev;
679 }
680 
681 static struct spdk_bdev *
682 _bdev_next_leaf(struct spdk_bdev *bdev)
683 {
684 	while (bdev != NULL) {
685 		if (bdev->internal.claim_module == NULL) {
686 			return bdev;
687 		} else {
688 			bdev = TAILQ_NEXT(bdev, internal.link);
689 		}
690 	}
691 
692 	return bdev;
693 }
694 
695 struct spdk_bdev *
696 spdk_bdev_first_leaf(void)
697 {
698 	struct spdk_bdev *bdev;
699 
700 	bdev = _bdev_next_leaf(TAILQ_FIRST(&g_bdev_mgr.bdevs));
701 
702 	if (bdev) {
703 		SPDK_DEBUGLOG(bdev, "Starting bdev iteration at %s\n", bdev->name);
704 	}
705 
706 	return bdev;
707 }
708 
709 struct spdk_bdev *
710 spdk_bdev_next_leaf(struct spdk_bdev *prev)
711 {
712 	struct spdk_bdev *bdev;
713 
714 	bdev = _bdev_next_leaf(TAILQ_NEXT(prev, internal.link));
715 
716 	if (bdev) {
717 		SPDK_DEBUGLOG(bdev, "Continuing bdev iteration at %s\n", bdev->name);
718 	}
719 
720 	return bdev;
721 }
722 
723 static inline bool
724 bdev_io_use_memory_domain(struct spdk_bdev_io *bdev_io)
725 {
726 	return bdev_io->internal.ext_opts && bdev_io->internal.ext_opts->memory_domain;
727 }
728 
729 void
730 spdk_bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len)
731 {
732 	struct iovec *iovs;
733 
734 	if (bdev_io->u.bdev.iovs == NULL) {
735 		bdev_io->u.bdev.iovs = &bdev_io->iov;
736 		bdev_io->u.bdev.iovcnt = 1;
737 	}
738 
739 	iovs = bdev_io->u.bdev.iovs;
740 
741 	assert(iovs != NULL);
742 	assert(bdev_io->u.bdev.iovcnt >= 1);
743 
744 	iovs[0].iov_base = buf;
745 	iovs[0].iov_len = len;
746 }
747 
748 void
749 spdk_bdev_io_set_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
750 {
751 	assert((len / spdk_bdev_get_md_size(bdev_io->bdev)) >= bdev_io->u.bdev.num_blocks);
752 	bdev_io->u.bdev.md_buf = md_buf;
753 }
754 
755 static bool
756 _is_buf_allocated(const struct iovec *iovs)
757 {
758 	if (iovs == NULL) {
759 		return false;
760 	}
761 
762 	return iovs[0].iov_base != NULL;
763 }
764 
765 static bool
766 _are_iovs_aligned(struct iovec *iovs, int iovcnt, uint32_t alignment)
767 {
768 	int i;
769 	uintptr_t iov_base;
770 
771 	if (spdk_likely(alignment == 1)) {
772 		return true;
773 	}
774 
775 	for (i = 0; i < iovcnt; i++) {
776 		iov_base = (uintptr_t)iovs[i].iov_base;
777 		if ((iov_base & (alignment - 1)) != 0) {
778 			return false;
779 		}
780 	}
781 
782 	return true;
783 }
784 
785 static void
786 bdev_io_get_buf_complete(struct spdk_bdev_io *bdev_io, bool status)
787 {
788 	struct spdk_io_channel *ch = spdk_bdev_io_get_io_channel(bdev_io);
789 	void *buf;
790 
791 	if (spdk_unlikely(bdev_io->internal.get_aux_buf_cb != NULL)) {
792 		buf = bdev_io->internal.buf;
793 		bdev_io->internal.buf = NULL;
794 		bdev_io->internal.get_aux_buf_cb(ch, bdev_io, buf);
795 		bdev_io->internal.get_aux_buf_cb = NULL;
796 	} else {
797 		assert(bdev_io->internal.get_buf_cb != NULL);
798 		bdev_io->internal.get_buf_cb(ch, bdev_io, status);
799 		bdev_io->internal.get_buf_cb = NULL;
800 	}
801 }
802 
803 static void
804 _bdev_io_pull_buffer_cpl(void *ctx, int rc)
805 {
806 	struct spdk_bdev_io *bdev_io = ctx;
807 
808 	if (rc) {
809 		SPDK_ERRLOG("Set bounce buffer failed with rc %d\n", rc);
810 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
811 	}
812 	bdev_io_get_buf_complete(bdev_io, !rc);
813 }
814 
815 static void
816 _bdev_io_pull_bounce_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
817 {
818 	int rc = 0;
819 
820 	/* save original md_buf */
821 	bdev_io->internal.orig_md_iov.iov_base = bdev_io->u.bdev.md_buf;
822 	bdev_io->internal.orig_md_iov.iov_len = len;
823 	bdev_io->internal.bounce_md_iov.iov_base = md_buf;
824 	bdev_io->internal.bounce_md_iov.iov_len = len;
825 	/* set bounce md_buf */
826 	bdev_io->u.bdev.md_buf = md_buf;
827 
828 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
829 		if (bdev_io_use_memory_domain(bdev_io)) {
830 			rc = spdk_memory_domain_pull_data(bdev_io->internal.ext_opts->memory_domain,
831 							  bdev_io->internal.ext_opts->memory_domain_ctx,
832 							  &bdev_io->internal.orig_md_iov, 1,
833 							  &bdev_io->internal.bounce_md_iov, 1,
834 							  bdev_io->internal.data_transfer_cpl,
835 							  bdev_io);
836 			if (rc == 0) {
837 				/* Continue to submit IO in completion callback */
838 				return;
839 			}
840 			SPDK_ERRLOG("Failed to pull data from memory domain %s, rc %d\n",
841 				    spdk_memory_domain_get_dma_device_id(bdev_io->internal.ext_opts->memory_domain), rc);
842 		} else {
843 			memcpy(md_buf, bdev_io->internal.orig_md_iov.iov_base, bdev_io->internal.orig_md_iov.iov_len);
844 		}
845 	}
846 
847 	assert(bdev_io->internal.data_transfer_cpl);
848 	bdev_io->internal.data_transfer_cpl(bdev_io, rc);
849 }
850 
851 static void
852 _bdev_io_set_md_buf(struct spdk_bdev_io *bdev_io)
853 {
854 	struct spdk_bdev *bdev = bdev_io->bdev;
855 	uint64_t md_len;
856 	void *buf;
857 
858 	if (spdk_bdev_is_md_separate(bdev)) {
859 		buf = (char *)bdev_io->u.bdev.iovs[0].iov_base + bdev_io->u.bdev.iovs[0].iov_len;
860 		md_len = bdev_io->u.bdev.num_blocks * bdev->md_len;
861 
862 		assert(((uintptr_t)buf & (spdk_bdev_get_buf_align(bdev) - 1)) == 0);
863 
864 		if (bdev_io->u.bdev.md_buf != NULL) {
865 			_bdev_io_pull_bounce_md_buf(bdev_io, buf, md_len);
866 			return;
867 		} else {
868 			spdk_bdev_io_set_md_buf(bdev_io, buf, md_len);
869 		}
870 	}
871 
872 	bdev_io_get_buf_complete(bdev_io, true);
873 }
874 
875 static void
876 _bdev_io_pull_bounce_data_buf_done(void *ctx, int rc)
877 {
878 	struct spdk_bdev_io *bdev_io = ctx;
879 
880 	if (rc) {
881 		SPDK_ERRLOG("Failed to get data buffer\n");
882 		assert(bdev_io->internal.data_transfer_cpl);
883 		bdev_io->internal.data_transfer_cpl(bdev_io, rc);
884 		return;
885 	}
886 
887 	_bdev_io_set_md_buf(bdev_io);
888 }
889 
890 static void
891 _bdev_io_pull_bounce_data_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len,
892 			      bdev_copy_bounce_buffer_cpl cpl_cb)
893 {
894 	int rc = 0;
895 
896 	bdev_io->internal.data_transfer_cpl = cpl_cb;
897 	/* save original iovec */
898 	bdev_io->internal.orig_iovs = bdev_io->u.bdev.iovs;
899 	bdev_io->internal.orig_iovcnt = bdev_io->u.bdev.iovcnt;
900 	/* set bounce iov */
901 	bdev_io->u.bdev.iovs = &bdev_io->internal.bounce_iov;
902 	bdev_io->u.bdev.iovcnt = 1;
903 	/* set bounce buffer for this operation */
904 	bdev_io->u.bdev.iovs[0].iov_base = buf;
905 	bdev_io->u.bdev.iovs[0].iov_len = len;
906 	/* if this is write path, copy data from original buffer to bounce buffer */
907 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
908 		if (bdev_io_use_memory_domain(bdev_io)) {
909 			rc = spdk_memory_domain_pull_data(bdev_io->internal.ext_opts->memory_domain,
910 							  bdev_io->internal.ext_opts->memory_domain_ctx,
911 							  bdev_io->internal.orig_iovs,
912 							  (uint32_t) bdev_io->internal.orig_iovcnt,
913 							  bdev_io->u.bdev.iovs, 1,
914 							  _bdev_io_pull_bounce_data_buf_done,
915 							  bdev_io);
916 			if (rc == 0) {
917 				/* Continue to submit IO in completion callback */
918 				return;
919 			}
920 			SPDK_ERRLOG("Failed to pull data from memory domain %s\n",
921 				    spdk_memory_domain_get_dma_device_id(bdev_io->internal.ext_opts->memory_domain));
922 		} else {
923 			spdk_copy_iovs_to_buf(buf, len, bdev_io->internal.orig_iovs, bdev_io->internal.orig_iovcnt);
924 		}
925 	}
926 
927 	_bdev_io_pull_bounce_data_buf_done(bdev_io, rc);
928 }
929 
930 static void
931 _bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, uint64_t len)
932 {
933 	struct spdk_bdev *bdev = bdev_io->bdev;
934 	bool buf_allocated;
935 	uint64_t alignment;
936 	void *aligned_buf;
937 
938 	bdev_io->internal.buf = buf;
939 
940 	if (spdk_unlikely(bdev_io->internal.get_aux_buf_cb != NULL)) {
941 		bdev_io_get_buf_complete(bdev_io, true);
942 		return;
943 	}
944 
945 	alignment = spdk_bdev_get_buf_align(bdev);
946 	buf_allocated = _is_buf_allocated(bdev_io->u.bdev.iovs);
947 	aligned_buf = (void *)(((uintptr_t)buf + (alignment - 1)) & ~(alignment - 1));
948 
949 	if (buf_allocated) {
950 		_bdev_io_pull_bounce_data_buf(bdev_io, aligned_buf, len, _bdev_io_pull_buffer_cpl);
951 		/* Continue in completion callback */
952 		return;
953 	} else {
954 		spdk_bdev_io_set_buf(bdev_io, aligned_buf, len);
955 	}
956 
957 	_bdev_io_set_md_buf(bdev_io);
958 }
959 
960 static void
961 _bdev_io_put_buf(struct spdk_bdev_io *bdev_io, void *buf, uint64_t buf_len)
962 {
963 	struct spdk_bdev *bdev = bdev_io->bdev;
964 	struct spdk_mempool *pool;
965 	struct spdk_bdev_io *tmp;
966 	bdev_io_stailq_t *stailq;
967 	struct spdk_bdev_mgmt_channel *ch;
968 	uint64_t md_len, alignment;
969 
970 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
971 	alignment = spdk_bdev_get_buf_align(bdev);
972 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
973 
974 	if (buf_len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
975 	    SPDK_BDEV_POOL_ALIGNMENT) {
976 		pool = g_bdev_mgr.buf_small_pool;
977 		stailq = &ch->need_buf_small;
978 	} else {
979 		pool = g_bdev_mgr.buf_large_pool;
980 		stailq = &ch->need_buf_large;
981 	}
982 
983 	if (STAILQ_EMPTY(stailq)) {
984 		spdk_mempool_put(pool, buf);
985 	} else {
986 		tmp = STAILQ_FIRST(stailq);
987 		STAILQ_REMOVE_HEAD(stailq, internal.buf_link);
988 		_bdev_io_set_buf(tmp, buf, tmp->internal.buf_len);
989 	}
990 }
991 
992 static void
993 bdev_io_put_buf(struct spdk_bdev_io *bdev_io)
994 {
995 	assert(bdev_io->internal.buf != NULL);
996 	_bdev_io_put_buf(bdev_io, bdev_io->internal.buf, bdev_io->internal.buf_len);
997 	bdev_io->internal.buf = NULL;
998 }
999 
1000 void
1001 spdk_bdev_io_put_aux_buf(struct spdk_bdev_io *bdev_io, void *buf)
1002 {
1003 	uint64_t len = bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
1004 
1005 	assert(buf != NULL);
1006 	_bdev_io_put_buf(bdev_io, buf, len);
1007 }
1008 
1009 static void
1010 bdev_ch_retry_io(struct spdk_bdev_channel *bdev_ch)
1011 {
1012 	struct spdk_bdev *bdev = bdev_ch->bdev;
1013 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1014 	struct spdk_bdev_io *bdev_io;
1015 
1016 	if (shared_resource->io_outstanding > shared_resource->nomem_threshold) {
1017 		/*
1018 		 * Allow some more I/O to complete before retrying the nomem_io queue.
1019 		 *  Some drivers (such as nvme) cannot immediately take a new I/O in
1020 		 *  the context of a completion, because the resources for the I/O are
1021 		 *  not released until control returns to the bdev poller.  Also, we
1022 		 *  may require several small I/O to complete before a larger I/O
1023 		 *  (that requires splitting) can be submitted.
1024 		 */
1025 		return;
1026 	}
1027 
1028 	while (!TAILQ_EMPTY(&shared_resource->nomem_io)) {
1029 		bdev_io = TAILQ_FIRST(&shared_resource->nomem_io);
1030 		TAILQ_REMOVE(&shared_resource->nomem_io, bdev_io, internal.link);
1031 		bdev_io->internal.ch->io_outstanding++;
1032 		shared_resource->io_outstanding++;
1033 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
1034 		bdev_io->internal.error.nvme.cdw0 = 0;
1035 		bdev_io->num_retries++;
1036 		bdev->fn_table->submit_request(spdk_bdev_io_get_io_channel(bdev_io), bdev_io);
1037 		if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
1038 			break;
1039 		}
1040 	}
1041 }
1042 
1043 static inline void
1044 _bdev_io_decrement_outstanding(struct spdk_bdev_channel *bdev_ch,
1045 			       struct spdk_bdev_shared_resource *shared_resource)
1046 {
1047 	assert(bdev_ch->io_outstanding > 0);
1048 	assert(shared_resource->io_outstanding > 0);
1049 	bdev_ch->io_outstanding--;
1050 	shared_resource->io_outstanding--;
1051 }
1052 
1053 static inline bool
1054 _bdev_io_handle_no_mem(struct spdk_bdev_io *bdev_io)
1055 {
1056 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1057 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1058 
1059 	if (spdk_unlikely(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM)) {
1060 		TAILQ_INSERT_HEAD(&shared_resource->nomem_io, bdev_io, internal.link);
1061 		/*
1062 		 * Wait for some of the outstanding I/O to complete before we
1063 		 *  retry any of the nomem_io.  Normally we will wait for
1064 		 *  NOMEM_THRESHOLD_COUNT I/O to complete but for low queue
1065 		 *  depth channels we will instead wait for half to complete.
1066 		 */
1067 		shared_resource->nomem_threshold = spdk_max((int64_t)shared_resource->io_outstanding / 2,
1068 						   (int64_t)shared_resource->io_outstanding - NOMEM_THRESHOLD_COUNT);
1069 		return true;
1070 	}
1071 
1072 	if (spdk_unlikely(!TAILQ_EMPTY(&shared_resource->nomem_io))) {
1073 		bdev_ch_retry_io(bdev_ch);
1074 	}
1075 
1076 	return false;
1077 }
1078 
1079 static void
1080 _bdev_io_complete_push_bounce_done(void *ctx, int rc)
1081 {
1082 	struct spdk_bdev_io *bdev_io = ctx;
1083 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1084 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1085 
1086 	if (rc) {
1087 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1088 	}
1089 	/* We want to free the bounce buffer here since we know we're done with it (as opposed
1090 	 * to waiting for the conditional free of internal.buf in spdk_bdev_free_io()).
1091 	 */
1092 	bdev_io_put_buf(bdev_io);
1093 
1094 	/* Continue with IO completion flow */
1095 	_bdev_io_decrement_outstanding(bdev_ch, shared_resource);
1096 	if (spdk_unlikely(_bdev_io_handle_no_mem(bdev_io))) {
1097 		return;
1098 	}
1099 
1100 	bdev_io_complete(bdev_io);
1101 }
1102 
1103 static inline void
1104 _bdev_io_push_bounce_md_buffer(struct spdk_bdev_io *bdev_io)
1105 {
1106 	int rc = 0;
1107 
1108 	/* do the same for metadata buffer */
1109 	if (spdk_unlikely(bdev_io->internal.orig_md_iov.iov_base != NULL)) {
1110 		assert(spdk_bdev_is_md_separate(bdev_io->bdev));
1111 
1112 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
1113 		    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
1114 			if (bdev_io_use_memory_domain(bdev_io)) {
1115 				/* If memory domain is used then we need to call async push function */
1116 				rc = spdk_memory_domain_push_data(bdev_io->internal.ext_opts->memory_domain,
1117 								  bdev_io->internal.ext_opts->memory_domain_ctx,
1118 								  &bdev_io->internal.orig_md_iov,
1119 								  (uint32_t)bdev_io->internal.orig_iovcnt,
1120 								  &bdev_io->internal.bounce_md_iov, 1,
1121 								  bdev_io->internal.data_transfer_cpl,
1122 								  bdev_io);
1123 				if (rc == 0) {
1124 					/* Continue IO completion in async callback */
1125 					return;
1126 				}
1127 				SPDK_ERRLOG("Failed to push md to memory domain %s\n",
1128 					    spdk_memory_domain_get_dma_device_id(bdev_io->internal.ext_opts->memory_domain));
1129 			} else {
1130 				memcpy(bdev_io->internal.orig_md_iov.iov_base, bdev_io->u.bdev.md_buf,
1131 				       bdev_io->internal.orig_md_iov.iov_len);
1132 			}
1133 		}
1134 	}
1135 
1136 	assert(bdev_io->internal.data_transfer_cpl);
1137 	bdev_io->internal.data_transfer_cpl(bdev_io, rc);
1138 }
1139 
1140 static void
1141 _bdev_io_push_bounce_data_buffer_done(void *ctx, int rc)
1142 {
1143 	struct spdk_bdev_io *bdev_io = ctx;
1144 
1145 	assert(bdev_io->internal.data_transfer_cpl);
1146 
1147 	if (rc) {
1148 		bdev_io->internal.data_transfer_cpl(bdev_io, rc);
1149 		return;
1150 	}
1151 
1152 	/* set original buffer for this io */
1153 	bdev_io->u.bdev.iovcnt = bdev_io->internal.orig_iovcnt;
1154 	bdev_io->u.bdev.iovs = bdev_io->internal.orig_iovs;
1155 	/* disable bouncing buffer for this io */
1156 	bdev_io->internal.orig_iovcnt = 0;
1157 	bdev_io->internal.orig_iovs = NULL;
1158 
1159 	_bdev_io_push_bounce_md_buffer(bdev_io);
1160 }
1161 
1162 static inline void
1163 _bdev_io_push_bounce_data_buffer(struct spdk_bdev_io *bdev_io, bdev_copy_bounce_buffer_cpl cpl_cb)
1164 {
1165 	int rc = 0;
1166 
1167 	bdev_io->internal.data_transfer_cpl = cpl_cb;
1168 
1169 	/* if this is read path, copy data from bounce buffer to original buffer */
1170 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
1171 	    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
1172 		if (bdev_io_use_memory_domain(bdev_io)) {
1173 			/* If memory domain is used then we need to call async push function */
1174 			rc = spdk_memory_domain_push_data(bdev_io->internal.ext_opts->memory_domain,
1175 							  bdev_io->internal.ext_opts->memory_domain_ctx,
1176 							  bdev_io->internal.orig_iovs,
1177 							  (uint32_t)bdev_io->internal.orig_iovcnt,
1178 							  &bdev_io->internal.bounce_iov, 1,
1179 							  _bdev_io_push_bounce_data_buffer_done,
1180 							  bdev_io);
1181 			if (rc == 0) {
1182 				/* Continue IO completion in async callback */
1183 				return;
1184 			}
1185 			SPDK_ERRLOG("Failed to push data to memory domain %s\n",
1186 				    spdk_memory_domain_get_dma_device_id(bdev_io->internal.ext_opts->memory_domain));
1187 		} else {
1188 			spdk_copy_buf_to_iovs(bdev_io->internal.orig_iovs,
1189 					      bdev_io->internal.orig_iovcnt,
1190 					      bdev_io->internal.bounce_iov.iov_base,
1191 					      bdev_io->internal.bounce_iov.iov_len);
1192 		}
1193 	}
1194 
1195 	_bdev_io_push_bounce_data_buffer_done(bdev_io, rc);
1196 }
1197 
1198 static void
1199 bdev_io_get_buf(struct spdk_bdev_io *bdev_io, uint64_t len)
1200 {
1201 	struct spdk_bdev *bdev = bdev_io->bdev;
1202 	struct spdk_mempool *pool;
1203 	bdev_io_stailq_t *stailq;
1204 	struct spdk_bdev_mgmt_channel *mgmt_ch;
1205 	uint64_t alignment, md_len;
1206 	void *buf;
1207 
1208 	alignment = spdk_bdev_get_buf_align(bdev);
1209 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
1210 
1211 	if (len + alignment + md_len > SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
1212 	    SPDK_BDEV_POOL_ALIGNMENT) {
1213 		SPDK_ERRLOG("Length + alignment %" PRIu64 " is larger than allowed\n",
1214 			    len + alignment);
1215 		bdev_io_get_buf_complete(bdev_io, false);
1216 		return;
1217 	}
1218 
1219 	mgmt_ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
1220 
1221 	bdev_io->internal.buf_len = len;
1222 
1223 	if (len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
1224 	    SPDK_BDEV_POOL_ALIGNMENT) {
1225 		pool = g_bdev_mgr.buf_small_pool;
1226 		stailq = &mgmt_ch->need_buf_small;
1227 	} else {
1228 		pool = g_bdev_mgr.buf_large_pool;
1229 		stailq = &mgmt_ch->need_buf_large;
1230 	}
1231 
1232 	buf = spdk_mempool_get(pool);
1233 	if (!buf) {
1234 		STAILQ_INSERT_TAIL(stailq, bdev_io, internal.buf_link);
1235 	} else {
1236 		_bdev_io_set_buf(bdev_io, buf, len);
1237 	}
1238 }
1239 
1240 void
1241 spdk_bdev_io_get_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_buf_cb cb, uint64_t len)
1242 {
1243 	struct spdk_bdev *bdev = bdev_io->bdev;
1244 	uint64_t alignment;
1245 
1246 	assert(cb != NULL);
1247 	bdev_io->internal.get_buf_cb = cb;
1248 
1249 	alignment = spdk_bdev_get_buf_align(bdev);
1250 
1251 	if (_is_buf_allocated(bdev_io->u.bdev.iovs) &&
1252 	    _are_iovs_aligned(bdev_io->u.bdev.iovs, bdev_io->u.bdev.iovcnt, alignment)) {
1253 		/* Buffer already present and aligned */
1254 		cb(spdk_bdev_io_get_io_channel(bdev_io), bdev_io, true);
1255 		return;
1256 	}
1257 
1258 	bdev_io_get_buf(bdev_io, len);
1259 }
1260 
1261 static void
1262 _bdev_memory_domain_get_io_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
1263 			      bool success)
1264 {
1265 	if (!success) {
1266 		SPDK_ERRLOG("Failed to get data buffer, completing IO\n");
1267 		bdev_io_complete(bdev_io);
1268 	} else {
1269 		bdev_io_submit(bdev_io);
1270 	}
1271 }
1272 
1273 static void
1274 _bdev_memory_domain_io_get_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_buf_cb cb,
1275 			       uint64_t len)
1276 {
1277 	assert(cb != NULL);
1278 	bdev_io->internal.get_buf_cb = cb;
1279 
1280 	bdev_io_get_buf(bdev_io, len);
1281 }
1282 
1283 void
1284 spdk_bdev_io_get_aux_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_aux_buf_cb cb)
1285 {
1286 	uint64_t len = bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
1287 
1288 	assert(cb != NULL);
1289 	assert(bdev_io->internal.get_aux_buf_cb == NULL);
1290 	bdev_io->internal.get_aux_buf_cb = cb;
1291 	bdev_io_get_buf(bdev_io, len);
1292 }
1293 
1294 static int
1295 bdev_module_get_max_ctx_size(void)
1296 {
1297 	struct spdk_bdev_module *bdev_module;
1298 	int max_bdev_module_size = 0;
1299 
1300 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1301 		if (bdev_module->get_ctx_size && bdev_module->get_ctx_size() > max_bdev_module_size) {
1302 			max_bdev_module_size = bdev_module->get_ctx_size();
1303 		}
1304 	}
1305 
1306 	return max_bdev_module_size;
1307 }
1308 
1309 static void
1310 bdev_qos_config_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
1311 {
1312 	int i;
1313 	struct spdk_bdev_qos *qos = bdev->internal.qos;
1314 	uint64_t limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
1315 
1316 	if (!qos) {
1317 		return;
1318 	}
1319 
1320 	spdk_bdev_get_qos_rate_limits(bdev, limits);
1321 
1322 	spdk_json_write_object_begin(w);
1323 	spdk_json_write_named_string(w, "method", "bdev_set_qos_limit");
1324 
1325 	spdk_json_write_named_object_begin(w, "params");
1326 	spdk_json_write_named_string(w, "name", bdev->name);
1327 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1328 		if (limits[i] > 0) {
1329 			spdk_json_write_named_uint64(w, qos_rpc_type[i], limits[i]);
1330 		}
1331 	}
1332 	spdk_json_write_object_end(w);
1333 
1334 	spdk_json_write_object_end(w);
1335 }
1336 
1337 void
1338 spdk_bdev_subsystem_config_json(struct spdk_json_write_ctx *w)
1339 {
1340 	struct spdk_bdev_module *bdev_module;
1341 	struct spdk_bdev *bdev;
1342 
1343 	assert(w != NULL);
1344 
1345 	spdk_json_write_array_begin(w);
1346 
1347 	spdk_json_write_object_begin(w);
1348 	spdk_json_write_named_string(w, "method", "bdev_set_options");
1349 	spdk_json_write_named_object_begin(w, "params");
1350 	spdk_json_write_named_uint32(w, "bdev_io_pool_size", g_bdev_opts.bdev_io_pool_size);
1351 	spdk_json_write_named_uint32(w, "bdev_io_cache_size", g_bdev_opts.bdev_io_cache_size);
1352 	spdk_json_write_named_bool(w, "bdev_auto_examine", g_bdev_opts.bdev_auto_examine);
1353 	spdk_json_write_object_end(w);
1354 	spdk_json_write_object_end(w);
1355 
1356 	bdev_examine_allowlist_config_json(w);
1357 
1358 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1359 		if (bdev_module->config_json) {
1360 			bdev_module->config_json(w);
1361 		}
1362 	}
1363 
1364 	pthread_mutex_lock(&g_bdev_mgr.mutex);
1365 
1366 	TAILQ_FOREACH(bdev, &g_bdev_mgr.bdevs, internal.link) {
1367 		if (bdev->fn_table->write_config_json) {
1368 			bdev->fn_table->write_config_json(bdev, w);
1369 		}
1370 
1371 		bdev_qos_config_json(bdev, w);
1372 	}
1373 
1374 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
1375 
1376 	/* This has to be last RPC in array to make sure all bdevs finished examine */
1377 	spdk_json_write_object_begin(w);
1378 	spdk_json_write_named_string(w, "method", "bdev_wait_for_examine");
1379 	spdk_json_write_object_end(w);
1380 
1381 	spdk_json_write_array_end(w);
1382 }
1383 
1384 static int
1385 bdev_mgmt_channel_create(void *io_device, void *ctx_buf)
1386 {
1387 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
1388 	struct spdk_bdev_io *bdev_io;
1389 	uint32_t i;
1390 
1391 	STAILQ_INIT(&ch->need_buf_small);
1392 	STAILQ_INIT(&ch->need_buf_large);
1393 
1394 	STAILQ_INIT(&ch->per_thread_cache);
1395 	ch->bdev_io_cache_size = g_bdev_opts.bdev_io_cache_size;
1396 
1397 	/* Pre-populate bdev_io cache to ensure this thread cannot be starved. */
1398 	ch->per_thread_cache_count = 0;
1399 	for (i = 0; i < ch->bdev_io_cache_size; i++) {
1400 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
1401 		assert(bdev_io != NULL);
1402 		ch->per_thread_cache_count++;
1403 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
1404 	}
1405 
1406 	TAILQ_INIT(&ch->shared_resources);
1407 	TAILQ_INIT(&ch->io_wait_queue);
1408 
1409 	return 0;
1410 }
1411 
1412 static void
1413 bdev_mgmt_channel_destroy(void *io_device, void *ctx_buf)
1414 {
1415 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
1416 	struct spdk_bdev_io *bdev_io;
1417 
1418 	if (!STAILQ_EMPTY(&ch->need_buf_small) || !STAILQ_EMPTY(&ch->need_buf_large)) {
1419 		SPDK_ERRLOG("Pending I/O list wasn't empty on mgmt channel free\n");
1420 	}
1421 
1422 	if (!TAILQ_EMPTY(&ch->shared_resources)) {
1423 		SPDK_ERRLOG("Module channel list wasn't empty on mgmt channel free\n");
1424 	}
1425 
1426 	while (!STAILQ_EMPTY(&ch->per_thread_cache)) {
1427 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
1428 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
1429 		ch->per_thread_cache_count--;
1430 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
1431 	}
1432 
1433 	assert(ch->per_thread_cache_count == 0);
1434 }
1435 
1436 static void
1437 bdev_init_complete(int rc)
1438 {
1439 	spdk_bdev_init_cb cb_fn = g_init_cb_fn;
1440 	void *cb_arg = g_init_cb_arg;
1441 	struct spdk_bdev_module *m;
1442 
1443 	g_bdev_mgr.init_complete = true;
1444 	g_init_cb_fn = NULL;
1445 	g_init_cb_arg = NULL;
1446 
1447 	/*
1448 	 * For modules that need to know when subsystem init is complete,
1449 	 * inform them now.
1450 	 */
1451 	if (rc == 0) {
1452 		TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1453 			if (m->init_complete) {
1454 				m->init_complete();
1455 			}
1456 		}
1457 	}
1458 
1459 	cb_fn(cb_arg, rc);
1460 }
1461 
1462 static bool
1463 bdev_module_all_actions_completed(void)
1464 {
1465 	struct spdk_bdev_module *m;
1466 
1467 	TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1468 		if (m->internal.action_in_progress > 0) {
1469 			return false;
1470 		}
1471 	}
1472 	return true;
1473 }
1474 
1475 static void
1476 bdev_module_action_complete(void)
1477 {
1478 	/*
1479 	 * Don't finish bdev subsystem initialization if
1480 	 * module pre-initialization is still in progress, or
1481 	 * the subsystem been already initialized.
1482 	 */
1483 	if (!g_bdev_mgr.module_init_complete || g_bdev_mgr.init_complete) {
1484 		return;
1485 	}
1486 
1487 	/*
1488 	 * Check all bdev modules for inits/examinations in progress. If any
1489 	 * exist, return immediately since we cannot finish bdev subsystem
1490 	 * initialization until all are completed.
1491 	 */
1492 	if (!bdev_module_all_actions_completed()) {
1493 		return;
1494 	}
1495 
1496 	/*
1497 	 * Modules already finished initialization - now that all
1498 	 * the bdev modules have finished their asynchronous I/O
1499 	 * processing, the entire bdev layer can be marked as complete.
1500 	 */
1501 	bdev_init_complete(0);
1502 }
1503 
1504 static void
1505 bdev_module_action_done(struct spdk_bdev_module *module)
1506 {
1507 	assert(module->internal.action_in_progress > 0);
1508 	module->internal.action_in_progress--;
1509 	bdev_module_action_complete();
1510 }
1511 
1512 void
1513 spdk_bdev_module_init_done(struct spdk_bdev_module *module)
1514 {
1515 	bdev_module_action_done(module);
1516 }
1517 
1518 void
1519 spdk_bdev_module_examine_done(struct spdk_bdev_module *module)
1520 {
1521 	bdev_module_action_done(module);
1522 }
1523 
1524 /** The last initialized bdev module */
1525 static struct spdk_bdev_module *g_resume_bdev_module = NULL;
1526 
1527 static void
1528 bdev_init_failed(void *cb_arg)
1529 {
1530 	struct spdk_bdev_module *module = cb_arg;
1531 
1532 	module->internal.action_in_progress--;
1533 	bdev_init_complete(-1);
1534 }
1535 
1536 static int
1537 bdev_modules_init(void)
1538 {
1539 	struct spdk_bdev_module *module;
1540 	int rc = 0;
1541 
1542 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1543 		g_resume_bdev_module = module;
1544 		if (module->async_init) {
1545 			module->internal.action_in_progress = 1;
1546 		}
1547 		rc = module->module_init();
1548 		if (rc != 0) {
1549 			/* Bump action_in_progress to prevent other modules from completion of modules_init
1550 			 * Send message to defer application shutdown until resources are cleaned up */
1551 			module->internal.action_in_progress = 1;
1552 			spdk_thread_send_msg(spdk_get_thread(), bdev_init_failed, module);
1553 			return rc;
1554 		}
1555 	}
1556 
1557 	g_resume_bdev_module = NULL;
1558 	return 0;
1559 }
1560 
1561 void
1562 spdk_bdev_initialize(spdk_bdev_init_cb cb_fn, void *cb_arg)
1563 {
1564 	int cache_size;
1565 	int rc = 0;
1566 	char mempool_name[32];
1567 
1568 	assert(cb_fn != NULL);
1569 
1570 	g_init_cb_fn = cb_fn;
1571 	g_init_cb_arg = cb_arg;
1572 
1573 	spdk_notify_type_register("bdev_register");
1574 	spdk_notify_type_register("bdev_unregister");
1575 
1576 	snprintf(mempool_name, sizeof(mempool_name), "bdev_io_%d", getpid());
1577 
1578 	g_bdev_mgr.bdev_io_pool = spdk_mempool_create(mempool_name,
1579 				  g_bdev_opts.bdev_io_pool_size,
1580 				  sizeof(struct spdk_bdev_io) +
1581 				  bdev_module_get_max_ctx_size(),
1582 				  0,
1583 				  SPDK_ENV_SOCKET_ID_ANY);
1584 
1585 	if (g_bdev_mgr.bdev_io_pool == NULL) {
1586 		SPDK_ERRLOG("could not allocate spdk_bdev_io pool\n");
1587 		bdev_init_complete(-1);
1588 		return;
1589 	}
1590 
1591 	/**
1592 	 * Ensure no more than half of the total buffers end up local caches, by
1593 	 *   using spdk_env_get_core_count() to determine how many local caches we need
1594 	 *   to account for.
1595 	 */
1596 	cache_size = BUF_SMALL_POOL_SIZE / (2 * spdk_env_get_core_count());
1597 	snprintf(mempool_name, sizeof(mempool_name), "buf_small_pool_%d", getpid());
1598 
1599 	g_bdev_mgr.buf_small_pool = spdk_mempool_create(mempool_name,
1600 				    g_bdev_opts.small_buf_pool_size,
1601 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
1602 				    SPDK_BDEV_POOL_ALIGNMENT,
1603 				    cache_size,
1604 				    SPDK_ENV_SOCKET_ID_ANY);
1605 	if (!g_bdev_mgr.buf_small_pool) {
1606 		SPDK_ERRLOG("create rbuf small pool failed\n");
1607 		bdev_init_complete(-1);
1608 		return;
1609 	}
1610 
1611 	cache_size = BUF_LARGE_POOL_SIZE / (2 * spdk_env_get_core_count());
1612 	snprintf(mempool_name, sizeof(mempool_name), "buf_large_pool_%d", getpid());
1613 
1614 	g_bdev_mgr.buf_large_pool = spdk_mempool_create(mempool_name,
1615 				    g_bdev_opts.large_buf_pool_size,
1616 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
1617 				    SPDK_BDEV_POOL_ALIGNMENT,
1618 				    cache_size,
1619 				    SPDK_ENV_SOCKET_ID_ANY);
1620 	if (!g_bdev_mgr.buf_large_pool) {
1621 		SPDK_ERRLOG("create rbuf large pool failed\n");
1622 		bdev_init_complete(-1);
1623 		return;
1624 	}
1625 
1626 	g_bdev_mgr.zero_buffer = spdk_zmalloc(ZERO_BUFFER_SIZE, ZERO_BUFFER_SIZE,
1627 					      NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1628 	if (!g_bdev_mgr.zero_buffer) {
1629 		SPDK_ERRLOG("create bdev zero buffer failed\n");
1630 		bdev_init_complete(-1);
1631 		return;
1632 	}
1633 
1634 #ifdef SPDK_CONFIG_VTUNE
1635 	g_bdev_mgr.domain = __itt_domain_create("spdk_bdev");
1636 #endif
1637 
1638 	spdk_io_device_register(&g_bdev_mgr, bdev_mgmt_channel_create,
1639 				bdev_mgmt_channel_destroy,
1640 				sizeof(struct spdk_bdev_mgmt_channel),
1641 				"bdev_mgr");
1642 
1643 	rc = bdev_modules_init();
1644 	g_bdev_mgr.module_init_complete = true;
1645 	if (rc != 0) {
1646 		SPDK_ERRLOG("bdev modules init failed\n");
1647 		return;
1648 	}
1649 
1650 	bdev_module_action_complete();
1651 }
1652 
1653 static void
1654 bdev_mgr_unregister_cb(void *io_device)
1655 {
1656 	spdk_bdev_fini_cb cb_fn = g_fini_cb_fn;
1657 
1658 	if (g_bdev_mgr.bdev_io_pool) {
1659 		if (spdk_mempool_count(g_bdev_mgr.bdev_io_pool) != g_bdev_opts.bdev_io_pool_size) {
1660 			SPDK_ERRLOG("bdev IO pool count is %zu but should be %u\n",
1661 				    spdk_mempool_count(g_bdev_mgr.bdev_io_pool),
1662 				    g_bdev_opts.bdev_io_pool_size);
1663 		}
1664 
1665 		spdk_mempool_free(g_bdev_mgr.bdev_io_pool);
1666 	}
1667 
1668 	if (g_bdev_mgr.buf_small_pool) {
1669 		if (spdk_mempool_count(g_bdev_mgr.buf_small_pool) != g_bdev_opts.small_buf_pool_size) {
1670 			SPDK_ERRLOG("Small buffer pool count is %zu but should be %u\n",
1671 				    spdk_mempool_count(g_bdev_mgr.buf_small_pool),
1672 				    g_bdev_opts.small_buf_pool_size);
1673 			assert(false);
1674 		}
1675 
1676 		spdk_mempool_free(g_bdev_mgr.buf_small_pool);
1677 	}
1678 
1679 	if (g_bdev_mgr.buf_large_pool) {
1680 		if (spdk_mempool_count(g_bdev_mgr.buf_large_pool) != g_bdev_opts.large_buf_pool_size) {
1681 			SPDK_ERRLOG("Large buffer pool count is %zu but should be %u\n",
1682 				    spdk_mempool_count(g_bdev_mgr.buf_large_pool),
1683 				    g_bdev_opts.large_buf_pool_size);
1684 			assert(false);
1685 		}
1686 
1687 		spdk_mempool_free(g_bdev_mgr.buf_large_pool);
1688 	}
1689 
1690 	spdk_free(g_bdev_mgr.zero_buffer);
1691 
1692 	bdev_examine_allowlist_free();
1693 
1694 	cb_fn(g_fini_cb_arg);
1695 	g_fini_cb_fn = NULL;
1696 	g_fini_cb_arg = NULL;
1697 	g_bdev_mgr.init_complete = false;
1698 	g_bdev_mgr.module_init_complete = false;
1699 }
1700 
1701 static void
1702 bdev_module_fini_iter(void *arg)
1703 {
1704 	struct spdk_bdev_module *bdev_module;
1705 
1706 	/* FIXME: Handling initialization failures is broken now,
1707 	 * so we won't even try cleaning up after successfully
1708 	 * initialized modules. if module_init_complete is false,
1709 	 * just call spdk_bdev_mgr_unregister_cb
1710 	 */
1711 	if (!g_bdev_mgr.module_init_complete) {
1712 		bdev_mgr_unregister_cb(NULL);
1713 		return;
1714 	}
1715 
1716 	/* Start iterating from the last touched module */
1717 	if (!g_resume_bdev_module) {
1718 		bdev_module = TAILQ_LAST(&g_bdev_mgr.bdev_modules, bdev_module_list);
1719 	} else {
1720 		bdev_module = TAILQ_PREV(g_resume_bdev_module, bdev_module_list,
1721 					 internal.tailq);
1722 	}
1723 
1724 	while (bdev_module) {
1725 		if (bdev_module->async_fini) {
1726 			/* Save our place so we can resume later. We must
1727 			 * save the variable here, before calling module_fini()
1728 			 * below, because in some cases the module may immediately
1729 			 * call spdk_bdev_module_fini_done() and re-enter
1730 			 * this function to continue iterating. */
1731 			g_resume_bdev_module = bdev_module;
1732 		}
1733 
1734 		if (bdev_module->module_fini) {
1735 			bdev_module->module_fini();
1736 		}
1737 
1738 		if (bdev_module->async_fini) {
1739 			return;
1740 		}
1741 
1742 		bdev_module = TAILQ_PREV(bdev_module, bdev_module_list,
1743 					 internal.tailq);
1744 	}
1745 
1746 	g_resume_bdev_module = NULL;
1747 	spdk_io_device_unregister(&g_bdev_mgr, bdev_mgr_unregister_cb);
1748 }
1749 
1750 void
1751 spdk_bdev_module_fini_done(void)
1752 {
1753 	if (spdk_get_thread() != g_fini_thread) {
1754 		spdk_thread_send_msg(g_fini_thread, bdev_module_fini_iter, NULL);
1755 	} else {
1756 		bdev_module_fini_iter(NULL);
1757 	}
1758 }
1759 
1760 static void
1761 bdev_finish_unregister_bdevs_iter(void *cb_arg, int bdeverrno)
1762 {
1763 	struct spdk_bdev *bdev = cb_arg;
1764 
1765 	if (bdeverrno && bdev) {
1766 		SPDK_WARNLOG("Unable to unregister bdev '%s' during spdk_bdev_finish()\n",
1767 			     bdev->name);
1768 
1769 		/*
1770 		 * Since the call to spdk_bdev_unregister() failed, we have no way to free this
1771 		 *  bdev; try to continue by manually removing this bdev from the list and continue
1772 		 *  with the next bdev in the list.
1773 		 */
1774 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
1775 	}
1776 
1777 	if (TAILQ_EMPTY(&g_bdev_mgr.bdevs)) {
1778 		SPDK_DEBUGLOG(bdev, "Done unregistering bdevs\n");
1779 		/*
1780 		 * Bdev module finish need to be deferred as we might be in the middle of some context
1781 		 * (like bdev part free) that will use this bdev (or private bdev driver ctx data)
1782 		 * after returning.
1783 		 */
1784 		spdk_thread_send_msg(spdk_get_thread(), bdev_module_fini_iter, NULL);
1785 		return;
1786 	}
1787 
1788 	/*
1789 	 * Unregister last unclaimed bdev in the list, to ensure that bdev subsystem
1790 	 * shutdown proceeds top-down. The goal is to give virtual bdevs an opportunity
1791 	 * to detect clean shutdown as opposed to run-time hot removal of the underlying
1792 	 * base bdevs.
1793 	 *
1794 	 * Also, walk the list in the reverse order.
1795 	 */
1796 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1797 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1798 		if (bdev->internal.claim_module != NULL) {
1799 			SPDK_DEBUGLOG(bdev, "Skipping claimed bdev '%s'(<-'%s').\n",
1800 				      bdev->name, bdev->internal.claim_module->name);
1801 			continue;
1802 		}
1803 
1804 		SPDK_DEBUGLOG(bdev, "Unregistering bdev '%s'\n", bdev->name);
1805 		spdk_bdev_unregister(bdev, bdev_finish_unregister_bdevs_iter, bdev);
1806 		return;
1807 	}
1808 
1809 	/*
1810 	 * If any bdev fails to unclaim underlying bdev properly, we may face the
1811 	 * case of bdev list consisting of claimed bdevs only (if claims are managed
1812 	 * correctly, this would mean there's a loop in the claims graph which is
1813 	 * clearly impossible). Warn and unregister last bdev on the list then.
1814 	 */
1815 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1816 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1817 		SPDK_WARNLOG("Unregistering claimed bdev '%s'!\n", bdev->name);
1818 		spdk_bdev_unregister(bdev, bdev_finish_unregister_bdevs_iter, bdev);
1819 		return;
1820 	}
1821 }
1822 
1823 static void
1824 bdev_module_fini_start_iter(void *arg)
1825 {
1826 	struct spdk_bdev_module *bdev_module;
1827 
1828 	if (!g_resume_bdev_module) {
1829 		bdev_module = TAILQ_LAST(&g_bdev_mgr.bdev_modules, bdev_module_list);
1830 	} else {
1831 		bdev_module = TAILQ_PREV(g_resume_bdev_module, bdev_module_list, internal.tailq);
1832 	}
1833 
1834 	while (bdev_module) {
1835 		if (bdev_module->async_fini_start) {
1836 			/* Save our place so we can resume later. We must
1837 			 * save the variable here, before calling fini_start()
1838 			 * below, because in some cases the module may immediately
1839 			 * call spdk_bdev_module_fini_start_done() and re-enter
1840 			 * this function to continue iterating. */
1841 			g_resume_bdev_module = bdev_module;
1842 		}
1843 
1844 		if (bdev_module->fini_start) {
1845 			bdev_module->fini_start();
1846 		}
1847 
1848 		if (bdev_module->async_fini_start) {
1849 			return;
1850 		}
1851 
1852 		bdev_module = TAILQ_PREV(bdev_module, bdev_module_list, internal.tailq);
1853 	}
1854 
1855 	g_resume_bdev_module = NULL;
1856 
1857 	bdev_finish_unregister_bdevs_iter(NULL, 0);
1858 }
1859 
1860 void
1861 spdk_bdev_module_fini_start_done(void)
1862 {
1863 	if (spdk_get_thread() != g_fini_thread) {
1864 		spdk_thread_send_msg(g_fini_thread, bdev_module_fini_start_iter, NULL);
1865 	} else {
1866 		bdev_module_fini_start_iter(NULL);
1867 	}
1868 }
1869 
1870 void
1871 spdk_bdev_finish(spdk_bdev_fini_cb cb_fn, void *cb_arg)
1872 {
1873 	assert(cb_fn != NULL);
1874 
1875 	g_fini_thread = spdk_get_thread();
1876 
1877 	g_fini_cb_fn = cb_fn;
1878 	g_fini_cb_arg = cb_arg;
1879 
1880 	bdev_module_fini_start_iter(NULL);
1881 }
1882 
1883 struct spdk_bdev_io *
1884 bdev_channel_get_io(struct spdk_bdev_channel *channel)
1885 {
1886 	struct spdk_bdev_mgmt_channel *ch = channel->shared_resource->mgmt_ch;
1887 	struct spdk_bdev_io *bdev_io;
1888 
1889 	if (ch->per_thread_cache_count > 0) {
1890 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
1891 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
1892 		ch->per_thread_cache_count--;
1893 	} else if (spdk_unlikely(!TAILQ_EMPTY(&ch->io_wait_queue))) {
1894 		/*
1895 		 * Don't try to look for bdev_ios in the global pool if there are
1896 		 * waiters on bdev_ios - we don't want this caller to jump the line.
1897 		 */
1898 		bdev_io = NULL;
1899 	} else {
1900 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
1901 	}
1902 
1903 	return bdev_io;
1904 }
1905 
1906 void
1907 spdk_bdev_free_io(struct spdk_bdev_io *bdev_io)
1908 {
1909 	struct spdk_bdev_mgmt_channel *ch;
1910 
1911 	assert(bdev_io != NULL);
1912 	assert(bdev_io->internal.status != SPDK_BDEV_IO_STATUS_PENDING);
1913 
1914 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
1915 
1916 	if (bdev_io->internal.buf != NULL) {
1917 		bdev_io_put_buf(bdev_io);
1918 	}
1919 
1920 	if (ch->per_thread_cache_count < ch->bdev_io_cache_size) {
1921 		ch->per_thread_cache_count++;
1922 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
1923 		while (ch->per_thread_cache_count > 0 && !TAILQ_EMPTY(&ch->io_wait_queue)) {
1924 			struct spdk_bdev_io_wait_entry *entry;
1925 
1926 			entry = TAILQ_FIRST(&ch->io_wait_queue);
1927 			TAILQ_REMOVE(&ch->io_wait_queue, entry, link);
1928 			entry->cb_fn(entry->cb_arg);
1929 		}
1930 	} else {
1931 		/* We should never have a full cache with entries on the io wait queue. */
1932 		assert(TAILQ_EMPTY(&ch->io_wait_queue));
1933 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
1934 	}
1935 }
1936 
1937 static bool
1938 bdev_qos_is_iops_rate_limit(enum spdk_bdev_qos_rate_limit_type limit)
1939 {
1940 	assert(limit != SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
1941 
1942 	switch (limit) {
1943 	case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
1944 		return true;
1945 	case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
1946 	case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
1947 	case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
1948 		return false;
1949 	case SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES:
1950 	default:
1951 		return false;
1952 	}
1953 }
1954 
1955 static bool
1956 bdev_qos_io_to_limit(struct spdk_bdev_io *bdev_io)
1957 {
1958 	switch (bdev_io->type) {
1959 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1960 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1961 	case SPDK_BDEV_IO_TYPE_READ:
1962 	case SPDK_BDEV_IO_TYPE_WRITE:
1963 		return true;
1964 	case SPDK_BDEV_IO_TYPE_ZCOPY:
1965 		if (bdev_io->u.bdev.zcopy.start) {
1966 			return true;
1967 		} else {
1968 			return false;
1969 		}
1970 	default:
1971 		return false;
1972 	}
1973 }
1974 
1975 static bool
1976 bdev_is_read_io(struct spdk_bdev_io *bdev_io)
1977 {
1978 	switch (bdev_io->type) {
1979 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1980 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1981 		/* Bit 1 (0x2) set for read operation */
1982 		if (bdev_io->u.nvme_passthru.cmd.opc & SPDK_NVME_OPC_READ) {
1983 			return true;
1984 		} else {
1985 			return false;
1986 		}
1987 	case SPDK_BDEV_IO_TYPE_READ:
1988 		return true;
1989 	case SPDK_BDEV_IO_TYPE_ZCOPY:
1990 		/* Populate to read from disk */
1991 		if (bdev_io->u.bdev.zcopy.populate) {
1992 			return true;
1993 		} else {
1994 			return false;
1995 		}
1996 	default:
1997 		return false;
1998 	}
1999 }
2000 
2001 static uint64_t
2002 bdev_get_io_size_in_byte(struct spdk_bdev_io *bdev_io)
2003 {
2004 	struct spdk_bdev	*bdev = bdev_io->bdev;
2005 
2006 	switch (bdev_io->type) {
2007 	case SPDK_BDEV_IO_TYPE_NVME_IO:
2008 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
2009 		return bdev_io->u.nvme_passthru.nbytes;
2010 	case SPDK_BDEV_IO_TYPE_READ:
2011 	case SPDK_BDEV_IO_TYPE_WRITE:
2012 		return bdev_io->u.bdev.num_blocks * bdev->blocklen;
2013 	case SPDK_BDEV_IO_TYPE_ZCOPY:
2014 		/* Track the data in the start phase only */
2015 		if (bdev_io->u.bdev.zcopy.start) {
2016 			return bdev_io->u.bdev.num_blocks * bdev->blocklen;
2017 		} else {
2018 			return 0;
2019 		}
2020 	default:
2021 		return 0;
2022 	}
2023 }
2024 
2025 static bool
2026 bdev_qos_rw_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2027 {
2028 	if (limit->max_per_timeslice > 0 && limit->remaining_this_timeslice <= 0) {
2029 		return true;
2030 	} else {
2031 		return false;
2032 	}
2033 }
2034 
2035 static bool
2036 bdev_qos_r_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2037 {
2038 	if (bdev_is_read_io(io) == false) {
2039 		return false;
2040 	}
2041 
2042 	return bdev_qos_rw_queue_io(limit, io);
2043 }
2044 
2045 static bool
2046 bdev_qos_w_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2047 {
2048 	if (bdev_is_read_io(io) == true) {
2049 		return false;
2050 	}
2051 
2052 	return bdev_qos_rw_queue_io(limit, io);
2053 }
2054 
2055 static void
2056 bdev_qos_rw_iops_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2057 {
2058 	limit->remaining_this_timeslice--;
2059 }
2060 
2061 static void
2062 bdev_qos_rw_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2063 {
2064 	limit->remaining_this_timeslice -= bdev_get_io_size_in_byte(io);
2065 }
2066 
2067 static void
2068 bdev_qos_r_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2069 {
2070 	if (bdev_is_read_io(io) == false) {
2071 		return;
2072 	}
2073 
2074 	return bdev_qos_rw_bps_update_quota(limit, io);
2075 }
2076 
2077 static void
2078 bdev_qos_w_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
2079 {
2080 	if (bdev_is_read_io(io) == true) {
2081 		return;
2082 	}
2083 
2084 	return bdev_qos_rw_bps_update_quota(limit, io);
2085 }
2086 
2087 static void
2088 bdev_qos_set_ops(struct spdk_bdev_qos *qos)
2089 {
2090 	int i;
2091 
2092 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2093 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
2094 			qos->rate_limits[i].queue_io = NULL;
2095 			qos->rate_limits[i].update_quota = NULL;
2096 			continue;
2097 		}
2098 
2099 		switch (i) {
2100 		case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
2101 			qos->rate_limits[i].queue_io = bdev_qos_rw_queue_io;
2102 			qos->rate_limits[i].update_quota = bdev_qos_rw_iops_update_quota;
2103 			break;
2104 		case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
2105 			qos->rate_limits[i].queue_io = bdev_qos_rw_queue_io;
2106 			qos->rate_limits[i].update_quota = bdev_qos_rw_bps_update_quota;
2107 			break;
2108 		case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
2109 			qos->rate_limits[i].queue_io = bdev_qos_r_queue_io;
2110 			qos->rate_limits[i].update_quota = bdev_qos_r_bps_update_quota;
2111 			break;
2112 		case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
2113 			qos->rate_limits[i].queue_io = bdev_qos_w_queue_io;
2114 			qos->rate_limits[i].update_quota = bdev_qos_w_bps_update_quota;
2115 			break;
2116 		default:
2117 			break;
2118 		}
2119 	}
2120 }
2121 
2122 static void
2123 _bdev_io_complete_in_submit(struct spdk_bdev_channel *bdev_ch,
2124 			    struct spdk_bdev_io *bdev_io,
2125 			    enum spdk_bdev_io_status status)
2126 {
2127 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
2128 
2129 	bdev_io->internal.in_submit_request = true;
2130 	bdev_ch->io_outstanding++;
2131 	shared_resource->io_outstanding++;
2132 	spdk_bdev_io_complete(bdev_io, status);
2133 	bdev_io->internal.in_submit_request = false;
2134 }
2135 
2136 static inline void
2137 bdev_io_do_submit(struct spdk_bdev_channel *bdev_ch, struct spdk_bdev_io *bdev_io)
2138 {
2139 	struct spdk_bdev *bdev = bdev_io->bdev;
2140 	struct spdk_io_channel *ch = bdev_ch->channel;
2141 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
2142 
2143 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_ABORT)) {
2144 		struct spdk_bdev_mgmt_channel *mgmt_channel = shared_resource->mgmt_ch;
2145 		struct spdk_bdev_io *bio_to_abort = bdev_io->u.abort.bio_to_abort;
2146 
2147 		if (bdev_abort_queued_io(&shared_resource->nomem_io, bio_to_abort) ||
2148 		    bdev_abort_buf_io(&mgmt_channel->need_buf_small, bio_to_abort) ||
2149 		    bdev_abort_buf_io(&mgmt_channel->need_buf_large, bio_to_abort)) {
2150 			_bdev_io_complete_in_submit(bdev_ch, bdev_io,
2151 						    SPDK_BDEV_IO_STATUS_SUCCESS);
2152 			return;
2153 		}
2154 	}
2155 
2156 	if (spdk_likely(TAILQ_EMPTY(&shared_resource->nomem_io))) {
2157 		bdev_ch->io_outstanding++;
2158 		shared_resource->io_outstanding++;
2159 		bdev_io->internal.in_submit_request = true;
2160 		bdev->fn_table->submit_request(ch, bdev_io);
2161 		bdev_io->internal.in_submit_request = false;
2162 	} else {
2163 		TAILQ_INSERT_TAIL(&shared_resource->nomem_io, bdev_io, internal.link);
2164 	}
2165 }
2166 
2167 static int
2168 bdev_qos_io_submit(struct spdk_bdev_channel *ch, struct spdk_bdev_qos *qos)
2169 {
2170 	struct spdk_bdev_io		*bdev_io = NULL, *tmp = NULL;
2171 	int				i, submitted_ios = 0;
2172 
2173 	TAILQ_FOREACH_SAFE(bdev_io, &qos->queued, internal.link, tmp) {
2174 		if (bdev_qos_io_to_limit(bdev_io) == true) {
2175 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2176 				if (!qos->rate_limits[i].queue_io) {
2177 					continue;
2178 				}
2179 
2180 				if (qos->rate_limits[i].queue_io(&qos->rate_limits[i],
2181 								 bdev_io) == true) {
2182 					return submitted_ios;
2183 				}
2184 			}
2185 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2186 				if (!qos->rate_limits[i].update_quota) {
2187 					continue;
2188 				}
2189 
2190 				qos->rate_limits[i].update_quota(&qos->rate_limits[i], bdev_io);
2191 			}
2192 		}
2193 
2194 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
2195 		bdev_io_do_submit(ch, bdev_io);
2196 		submitted_ios++;
2197 	}
2198 
2199 	return submitted_ios;
2200 }
2201 
2202 static void
2203 bdev_queue_io_wait_with_cb(struct spdk_bdev_io *bdev_io, spdk_bdev_io_wait_cb cb_fn)
2204 {
2205 	int rc;
2206 
2207 	bdev_io->internal.waitq_entry.bdev = bdev_io->bdev;
2208 	bdev_io->internal.waitq_entry.cb_fn = cb_fn;
2209 	bdev_io->internal.waitq_entry.cb_arg = bdev_io;
2210 	rc = spdk_bdev_queue_io_wait(bdev_io->bdev, spdk_io_channel_from_ctx(bdev_io->internal.ch),
2211 				     &bdev_io->internal.waitq_entry);
2212 	if (rc != 0) {
2213 		SPDK_ERRLOG("Queue IO failed, rc=%d\n", rc);
2214 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2215 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
2216 	}
2217 }
2218 
2219 static bool
2220 bdev_rw_should_split(struct spdk_bdev_io *bdev_io)
2221 {
2222 	uint32_t io_boundary = bdev_io->bdev->optimal_io_boundary;
2223 	uint32_t max_size = bdev_io->bdev->max_segment_size;
2224 	int max_segs = bdev_io->bdev->max_num_segments;
2225 
2226 	io_boundary = bdev_io->bdev->split_on_optimal_io_boundary ? io_boundary : 0;
2227 
2228 	if (spdk_likely(!io_boundary && !max_segs && !max_size)) {
2229 		return false;
2230 	}
2231 
2232 	if (io_boundary) {
2233 		uint64_t start_stripe, end_stripe;
2234 
2235 		start_stripe = bdev_io->u.bdev.offset_blocks;
2236 		end_stripe = start_stripe + bdev_io->u.bdev.num_blocks - 1;
2237 		/* Avoid expensive div operations if possible.  These spdk_u32 functions are very cheap. */
2238 		if (spdk_likely(spdk_u32_is_pow2(io_boundary))) {
2239 			start_stripe >>= spdk_u32log2(io_boundary);
2240 			end_stripe >>= spdk_u32log2(io_boundary);
2241 		} else {
2242 			start_stripe /= io_boundary;
2243 			end_stripe /= io_boundary;
2244 		}
2245 
2246 		if (start_stripe != end_stripe) {
2247 			return true;
2248 		}
2249 	}
2250 
2251 	if (max_segs) {
2252 		if (bdev_io->u.bdev.iovcnt > max_segs) {
2253 			return true;
2254 		}
2255 	}
2256 
2257 	if (max_size) {
2258 		for (int i = 0; i < bdev_io->u.bdev.iovcnt; i++) {
2259 			if (bdev_io->u.bdev.iovs[i].iov_len > max_size) {
2260 				return true;
2261 			}
2262 		}
2263 	}
2264 
2265 	return false;
2266 }
2267 
2268 static bool
2269 bdev_unmap_should_split(struct spdk_bdev_io *bdev_io)
2270 {
2271 	uint32_t num_unmap_segments;
2272 
2273 	if (!bdev_io->bdev->max_unmap || !bdev_io->bdev->max_unmap_segments) {
2274 		return false;
2275 	}
2276 	num_unmap_segments = spdk_divide_round_up(bdev_io->u.bdev.num_blocks, bdev_io->bdev->max_unmap);
2277 	if (num_unmap_segments > bdev_io->bdev->max_unmap_segments) {
2278 		return true;
2279 	}
2280 
2281 	return false;
2282 }
2283 
2284 static bool
2285 bdev_write_zeroes_should_split(struct spdk_bdev_io *bdev_io)
2286 {
2287 	if (!bdev_io->bdev->max_write_zeroes) {
2288 		return false;
2289 	}
2290 
2291 	if (bdev_io->u.bdev.num_blocks > bdev_io->bdev->max_write_zeroes) {
2292 		return true;
2293 	}
2294 
2295 	return false;
2296 }
2297 
2298 static bool
2299 bdev_io_should_split(struct spdk_bdev_io *bdev_io)
2300 {
2301 	switch (bdev_io->type) {
2302 	case SPDK_BDEV_IO_TYPE_READ:
2303 	case SPDK_BDEV_IO_TYPE_WRITE:
2304 		return bdev_rw_should_split(bdev_io);
2305 	case SPDK_BDEV_IO_TYPE_UNMAP:
2306 		return bdev_unmap_should_split(bdev_io);
2307 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2308 		return bdev_write_zeroes_should_split(bdev_io);
2309 	default:
2310 		return false;
2311 	}
2312 }
2313 
2314 static uint32_t
2315 _to_next_boundary(uint64_t offset, uint32_t boundary)
2316 {
2317 	return (boundary - (offset % boundary));
2318 }
2319 
2320 static void bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
2321 
2322 static void _bdev_rw_split(void *_bdev_io);
2323 
2324 static void bdev_unmap_split(struct spdk_bdev_io *bdev_io);
2325 
2326 static void
2327 _bdev_unmap_split(void *_bdev_io)
2328 {
2329 	return bdev_unmap_split((struct spdk_bdev_io *)_bdev_io);
2330 }
2331 
2332 static void bdev_write_zeroes_split(struct spdk_bdev_io *bdev_io);
2333 
2334 static void
2335 _bdev_write_zeroes_split(void *_bdev_io)
2336 {
2337 	return bdev_write_zeroes_split((struct spdk_bdev_io *)_bdev_io);
2338 }
2339 
2340 static int
2341 bdev_io_split_submit(struct spdk_bdev_io *bdev_io, struct iovec *iov, int iovcnt, void *md_buf,
2342 		     uint64_t num_blocks, uint64_t *offset, uint64_t *remaining)
2343 {
2344 	int rc;
2345 	uint64_t current_offset, current_remaining;
2346 	spdk_bdev_io_wait_cb io_wait_fn;
2347 
2348 	current_offset = *offset;
2349 	current_remaining = *remaining;
2350 
2351 	bdev_io->u.bdev.split_outstanding++;
2352 
2353 	io_wait_fn = _bdev_rw_split;
2354 	switch (bdev_io->type) {
2355 	case SPDK_BDEV_IO_TYPE_READ:
2356 		rc = bdev_readv_blocks_with_md(bdev_io->internal.desc,
2357 					       spdk_io_channel_from_ctx(bdev_io->internal.ch),
2358 					       iov, iovcnt, md_buf, current_offset,
2359 					       num_blocks,
2360 					       bdev_io_split_done, bdev_io,
2361 					       bdev_io->internal.ext_opts, true);
2362 		break;
2363 	case SPDK_BDEV_IO_TYPE_WRITE:
2364 		rc = bdev_writev_blocks_with_md(bdev_io->internal.desc,
2365 						spdk_io_channel_from_ctx(bdev_io->internal.ch),
2366 						iov, iovcnt, md_buf, current_offset,
2367 						num_blocks,
2368 						bdev_io_split_done, bdev_io,
2369 						bdev_io->internal.ext_opts, true);
2370 		break;
2371 	case SPDK_BDEV_IO_TYPE_UNMAP:
2372 		io_wait_fn = _bdev_unmap_split;
2373 		rc = spdk_bdev_unmap_blocks(bdev_io->internal.desc,
2374 					    spdk_io_channel_from_ctx(bdev_io->internal.ch),
2375 					    current_offset, num_blocks,
2376 					    bdev_io_split_done, bdev_io);
2377 		break;
2378 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2379 		io_wait_fn = _bdev_write_zeroes_split;
2380 		rc = spdk_bdev_write_zeroes_blocks(bdev_io->internal.desc,
2381 						   spdk_io_channel_from_ctx(bdev_io->internal.ch),
2382 						   current_offset, num_blocks,
2383 						   bdev_io_split_done, bdev_io);
2384 		break;
2385 	default:
2386 		assert(false);
2387 		rc = -EINVAL;
2388 		break;
2389 	}
2390 
2391 	if (rc == 0) {
2392 		current_offset += num_blocks;
2393 		current_remaining -= num_blocks;
2394 		bdev_io->u.bdev.split_current_offset_blocks = current_offset;
2395 		bdev_io->u.bdev.split_remaining_num_blocks = current_remaining;
2396 		*offset = current_offset;
2397 		*remaining = current_remaining;
2398 	} else {
2399 		bdev_io->u.bdev.split_outstanding--;
2400 		if (rc == -ENOMEM) {
2401 			if (bdev_io->u.bdev.split_outstanding == 0) {
2402 				/* No I/O is outstanding. Hence we should wait here. */
2403 				bdev_queue_io_wait_with_cb(bdev_io, io_wait_fn);
2404 			}
2405 		} else {
2406 			bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2407 			if (bdev_io->u.bdev.split_outstanding == 0) {
2408 				spdk_trace_record(TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io, bdev_io->internal.caller_ctx);
2409 				TAILQ_REMOVE(&bdev_io->internal.ch->io_submitted, bdev_io, internal.ch_link);
2410 				bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
2411 			}
2412 		}
2413 	}
2414 
2415 	return rc;
2416 }
2417 
2418 static void
2419 _bdev_rw_split(void *_bdev_io)
2420 {
2421 	struct iovec *parent_iov, *iov;
2422 	struct spdk_bdev_io *bdev_io = _bdev_io;
2423 	struct spdk_bdev *bdev = bdev_io->bdev;
2424 	uint64_t parent_offset, current_offset, remaining;
2425 	uint32_t parent_iov_offset, parent_iovcnt, parent_iovpos, child_iovcnt;
2426 	uint32_t to_next_boundary, to_next_boundary_bytes, to_last_block_bytes;
2427 	uint32_t iovcnt, iov_len, child_iovsize;
2428 	uint32_t blocklen = bdev->blocklen;
2429 	uint32_t io_boundary = bdev->optimal_io_boundary;
2430 	uint32_t max_segment_size = bdev->max_segment_size;
2431 	uint32_t max_child_iovcnt = bdev->max_num_segments;
2432 	void *md_buf = NULL;
2433 	int rc;
2434 
2435 	max_segment_size = max_segment_size ? max_segment_size : UINT32_MAX;
2436 	max_child_iovcnt = max_child_iovcnt ? spdk_min(max_child_iovcnt, BDEV_IO_NUM_CHILD_IOV) :
2437 			   BDEV_IO_NUM_CHILD_IOV;
2438 	io_boundary = bdev->split_on_optimal_io_boundary ? io_boundary : UINT32_MAX;
2439 
2440 	remaining = bdev_io->u.bdev.split_remaining_num_blocks;
2441 	current_offset = bdev_io->u.bdev.split_current_offset_blocks;
2442 	parent_offset = bdev_io->u.bdev.offset_blocks;
2443 	parent_iov_offset = (current_offset - parent_offset) * blocklen;
2444 	parent_iovcnt = bdev_io->u.bdev.iovcnt;
2445 
2446 	for (parent_iovpos = 0; parent_iovpos < parent_iovcnt; parent_iovpos++) {
2447 		parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
2448 		if (parent_iov_offset < parent_iov->iov_len) {
2449 			break;
2450 		}
2451 		parent_iov_offset -= parent_iov->iov_len;
2452 	}
2453 
2454 	child_iovcnt = 0;
2455 	while (remaining > 0 && parent_iovpos < parent_iovcnt && child_iovcnt < BDEV_IO_NUM_CHILD_IOV) {
2456 		to_next_boundary = _to_next_boundary(current_offset, io_boundary);
2457 		to_next_boundary = spdk_min(remaining, to_next_boundary);
2458 		to_next_boundary_bytes = to_next_boundary * blocklen;
2459 
2460 		iov = &bdev_io->child_iov[child_iovcnt];
2461 		iovcnt = 0;
2462 
2463 		if (bdev_io->u.bdev.md_buf) {
2464 			md_buf = (char *)bdev_io->u.bdev.md_buf +
2465 				 (current_offset - parent_offset) * spdk_bdev_get_md_size(bdev);
2466 		}
2467 
2468 		child_iovsize = spdk_min(BDEV_IO_NUM_CHILD_IOV - child_iovcnt, max_child_iovcnt);
2469 		while (to_next_boundary_bytes > 0 && parent_iovpos < parent_iovcnt &&
2470 		       iovcnt < child_iovsize) {
2471 			parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
2472 			iov_len = parent_iov->iov_len - parent_iov_offset;
2473 
2474 			iov_len = spdk_min(iov_len, max_segment_size);
2475 			iov_len = spdk_min(iov_len, to_next_boundary_bytes);
2476 			to_next_boundary_bytes -= iov_len;
2477 
2478 			bdev_io->child_iov[child_iovcnt].iov_base = parent_iov->iov_base + parent_iov_offset;
2479 			bdev_io->child_iov[child_iovcnt].iov_len = iov_len;
2480 
2481 			if (iov_len < parent_iov->iov_len - parent_iov_offset) {
2482 				parent_iov_offset += iov_len;
2483 			} else {
2484 				parent_iovpos++;
2485 				parent_iov_offset = 0;
2486 			}
2487 			child_iovcnt++;
2488 			iovcnt++;
2489 		}
2490 
2491 		if (to_next_boundary_bytes > 0) {
2492 			/* We had to stop this child I/O early because we ran out of
2493 			 * child_iov space or were limited by max_num_segments.
2494 			 * Ensure the iovs to be aligned with block size and
2495 			 * then adjust to_next_boundary before starting the
2496 			 * child I/O.
2497 			 */
2498 			assert(child_iovcnt == BDEV_IO_NUM_CHILD_IOV ||
2499 			       iovcnt == child_iovsize);
2500 			to_last_block_bytes = to_next_boundary_bytes % blocklen;
2501 			if (to_last_block_bytes != 0) {
2502 				uint32_t child_iovpos = child_iovcnt - 1;
2503 				/* don't decrease child_iovcnt when it equals to BDEV_IO_NUM_CHILD_IOV
2504 				 * so the loop will naturally end
2505 				 */
2506 
2507 				to_last_block_bytes = blocklen - to_last_block_bytes;
2508 				to_next_boundary_bytes += to_last_block_bytes;
2509 				while (to_last_block_bytes > 0 && iovcnt > 0) {
2510 					iov_len = spdk_min(to_last_block_bytes,
2511 							   bdev_io->child_iov[child_iovpos].iov_len);
2512 					bdev_io->child_iov[child_iovpos].iov_len -= iov_len;
2513 					if (bdev_io->child_iov[child_iovpos].iov_len == 0) {
2514 						child_iovpos--;
2515 						if (--iovcnt == 0) {
2516 							/* If the child IO is less than a block size just return.
2517 							 * If the first child IO of any split round is less than
2518 							 * a block size, an error exit.
2519 							 */
2520 							if (bdev_io->u.bdev.split_outstanding == 0) {
2521 								SPDK_ERRLOG("The first child io was less than a block size\n");
2522 								bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2523 								spdk_trace_record(TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io, bdev_io->internal.caller_ctx);
2524 								TAILQ_REMOVE(&bdev_io->internal.ch->io_submitted, bdev_io, internal.ch_link);
2525 								bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
2526 							}
2527 
2528 							return;
2529 						}
2530 					}
2531 
2532 					to_last_block_bytes -= iov_len;
2533 
2534 					if (parent_iov_offset == 0) {
2535 						parent_iovpos--;
2536 						parent_iov_offset = bdev_io->u.bdev.iovs[parent_iovpos].iov_len;
2537 					}
2538 					parent_iov_offset -= iov_len;
2539 				}
2540 
2541 				assert(to_last_block_bytes == 0);
2542 			}
2543 			to_next_boundary -= to_next_boundary_bytes / blocklen;
2544 		}
2545 
2546 		rc = bdev_io_split_submit(bdev_io, iov, iovcnt, md_buf, to_next_boundary,
2547 					  &current_offset, &remaining);
2548 		if (spdk_unlikely(rc)) {
2549 			return;
2550 		}
2551 	}
2552 }
2553 
2554 static void
2555 bdev_unmap_split(struct spdk_bdev_io *bdev_io)
2556 {
2557 	uint64_t offset, unmap_blocks, remaining, max_unmap_blocks;
2558 	uint32_t num_children_reqs = 0;
2559 	int rc;
2560 
2561 	offset = bdev_io->u.bdev.split_current_offset_blocks;
2562 	remaining = bdev_io->u.bdev.split_remaining_num_blocks;
2563 	max_unmap_blocks = bdev_io->bdev->max_unmap * bdev_io->bdev->max_unmap_segments;
2564 
2565 	while (remaining && (num_children_reqs < SPDK_BDEV_MAX_CHILDREN_UNMAP_WRITE_ZEROES_REQS)) {
2566 		unmap_blocks = spdk_min(remaining, max_unmap_blocks);
2567 
2568 		rc = bdev_io_split_submit(bdev_io, NULL, 0, NULL, unmap_blocks,
2569 					  &offset, &remaining);
2570 		if (spdk_likely(rc == 0)) {
2571 			num_children_reqs++;
2572 		} else {
2573 			return;
2574 		}
2575 	}
2576 }
2577 
2578 static void
2579 bdev_write_zeroes_split(struct spdk_bdev_io *bdev_io)
2580 {
2581 	uint64_t offset, write_zeroes_blocks, remaining;
2582 	uint32_t num_children_reqs = 0;
2583 	int rc;
2584 
2585 	offset = bdev_io->u.bdev.split_current_offset_blocks;
2586 	remaining = bdev_io->u.bdev.split_remaining_num_blocks;
2587 
2588 	while (remaining && (num_children_reqs < SPDK_BDEV_MAX_CHILDREN_UNMAP_WRITE_ZEROES_REQS)) {
2589 		write_zeroes_blocks = spdk_min(remaining, bdev_io->bdev->max_write_zeroes);
2590 
2591 		rc = bdev_io_split_submit(bdev_io, NULL, 0, NULL, write_zeroes_blocks,
2592 					  &offset, &remaining);
2593 		if (spdk_likely(rc == 0)) {
2594 			num_children_reqs++;
2595 		} else {
2596 			return;
2597 		}
2598 	}
2599 }
2600 
2601 static void
2602 parent_bdev_io_complete(void *ctx, int rc)
2603 {
2604 	struct spdk_bdev_io *parent_io = ctx;
2605 
2606 	if (rc) {
2607 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2608 	}
2609 
2610 	parent_io->internal.cb(parent_io, parent_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
2611 			       parent_io->internal.caller_ctx);
2612 }
2613 
2614 static void
2615 bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
2616 {
2617 	struct spdk_bdev_io *parent_io = cb_arg;
2618 
2619 	spdk_bdev_free_io(bdev_io);
2620 
2621 	if (!success) {
2622 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2623 		/* If any child I/O failed, stop further splitting process. */
2624 		parent_io->u.bdev.split_current_offset_blocks += parent_io->u.bdev.split_remaining_num_blocks;
2625 		parent_io->u.bdev.split_remaining_num_blocks = 0;
2626 	}
2627 	parent_io->u.bdev.split_outstanding--;
2628 	if (parent_io->u.bdev.split_outstanding != 0) {
2629 		return;
2630 	}
2631 
2632 	/*
2633 	 * Parent I/O finishes when all blocks are consumed.
2634 	 */
2635 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
2636 		assert(parent_io->internal.cb != bdev_io_split_done);
2637 		spdk_trace_record(TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)parent_io, bdev_io->internal.caller_ctx);
2638 		TAILQ_REMOVE(&parent_io->internal.ch->io_submitted, parent_io, internal.ch_link);
2639 
2640 		if (parent_io->internal.orig_iovcnt != 0) {
2641 			_bdev_io_push_bounce_data_buffer(parent_io, parent_bdev_io_complete);
2642 			/* bdev IO will be completed in the callback */
2643 		} else {
2644 			parent_bdev_io_complete(parent_io, 0);
2645 		}
2646 		return;
2647 	}
2648 
2649 	/*
2650 	 * Continue with the splitting process.  This function will complete the parent I/O if the
2651 	 * splitting is done.
2652 	 */
2653 	switch (parent_io->type) {
2654 	case SPDK_BDEV_IO_TYPE_READ:
2655 	case SPDK_BDEV_IO_TYPE_WRITE:
2656 		_bdev_rw_split(parent_io);
2657 		break;
2658 	case SPDK_BDEV_IO_TYPE_UNMAP:
2659 		bdev_unmap_split(parent_io);
2660 		break;
2661 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2662 		bdev_write_zeroes_split(parent_io);
2663 		break;
2664 	default:
2665 		assert(false);
2666 		break;
2667 	}
2668 }
2669 
2670 static void bdev_rw_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
2671 				     bool success);
2672 
2673 static void
2674 bdev_io_split(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io)
2675 {
2676 	bdev_io->u.bdev.split_current_offset_blocks = bdev_io->u.bdev.offset_blocks;
2677 	bdev_io->u.bdev.split_remaining_num_blocks = bdev_io->u.bdev.num_blocks;
2678 	bdev_io->u.bdev.split_outstanding = 0;
2679 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
2680 
2681 	switch (bdev_io->type) {
2682 	case SPDK_BDEV_IO_TYPE_READ:
2683 	case SPDK_BDEV_IO_TYPE_WRITE:
2684 		if (_is_buf_allocated(bdev_io->u.bdev.iovs)) {
2685 			_bdev_rw_split(bdev_io);
2686 		} else {
2687 			assert(bdev_io->type == SPDK_BDEV_IO_TYPE_READ);
2688 			spdk_bdev_io_get_buf(bdev_io, bdev_rw_split_get_buf_cb,
2689 					     bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
2690 		}
2691 		break;
2692 	case SPDK_BDEV_IO_TYPE_UNMAP:
2693 		bdev_unmap_split(bdev_io);
2694 		break;
2695 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2696 		bdev_write_zeroes_split(bdev_io);
2697 		break;
2698 	default:
2699 		assert(false);
2700 		break;
2701 	}
2702 }
2703 
2704 static void
2705 bdev_rw_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success)
2706 {
2707 	if (!success) {
2708 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2709 		return;
2710 	}
2711 
2712 	_bdev_rw_split(bdev_io);
2713 }
2714 
2715 /* Explicitly mark this inline, since it's used as a function pointer and otherwise won't
2716  *  be inlined, at least on some compilers.
2717  */
2718 static inline void
2719 _bdev_io_submit(void *ctx)
2720 {
2721 	struct spdk_bdev_io *bdev_io = ctx;
2722 	struct spdk_bdev *bdev = bdev_io->bdev;
2723 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
2724 	uint64_t tsc;
2725 
2726 	tsc = spdk_get_ticks();
2727 	bdev_io->internal.submit_tsc = tsc;
2728 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_START, 0, 0, (uintptr_t)bdev_io,
2729 			      (uint64_t)bdev_io->type, bdev_io->internal.caller_ctx,
2730 			      bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks);
2731 
2732 	if (spdk_likely(bdev_ch->flags == 0)) {
2733 		bdev_io_do_submit(bdev_ch, bdev_io);
2734 		return;
2735 	}
2736 
2737 	if (bdev_ch->flags & BDEV_CH_RESET_IN_PROGRESS) {
2738 		_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
2739 	} else if (bdev_ch->flags & BDEV_CH_QOS_ENABLED) {
2740 		if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_ABORT) &&
2741 		    bdev_abort_queued_io(&bdev->internal.qos->queued, bdev_io->u.abort.bio_to_abort)) {
2742 			_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_SUCCESS);
2743 		} else {
2744 			TAILQ_INSERT_TAIL(&bdev->internal.qos->queued, bdev_io, internal.link);
2745 			bdev_qos_io_submit(bdev_ch, bdev->internal.qos);
2746 		}
2747 	} else {
2748 		SPDK_ERRLOG("unknown bdev_ch flag %x found\n", bdev_ch->flags);
2749 		_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2750 	}
2751 }
2752 
2753 bool bdev_lba_range_overlapped(struct lba_range *range1, struct lba_range *range2);
2754 
2755 bool
2756 bdev_lba_range_overlapped(struct lba_range *range1, struct lba_range *range2)
2757 {
2758 	if (range1->length == 0 || range2->length == 0) {
2759 		return false;
2760 	}
2761 
2762 	if (range1->offset + range1->length <= range2->offset) {
2763 		return false;
2764 	}
2765 
2766 	if (range2->offset + range2->length <= range1->offset) {
2767 		return false;
2768 	}
2769 
2770 	return true;
2771 }
2772 
2773 static bool
2774 bdev_io_range_is_locked(struct spdk_bdev_io *bdev_io, struct lba_range *range)
2775 {
2776 	struct spdk_bdev_channel *ch = bdev_io->internal.ch;
2777 	struct lba_range r;
2778 
2779 	switch (bdev_io->type) {
2780 	case SPDK_BDEV_IO_TYPE_NVME_IO:
2781 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
2782 		/* Don't try to decode the NVMe command - just assume worst-case and that
2783 		 * it overlaps a locked range.
2784 		 */
2785 		return true;
2786 	case SPDK_BDEV_IO_TYPE_WRITE:
2787 	case SPDK_BDEV_IO_TYPE_UNMAP:
2788 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2789 	case SPDK_BDEV_IO_TYPE_ZCOPY:
2790 		r.offset = bdev_io->u.bdev.offset_blocks;
2791 		r.length = bdev_io->u.bdev.num_blocks;
2792 		if (!bdev_lba_range_overlapped(range, &r)) {
2793 			/* This I/O doesn't overlap the specified LBA range. */
2794 			return false;
2795 		} else if (range->owner_ch == ch && range->locked_ctx == bdev_io->internal.caller_ctx) {
2796 			/* This I/O overlaps, but the I/O is on the same channel that locked this
2797 			 * range, and the caller_ctx is the same as the locked_ctx.  This means
2798 			 * that this I/O is associated with the lock, and is allowed to execute.
2799 			 */
2800 			return false;
2801 		} else {
2802 			return true;
2803 		}
2804 	default:
2805 		return false;
2806 	}
2807 }
2808 
2809 void
2810 bdev_io_submit(struct spdk_bdev_io *bdev_io)
2811 {
2812 	struct spdk_bdev *bdev = bdev_io->bdev;
2813 	struct spdk_thread *thread = spdk_bdev_io_get_thread(bdev_io);
2814 	struct spdk_bdev_channel *ch = bdev_io->internal.ch;
2815 
2816 	assert(thread != NULL);
2817 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
2818 
2819 	if (!TAILQ_EMPTY(&ch->locked_ranges)) {
2820 		struct lba_range *range;
2821 
2822 		TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
2823 			if (bdev_io_range_is_locked(bdev_io, range)) {
2824 				TAILQ_INSERT_TAIL(&ch->io_locked, bdev_io, internal.ch_link);
2825 				return;
2826 			}
2827 		}
2828 	}
2829 
2830 	TAILQ_INSERT_TAIL(&ch->io_submitted, bdev_io, internal.ch_link);
2831 
2832 	if (bdev_io_should_split(bdev_io)) {
2833 		bdev_io->internal.submit_tsc = spdk_get_ticks();
2834 		spdk_trace_record_tsc(bdev_io->internal.submit_tsc, TRACE_BDEV_IO_START, 0, 0,
2835 				      (uintptr_t)bdev_io, (uint64_t)bdev_io->type, bdev_io->internal.caller_ctx,
2836 				      bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks);
2837 		bdev_io_split(NULL, bdev_io);
2838 		return;
2839 	}
2840 
2841 	if (ch->flags & BDEV_CH_QOS_ENABLED) {
2842 		if ((thread == bdev->internal.qos->thread) || !bdev->internal.qos->thread) {
2843 			_bdev_io_submit(bdev_io);
2844 		} else {
2845 			bdev_io->internal.io_submit_ch = ch;
2846 			bdev_io->internal.ch = bdev->internal.qos->ch;
2847 			spdk_thread_send_msg(bdev->internal.qos->thread, _bdev_io_submit, bdev_io);
2848 		}
2849 	} else {
2850 		_bdev_io_submit(bdev_io);
2851 	}
2852 }
2853 
2854 static inline void
2855 _bdev_io_copy_ext_opts(struct spdk_bdev_io *bdev_io, struct spdk_bdev_ext_io_opts *opts)
2856 {
2857 	struct spdk_bdev_ext_io_opts *opts_copy = &bdev_io->internal.ext_opts_copy;
2858 
2859 	/* Zero part we don't copy */
2860 	memset(((char *)opts_copy) + opts->size, 0, sizeof(*opts) - opts->size);
2861 	memcpy(opts_copy, opts, opts->size);
2862 	opts_copy->size = sizeof(*opts_copy);
2863 	opts_copy->metadata = bdev_io->u.bdev.md_buf;
2864 	/* Save pointer to the copied ext_opts which will be used by bdev modules */
2865 	bdev_io->u.bdev.ext_opts = opts_copy;
2866 }
2867 
2868 static inline void
2869 _bdev_io_ext_use_bounce_buffer(struct spdk_bdev_io *bdev_io)
2870 {
2871 	/* bdev doesn't support memory domains, thereby buffers in this IO request can't
2872 	 * be accessed directly. It is needed to allocate buffers before issuing IO operation.
2873 	 * For write operation we need to pull buffers from memory domain before submitting IO.
2874 	 * Once read operation completes, we need to use memory_domain push functionality to
2875 	 * update data in original memory domain IO buffer
2876 	 * This IO request will go through a regular IO flow, so clear memory domains pointers in
2877 	 * the copied ext_opts */
2878 	bdev_io->internal.ext_opts_copy.memory_domain = NULL;
2879 	bdev_io->internal.ext_opts_copy.memory_domain_ctx = NULL;
2880 	_bdev_memory_domain_io_get_buf(bdev_io, _bdev_memory_domain_get_io_cb,
2881 				       bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
2882 }
2883 
2884 static inline void
2885 _bdev_io_submit_ext(struct spdk_bdev_desc *desc, struct spdk_bdev_io *bdev_io,
2886 		    struct spdk_bdev_ext_io_opts *opts, bool copy_opts)
2887 {
2888 	if (opts) {
2889 		bool use_pull_push = opts->memory_domain && !desc->memory_domains_supported;
2890 		assert(opts->size <= sizeof(*opts));
2891 		/*
2892 		 * copy if size is smaller than opts struct to avoid having to check size
2893 		 * on every access to bdev_io->u.bdev.ext_opts
2894 		 */
2895 		if (copy_opts || use_pull_push || opts->size < sizeof(*opts)) {
2896 			_bdev_io_copy_ext_opts(bdev_io, opts);
2897 			if (use_pull_push) {
2898 				_bdev_io_ext_use_bounce_buffer(bdev_io);
2899 				return;
2900 			}
2901 		}
2902 	}
2903 	bdev_io_submit(bdev_io);
2904 }
2905 
2906 static void
2907 bdev_io_submit_reset(struct spdk_bdev_io *bdev_io)
2908 {
2909 	struct spdk_bdev *bdev = bdev_io->bdev;
2910 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
2911 	struct spdk_io_channel *ch = bdev_ch->channel;
2912 
2913 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
2914 
2915 	bdev_io->internal.in_submit_request = true;
2916 	bdev->fn_table->submit_request(ch, bdev_io);
2917 	bdev_io->internal.in_submit_request = false;
2918 }
2919 
2920 void
2921 bdev_io_init(struct spdk_bdev_io *bdev_io,
2922 	     struct spdk_bdev *bdev, void *cb_arg,
2923 	     spdk_bdev_io_completion_cb cb)
2924 {
2925 	bdev_io->bdev = bdev;
2926 	bdev_io->internal.caller_ctx = cb_arg;
2927 	bdev_io->internal.cb = cb;
2928 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
2929 	bdev_io->internal.in_submit_request = false;
2930 	bdev_io->internal.buf = NULL;
2931 	bdev_io->internal.io_submit_ch = NULL;
2932 	bdev_io->internal.orig_iovs = NULL;
2933 	bdev_io->internal.orig_iovcnt = 0;
2934 	bdev_io->internal.orig_md_iov.iov_base = NULL;
2935 	bdev_io->internal.error.nvme.cdw0 = 0;
2936 	bdev_io->num_retries = 0;
2937 	bdev_io->internal.get_buf_cb = NULL;
2938 	bdev_io->internal.get_aux_buf_cb = NULL;
2939 	bdev_io->internal.ext_opts = NULL;
2940 	bdev_io->internal.data_transfer_cpl = NULL;
2941 }
2942 
2943 static bool
2944 bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
2945 {
2946 	return bdev->fn_table->io_type_supported(bdev->ctxt, io_type);
2947 }
2948 
2949 bool
2950 spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
2951 {
2952 	bool supported;
2953 
2954 	supported = bdev_io_type_supported(bdev, io_type);
2955 
2956 	if (!supported) {
2957 		switch (io_type) {
2958 		case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2959 			/* The bdev layer will emulate write zeroes as long as write is supported. */
2960 			supported = bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
2961 			break;
2962 		default:
2963 			break;
2964 		}
2965 	}
2966 
2967 	return supported;
2968 }
2969 
2970 int
2971 spdk_bdev_dump_info_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
2972 {
2973 	if (bdev->fn_table->dump_info_json) {
2974 		return bdev->fn_table->dump_info_json(bdev->ctxt, w);
2975 	}
2976 
2977 	return 0;
2978 }
2979 
2980 static void
2981 bdev_qos_update_max_quota_per_timeslice(struct spdk_bdev_qos *qos)
2982 {
2983 	uint32_t max_per_timeslice = 0;
2984 	int i;
2985 
2986 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2987 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
2988 			qos->rate_limits[i].max_per_timeslice = 0;
2989 			continue;
2990 		}
2991 
2992 		max_per_timeslice = qos->rate_limits[i].limit *
2993 				    SPDK_BDEV_QOS_TIMESLICE_IN_USEC / SPDK_SEC_TO_USEC;
2994 
2995 		qos->rate_limits[i].max_per_timeslice = spdk_max(max_per_timeslice,
2996 							qos->rate_limits[i].min_per_timeslice);
2997 
2998 		qos->rate_limits[i].remaining_this_timeslice = qos->rate_limits[i].max_per_timeslice;
2999 	}
3000 
3001 	bdev_qos_set_ops(qos);
3002 }
3003 
3004 static int
3005 bdev_channel_poll_qos(void *arg)
3006 {
3007 	struct spdk_bdev_qos *qos = arg;
3008 	uint64_t now = spdk_get_ticks();
3009 	int i;
3010 
3011 	if (now < (qos->last_timeslice + qos->timeslice_size)) {
3012 		/* We received our callback earlier than expected - return
3013 		 *  immediately and wait to do accounting until at least one
3014 		 *  timeslice has actually expired.  This should never happen
3015 		 *  with a well-behaved timer implementation.
3016 		 */
3017 		return SPDK_POLLER_IDLE;
3018 	}
3019 
3020 	/* Reset for next round of rate limiting */
3021 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3022 		/* We may have allowed the IOs or bytes to slightly overrun in the last
3023 		 * timeslice. remaining_this_timeslice is signed, so if it's negative
3024 		 * here, we'll account for the overrun so that the next timeslice will
3025 		 * be appropriately reduced.
3026 		 */
3027 		if (qos->rate_limits[i].remaining_this_timeslice > 0) {
3028 			qos->rate_limits[i].remaining_this_timeslice = 0;
3029 		}
3030 	}
3031 
3032 	while (now >= (qos->last_timeslice + qos->timeslice_size)) {
3033 		qos->last_timeslice += qos->timeslice_size;
3034 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3035 			qos->rate_limits[i].remaining_this_timeslice +=
3036 				qos->rate_limits[i].max_per_timeslice;
3037 		}
3038 	}
3039 
3040 	return bdev_qos_io_submit(qos->ch, qos);
3041 }
3042 
3043 static void
3044 bdev_channel_destroy_resource(struct spdk_bdev_channel *ch)
3045 {
3046 	struct spdk_bdev_shared_resource *shared_resource;
3047 	struct lba_range *range;
3048 
3049 	while (!TAILQ_EMPTY(&ch->locked_ranges)) {
3050 		range = TAILQ_FIRST(&ch->locked_ranges);
3051 		TAILQ_REMOVE(&ch->locked_ranges, range, tailq);
3052 		free(range);
3053 	}
3054 
3055 	spdk_put_io_channel(ch->channel);
3056 
3057 	shared_resource = ch->shared_resource;
3058 
3059 	assert(TAILQ_EMPTY(&ch->io_locked));
3060 	assert(TAILQ_EMPTY(&ch->io_submitted));
3061 	assert(ch->io_outstanding == 0);
3062 	assert(shared_resource->ref > 0);
3063 	shared_resource->ref--;
3064 	if (shared_resource->ref == 0) {
3065 		assert(shared_resource->io_outstanding == 0);
3066 		TAILQ_REMOVE(&shared_resource->mgmt_ch->shared_resources, shared_resource, link);
3067 		spdk_put_io_channel(spdk_io_channel_from_ctx(shared_resource->mgmt_ch));
3068 		free(shared_resource);
3069 	}
3070 }
3071 
3072 /* Caller must hold bdev->internal.mutex. */
3073 static void
3074 bdev_enable_qos(struct spdk_bdev *bdev, struct spdk_bdev_channel *ch)
3075 {
3076 	struct spdk_bdev_qos	*qos = bdev->internal.qos;
3077 	int			i;
3078 
3079 	/* Rate limiting on this bdev enabled */
3080 	if (qos) {
3081 		if (qos->ch == NULL) {
3082 			struct spdk_io_channel *io_ch;
3083 
3084 			SPDK_DEBUGLOG(bdev, "Selecting channel %p as QoS channel for bdev %s on thread %p\n", ch,
3085 				      bdev->name, spdk_get_thread());
3086 
3087 			/* No qos channel has been selected, so set one up */
3088 
3089 			/* Take another reference to ch */
3090 			io_ch = spdk_get_io_channel(__bdev_to_io_dev(bdev));
3091 			assert(io_ch != NULL);
3092 			qos->ch = ch;
3093 
3094 			qos->thread = spdk_io_channel_get_thread(io_ch);
3095 
3096 			TAILQ_INIT(&qos->queued);
3097 
3098 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3099 				if (bdev_qos_is_iops_rate_limit(i) == true) {
3100 					qos->rate_limits[i].min_per_timeslice =
3101 						SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE;
3102 				} else {
3103 					qos->rate_limits[i].min_per_timeslice =
3104 						SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE;
3105 				}
3106 
3107 				if (qos->rate_limits[i].limit == 0) {
3108 					qos->rate_limits[i].limit = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
3109 				}
3110 			}
3111 			bdev_qos_update_max_quota_per_timeslice(qos);
3112 			qos->timeslice_size =
3113 				SPDK_BDEV_QOS_TIMESLICE_IN_USEC * spdk_get_ticks_hz() / SPDK_SEC_TO_USEC;
3114 			qos->last_timeslice = spdk_get_ticks();
3115 			qos->poller = SPDK_POLLER_REGISTER(bdev_channel_poll_qos,
3116 							   qos,
3117 							   SPDK_BDEV_QOS_TIMESLICE_IN_USEC);
3118 		}
3119 
3120 		ch->flags |= BDEV_CH_QOS_ENABLED;
3121 	}
3122 }
3123 
3124 struct poll_timeout_ctx {
3125 	struct spdk_bdev_desc	*desc;
3126 	uint64_t		timeout_in_sec;
3127 	spdk_bdev_io_timeout_cb	cb_fn;
3128 	void			*cb_arg;
3129 };
3130 
3131 static void
3132 bdev_desc_free(struct spdk_bdev_desc *desc)
3133 {
3134 	pthread_mutex_destroy(&desc->mutex);
3135 	free(desc->media_events_buffer);
3136 	free(desc);
3137 }
3138 
3139 static void
3140 bdev_channel_poll_timeout_io_done(struct spdk_io_channel_iter *i, int status)
3141 {
3142 	struct poll_timeout_ctx *ctx  = spdk_io_channel_iter_get_ctx(i);
3143 	struct spdk_bdev_desc *desc = ctx->desc;
3144 
3145 	free(ctx);
3146 
3147 	pthread_mutex_lock(&desc->mutex);
3148 	desc->refs--;
3149 	if (desc->closed == true && desc->refs == 0) {
3150 		pthread_mutex_unlock(&desc->mutex);
3151 		bdev_desc_free(desc);
3152 		return;
3153 	}
3154 	pthread_mutex_unlock(&desc->mutex);
3155 }
3156 
3157 static void
3158 bdev_channel_poll_timeout_io(struct spdk_io_channel_iter *i)
3159 {
3160 	struct poll_timeout_ctx *ctx  = spdk_io_channel_iter_get_ctx(i);
3161 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
3162 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(io_ch);
3163 	struct spdk_bdev_desc *desc = ctx->desc;
3164 	struct spdk_bdev_io *bdev_io;
3165 	uint64_t now;
3166 
3167 	pthread_mutex_lock(&desc->mutex);
3168 	if (desc->closed == true) {
3169 		pthread_mutex_unlock(&desc->mutex);
3170 		spdk_for_each_channel_continue(i, -1);
3171 		return;
3172 	}
3173 	pthread_mutex_unlock(&desc->mutex);
3174 
3175 	now = spdk_get_ticks();
3176 	TAILQ_FOREACH(bdev_io, &bdev_ch->io_submitted, internal.ch_link) {
3177 		/* Exclude any I/O that are generated via splitting. */
3178 		if (bdev_io->internal.cb == bdev_io_split_done) {
3179 			continue;
3180 		}
3181 
3182 		/* Once we find an I/O that has not timed out, we can immediately
3183 		 * exit the loop.
3184 		 */
3185 		if (now < (bdev_io->internal.submit_tsc +
3186 			   ctx->timeout_in_sec * spdk_get_ticks_hz())) {
3187 			goto end;
3188 		}
3189 
3190 		if (bdev_io->internal.desc == desc) {
3191 			ctx->cb_fn(ctx->cb_arg, bdev_io);
3192 		}
3193 	}
3194 
3195 end:
3196 	spdk_for_each_channel_continue(i, 0);
3197 }
3198 
3199 static int
3200 bdev_poll_timeout_io(void *arg)
3201 {
3202 	struct spdk_bdev_desc *desc = arg;
3203 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3204 	struct poll_timeout_ctx *ctx;
3205 
3206 	ctx = calloc(1, sizeof(struct poll_timeout_ctx));
3207 	if (!ctx) {
3208 		SPDK_ERRLOG("failed to allocate memory\n");
3209 		return SPDK_POLLER_BUSY;
3210 	}
3211 	ctx->desc = desc;
3212 	ctx->cb_arg = desc->cb_arg;
3213 	ctx->cb_fn = desc->cb_fn;
3214 	ctx->timeout_in_sec = desc->timeout_in_sec;
3215 
3216 	/* Take a ref on the descriptor in case it gets closed while we are checking
3217 	 * all of the channels.
3218 	 */
3219 	pthread_mutex_lock(&desc->mutex);
3220 	desc->refs++;
3221 	pthread_mutex_unlock(&desc->mutex);
3222 
3223 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
3224 			      bdev_channel_poll_timeout_io,
3225 			      ctx,
3226 			      bdev_channel_poll_timeout_io_done);
3227 
3228 	return SPDK_POLLER_BUSY;
3229 }
3230 
3231 int
3232 spdk_bdev_set_timeout(struct spdk_bdev_desc *desc, uint64_t timeout_in_sec,
3233 		      spdk_bdev_io_timeout_cb cb_fn, void *cb_arg)
3234 {
3235 	assert(desc->thread == spdk_get_thread());
3236 
3237 	spdk_poller_unregister(&desc->io_timeout_poller);
3238 
3239 	if (timeout_in_sec) {
3240 		assert(cb_fn != NULL);
3241 		desc->io_timeout_poller = SPDK_POLLER_REGISTER(bdev_poll_timeout_io,
3242 					  desc,
3243 					  SPDK_BDEV_IO_POLL_INTERVAL_IN_MSEC * SPDK_SEC_TO_USEC /
3244 					  1000);
3245 		if (desc->io_timeout_poller == NULL) {
3246 			SPDK_ERRLOG("can not register the desc timeout IO poller\n");
3247 			return -1;
3248 		}
3249 	}
3250 
3251 	desc->cb_fn = cb_fn;
3252 	desc->cb_arg = cb_arg;
3253 	desc->timeout_in_sec = timeout_in_sec;
3254 
3255 	return 0;
3256 }
3257 
3258 static int
3259 bdev_channel_create(void *io_device, void *ctx_buf)
3260 {
3261 	struct spdk_bdev		*bdev = __bdev_from_io_dev(io_device);
3262 	struct spdk_bdev_channel	*ch = ctx_buf;
3263 	struct spdk_io_channel		*mgmt_io_ch;
3264 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
3265 	struct spdk_bdev_shared_resource *shared_resource;
3266 	struct lba_range		*range;
3267 
3268 	ch->bdev = bdev;
3269 	ch->channel = bdev->fn_table->get_io_channel(bdev->ctxt);
3270 	if (!ch->channel) {
3271 		return -1;
3272 	}
3273 
3274 	spdk_trace_record(TRACE_BDEV_IOCH_CREATE, 0, 0, 0, ch->bdev->name,
3275 			  spdk_thread_get_id(spdk_io_channel_get_thread(ch->channel)));
3276 
3277 	assert(ch->histogram == NULL);
3278 	if (bdev->internal.histogram_enabled) {
3279 		ch->histogram = spdk_histogram_data_alloc();
3280 		if (ch->histogram == NULL) {
3281 			SPDK_ERRLOG("Could not allocate histogram\n");
3282 		}
3283 	}
3284 
3285 	mgmt_io_ch = spdk_get_io_channel(&g_bdev_mgr);
3286 	if (!mgmt_io_ch) {
3287 		spdk_put_io_channel(ch->channel);
3288 		return -1;
3289 	}
3290 
3291 	mgmt_ch = spdk_io_channel_get_ctx(mgmt_io_ch);
3292 	TAILQ_FOREACH(shared_resource, &mgmt_ch->shared_resources, link) {
3293 		if (shared_resource->shared_ch == ch->channel) {
3294 			spdk_put_io_channel(mgmt_io_ch);
3295 			shared_resource->ref++;
3296 			break;
3297 		}
3298 	}
3299 
3300 	if (shared_resource == NULL) {
3301 		shared_resource = calloc(1, sizeof(*shared_resource));
3302 		if (shared_resource == NULL) {
3303 			spdk_put_io_channel(ch->channel);
3304 			spdk_put_io_channel(mgmt_io_ch);
3305 			return -1;
3306 		}
3307 
3308 		shared_resource->mgmt_ch = mgmt_ch;
3309 		shared_resource->io_outstanding = 0;
3310 		TAILQ_INIT(&shared_resource->nomem_io);
3311 		shared_resource->nomem_threshold = 0;
3312 		shared_resource->shared_ch = ch->channel;
3313 		shared_resource->ref = 1;
3314 		TAILQ_INSERT_TAIL(&mgmt_ch->shared_resources, shared_resource, link);
3315 	}
3316 
3317 	memset(&ch->stat, 0, sizeof(ch->stat));
3318 	ch->stat.ticks_rate = spdk_get_ticks_hz();
3319 	ch->io_outstanding = 0;
3320 	TAILQ_INIT(&ch->queued_resets);
3321 	TAILQ_INIT(&ch->locked_ranges);
3322 	ch->flags = 0;
3323 	ch->shared_resource = shared_resource;
3324 
3325 	TAILQ_INIT(&ch->io_submitted);
3326 	TAILQ_INIT(&ch->io_locked);
3327 
3328 #ifdef SPDK_CONFIG_VTUNE
3329 	{
3330 		char *name;
3331 		__itt_init_ittlib(NULL, 0);
3332 		name = spdk_sprintf_alloc("spdk_bdev_%s_%p", ch->bdev->name, ch);
3333 		if (!name) {
3334 			bdev_channel_destroy_resource(ch);
3335 			return -1;
3336 		}
3337 		ch->handle = __itt_string_handle_create(name);
3338 		free(name);
3339 		ch->start_tsc = spdk_get_ticks();
3340 		ch->interval_tsc = spdk_get_ticks_hz() / 100;
3341 		memset(&ch->prev_stat, 0, sizeof(ch->prev_stat));
3342 	}
3343 #endif
3344 
3345 	pthread_mutex_lock(&bdev->internal.mutex);
3346 	bdev_enable_qos(bdev, ch);
3347 
3348 	TAILQ_FOREACH(range, &bdev->internal.locked_ranges, tailq) {
3349 		struct lba_range *new_range;
3350 
3351 		new_range = calloc(1, sizeof(*new_range));
3352 		if (new_range == NULL) {
3353 			pthread_mutex_unlock(&bdev->internal.mutex);
3354 			bdev_channel_destroy_resource(ch);
3355 			return -1;
3356 		}
3357 		new_range->length = range->length;
3358 		new_range->offset = range->offset;
3359 		new_range->locked_ctx = range->locked_ctx;
3360 		TAILQ_INSERT_TAIL(&ch->locked_ranges, new_range, tailq);
3361 	}
3362 
3363 	pthread_mutex_unlock(&bdev->internal.mutex);
3364 
3365 	return 0;
3366 }
3367 
3368 /*
3369  * Abort I/O that are waiting on a data buffer.  These types of I/O are
3370  *  linked using the spdk_bdev_io internal.buf_link TAILQ_ENTRY.
3371  */
3372 static void
3373 bdev_abort_all_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_channel *ch)
3374 {
3375 	bdev_io_stailq_t tmp;
3376 	struct spdk_bdev_io *bdev_io;
3377 
3378 	STAILQ_INIT(&tmp);
3379 
3380 	while (!STAILQ_EMPTY(queue)) {
3381 		bdev_io = STAILQ_FIRST(queue);
3382 		STAILQ_REMOVE_HEAD(queue, internal.buf_link);
3383 		if (bdev_io->internal.ch == ch) {
3384 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
3385 		} else {
3386 			STAILQ_INSERT_TAIL(&tmp, bdev_io, internal.buf_link);
3387 		}
3388 	}
3389 
3390 	STAILQ_SWAP(&tmp, queue, spdk_bdev_io);
3391 }
3392 
3393 /*
3394  * Abort I/O that are queued waiting for submission.  These types of I/O are
3395  *  linked using the spdk_bdev_io link TAILQ_ENTRY.
3396  */
3397 static void
3398 bdev_abort_all_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_channel *ch)
3399 {
3400 	struct spdk_bdev_io *bdev_io, *tmp;
3401 
3402 	TAILQ_FOREACH_SAFE(bdev_io, queue, internal.link, tmp) {
3403 		if (bdev_io->internal.ch == ch) {
3404 			TAILQ_REMOVE(queue, bdev_io, internal.link);
3405 			/*
3406 			 * spdk_bdev_io_complete() assumes that the completed I/O had
3407 			 *  been submitted to the bdev module.  Since in this case it
3408 			 *  hadn't, bump io_outstanding to account for the decrement
3409 			 *  that spdk_bdev_io_complete() will do.
3410 			 */
3411 			if (bdev_io->type != SPDK_BDEV_IO_TYPE_RESET) {
3412 				ch->io_outstanding++;
3413 				ch->shared_resource->io_outstanding++;
3414 			}
3415 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
3416 		}
3417 	}
3418 }
3419 
3420 static bool
3421 bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_io *bio_to_abort)
3422 {
3423 	struct spdk_bdev_io *bdev_io;
3424 
3425 	TAILQ_FOREACH(bdev_io, queue, internal.link) {
3426 		if (bdev_io == bio_to_abort) {
3427 			TAILQ_REMOVE(queue, bio_to_abort, internal.link);
3428 			spdk_bdev_io_complete(bio_to_abort, SPDK_BDEV_IO_STATUS_ABORTED);
3429 			return true;
3430 		}
3431 	}
3432 
3433 	return false;
3434 }
3435 
3436 static bool
3437 bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_io *bio_to_abort)
3438 {
3439 	struct spdk_bdev_io *bdev_io;
3440 
3441 	STAILQ_FOREACH(bdev_io, queue, internal.buf_link) {
3442 		if (bdev_io == bio_to_abort) {
3443 			STAILQ_REMOVE(queue, bio_to_abort, spdk_bdev_io, internal.buf_link);
3444 			spdk_bdev_io_complete(bio_to_abort, SPDK_BDEV_IO_STATUS_ABORTED);
3445 			return true;
3446 		}
3447 	}
3448 
3449 	return false;
3450 }
3451 
3452 static void
3453 bdev_qos_channel_destroy(void *cb_arg)
3454 {
3455 	struct spdk_bdev_qos *qos = cb_arg;
3456 
3457 	spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
3458 	spdk_poller_unregister(&qos->poller);
3459 
3460 	SPDK_DEBUGLOG(bdev, "Free QoS %p.\n", qos);
3461 
3462 	free(qos);
3463 }
3464 
3465 static int
3466 bdev_qos_destroy(struct spdk_bdev *bdev)
3467 {
3468 	int i;
3469 
3470 	/*
3471 	 * Cleanly shutting down the QoS poller is tricky, because
3472 	 * during the asynchronous operation the user could open
3473 	 * a new descriptor and create a new channel, spawning
3474 	 * a new QoS poller.
3475 	 *
3476 	 * The strategy is to create a new QoS structure here and swap it
3477 	 * in. The shutdown path then continues to refer to the old one
3478 	 * until it completes and then releases it.
3479 	 */
3480 	struct spdk_bdev_qos *new_qos, *old_qos;
3481 
3482 	old_qos = bdev->internal.qos;
3483 
3484 	new_qos = calloc(1, sizeof(*new_qos));
3485 	if (!new_qos) {
3486 		SPDK_ERRLOG("Unable to allocate memory to shut down QoS.\n");
3487 		return -ENOMEM;
3488 	}
3489 
3490 	/* Copy the old QoS data into the newly allocated structure */
3491 	memcpy(new_qos, old_qos, sizeof(*new_qos));
3492 
3493 	/* Zero out the key parts of the QoS structure */
3494 	new_qos->ch = NULL;
3495 	new_qos->thread = NULL;
3496 	new_qos->poller = NULL;
3497 	TAILQ_INIT(&new_qos->queued);
3498 	/*
3499 	 * The limit member of spdk_bdev_qos_limit structure is not zeroed.
3500 	 * It will be used later for the new QoS structure.
3501 	 */
3502 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3503 		new_qos->rate_limits[i].remaining_this_timeslice = 0;
3504 		new_qos->rate_limits[i].min_per_timeslice = 0;
3505 		new_qos->rate_limits[i].max_per_timeslice = 0;
3506 	}
3507 
3508 	bdev->internal.qos = new_qos;
3509 
3510 	if (old_qos->thread == NULL) {
3511 		free(old_qos);
3512 	} else {
3513 		spdk_thread_send_msg(old_qos->thread, bdev_qos_channel_destroy, old_qos);
3514 	}
3515 
3516 	/* It is safe to continue with destroying the bdev even though the QoS channel hasn't
3517 	 * been destroyed yet. The destruction path will end up waiting for the final
3518 	 * channel to be put before it releases resources. */
3519 
3520 	return 0;
3521 }
3522 
3523 static void
3524 bdev_io_stat_add(struct spdk_bdev_io_stat *total, struct spdk_bdev_io_stat *add)
3525 {
3526 	total->bytes_read += add->bytes_read;
3527 	total->num_read_ops += add->num_read_ops;
3528 	total->bytes_written += add->bytes_written;
3529 	total->num_write_ops += add->num_write_ops;
3530 	total->bytes_unmapped += add->bytes_unmapped;
3531 	total->num_unmap_ops += add->num_unmap_ops;
3532 	total->read_latency_ticks += add->read_latency_ticks;
3533 	total->write_latency_ticks += add->write_latency_ticks;
3534 	total->unmap_latency_ticks += add->unmap_latency_ticks;
3535 }
3536 
3537 static void
3538 bdev_channel_abort_queued_ios(struct spdk_bdev_channel *ch)
3539 {
3540 	struct spdk_bdev_shared_resource *shared_resource = ch->shared_resource;
3541 	struct spdk_bdev_mgmt_channel *mgmt_ch = shared_resource->mgmt_ch;
3542 
3543 	bdev_abort_all_queued_io(&shared_resource->nomem_io, ch);
3544 	bdev_abort_all_buf_io(&mgmt_ch->need_buf_small, ch);
3545 	bdev_abort_all_buf_io(&mgmt_ch->need_buf_large, ch);
3546 }
3547 
3548 static void
3549 bdev_channel_destroy(void *io_device, void *ctx_buf)
3550 {
3551 	struct spdk_bdev_channel *ch = ctx_buf;
3552 
3553 	SPDK_DEBUGLOG(bdev, "Destroying channel %p for bdev %s on thread %p\n", ch, ch->bdev->name,
3554 		      spdk_get_thread());
3555 
3556 	spdk_trace_record(TRACE_BDEV_IOCH_DESTROY, 0, 0, 0, ch->bdev->name,
3557 			  spdk_thread_get_id(spdk_io_channel_get_thread(ch->channel)));
3558 
3559 	/* This channel is going away, so add its statistics into the bdev so that they don't get lost. */
3560 	pthread_mutex_lock(&ch->bdev->internal.mutex);
3561 	bdev_io_stat_add(&ch->bdev->internal.stat, &ch->stat);
3562 	pthread_mutex_unlock(&ch->bdev->internal.mutex);
3563 
3564 	bdev_abort_all_queued_io(&ch->queued_resets, ch);
3565 
3566 	bdev_channel_abort_queued_ios(ch);
3567 
3568 	if (ch->histogram) {
3569 		spdk_histogram_data_free(ch->histogram);
3570 	}
3571 
3572 	bdev_channel_destroy_resource(ch);
3573 }
3574 
3575 /*
3576  * If the name already exists in the global bdev name tree, RB_INSERT() returns a pointer
3577  * to it. Hence we do not have to call bdev_get_by_name() when using this function.
3578  */
3579 static int
3580 bdev_name_add(struct spdk_bdev_name *bdev_name, struct spdk_bdev *bdev, const char *name)
3581 {
3582 	struct spdk_bdev_name *tmp;
3583 
3584 	bdev_name->name = strdup(name);
3585 	if (bdev_name->name == NULL) {
3586 		SPDK_ERRLOG("Unable to allocate bdev name\n");
3587 		return -ENOMEM;
3588 	}
3589 
3590 	bdev_name->bdev = bdev;
3591 
3592 	pthread_mutex_lock(&g_bdev_mgr.mutex);
3593 	tmp = RB_INSERT(bdev_name_tree, &g_bdev_mgr.bdev_names, bdev_name);
3594 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
3595 
3596 	if (tmp != NULL) {
3597 		SPDK_ERRLOG("Bdev name %s already exists\n", name);
3598 		free(bdev_name->name);
3599 		return -EEXIST;
3600 	}
3601 
3602 	return 0;
3603 }
3604 
3605 static void
3606 bdev_name_del_unsafe(struct spdk_bdev_name *bdev_name)
3607 {
3608 	RB_REMOVE(bdev_name_tree, &g_bdev_mgr.bdev_names, bdev_name);
3609 	free(bdev_name->name);
3610 }
3611 
3612 static void
3613 bdev_name_del(struct spdk_bdev_name *bdev_name)
3614 {
3615 	pthread_mutex_lock(&g_bdev_mgr.mutex);
3616 	bdev_name_del_unsafe(bdev_name);
3617 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
3618 }
3619 
3620 int
3621 spdk_bdev_alias_add(struct spdk_bdev *bdev, const char *alias)
3622 {
3623 	struct spdk_bdev_alias *tmp;
3624 	int ret;
3625 
3626 	if (alias == NULL) {
3627 		SPDK_ERRLOG("Empty alias passed\n");
3628 		return -EINVAL;
3629 	}
3630 
3631 	tmp = calloc(1, sizeof(*tmp));
3632 	if (tmp == NULL) {
3633 		SPDK_ERRLOG("Unable to allocate alias\n");
3634 		return -ENOMEM;
3635 	}
3636 
3637 	ret = bdev_name_add(&tmp->alias, bdev, alias);
3638 	if (ret != 0) {
3639 		free(tmp);
3640 		return ret;
3641 	}
3642 
3643 	TAILQ_INSERT_TAIL(&bdev->aliases, tmp, tailq);
3644 
3645 	return 0;
3646 }
3647 
3648 static int
3649 bdev_alias_del(struct spdk_bdev *bdev, const char *alias,
3650 	       void (*alias_del_fn)(struct spdk_bdev_name *n))
3651 {
3652 	struct spdk_bdev_alias *tmp;
3653 
3654 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
3655 		if (strcmp(alias, tmp->alias.name) == 0) {
3656 			TAILQ_REMOVE(&bdev->aliases, tmp, tailq);
3657 			alias_del_fn(&tmp->alias);
3658 			free(tmp);
3659 			return 0;
3660 		}
3661 	}
3662 
3663 	return -ENOENT;
3664 }
3665 
3666 int
3667 spdk_bdev_alias_del(struct spdk_bdev *bdev, const char *alias)
3668 {
3669 	int rc;
3670 
3671 	rc = bdev_alias_del(bdev, alias, bdev_name_del);
3672 	if (rc == -ENOENT) {
3673 		SPDK_INFOLOG(bdev, "Alias %s does not exist\n", alias);
3674 	}
3675 
3676 	return rc;
3677 }
3678 
3679 void
3680 spdk_bdev_alias_del_all(struct spdk_bdev *bdev)
3681 {
3682 	struct spdk_bdev_alias *p, *tmp;
3683 
3684 	TAILQ_FOREACH_SAFE(p, &bdev->aliases, tailq, tmp) {
3685 		TAILQ_REMOVE(&bdev->aliases, p, tailq);
3686 		bdev_name_del(&p->alias);
3687 		free(p);
3688 	}
3689 }
3690 
3691 struct spdk_io_channel *
3692 spdk_bdev_get_io_channel(struct spdk_bdev_desc *desc)
3693 {
3694 	return spdk_get_io_channel(__bdev_to_io_dev(spdk_bdev_desc_get_bdev(desc)));
3695 }
3696 
3697 void *
3698 spdk_bdev_get_module_ctx(struct spdk_bdev_desc *desc)
3699 {
3700 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3701 	void *ctx = NULL;
3702 
3703 	if (bdev->fn_table->get_module_ctx) {
3704 		ctx = bdev->fn_table->get_module_ctx(bdev->ctxt);
3705 	}
3706 
3707 	return ctx;
3708 }
3709 
3710 const char *
3711 spdk_bdev_get_module_name(const struct spdk_bdev *bdev)
3712 {
3713 	return bdev->module->name;
3714 }
3715 
3716 const char *
3717 spdk_bdev_get_name(const struct spdk_bdev *bdev)
3718 {
3719 	return bdev->name;
3720 }
3721 
3722 const char *
3723 spdk_bdev_get_product_name(const struct spdk_bdev *bdev)
3724 {
3725 	return bdev->product_name;
3726 }
3727 
3728 const struct spdk_bdev_aliases_list *
3729 spdk_bdev_get_aliases(const struct spdk_bdev *bdev)
3730 {
3731 	return &bdev->aliases;
3732 }
3733 
3734 uint32_t
3735 spdk_bdev_get_block_size(const struct spdk_bdev *bdev)
3736 {
3737 	return bdev->blocklen;
3738 }
3739 
3740 uint32_t
3741 spdk_bdev_get_write_unit_size(const struct spdk_bdev *bdev)
3742 {
3743 	return bdev->write_unit_size;
3744 }
3745 
3746 uint64_t
3747 spdk_bdev_get_num_blocks(const struct spdk_bdev *bdev)
3748 {
3749 	return bdev->blockcnt;
3750 }
3751 
3752 const char *
3753 spdk_bdev_get_qos_rpc_type(enum spdk_bdev_qos_rate_limit_type type)
3754 {
3755 	return qos_rpc_type[type];
3756 }
3757 
3758 void
3759 spdk_bdev_get_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
3760 {
3761 	int i;
3762 
3763 	memset(limits, 0, sizeof(*limits) * SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
3764 
3765 	pthread_mutex_lock(&bdev->internal.mutex);
3766 	if (bdev->internal.qos) {
3767 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3768 			if (bdev->internal.qos->rate_limits[i].limit !=
3769 			    SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3770 				limits[i] = bdev->internal.qos->rate_limits[i].limit;
3771 				if (bdev_qos_is_iops_rate_limit(i) == false) {
3772 					/* Change from Byte to Megabyte which is user visible. */
3773 					limits[i] = limits[i] / 1024 / 1024;
3774 				}
3775 			}
3776 		}
3777 	}
3778 	pthread_mutex_unlock(&bdev->internal.mutex);
3779 }
3780 
3781 size_t
3782 spdk_bdev_get_buf_align(const struct spdk_bdev *bdev)
3783 {
3784 	return 1 << bdev->required_alignment;
3785 }
3786 
3787 uint32_t
3788 spdk_bdev_get_optimal_io_boundary(const struct spdk_bdev *bdev)
3789 {
3790 	return bdev->optimal_io_boundary;
3791 }
3792 
3793 bool
3794 spdk_bdev_has_write_cache(const struct spdk_bdev *bdev)
3795 {
3796 	return bdev->write_cache;
3797 }
3798 
3799 const struct spdk_uuid *
3800 spdk_bdev_get_uuid(const struct spdk_bdev *bdev)
3801 {
3802 	return &bdev->uuid;
3803 }
3804 
3805 uint16_t
3806 spdk_bdev_get_acwu(const struct spdk_bdev *bdev)
3807 {
3808 	return bdev->acwu;
3809 }
3810 
3811 uint32_t
3812 spdk_bdev_get_md_size(const struct spdk_bdev *bdev)
3813 {
3814 	return bdev->md_len;
3815 }
3816 
3817 bool
3818 spdk_bdev_is_md_interleaved(const struct spdk_bdev *bdev)
3819 {
3820 	return (bdev->md_len != 0) && bdev->md_interleave;
3821 }
3822 
3823 bool
3824 spdk_bdev_is_md_separate(const struct spdk_bdev *bdev)
3825 {
3826 	return (bdev->md_len != 0) && !bdev->md_interleave;
3827 }
3828 
3829 bool
3830 spdk_bdev_is_zoned(const struct spdk_bdev *bdev)
3831 {
3832 	return bdev->zoned;
3833 }
3834 
3835 uint32_t
3836 spdk_bdev_get_data_block_size(const struct spdk_bdev *bdev)
3837 {
3838 	if (spdk_bdev_is_md_interleaved(bdev)) {
3839 		return bdev->blocklen - bdev->md_len;
3840 	} else {
3841 		return bdev->blocklen;
3842 	}
3843 }
3844 
3845 uint32_t
3846 spdk_bdev_get_physical_block_size(const struct spdk_bdev *bdev)
3847 {
3848 	return bdev->phys_blocklen;
3849 }
3850 
3851 static uint32_t
3852 _bdev_get_block_size_with_md(const struct spdk_bdev *bdev)
3853 {
3854 	if (!spdk_bdev_is_md_interleaved(bdev)) {
3855 		return bdev->blocklen + bdev->md_len;
3856 	} else {
3857 		return bdev->blocklen;
3858 	}
3859 }
3860 
3861 /* We have to use the typedef in the function declaration to appease astyle. */
3862 typedef enum spdk_dif_type spdk_dif_type_t;
3863 
3864 spdk_dif_type_t
3865 spdk_bdev_get_dif_type(const struct spdk_bdev *bdev)
3866 {
3867 	if (bdev->md_len != 0) {
3868 		return bdev->dif_type;
3869 	} else {
3870 		return SPDK_DIF_DISABLE;
3871 	}
3872 }
3873 
3874 bool
3875 spdk_bdev_is_dif_head_of_md(const struct spdk_bdev *bdev)
3876 {
3877 	if (spdk_bdev_get_dif_type(bdev) != SPDK_DIF_DISABLE) {
3878 		return bdev->dif_is_head_of_md;
3879 	} else {
3880 		return false;
3881 	}
3882 }
3883 
3884 bool
3885 spdk_bdev_is_dif_check_enabled(const struct spdk_bdev *bdev,
3886 			       enum spdk_dif_check_type check_type)
3887 {
3888 	if (spdk_bdev_get_dif_type(bdev) == SPDK_DIF_DISABLE) {
3889 		return false;
3890 	}
3891 
3892 	switch (check_type) {
3893 	case SPDK_DIF_CHECK_TYPE_REFTAG:
3894 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_REFTAG_CHECK) != 0;
3895 	case SPDK_DIF_CHECK_TYPE_APPTAG:
3896 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_APPTAG_CHECK) != 0;
3897 	case SPDK_DIF_CHECK_TYPE_GUARD:
3898 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_GUARD_CHECK) != 0;
3899 	default:
3900 		return false;
3901 	}
3902 }
3903 
3904 uint64_t
3905 spdk_bdev_get_qd(const struct spdk_bdev *bdev)
3906 {
3907 	return bdev->internal.measured_queue_depth;
3908 }
3909 
3910 uint64_t
3911 spdk_bdev_get_qd_sampling_period(const struct spdk_bdev *bdev)
3912 {
3913 	return bdev->internal.period;
3914 }
3915 
3916 uint64_t
3917 spdk_bdev_get_weighted_io_time(const struct spdk_bdev *bdev)
3918 {
3919 	return bdev->internal.weighted_io_time;
3920 }
3921 
3922 uint64_t
3923 spdk_bdev_get_io_time(const struct spdk_bdev *bdev)
3924 {
3925 	return bdev->internal.io_time;
3926 }
3927 
3928 static void
3929 _calculate_measured_qd_cpl(struct spdk_io_channel_iter *i, int status)
3930 {
3931 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
3932 
3933 	bdev->internal.measured_queue_depth = bdev->internal.temporary_queue_depth;
3934 
3935 	if (bdev->internal.measured_queue_depth) {
3936 		bdev->internal.io_time += bdev->internal.period;
3937 		bdev->internal.weighted_io_time += bdev->internal.period * bdev->internal.measured_queue_depth;
3938 	}
3939 }
3940 
3941 static void
3942 _calculate_measured_qd(struct spdk_io_channel_iter *i)
3943 {
3944 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
3945 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
3946 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(io_ch);
3947 
3948 	bdev->internal.temporary_queue_depth += ch->io_outstanding;
3949 	spdk_for_each_channel_continue(i, 0);
3950 }
3951 
3952 static int
3953 bdev_calculate_measured_queue_depth(void *ctx)
3954 {
3955 	struct spdk_bdev *bdev = ctx;
3956 	bdev->internal.temporary_queue_depth = 0;
3957 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _calculate_measured_qd, bdev,
3958 			      _calculate_measured_qd_cpl);
3959 	return SPDK_POLLER_BUSY;
3960 }
3961 
3962 void
3963 spdk_bdev_set_qd_sampling_period(struct spdk_bdev *bdev, uint64_t period)
3964 {
3965 	bdev->internal.period = period;
3966 
3967 	if (bdev->internal.qd_poller != NULL) {
3968 		spdk_poller_unregister(&bdev->internal.qd_poller);
3969 		bdev->internal.measured_queue_depth = UINT64_MAX;
3970 	}
3971 
3972 	if (period != 0) {
3973 		bdev->internal.qd_poller = SPDK_POLLER_REGISTER(bdev_calculate_measured_queue_depth, bdev,
3974 					   period);
3975 	}
3976 }
3977 
3978 static void
3979 _resize_notify(void *arg)
3980 {
3981 	struct spdk_bdev_desc *desc = arg;
3982 
3983 	pthread_mutex_lock(&desc->mutex);
3984 	desc->refs--;
3985 	if (!desc->closed) {
3986 		pthread_mutex_unlock(&desc->mutex);
3987 		desc->callback.event_fn(SPDK_BDEV_EVENT_RESIZE,
3988 					desc->bdev,
3989 					desc->callback.ctx);
3990 		return;
3991 	} else if (0 == desc->refs) {
3992 		/* This descriptor was closed after this resize_notify message was sent.
3993 		 * spdk_bdev_close() could not free the descriptor since this message was
3994 		 * in flight, so we free it now using bdev_desc_free().
3995 		 */
3996 		pthread_mutex_unlock(&desc->mutex);
3997 		bdev_desc_free(desc);
3998 		return;
3999 	}
4000 	pthread_mutex_unlock(&desc->mutex);
4001 }
4002 
4003 int
4004 spdk_bdev_notify_blockcnt_change(struct spdk_bdev *bdev, uint64_t size)
4005 {
4006 	struct spdk_bdev_desc *desc;
4007 	int ret;
4008 
4009 	if (size == bdev->blockcnt) {
4010 		return 0;
4011 	}
4012 
4013 	pthread_mutex_lock(&bdev->internal.mutex);
4014 
4015 	/* bdev has open descriptors */
4016 	if (!TAILQ_EMPTY(&bdev->internal.open_descs) &&
4017 	    bdev->blockcnt > size) {
4018 		ret = -EBUSY;
4019 	} else {
4020 		bdev->blockcnt = size;
4021 		TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
4022 			pthread_mutex_lock(&desc->mutex);
4023 			if (!desc->closed) {
4024 				desc->refs++;
4025 				spdk_thread_send_msg(desc->thread, _resize_notify, desc);
4026 			}
4027 			pthread_mutex_unlock(&desc->mutex);
4028 		}
4029 		ret = 0;
4030 	}
4031 
4032 	pthread_mutex_unlock(&bdev->internal.mutex);
4033 
4034 	return ret;
4035 }
4036 
4037 /*
4038  * Convert I/O offset and length from bytes to blocks.
4039  *
4040  * Returns zero on success or non-zero if the byte parameters aren't divisible by the block size.
4041  */
4042 static uint64_t
4043 bdev_bytes_to_blocks(struct spdk_bdev *bdev, uint64_t offset_bytes, uint64_t *offset_blocks,
4044 		     uint64_t num_bytes, uint64_t *num_blocks)
4045 {
4046 	uint32_t block_size = bdev->blocklen;
4047 	uint8_t shift_cnt;
4048 
4049 	/* Avoid expensive div operations if possible. These spdk_u32 functions are very cheap. */
4050 	if (spdk_likely(spdk_u32_is_pow2(block_size))) {
4051 		shift_cnt = spdk_u32log2(block_size);
4052 		*offset_blocks = offset_bytes >> shift_cnt;
4053 		*num_blocks = num_bytes >> shift_cnt;
4054 		return (offset_bytes - (*offset_blocks << shift_cnt)) |
4055 		       (num_bytes - (*num_blocks << shift_cnt));
4056 	} else {
4057 		*offset_blocks = offset_bytes / block_size;
4058 		*num_blocks = num_bytes / block_size;
4059 		return (offset_bytes % block_size) | (num_bytes % block_size);
4060 	}
4061 }
4062 
4063 static bool
4064 bdev_io_valid_blocks(struct spdk_bdev *bdev, uint64_t offset_blocks, uint64_t num_blocks)
4065 {
4066 	/* Return failure if offset_blocks + num_blocks is less than offset_blocks; indicates there
4067 	 * has been an overflow and hence the offset has been wrapped around */
4068 	if (offset_blocks + num_blocks < offset_blocks) {
4069 		return false;
4070 	}
4071 
4072 	/* Return failure if offset_blocks + num_blocks exceeds the size of the bdev */
4073 	if (offset_blocks + num_blocks > bdev->blockcnt) {
4074 		return false;
4075 	}
4076 
4077 	return true;
4078 }
4079 
4080 static bool
4081 _bdev_io_check_md_buf(const struct iovec *iovs, const void *md_buf)
4082 {
4083 	return _is_buf_allocated(iovs) == (md_buf != NULL);
4084 }
4085 
4086 static int
4087 bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf,
4088 			 void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4089 			 spdk_bdev_io_completion_cb cb, void *cb_arg)
4090 {
4091 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4092 	struct spdk_bdev_io *bdev_io;
4093 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4094 
4095 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4096 		return -EINVAL;
4097 	}
4098 
4099 	bdev_io = bdev_channel_get_io(channel);
4100 	if (!bdev_io) {
4101 		return -ENOMEM;
4102 	}
4103 
4104 	bdev_io->internal.ch = channel;
4105 	bdev_io->internal.desc = desc;
4106 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
4107 	bdev_io->u.bdev.iovs = &bdev_io->iov;
4108 	bdev_io->u.bdev.iovs[0].iov_base = buf;
4109 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
4110 	bdev_io->u.bdev.iovcnt = 1;
4111 	bdev_io->u.bdev.md_buf = md_buf;
4112 	bdev_io->u.bdev.num_blocks = num_blocks;
4113 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4114 	bdev_io->u.bdev.ext_opts = NULL;
4115 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4116 
4117 	bdev_io_submit(bdev_io);
4118 	return 0;
4119 }
4120 
4121 int
4122 spdk_bdev_read(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4123 	       void *buf, uint64_t offset, uint64_t nbytes,
4124 	       spdk_bdev_io_completion_cb cb, void *cb_arg)
4125 {
4126 	uint64_t offset_blocks, num_blocks;
4127 
4128 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4129 				 nbytes, &num_blocks) != 0) {
4130 		return -EINVAL;
4131 	}
4132 
4133 	return spdk_bdev_read_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
4134 }
4135 
4136 int
4137 spdk_bdev_read_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4138 		      void *buf, uint64_t offset_blocks, uint64_t num_blocks,
4139 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
4140 {
4141 	return bdev_read_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks, cb, cb_arg);
4142 }
4143 
4144 int
4145 spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4146 			      void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4147 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
4148 {
4149 	struct iovec iov = {
4150 		.iov_base = buf,
4151 	};
4152 
4153 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4154 		return -EINVAL;
4155 	}
4156 
4157 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
4158 		return -EINVAL;
4159 	}
4160 
4161 	return bdev_read_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
4162 					cb, cb_arg);
4163 }
4164 
4165 int
4166 spdk_bdev_readv(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4167 		struct iovec *iov, int iovcnt,
4168 		uint64_t offset, uint64_t nbytes,
4169 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4170 {
4171 	uint64_t offset_blocks, num_blocks;
4172 
4173 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4174 				 nbytes, &num_blocks) != 0) {
4175 		return -EINVAL;
4176 	}
4177 
4178 	return spdk_bdev_readv_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
4179 }
4180 
4181 static int
4182 bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4183 			  struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
4184 			  uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg,
4185 			  struct spdk_bdev_ext_io_opts *opts, bool copy_opts)
4186 {
4187 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4188 	struct spdk_bdev_io *bdev_io;
4189 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4190 
4191 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4192 		return -EINVAL;
4193 	}
4194 
4195 	bdev_io = bdev_channel_get_io(channel);
4196 	if (!bdev_io) {
4197 		return -ENOMEM;
4198 	}
4199 
4200 	bdev_io->internal.ch = channel;
4201 	bdev_io->internal.desc = desc;
4202 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
4203 	bdev_io->u.bdev.iovs = iov;
4204 	bdev_io->u.bdev.iovcnt = iovcnt;
4205 	bdev_io->u.bdev.md_buf = md_buf;
4206 	bdev_io->u.bdev.num_blocks = num_blocks;
4207 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4208 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4209 	bdev_io->internal.ext_opts = opts;
4210 	bdev_io->u.bdev.ext_opts = opts;
4211 
4212 	_bdev_io_submit_ext(desc, bdev_io, opts, copy_opts);
4213 
4214 	return 0;
4215 }
4216 
4217 int
4218 spdk_bdev_readv_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4219 		       struct iovec *iov, int iovcnt,
4220 		       uint64_t offset_blocks, uint64_t num_blocks,
4221 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4222 {
4223 	return bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
4224 					 num_blocks, cb, cb_arg, NULL, false);
4225 }
4226 
4227 int
4228 spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4229 			       struct iovec *iov, int iovcnt, void *md_buf,
4230 			       uint64_t offset_blocks, uint64_t num_blocks,
4231 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
4232 {
4233 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4234 		return -EINVAL;
4235 	}
4236 
4237 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
4238 		return -EINVAL;
4239 	}
4240 
4241 	return bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
4242 					 num_blocks, cb, cb_arg, NULL, false);
4243 }
4244 
4245 static inline bool
4246 _bdev_io_check_opts(struct spdk_bdev_ext_io_opts *opts, struct iovec *iov)
4247 {
4248 	/*
4249 	 * We check if opts size is at least of size when we first introduced
4250 	 * spdk_bdev_ext_io_opts (ac6f2bdd8d) since access to those members
4251 	 * are not checked internal.
4252 	 */
4253 	return opts->size >= offsetof(struct spdk_bdev_ext_io_opts, metadata) +
4254 	       sizeof(opts->metadata) &&
4255 	       opts->size <= sizeof(*opts) &&
4256 	       /* When memory domain is used, the user must provide data buffers */
4257 	       (!opts->memory_domain || (iov && iov[0].iov_base));
4258 }
4259 
4260 int
4261 spdk_bdev_readv_blocks_ext(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4262 			   struct iovec *iov, int iovcnt,
4263 			   uint64_t offset_blocks, uint64_t num_blocks,
4264 			   spdk_bdev_io_completion_cb cb, void *cb_arg,
4265 			   struct spdk_bdev_ext_io_opts *opts)
4266 {
4267 	void *md = NULL;
4268 
4269 	if (opts) {
4270 		if (spdk_unlikely(!_bdev_io_check_opts(opts, iov))) {
4271 			return -EINVAL;
4272 		}
4273 		md = opts->metadata;
4274 	}
4275 
4276 	if (md && !spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4277 		return -EINVAL;
4278 	}
4279 
4280 	if (md && !_bdev_io_check_md_buf(iov, md)) {
4281 		return -EINVAL;
4282 	}
4283 
4284 	return bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, md, offset_blocks,
4285 					 num_blocks, cb, cb_arg, opts, false);
4286 }
4287 
4288 static int
4289 bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4290 			  void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4291 			  spdk_bdev_io_completion_cb cb, void *cb_arg)
4292 {
4293 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4294 	struct spdk_bdev_io *bdev_io;
4295 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4296 
4297 	if (!desc->write) {
4298 		return -EBADF;
4299 	}
4300 
4301 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4302 		return -EINVAL;
4303 	}
4304 
4305 	bdev_io = bdev_channel_get_io(channel);
4306 	if (!bdev_io) {
4307 		return -ENOMEM;
4308 	}
4309 
4310 	bdev_io->internal.ch = channel;
4311 	bdev_io->internal.desc = desc;
4312 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
4313 	bdev_io->u.bdev.iovs = &bdev_io->iov;
4314 	bdev_io->u.bdev.iovs[0].iov_base = buf;
4315 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
4316 	bdev_io->u.bdev.iovcnt = 1;
4317 	bdev_io->u.bdev.md_buf = md_buf;
4318 	bdev_io->u.bdev.num_blocks = num_blocks;
4319 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4320 	bdev_io->u.bdev.ext_opts = NULL;
4321 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4322 
4323 	bdev_io_submit(bdev_io);
4324 	return 0;
4325 }
4326 
4327 int
4328 spdk_bdev_write(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4329 		void *buf, uint64_t offset, uint64_t nbytes,
4330 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4331 {
4332 	uint64_t offset_blocks, num_blocks;
4333 
4334 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4335 				 nbytes, &num_blocks) != 0) {
4336 		return -EINVAL;
4337 	}
4338 
4339 	return spdk_bdev_write_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
4340 }
4341 
4342 int
4343 spdk_bdev_write_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4344 		       void *buf, uint64_t offset_blocks, uint64_t num_blocks,
4345 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4346 {
4347 	return bdev_write_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
4348 					 cb, cb_arg);
4349 }
4350 
4351 int
4352 spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4353 			       void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4354 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
4355 {
4356 	struct iovec iov = {
4357 		.iov_base = buf,
4358 	};
4359 
4360 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4361 		return -EINVAL;
4362 	}
4363 
4364 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
4365 		return -EINVAL;
4366 	}
4367 
4368 	return bdev_write_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
4369 					 cb, cb_arg);
4370 }
4371 
4372 static int
4373 bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4374 			   struct iovec *iov, int iovcnt, void *md_buf,
4375 			   uint64_t offset_blocks, uint64_t num_blocks,
4376 			   spdk_bdev_io_completion_cb cb, void *cb_arg,
4377 			   struct spdk_bdev_ext_io_opts *opts, bool copy_opts)
4378 {
4379 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4380 	struct spdk_bdev_io *bdev_io;
4381 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4382 
4383 	if (!desc->write) {
4384 		return -EBADF;
4385 	}
4386 
4387 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4388 		return -EINVAL;
4389 	}
4390 
4391 	bdev_io = bdev_channel_get_io(channel);
4392 	if (!bdev_io) {
4393 		return -ENOMEM;
4394 	}
4395 
4396 	bdev_io->internal.ch = channel;
4397 	bdev_io->internal.desc = desc;
4398 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
4399 	bdev_io->u.bdev.iovs = iov;
4400 	bdev_io->u.bdev.iovcnt = iovcnt;
4401 	bdev_io->u.bdev.md_buf = md_buf;
4402 	bdev_io->u.bdev.num_blocks = num_blocks;
4403 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4404 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4405 	bdev_io->internal.ext_opts = opts;
4406 	bdev_io->u.bdev.ext_opts = opts;
4407 
4408 	_bdev_io_submit_ext(desc, bdev_io, opts, copy_opts);
4409 
4410 	return 0;
4411 }
4412 
4413 int
4414 spdk_bdev_writev(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4415 		 struct iovec *iov, int iovcnt,
4416 		 uint64_t offset, uint64_t len,
4417 		 spdk_bdev_io_completion_cb cb, void *cb_arg)
4418 {
4419 	uint64_t offset_blocks, num_blocks;
4420 
4421 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4422 				 len, &num_blocks) != 0) {
4423 		return -EINVAL;
4424 	}
4425 
4426 	return spdk_bdev_writev_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
4427 }
4428 
4429 int
4430 spdk_bdev_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4431 			struct iovec *iov, int iovcnt,
4432 			uint64_t offset_blocks, uint64_t num_blocks,
4433 			spdk_bdev_io_completion_cb cb, void *cb_arg)
4434 {
4435 	return bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
4436 					  num_blocks, cb, cb_arg, NULL, false);
4437 }
4438 
4439 int
4440 spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4441 				struct iovec *iov, int iovcnt, void *md_buf,
4442 				uint64_t offset_blocks, uint64_t num_blocks,
4443 				spdk_bdev_io_completion_cb cb, void *cb_arg)
4444 {
4445 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4446 		return -EINVAL;
4447 	}
4448 
4449 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
4450 		return -EINVAL;
4451 	}
4452 
4453 	return bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
4454 					  num_blocks, cb, cb_arg, NULL, false);
4455 }
4456 
4457 int
4458 spdk_bdev_writev_blocks_ext(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4459 			    struct iovec *iov, int iovcnt,
4460 			    uint64_t offset_blocks, uint64_t num_blocks,
4461 			    spdk_bdev_io_completion_cb cb, void *cb_arg,
4462 			    struct spdk_bdev_ext_io_opts *opts)
4463 {
4464 	void *md = NULL;
4465 
4466 	if (opts) {
4467 		if (spdk_unlikely(!_bdev_io_check_opts(opts, iov))) {
4468 			return -EINVAL;
4469 		}
4470 		md = opts->metadata;
4471 	}
4472 
4473 	if (md && !spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4474 		return -EINVAL;
4475 	}
4476 
4477 	if (md && !_bdev_io_check_md_buf(iov, md)) {
4478 		return -EINVAL;
4479 	}
4480 
4481 	return bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, md, offset_blocks,
4482 					  num_blocks, cb, cb_arg, opts, false);
4483 }
4484 
4485 static void
4486 bdev_compare_do_read_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4487 {
4488 	struct spdk_bdev_io *parent_io = cb_arg;
4489 	uint8_t *read_buf = bdev_io->u.bdev.iovs[0].iov_base;
4490 	int i, rc = 0;
4491 
4492 	if (!success) {
4493 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4494 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
4495 		spdk_bdev_free_io(bdev_io);
4496 		return;
4497 	}
4498 
4499 	for (i = 0; i < parent_io->u.bdev.iovcnt; i++) {
4500 		rc = memcmp(read_buf,
4501 			    parent_io->u.bdev.iovs[i].iov_base,
4502 			    parent_io->u.bdev.iovs[i].iov_len);
4503 		if (rc) {
4504 			break;
4505 		}
4506 		read_buf += parent_io->u.bdev.iovs[i].iov_len;
4507 	}
4508 
4509 	spdk_bdev_free_io(bdev_io);
4510 
4511 	if (rc == 0) {
4512 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4513 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
4514 	} else {
4515 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_MISCOMPARE;
4516 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
4517 	}
4518 }
4519 
4520 static void
4521 bdev_compare_do_read(void *_bdev_io)
4522 {
4523 	struct spdk_bdev_io *bdev_io = _bdev_io;
4524 	int rc;
4525 
4526 	rc = spdk_bdev_read_blocks(bdev_io->internal.desc,
4527 				   spdk_io_channel_from_ctx(bdev_io->internal.ch), NULL,
4528 				   bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4529 				   bdev_compare_do_read_done, bdev_io);
4530 
4531 	if (rc == -ENOMEM) {
4532 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_do_read);
4533 	} else if (rc != 0) {
4534 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4535 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
4536 	}
4537 }
4538 
4539 static int
4540 bdev_comparev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4541 			     struct iovec *iov, int iovcnt, void *md_buf,
4542 			     uint64_t offset_blocks, uint64_t num_blocks,
4543 			     spdk_bdev_io_completion_cb cb, void *cb_arg)
4544 {
4545 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4546 	struct spdk_bdev_io *bdev_io;
4547 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4548 
4549 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4550 		return -EINVAL;
4551 	}
4552 
4553 	bdev_io = bdev_channel_get_io(channel);
4554 	if (!bdev_io) {
4555 		return -ENOMEM;
4556 	}
4557 
4558 	bdev_io->internal.ch = channel;
4559 	bdev_io->internal.desc = desc;
4560 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE;
4561 	bdev_io->u.bdev.iovs = iov;
4562 	bdev_io->u.bdev.iovcnt = iovcnt;
4563 	bdev_io->u.bdev.md_buf = md_buf;
4564 	bdev_io->u.bdev.num_blocks = num_blocks;
4565 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4566 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4567 
4568 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE)) {
4569 		bdev_io_submit(bdev_io);
4570 		return 0;
4571 	}
4572 
4573 	bdev_compare_do_read(bdev_io);
4574 
4575 	return 0;
4576 }
4577 
4578 int
4579 spdk_bdev_comparev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4580 			  struct iovec *iov, int iovcnt,
4581 			  uint64_t offset_blocks, uint64_t num_blocks,
4582 			  spdk_bdev_io_completion_cb cb, void *cb_arg)
4583 {
4584 	return bdev_comparev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
4585 					    num_blocks, cb, cb_arg);
4586 }
4587 
4588 int
4589 spdk_bdev_comparev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4590 				  struct iovec *iov, int iovcnt, void *md_buf,
4591 				  uint64_t offset_blocks, uint64_t num_blocks,
4592 				  spdk_bdev_io_completion_cb cb, void *cb_arg)
4593 {
4594 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4595 		return -EINVAL;
4596 	}
4597 
4598 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
4599 		return -EINVAL;
4600 	}
4601 
4602 	return bdev_comparev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
4603 					    num_blocks, cb, cb_arg);
4604 }
4605 
4606 static int
4607 bdev_compare_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4608 			    void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4609 			    spdk_bdev_io_completion_cb cb, void *cb_arg)
4610 {
4611 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4612 	struct spdk_bdev_io *bdev_io;
4613 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4614 
4615 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4616 		return -EINVAL;
4617 	}
4618 
4619 	bdev_io = bdev_channel_get_io(channel);
4620 	if (!bdev_io) {
4621 		return -ENOMEM;
4622 	}
4623 
4624 	bdev_io->internal.ch = channel;
4625 	bdev_io->internal.desc = desc;
4626 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE;
4627 	bdev_io->u.bdev.iovs = &bdev_io->iov;
4628 	bdev_io->u.bdev.iovs[0].iov_base = buf;
4629 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
4630 	bdev_io->u.bdev.iovcnt = 1;
4631 	bdev_io->u.bdev.md_buf = md_buf;
4632 	bdev_io->u.bdev.num_blocks = num_blocks;
4633 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4634 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4635 
4636 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE)) {
4637 		bdev_io_submit(bdev_io);
4638 		return 0;
4639 	}
4640 
4641 	bdev_compare_do_read(bdev_io);
4642 
4643 	return 0;
4644 }
4645 
4646 int
4647 spdk_bdev_compare_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4648 			 void *buf, uint64_t offset_blocks, uint64_t num_blocks,
4649 			 spdk_bdev_io_completion_cb cb, void *cb_arg)
4650 {
4651 	return bdev_compare_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
4652 					   cb, cb_arg);
4653 }
4654 
4655 int
4656 spdk_bdev_compare_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4657 				 void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4658 				 spdk_bdev_io_completion_cb cb, void *cb_arg)
4659 {
4660 	struct iovec iov = {
4661 		.iov_base = buf,
4662 	};
4663 
4664 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4665 		return -EINVAL;
4666 	}
4667 
4668 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
4669 		return -EINVAL;
4670 	}
4671 
4672 	return bdev_compare_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
4673 					   cb, cb_arg);
4674 }
4675 
4676 static void
4677 bdev_comparev_and_writev_blocks_unlocked(void *ctx, int unlock_status)
4678 {
4679 	struct spdk_bdev_io *bdev_io = ctx;
4680 
4681 	if (unlock_status) {
4682 		SPDK_ERRLOG("LBA range unlock failed\n");
4683 	}
4684 
4685 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS ? true :
4686 			     false, bdev_io->internal.caller_ctx);
4687 }
4688 
4689 static void
4690 bdev_comparev_and_writev_blocks_unlock(struct spdk_bdev_io *bdev_io, int status)
4691 {
4692 	bdev_io->internal.status = status;
4693 
4694 	bdev_unlock_lba_range(bdev_io->internal.desc, spdk_io_channel_from_ctx(bdev_io->internal.ch),
4695 			      bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4696 			      bdev_comparev_and_writev_blocks_unlocked, bdev_io);
4697 }
4698 
4699 static void
4700 bdev_compare_and_write_do_write_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4701 {
4702 	struct spdk_bdev_io *parent_io = cb_arg;
4703 
4704 	if (!success) {
4705 		SPDK_ERRLOG("Compare and write operation failed\n");
4706 	}
4707 
4708 	spdk_bdev_free_io(bdev_io);
4709 
4710 	bdev_comparev_and_writev_blocks_unlock(parent_io,
4711 					       success ? SPDK_BDEV_IO_STATUS_SUCCESS : SPDK_BDEV_IO_STATUS_FAILED);
4712 }
4713 
4714 static void
4715 bdev_compare_and_write_do_write(void *_bdev_io)
4716 {
4717 	struct spdk_bdev_io *bdev_io = _bdev_io;
4718 	int rc;
4719 
4720 	rc = spdk_bdev_writev_blocks(bdev_io->internal.desc,
4721 				     spdk_io_channel_from_ctx(bdev_io->internal.ch),
4722 				     bdev_io->u.bdev.fused_iovs, bdev_io->u.bdev.fused_iovcnt,
4723 				     bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4724 				     bdev_compare_and_write_do_write_done, bdev_io);
4725 
4726 
4727 	if (rc == -ENOMEM) {
4728 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_and_write_do_write);
4729 	} else if (rc != 0) {
4730 		bdev_comparev_and_writev_blocks_unlock(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
4731 	}
4732 }
4733 
4734 static void
4735 bdev_compare_and_write_do_compare_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4736 {
4737 	struct spdk_bdev_io *parent_io = cb_arg;
4738 
4739 	spdk_bdev_free_io(bdev_io);
4740 
4741 	if (!success) {
4742 		bdev_comparev_and_writev_blocks_unlock(parent_io, SPDK_BDEV_IO_STATUS_MISCOMPARE);
4743 		return;
4744 	}
4745 
4746 	bdev_compare_and_write_do_write(parent_io);
4747 }
4748 
4749 static void
4750 bdev_compare_and_write_do_compare(void *_bdev_io)
4751 {
4752 	struct spdk_bdev_io *bdev_io = _bdev_io;
4753 	int rc;
4754 
4755 	rc = spdk_bdev_comparev_blocks(bdev_io->internal.desc,
4756 				       spdk_io_channel_from_ctx(bdev_io->internal.ch), bdev_io->u.bdev.iovs,
4757 				       bdev_io->u.bdev.iovcnt, bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4758 				       bdev_compare_and_write_do_compare_done, bdev_io);
4759 
4760 	if (rc == -ENOMEM) {
4761 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_and_write_do_compare);
4762 	} else if (rc != 0) {
4763 		bdev_comparev_and_writev_blocks_unlock(bdev_io, SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED);
4764 	}
4765 }
4766 
4767 static void
4768 bdev_comparev_and_writev_blocks_locked(void *ctx, int status)
4769 {
4770 	struct spdk_bdev_io *bdev_io = ctx;
4771 
4772 	if (status) {
4773 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED;
4774 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
4775 		return;
4776 	}
4777 
4778 	bdev_compare_and_write_do_compare(bdev_io);
4779 }
4780 
4781 int
4782 spdk_bdev_comparev_and_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4783 				     struct iovec *compare_iov, int compare_iovcnt,
4784 				     struct iovec *write_iov, int write_iovcnt,
4785 				     uint64_t offset_blocks, uint64_t num_blocks,
4786 				     spdk_bdev_io_completion_cb cb, void *cb_arg)
4787 {
4788 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4789 	struct spdk_bdev_io *bdev_io;
4790 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4791 
4792 	if (!desc->write) {
4793 		return -EBADF;
4794 	}
4795 
4796 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4797 		return -EINVAL;
4798 	}
4799 
4800 	if (num_blocks > bdev->acwu) {
4801 		return -EINVAL;
4802 	}
4803 
4804 	bdev_io = bdev_channel_get_io(channel);
4805 	if (!bdev_io) {
4806 		return -ENOMEM;
4807 	}
4808 
4809 	bdev_io->internal.ch = channel;
4810 	bdev_io->internal.desc = desc;
4811 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE_AND_WRITE;
4812 	bdev_io->u.bdev.iovs = compare_iov;
4813 	bdev_io->u.bdev.iovcnt = compare_iovcnt;
4814 	bdev_io->u.bdev.fused_iovs = write_iov;
4815 	bdev_io->u.bdev.fused_iovcnt = write_iovcnt;
4816 	bdev_io->u.bdev.md_buf = NULL;
4817 	bdev_io->u.bdev.num_blocks = num_blocks;
4818 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4819 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4820 
4821 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE_AND_WRITE)) {
4822 		bdev_io_submit(bdev_io);
4823 		return 0;
4824 	}
4825 
4826 	return bdev_lock_lba_range(desc, ch, offset_blocks, num_blocks,
4827 				   bdev_comparev_and_writev_blocks_locked, bdev_io);
4828 }
4829 
4830 int
4831 spdk_bdev_zcopy_start(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4832 		      struct iovec *iov, int iovcnt,
4833 		      uint64_t offset_blocks, uint64_t num_blocks,
4834 		      bool populate,
4835 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
4836 {
4837 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4838 	struct spdk_bdev_io *bdev_io;
4839 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4840 
4841 	if (!desc->write) {
4842 		return -EBADF;
4843 	}
4844 
4845 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4846 		return -EINVAL;
4847 	}
4848 
4849 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
4850 		return -ENOTSUP;
4851 	}
4852 
4853 	bdev_io = bdev_channel_get_io(channel);
4854 	if (!bdev_io) {
4855 		return -ENOMEM;
4856 	}
4857 
4858 	bdev_io->internal.ch = channel;
4859 	bdev_io->internal.desc = desc;
4860 	bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
4861 	bdev_io->u.bdev.num_blocks = num_blocks;
4862 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4863 	bdev_io->u.bdev.iovs = iov;
4864 	bdev_io->u.bdev.iovcnt = iovcnt;
4865 	bdev_io->u.bdev.md_buf = NULL;
4866 	bdev_io->u.bdev.zcopy.populate = populate ? 1 : 0;
4867 	bdev_io->u.bdev.zcopy.commit = 0;
4868 	bdev_io->u.bdev.zcopy.start = 1;
4869 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4870 
4871 	bdev_io_submit(bdev_io);
4872 
4873 	return 0;
4874 }
4875 
4876 int
4877 spdk_bdev_zcopy_end(struct spdk_bdev_io *bdev_io, bool commit,
4878 		    spdk_bdev_io_completion_cb cb, void *cb_arg)
4879 {
4880 	if (bdev_io->type != SPDK_BDEV_IO_TYPE_ZCOPY) {
4881 		return -EINVAL;
4882 	}
4883 
4884 	bdev_io->u.bdev.zcopy.commit = commit ? 1 : 0;
4885 	bdev_io->u.bdev.zcopy.start = 0;
4886 	bdev_io->internal.caller_ctx = cb_arg;
4887 	bdev_io->internal.cb = cb;
4888 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
4889 
4890 	bdev_io_submit(bdev_io);
4891 
4892 	return 0;
4893 }
4894 
4895 int
4896 spdk_bdev_write_zeroes(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4897 		       uint64_t offset, uint64_t len,
4898 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4899 {
4900 	uint64_t offset_blocks, num_blocks;
4901 
4902 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4903 				 len, &num_blocks) != 0) {
4904 		return -EINVAL;
4905 	}
4906 
4907 	return spdk_bdev_write_zeroes_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
4908 }
4909 
4910 int
4911 spdk_bdev_write_zeroes_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4912 			      uint64_t offset_blocks, uint64_t num_blocks,
4913 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
4914 {
4915 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4916 	struct spdk_bdev_io *bdev_io;
4917 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4918 
4919 	if (!desc->write) {
4920 		return -EBADF;
4921 	}
4922 
4923 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4924 		return -EINVAL;
4925 	}
4926 
4927 	if (!bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES) &&
4928 	    !bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE)) {
4929 		return -ENOTSUP;
4930 	}
4931 
4932 	bdev_io = bdev_channel_get_io(channel);
4933 
4934 	if (!bdev_io) {
4935 		return -ENOMEM;
4936 	}
4937 
4938 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE_ZEROES;
4939 	bdev_io->internal.ch = channel;
4940 	bdev_io->internal.desc = desc;
4941 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4942 	bdev_io->u.bdev.num_blocks = num_blocks;
4943 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4944 
4945 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES)) {
4946 		bdev_io_submit(bdev_io);
4947 		return 0;
4948 	}
4949 
4950 	assert(bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE));
4951 	assert(_bdev_get_block_size_with_md(bdev) <= ZERO_BUFFER_SIZE);
4952 	bdev_io->u.bdev.split_remaining_num_blocks = num_blocks;
4953 	bdev_io->u.bdev.split_current_offset_blocks = offset_blocks;
4954 	bdev_write_zero_buffer_next(bdev_io);
4955 
4956 	return 0;
4957 }
4958 
4959 int
4960 spdk_bdev_unmap(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4961 		uint64_t offset, uint64_t nbytes,
4962 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4963 {
4964 	uint64_t offset_blocks, num_blocks;
4965 
4966 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4967 				 nbytes, &num_blocks) != 0) {
4968 		return -EINVAL;
4969 	}
4970 
4971 	return spdk_bdev_unmap_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
4972 }
4973 
4974 int
4975 spdk_bdev_unmap_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4976 		       uint64_t offset_blocks, uint64_t num_blocks,
4977 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4978 {
4979 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4980 	struct spdk_bdev_io *bdev_io;
4981 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4982 
4983 	if (!desc->write) {
4984 		return -EBADF;
4985 	}
4986 
4987 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4988 		return -EINVAL;
4989 	}
4990 
4991 	if (num_blocks == 0) {
4992 		SPDK_ERRLOG("Can't unmap 0 bytes\n");
4993 		return -EINVAL;
4994 	}
4995 
4996 	bdev_io = bdev_channel_get_io(channel);
4997 	if (!bdev_io) {
4998 		return -ENOMEM;
4999 	}
5000 
5001 	bdev_io->internal.ch = channel;
5002 	bdev_io->internal.desc = desc;
5003 	bdev_io->type = SPDK_BDEV_IO_TYPE_UNMAP;
5004 
5005 	bdev_io->u.bdev.iovs = &bdev_io->iov;
5006 	bdev_io->u.bdev.iovs[0].iov_base = NULL;
5007 	bdev_io->u.bdev.iovs[0].iov_len = 0;
5008 	bdev_io->u.bdev.iovcnt = 1;
5009 
5010 	bdev_io->u.bdev.offset_blocks = offset_blocks;
5011 	bdev_io->u.bdev.num_blocks = num_blocks;
5012 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5013 
5014 	bdev_io_submit(bdev_io);
5015 	return 0;
5016 }
5017 
5018 int
5019 spdk_bdev_flush(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5020 		uint64_t offset, uint64_t length,
5021 		spdk_bdev_io_completion_cb cb, void *cb_arg)
5022 {
5023 	uint64_t offset_blocks, num_blocks;
5024 
5025 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
5026 				 length, &num_blocks) != 0) {
5027 		return -EINVAL;
5028 	}
5029 
5030 	return spdk_bdev_flush_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
5031 }
5032 
5033 int
5034 spdk_bdev_flush_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5035 		       uint64_t offset_blocks, uint64_t num_blocks,
5036 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
5037 {
5038 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5039 	struct spdk_bdev_io *bdev_io;
5040 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5041 
5042 	if (!desc->write) {
5043 		return -EBADF;
5044 	}
5045 
5046 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
5047 		return -EINVAL;
5048 	}
5049 
5050 	bdev_io = bdev_channel_get_io(channel);
5051 	if (!bdev_io) {
5052 		return -ENOMEM;
5053 	}
5054 
5055 	bdev_io->internal.ch = channel;
5056 	bdev_io->internal.desc = desc;
5057 	bdev_io->type = SPDK_BDEV_IO_TYPE_FLUSH;
5058 	bdev_io->u.bdev.iovs = NULL;
5059 	bdev_io->u.bdev.iovcnt = 0;
5060 	bdev_io->u.bdev.offset_blocks = offset_blocks;
5061 	bdev_io->u.bdev.num_blocks = num_blocks;
5062 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5063 
5064 	bdev_io_submit(bdev_io);
5065 	return 0;
5066 }
5067 
5068 static void
5069 bdev_reset_dev(struct spdk_io_channel_iter *i, int status)
5070 {
5071 	struct spdk_bdev_channel *ch = spdk_io_channel_iter_get_ctx(i);
5072 	struct spdk_bdev_io *bdev_io;
5073 
5074 	bdev_io = TAILQ_FIRST(&ch->queued_resets);
5075 	TAILQ_REMOVE(&ch->queued_resets, bdev_io, internal.link);
5076 	bdev_io_submit_reset(bdev_io);
5077 }
5078 
5079 static void
5080 bdev_reset_freeze_channel(struct spdk_io_channel_iter *i)
5081 {
5082 	struct spdk_io_channel		*ch;
5083 	struct spdk_bdev_channel	*channel;
5084 	struct spdk_bdev_mgmt_channel	*mgmt_channel;
5085 	struct spdk_bdev_shared_resource *shared_resource;
5086 	bdev_io_tailq_t			tmp_queued;
5087 
5088 	TAILQ_INIT(&tmp_queued);
5089 
5090 	ch = spdk_io_channel_iter_get_channel(i);
5091 	channel = spdk_io_channel_get_ctx(ch);
5092 	shared_resource = channel->shared_resource;
5093 	mgmt_channel = shared_resource->mgmt_ch;
5094 
5095 	channel->flags |= BDEV_CH_RESET_IN_PROGRESS;
5096 
5097 	if ((channel->flags & BDEV_CH_QOS_ENABLED) != 0) {
5098 		/* The QoS object is always valid and readable while
5099 		 * the channel flag is set, so the lock here should not
5100 		 * be necessary. We're not in the fast path though, so
5101 		 * just take it anyway. */
5102 		pthread_mutex_lock(&channel->bdev->internal.mutex);
5103 		if (channel->bdev->internal.qos->ch == channel) {
5104 			TAILQ_SWAP(&channel->bdev->internal.qos->queued, &tmp_queued, spdk_bdev_io, internal.link);
5105 		}
5106 		pthread_mutex_unlock(&channel->bdev->internal.mutex);
5107 	}
5108 
5109 	bdev_abort_all_queued_io(&shared_resource->nomem_io, channel);
5110 	bdev_abort_all_buf_io(&mgmt_channel->need_buf_small, channel);
5111 	bdev_abort_all_buf_io(&mgmt_channel->need_buf_large, channel);
5112 	bdev_abort_all_queued_io(&tmp_queued, channel);
5113 
5114 	spdk_for_each_channel_continue(i, 0);
5115 }
5116 
5117 static void
5118 bdev_start_reset(void *ctx)
5119 {
5120 	struct spdk_bdev_channel *ch = ctx;
5121 
5122 	spdk_for_each_channel(__bdev_to_io_dev(ch->bdev), bdev_reset_freeze_channel,
5123 			      ch, bdev_reset_dev);
5124 }
5125 
5126 static void
5127 bdev_channel_start_reset(struct spdk_bdev_channel *ch)
5128 {
5129 	struct spdk_bdev *bdev = ch->bdev;
5130 
5131 	assert(!TAILQ_EMPTY(&ch->queued_resets));
5132 
5133 	pthread_mutex_lock(&bdev->internal.mutex);
5134 	if (bdev->internal.reset_in_progress == NULL) {
5135 		bdev->internal.reset_in_progress = TAILQ_FIRST(&ch->queued_resets);
5136 		/*
5137 		 * Take a channel reference for the target bdev for the life of this
5138 		 *  reset.  This guards against the channel getting destroyed while
5139 		 *  spdk_for_each_channel() calls related to this reset IO are in
5140 		 *  progress.  We will release the reference when this reset is
5141 		 *  completed.
5142 		 */
5143 		bdev->internal.reset_in_progress->u.reset.ch_ref = spdk_get_io_channel(__bdev_to_io_dev(bdev));
5144 		bdev_start_reset(ch);
5145 	}
5146 	pthread_mutex_unlock(&bdev->internal.mutex);
5147 }
5148 
5149 int
5150 spdk_bdev_reset(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5151 		spdk_bdev_io_completion_cb cb, void *cb_arg)
5152 {
5153 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5154 	struct spdk_bdev_io *bdev_io;
5155 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5156 
5157 	bdev_io = bdev_channel_get_io(channel);
5158 	if (!bdev_io) {
5159 		return -ENOMEM;
5160 	}
5161 
5162 	bdev_io->internal.ch = channel;
5163 	bdev_io->internal.desc = desc;
5164 	bdev_io->internal.submit_tsc = spdk_get_ticks();
5165 	bdev_io->type = SPDK_BDEV_IO_TYPE_RESET;
5166 	bdev_io->u.reset.ch_ref = NULL;
5167 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5168 
5169 	pthread_mutex_lock(&bdev->internal.mutex);
5170 	TAILQ_INSERT_TAIL(&channel->queued_resets, bdev_io, internal.link);
5171 	pthread_mutex_unlock(&bdev->internal.mutex);
5172 
5173 	TAILQ_INSERT_TAIL(&bdev_io->internal.ch->io_submitted, bdev_io,
5174 			  internal.ch_link);
5175 
5176 	bdev_channel_start_reset(channel);
5177 
5178 	return 0;
5179 }
5180 
5181 void
5182 spdk_bdev_get_io_stat(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
5183 		      struct spdk_bdev_io_stat *stat)
5184 {
5185 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5186 
5187 	*stat = channel->stat;
5188 }
5189 
5190 static void
5191 bdev_get_device_stat_done(struct spdk_io_channel_iter *i, int status)
5192 {
5193 	void *io_device = spdk_io_channel_iter_get_io_device(i);
5194 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
5195 
5196 	bdev_iostat_ctx->cb(__bdev_from_io_dev(io_device), bdev_iostat_ctx->stat,
5197 			    bdev_iostat_ctx->cb_arg, 0);
5198 	free(bdev_iostat_ctx);
5199 }
5200 
5201 static void
5202 bdev_get_each_channel_stat(struct spdk_io_channel_iter *i)
5203 {
5204 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
5205 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
5206 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5207 
5208 	bdev_io_stat_add(bdev_iostat_ctx->stat, &channel->stat);
5209 	spdk_for_each_channel_continue(i, 0);
5210 }
5211 
5212 void
5213 spdk_bdev_get_device_stat(struct spdk_bdev *bdev, struct spdk_bdev_io_stat *stat,
5214 			  spdk_bdev_get_device_stat_cb cb, void *cb_arg)
5215 {
5216 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx;
5217 
5218 	assert(bdev != NULL);
5219 	assert(stat != NULL);
5220 	assert(cb != NULL);
5221 
5222 	bdev_iostat_ctx = calloc(1, sizeof(struct spdk_bdev_iostat_ctx));
5223 	if (bdev_iostat_ctx == NULL) {
5224 		SPDK_ERRLOG("Unable to allocate memory for spdk_bdev_iostat_ctx\n");
5225 		cb(bdev, stat, cb_arg, -ENOMEM);
5226 		return;
5227 	}
5228 
5229 	bdev_iostat_ctx->stat = stat;
5230 	bdev_iostat_ctx->cb = cb;
5231 	bdev_iostat_ctx->cb_arg = cb_arg;
5232 
5233 	/* Start with the statistics from previously deleted channels. */
5234 	pthread_mutex_lock(&bdev->internal.mutex);
5235 	bdev_io_stat_add(bdev_iostat_ctx->stat, &bdev->internal.stat);
5236 	pthread_mutex_unlock(&bdev->internal.mutex);
5237 
5238 	/* Then iterate and add the statistics from each existing channel. */
5239 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
5240 			      bdev_get_each_channel_stat,
5241 			      bdev_iostat_ctx,
5242 			      bdev_get_device_stat_done);
5243 }
5244 
5245 int
5246 spdk_bdev_nvme_admin_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5247 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
5248 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
5249 {
5250 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5251 	struct spdk_bdev_io *bdev_io;
5252 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5253 
5254 	if (!desc->write) {
5255 		return -EBADF;
5256 	}
5257 
5258 	if (spdk_unlikely(!bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_NVME_ADMIN))) {
5259 		return -ENOTSUP;
5260 	}
5261 
5262 	bdev_io = bdev_channel_get_io(channel);
5263 	if (!bdev_io) {
5264 		return -ENOMEM;
5265 	}
5266 
5267 	bdev_io->internal.ch = channel;
5268 	bdev_io->internal.desc = desc;
5269 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_ADMIN;
5270 	bdev_io->u.nvme_passthru.cmd = *cmd;
5271 	bdev_io->u.nvme_passthru.buf = buf;
5272 	bdev_io->u.nvme_passthru.nbytes = nbytes;
5273 	bdev_io->u.nvme_passthru.md_buf = NULL;
5274 	bdev_io->u.nvme_passthru.md_len = 0;
5275 
5276 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5277 
5278 	bdev_io_submit(bdev_io);
5279 	return 0;
5280 }
5281 
5282 int
5283 spdk_bdev_nvme_io_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5284 			   const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
5285 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
5286 {
5287 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5288 	struct spdk_bdev_io *bdev_io;
5289 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5290 
5291 	if (!desc->write) {
5292 		/*
5293 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
5294 		 *  to easily determine if the command is a read or write, but for now just
5295 		 *  do not allow io_passthru with a read-only descriptor.
5296 		 */
5297 		return -EBADF;
5298 	}
5299 
5300 	if (spdk_unlikely(!bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_NVME_IO))) {
5301 		return -ENOTSUP;
5302 	}
5303 
5304 	bdev_io = bdev_channel_get_io(channel);
5305 	if (!bdev_io) {
5306 		return -ENOMEM;
5307 	}
5308 
5309 	bdev_io->internal.ch = channel;
5310 	bdev_io->internal.desc = desc;
5311 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO;
5312 	bdev_io->u.nvme_passthru.cmd = *cmd;
5313 	bdev_io->u.nvme_passthru.buf = buf;
5314 	bdev_io->u.nvme_passthru.nbytes = nbytes;
5315 	bdev_io->u.nvme_passthru.md_buf = NULL;
5316 	bdev_io->u.nvme_passthru.md_len = 0;
5317 
5318 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5319 
5320 	bdev_io_submit(bdev_io);
5321 	return 0;
5322 }
5323 
5324 int
5325 spdk_bdev_nvme_io_passthru_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5326 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes, void *md_buf, size_t md_len,
5327 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
5328 {
5329 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5330 	struct spdk_bdev_io *bdev_io;
5331 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5332 
5333 	if (!desc->write) {
5334 		/*
5335 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
5336 		 *  to easily determine if the command is a read or write, but for now just
5337 		 *  do not allow io_passthru with a read-only descriptor.
5338 		 */
5339 		return -EBADF;
5340 	}
5341 
5342 	if (spdk_unlikely(!bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_NVME_IO_MD))) {
5343 		return -ENOTSUP;
5344 	}
5345 
5346 	bdev_io = bdev_channel_get_io(channel);
5347 	if (!bdev_io) {
5348 		return -ENOMEM;
5349 	}
5350 
5351 	bdev_io->internal.ch = channel;
5352 	bdev_io->internal.desc = desc;
5353 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO_MD;
5354 	bdev_io->u.nvme_passthru.cmd = *cmd;
5355 	bdev_io->u.nvme_passthru.buf = buf;
5356 	bdev_io->u.nvme_passthru.nbytes = nbytes;
5357 	bdev_io->u.nvme_passthru.md_buf = md_buf;
5358 	bdev_io->u.nvme_passthru.md_len = md_len;
5359 
5360 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5361 
5362 	bdev_io_submit(bdev_io);
5363 	return 0;
5364 }
5365 
5366 static void bdev_abort_retry(void *ctx);
5367 static void bdev_abort(struct spdk_bdev_io *parent_io);
5368 
5369 static void
5370 bdev_abort_io_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
5371 {
5372 	struct spdk_bdev_channel *channel = bdev_io->internal.ch;
5373 	struct spdk_bdev_io *parent_io = cb_arg;
5374 	struct spdk_bdev_io *bio_to_abort, *tmp_io;
5375 
5376 	bio_to_abort = bdev_io->u.abort.bio_to_abort;
5377 
5378 	spdk_bdev_free_io(bdev_io);
5379 
5380 	if (!success) {
5381 		/* Check if the target I/O completed in the meantime. */
5382 		TAILQ_FOREACH(tmp_io, &channel->io_submitted, internal.ch_link) {
5383 			if (tmp_io == bio_to_abort) {
5384 				break;
5385 			}
5386 		}
5387 
5388 		/* If the target I/O still exists, set the parent to failed. */
5389 		if (tmp_io != NULL) {
5390 			parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
5391 		}
5392 	}
5393 
5394 	parent_io->u.bdev.split_outstanding--;
5395 	if (parent_io->u.bdev.split_outstanding == 0) {
5396 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
5397 			bdev_abort_retry(parent_io);
5398 		} else {
5399 			bdev_io_complete(parent_io);
5400 		}
5401 	}
5402 }
5403 
5404 static int
5405 bdev_abort_io(struct spdk_bdev_desc *desc, struct spdk_bdev_channel *channel,
5406 	      struct spdk_bdev_io *bio_to_abort,
5407 	      spdk_bdev_io_completion_cb cb, void *cb_arg)
5408 {
5409 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5410 	struct spdk_bdev_io *bdev_io;
5411 
5412 	if (bio_to_abort->type == SPDK_BDEV_IO_TYPE_ABORT ||
5413 	    bio_to_abort->type == SPDK_BDEV_IO_TYPE_RESET) {
5414 		/* TODO: Abort reset or abort request. */
5415 		return -ENOTSUP;
5416 	}
5417 
5418 	bdev_io = bdev_channel_get_io(channel);
5419 	if (bdev_io == NULL) {
5420 		return -ENOMEM;
5421 	}
5422 
5423 	bdev_io->internal.ch = channel;
5424 	bdev_io->internal.desc = desc;
5425 	bdev_io->type = SPDK_BDEV_IO_TYPE_ABORT;
5426 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5427 
5428 	if (bdev->split_on_optimal_io_boundary && bdev_io_should_split(bio_to_abort)) {
5429 		bdev_io->u.bdev.abort.bio_cb_arg = bio_to_abort;
5430 
5431 		/* Parent abort request is not submitted directly, but to manage its
5432 		 * execution add it to the submitted list here.
5433 		 */
5434 		bdev_io->internal.submit_tsc = spdk_get_ticks();
5435 		TAILQ_INSERT_TAIL(&channel->io_submitted, bdev_io, internal.ch_link);
5436 
5437 		bdev_abort(bdev_io);
5438 
5439 		return 0;
5440 	}
5441 
5442 	bdev_io->u.abort.bio_to_abort = bio_to_abort;
5443 
5444 	/* Submit the abort request to the underlying bdev module. */
5445 	bdev_io_submit(bdev_io);
5446 
5447 	return 0;
5448 }
5449 
5450 static uint32_t
5451 _bdev_abort(struct spdk_bdev_io *parent_io)
5452 {
5453 	struct spdk_bdev_desc *desc = parent_io->internal.desc;
5454 	struct spdk_bdev_channel *channel = parent_io->internal.ch;
5455 	void *bio_cb_arg;
5456 	struct spdk_bdev_io *bio_to_abort;
5457 	uint32_t matched_ios;
5458 	int rc;
5459 
5460 	bio_cb_arg = parent_io->u.bdev.abort.bio_cb_arg;
5461 
5462 	/* matched_ios is returned and will be kept by the caller.
5463 	 *
5464 	 * This funcion will be used for two cases, 1) the same cb_arg is used for
5465 	 * multiple I/Os, 2) a single large I/O is split into smaller ones.
5466 	 * Incrementing split_outstanding directly here may confuse readers especially
5467 	 * for the 1st case.
5468 	 *
5469 	 * Completion of I/O abort is processed after stack unwinding. Hence this trick
5470 	 * works as expected.
5471 	 */
5472 	matched_ios = 0;
5473 	parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5474 
5475 	TAILQ_FOREACH(bio_to_abort, &channel->io_submitted, internal.ch_link) {
5476 		if (bio_to_abort->internal.caller_ctx != bio_cb_arg) {
5477 			continue;
5478 		}
5479 
5480 		if (bio_to_abort->internal.submit_tsc > parent_io->internal.submit_tsc) {
5481 			/* Any I/O which was submitted after this abort command should be excluded. */
5482 			continue;
5483 		}
5484 
5485 		rc = bdev_abort_io(desc, channel, bio_to_abort, bdev_abort_io_done, parent_io);
5486 		if (rc != 0) {
5487 			if (rc == -ENOMEM) {
5488 				parent_io->internal.status = SPDK_BDEV_IO_STATUS_NOMEM;
5489 			} else {
5490 				parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
5491 			}
5492 			break;
5493 		}
5494 		matched_ios++;
5495 	}
5496 
5497 	return matched_ios;
5498 }
5499 
5500 static void
5501 bdev_abort_retry(void *ctx)
5502 {
5503 	struct spdk_bdev_io *parent_io = ctx;
5504 	uint32_t matched_ios;
5505 
5506 	matched_ios = _bdev_abort(parent_io);
5507 
5508 	if (matched_ios == 0) {
5509 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
5510 			bdev_queue_io_wait_with_cb(parent_io, bdev_abort_retry);
5511 		} else {
5512 			/* For retry, the case that no target I/O was found is success
5513 			 * because it means target I/Os completed in the meantime.
5514 			 */
5515 			bdev_io_complete(parent_io);
5516 		}
5517 		return;
5518 	}
5519 
5520 	/* Use split_outstanding to manage the progress of aborting I/Os. */
5521 	parent_io->u.bdev.split_outstanding = matched_ios;
5522 }
5523 
5524 static void
5525 bdev_abort(struct spdk_bdev_io *parent_io)
5526 {
5527 	uint32_t matched_ios;
5528 
5529 	matched_ios = _bdev_abort(parent_io);
5530 
5531 	if (matched_ios == 0) {
5532 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
5533 			bdev_queue_io_wait_with_cb(parent_io, bdev_abort_retry);
5534 		} else {
5535 			/* The case the no target I/O was found is failure. */
5536 			parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
5537 			bdev_io_complete(parent_io);
5538 		}
5539 		return;
5540 	}
5541 
5542 	/* Use split_outstanding to manage the progress of aborting I/Os. */
5543 	parent_io->u.bdev.split_outstanding = matched_ios;
5544 }
5545 
5546 int
5547 spdk_bdev_abort(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
5548 		void *bio_cb_arg,
5549 		spdk_bdev_io_completion_cb cb, void *cb_arg)
5550 {
5551 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5552 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5553 	struct spdk_bdev_io *bdev_io;
5554 
5555 	if (bio_cb_arg == NULL) {
5556 		return -EINVAL;
5557 	}
5558 
5559 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ABORT)) {
5560 		return -ENOTSUP;
5561 	}
5562 
5563 	bdev_io = bdev_channel_get_io(channel);
5564 	if (bdev_io == NULL) {
5565 		return -ENOMEM;
5566 	}
5567 
5568 	bdev_io->internal.ch = channel;
5569 	bdev_io->internal.desc = desc;
5570 	bdev_io->internal.submit_tsc = spdk_get_ticks();
5571 	bdev_io->type = SPDK_BDEV_IO_TYPE_ABORT;
5572 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
5573 
5574 	bdev_io->u.bdev.abort.bio_cb_arg = bio_cb_arg;
5575 
5576 	/* Parent abort request is not submitted directly, but to manage its execution,
5577 	 * add it to the submitted list here.
5578 	 */
5579 	TAILQ_INSERT_TAIL(&channel->io_submitted, bdev_io, internal.ch_link);
5580 
5581 	bdev_abort(bdev_io);
5582 
5583 	return 0;
5584 }
5585 
5586 int
5587 spdk_bdev_queue_io_wait(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
5588 			struct spdk_bdev_io_wait_entry *entry)
5589 {
5590 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
5591 	struct spdk_bdev_mgmt_channel *mgmt_ch = channel->shared_resource->mgmt_ch;
5592 
5593 	if (bdev != entry->bdev) {
5594 		SPDK_ERRLOG("bdevs do not match\n");
5595 		return -EINVAL;
5596 	}
5597 
5598 	if (mgmt_ch->per_thread_cache_count > 0) {
5599 		SPDK_ERRLOG("Cannot queue io_wait if spdk_bdev_io available in per-thread cache\n");
5600 		return -EINVAL;
5601 	}
5602 
5603 	TAILQ_INSERT_TAIL(&mgmt_ch->io_wait_queue, entry, link);
5604 	return 0;
5605 }
5606 
5607 static inline void
5608 bdev_io_complete(void *ctx)
5609 {
5610 	struct spdk_bdev_io *bdev_io = ctx;
5611 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
5612 	uint64_t tsc, tsc_diff;
5613 
5614 	if (spdk_unlikely(bdev_io->internal.in_submit_request || bdev_io->internal.io_submit_ch)) {
5615 		/*
5616 		 * Send the completion to the thread that originally submitted the I/O,
5617 		 * which may not be the current thread in the case of QoS.
5618 		 */
5619 		if (bdev_io->internal.io_submit_ch) {
5620 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
5621 			bdev_io->internal.io_submit_ch = NULL;
5622 		}
5623 
5624 		/*
5625 		 * Defer completion to avoid potential infinite recursion if the
5626 		 * user's completion callback issues a new I/O.
5627 		 */
5628 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
5629 				     bdev_io_complete, bdev_io);
5630 		return;
5631 	}
5632 
5633 	tsc = spdk_get_ticks();
5634 	tsc_diff = tsc - bdev_io->internal.submit_tsc;
5635 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io,
5636 			      bdev_io->internal.caller_ctx);
5637 
5638 	TAILQ_REMOVE(&bdev_ch->io_submitted, bdev_io, internal.ch_link);
5639 
5640 	if (bdev_io->internal.ch->histogram) {
5641 		spdk_histogram_data_tally(bdev_io->internal.ch->histogram, tsc_diff);
5642 	}
5643 
5644 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5645 		switch (bdev_io->type) {
5646 		case SPDK_BDEV_IO_TYPE_READ:
5647 			bdev_io->internal.ch->stat.bytes_read += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5648 			bdev_io->internal.ch->stat.num_read_ops++;
5649 			bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
5650 			break;
5651 		case SPDK_BDEV_IO_TYPE_WRITE:
5652 			bdev_io->internal.ch->stat.bytes_written += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5653 			bdev_io->internal.ch->stat.num_write_ops++;
5654 			bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
5655 			break;
5656 		case SPDK_BDEV_IO_TYPE_UNMAP:
5657 			bdev_io->internal.ch->stat.bytes_unmapped += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5658 			bdev_io->internal.ch->stat.num_unmap_ops++;
5659 			bdev_io->internal.ch->stat.unmap_latency_ticks += tsc_diff;
5660 			break;
5661 		case SPDK_BDEV_IO_TYPE_ZCOPY:
5662 			/* Track the data in the start phase only */
5663 			if (bdev_io->u.bdev.zcopy.start) {
5664 				if (bdev_io->u.bdev.zcopy.populate) {
5665 					bdev_io->internal.ch->stat.bytes_read +=
5666 						bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5667 					bdev_io->internal.ch->stat.num_read_ops++;
5668 					bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
5669 				} else {
5670 					bdev_io->internal.ch->stat.bytes_written +=
5671 						bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5672 					bdev_io->internal.ch->stat.num_write_ops++;
5673 					bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
5674 				}
5675 			}
5676 			break;
5677 		default:
5678 			break;
5679 		}
5680 	}
5681 
5682 #ifdef SPDK_CONFIG_VTUNE
5683 	uint64_t now_tsc = spdk_get_ticks();
5684 	if (now_tsc > (bdev_io->internal.ch->start_tsc + bdev_io->internal.ch->interval_tsc)) {
5685 		uint64_t data[5];
5686 
5687 		data[0] = bdev_io->internal.ch->stat.num_read_ops - bdev_io->internal.ch->prev_stat.num_read_ops;
5688 		data[1] = bdev_io->internal.ch->stat.bytes_read - bdev_io->internal.ch->prev_stat.bytes_read;
5689 		data[2] = bdev_io->internal.ch->stat.num_write_ops - bdev_io->internal.ch->prev_stat.num_write_ops;
5690 		data[3] = bdev_io->internal.ch->stat.bytes_written - bdev_io->internal.ch->prev_stat.bytes_written;
5691 		data[4] = bdev_io->bdev->fn_table->get_spin_time ?
5692 			  bdev_io->bdev->fn_table->get_spin_time(spdk_bdev_io_get_io_channel(bdev_io)) : 0;
5693 
5694 		__itt_metadata_add(g_bdev_mgr.domain, __itt_null, bdev_io->internal.ch->handle,
5695 				   __itt_metadata_u64, 5, data);
5696 
5697 		bdev_io->internal.ch->prev_stat = bdev_io->internal.ch->stat;
5698 		bdev_io->internal.ch->start_tsc = now_tsc;
5699 	}
5700 #endif
5701 
5702 	assert(bdev_io->internal.cb != NULL);
5703 	assert(spdk_get_thread() == spdk_bdev_io_get_thread(bdev_io));
5704 
5705 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
5706 			     bdev_io->internal.caller_ctx);
5707 }
5708 
5709 static void bdev_destroy_cb(void *io_device);
5710 
5711 static void
5712 bdev_reset_complete(struct spdk_io_channel_iter *i, int status)
5713 {
5714 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
5715 	struct spdk_bdev *bdev = bdev_io->bdev;
5716 
5717 	if (bdev_io->u.reset.ch_ref != NULL) {
5718 		spdk_put_io_channel(bdev_io->u.reset.ch_ref);
5719 		bdev_io->u.reset.ch_ref = NULL;
5720 	}
5721 
5722 	bdev_io_complete(bdev_io);
5723 
5724 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING &&
5725 	    TAILQ_EMPTY(&bdev->internal.open_descs)) {
5726 		spdk_io_device_unregister(__bdev_to_io_dev(bdev), bdev_destroy_cb);
5727 	}
5728 }
5729 
5730 static void
5731 bdev_unfreeze_channel(struct spdk_io_channel_iter *i)
5732 {
5733 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
5734 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5735 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5736 	struct spdk_bdev_io *queued_reset;
5737 
5738 	ch->flags &= ~BDEV_CH_RESET_IN_PROGRESS;
5739 	while (!TAILQ_EMPTY(&ch->queued_resets)) {
5740 		queued_reset = TAILQ_FIRST(&ch->queued_resets);
5741 		TAILQ_REMOVE(&ch->queued_resets, queued_reset, internal.link);
5742 		spdk_bdev_io_complete(queued_reset, bdev_io->internal.status);
5743 	}
5744 
5745 	spdk_for_each_channel_continue(i, 0);
5746 }
5747 
5748 void
5749 spdk_bdev_io_complete(struct spdk_bdev_io *bdev_io, enum spdk_bdev_io_status status)
5750 {
5751 	struct spdk_bdev *bdev = bdev_io->bdev;
5752 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
5753 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
5754 
5755 	bdev_io->internal.status = status;
5756 
5757 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_RESET)) {
5758 		bool unlock_channels = false;
5759 
5760 		if (status == SPDK_BDEV_IO_STATUS_NOMEM) {
5761 			SPDK_ERRLOG("NOMEM returned for reset\n");
5762 		}
5763 		pthread_mutex_lock(&bdev->internal.mutex);
5764 		if (bdev_io == bdev->internal.reset_in_progress) {
5765 			bdev->internal.reset_in_progress = NULL;
5766 			unlock_channels = true;
5767 		}
5768 		pthread_mutex_unlock(&bdev->internal.mutex);
5769 
5770 		if (unlock_channels) {
5771 			spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_unfreeze_channel,
5772 					      bdev_io, bdev_reset_complete);
5773 			return;
5774 		}
5775 	} else {
5776 		if (spdk_unlikely(bdev_io->internal.orig_iovcnt != 0)) {
5777 			_bdev_io_push_bounce_data_buffer(bdev_io, _bdev_io_complete_push_bounce_done);
5778 			/* bdev IO will be completed in the callback */
5779 			return;
5780 		}
5781 
5782 		_bdev_io_decrement_outstanding(bdev_ch, shared_resource);
5783 		if (spdk_unlikely(_bdev_io_handle_no_mem(bdev_io))) {
5784 			return;
5785 		}
5786 	}
5787 
5788 	bdev_io_complete(bdev_io);
5789 }
5790 
5791 void
5792 spdk_bdev_io_complete_scsi_status(struct spdk_bdev_io *bdev_io, enum spdk_scsi_status sc,
5793 				  enum spdk_scsi_sense sk, uint8_t asc, uint8_t ascq)
5794 {
5795 	if (sc == SPDK_SCSI_STATUS_GOOD) {
5796 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5797 	} else {
5798 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SCSI_ERROR;
5799 		bdev_io->internal.error.scsi.sc = sc;
5800 		bdev_io->internal.error.scsi.sk = sk;
5801 		bdev_io->internal.error.scsi.asc = asc;
5802 		bdev_io->internal.error.scsi.ascq = ascq;
5803 	}
5804 
5805 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5806 }
5807 
5808 void
5809 spdk_bdev_io_get_scsi_status(const struct spdk_bdev_io *bdev_io,
5810 			     int *sc, int *sk, int *asc, int *ascq)
5811 {
5812 	assert(sc != NULL);
5813 	assert(sk != NULL);
5814 	assert(asc != NULL);
5815 	assert(ascq != NULL);
5816 
5817 	switch (bdev_io->internal.status) {
5818 	case SPDK_BDEV_IO_STATUS_SUCCESS:
5819 		*sc = SPDK_SCSI_STATUS_GOOD;
5820 		*sk = SPDK_SCSI_SENSE_NO_SENSE;
5821 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
5822 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
5823 		break;
5824 	case SPDK_BDEV_IO_STATUS_NVME_ERROR:
5825 		spdk_scsi_nvme_translate(bdev_io, sc, sk, asc, ascq);
5826 		break;
5827 	case SPDK_BDEV_IO_STATUS_SCSI_ERROR:
5828 		*sc = bdev_io->internal.error.scsi.sc;
5829 		*sk = bdev_io->internal.error.scsi.sk;
5830 		*asc = bdev_io->internal.error.scsi.asc;
5831 		*ascq = bdev_io->internal.error.scsi.ascq;
5832 		break;
5833 	default:
5834 		*sc = SPDK_SCSI_STATUS_CHECK_CONDITION;
5835 		*sk = SPDK_SCSI_SENSE_ABORTED_COMMAND;
5836 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
5837 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
5838 		break;
5839 	}
5840 }
5841 
5842 void
5843 spdk_bdev_io_complete_aio_status(struct spdk_bdev_io *bdev_io, int aio_result)
5844 {
5845 	if (aio_result == 0) {
5846 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5847 	} else {
5848 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_AIO_ERROR;
5849 	}
5850 
5851 	bdev_io->internal.error.aio_result = aio_result;
5852 
5853 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5854 }
5855 
5856 void
5857 spdk_bdev_io_get_aio_status(const struct spdk_bdev_io *bdev_io, int *aio_result)
5858 {
5859 	assert(aio_result != NULL);
5860 
5861 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_AIO_ERROR) {
5862 		*aio_result = bdev_io->internal.error.aio_result;
5863 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5864 		*aio_result = 0;
5865 	} else {
5866 		*aio_result = -EIO;
5867 	}
5868 }
5869 
5870 void
5871 spdk_bdev_io_complete_nvme_status(struct spdk_bdev_io *bdev_io, uint32_t cdw0, int sct, int sc)
5872 {
5873 	if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_SUCCESS) {
5874 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5875 	} else if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_ABORTED_BY_REQUEST) {
5876 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_ABORTED;
5877 	} else {
5878 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NVME_ERROR;
5879 	}
5880 
5881 	bdev_io->internal.error.nvme.cdw0 = cdw0;
5882 	bdev_io->internal.error.nvme.sct = sct;
5883 	bdev_io->internal.error.nvme.sc = sc;
5884 
5885 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5886 }
5887 
5888 void
5889 spdk_bdev_io_get_nvme_status(const struct spdk_bdev_io *bdev_io, uint32_t *cdw0, int *sct, int *sc)
5890 {
5891 	assert(sct != NULL);
5892 	assert(sc != NULL);
5893 	assert(cdw0 != NULL);
5894 
5895 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_ABORT)) {
5896 		*sct = SPDK_NVME_SCT_GENERIC;
5897 		*sc = SPDK_NVME_SC_SUCCESS;
5898 		if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5899 			*cdw0 = 0;
5900 		} else {
5901 			*cdw0 = 1U;
5902 		}
5903 		return;
5904 	}
5905 
5906 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
5907 		*sct = bdev_io->internal.error.nvme.sct;
5908 		*sc = bdev_io->internal.error.nvme.sc;
5909 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5910 		*sct = SPDK_NVME_SCT_GENERIC;
5911 		*sc = SPDK_NVME_SC_SUCCESS;
5912 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_ABORTED) {
5913 		*sct = SPDK_NVME_SCT_GENERIC;
5914 		*sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
5915 	} else {
5916 		*sct = SPDK_NVME_SCT_GENERIC;
5917 		*sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5918 	}
5919 
5920 	*cdw0 = bdev_io->internal.error.nvme.cdw0;
5921 }
5922 
5923 void
5924 spdk_bdev_io_get_nvme_fused_status(const struct spdk_bdev_io *bdev_io, uint32_t *cdw0,
5925 				   int *first_sct, int *first_sc, int *second_sct, int *second_sc)
5926 {
5927 	assert(first_sct != NULL);
5928 	assert(first_sc != NULL);
5929 	assert(second_sct != NULL);
5930 	assert(second_sc != NULL);
5931 	assert(cdw0 != NULL);
5932 
5933 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
5934 		if (bdev_io->internal.error.nvme.sct == SPDK_NVME_SCT_MEDIA_ERROR &&
5935 		    bdev_io->internal.error.nvme.sc == SPDK_NVME_SC_COMPARE_FAILURE) {
5936 			*first_sct = bdev_io->internal.error.nvme.sct;
5937 			*first_sc = bdev_io->internal.error.nvme.sc;
5938 			*second_sct = SPDK_NVME_SCT_GENERIC;
5939 			*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5940 		} else {
5941 			*first_sct = SPDK_NVME_SCT_GENERIC;
5942 			*first_sc = SPDK_NVME_SC_SUCCESS;
5943 			*second_sct = bdev_io->internal.error.nvme.sct;
5944 			*second_sc = bdev_io->internal.error.nvme.sc;
5945 		}
5946 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_ABORTED) {
5947 		*first_sct = SPDK_NVME_SCT_GENERIC;
5948 		*first_sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
5949 		*second_sct = SPDK_NVME_SCT_GENERIC;
5950 		*second_sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
5951 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5952 		*first_sct = SPDK_NVME_SCT_GENERIC;
5953 		*first_sc = SPDK_NVME_SC_SUCCESS;
5954 		*second_sct = SPDK_NVME_SCT_GENERIC;
5955 		*second_sc = SPDK_NVME_SC_SUCCESS;
5956 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED) {
5957 		*first_sct = SPDK_NVME_SCT_GENERIC;
5958 		*first_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5959 		*second_sct = SPDK_NVME_SCT_GENERIC;
5960 		*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5961 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_MISCOMPARE) {
5962 		*first_sct = SPDK_NVME_SCT_MEDIA_ERROR;
5963 		*first_sc = SPDK_NVME_SC_COMPARE_FAILURE;
5964 		*second_sct = SPDK_NVME_SCT_GENERIC;
5965 		*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5966 	} else {
5967 		*first_sct = SPDK_NVME_SCT_GENERIC;
5968 		*first_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5969 		*second_sct = SPDK_NVME_SCT_GENERIC;
5970 		*second_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5971 	}
5972 
5973 	*cdw0 = bdev_io->internal.error.nvme.cdw0;
5974 }
5975 
5976 struct spdk_thread *
5977 spdk_bdev_io_get_thread(struct spdk_bdev_io *bdev_io)
5978 {
5979 	return spdk_io_channel_get_thread(bdev_io->internal.ch->channel);
5980 }
5981 
5982 struct spdk_io_channel *
5983 spdk_bdev_io_get_io_channel(struct spdk_bdev_io *bdev_io)
5984 {
5985 	return bdev_io->internal.ch->channel;
5986 }
5987 
5988 static int
5989 bdev_register(struct spdk_bdev *bdev)
5990 {
5991 	char *bdev_name;
5992 	char uuid[SPDK_UUID_STRING_LEN];
5993 	int ret;
5994 
5995 	assert(bdev->module != NULL);
5996 
5997 	if (!bdev->name) {
5998 		SPDK_ERRLOG("Bdev name is NULL\n");
5999 		return -EINVAL;
6000 	}
6001 
6002 	if (!strlen(bdev->name)) {
6003 		SPDK_ERRLOG("Bdev name must not be an empty string\n");
6004 		return -EINVAL;
6005 	}
6006 
6007 	/* Users often register their own I/O devices using the bdev name. In
6008 	 * order to avoid conflicts, prepend bdev_. */
6009 	bdev_name = spdk_sprintf_alloc("bdev_%s", bdev->name);
6010 	if (!bdev_name) {
6011 		SPDK_ERRLOG("Unable to allocate memory for internal bdev name.\n");
6012 		return -ENOMEM;
6013 	}
6014 
6015 	bdev->internal.status = SPDK_BDEV_STATUS_READY;
6016 	bdev->internal.measured_queue_depth = UINT64_MAX;
6017 	bdev->internal.claim_module = NULL;
6018 	bdev->internal.qd_poller = NULL;
6019 	bdev->internal.qos = NULL;
6020 
6021 	TAILQ_INIT(&bdev->internal.open_descs);
6022 	TAILQ_INIT(&bdev->internal.locked_ranges);
6023 	TAILQ_INIT(&bdev->internal.pending_locked_ranges);
6024 	TAILQ_INIT(&bdev->aliases);
6025 
6026 	ret = bdev_name_add(&bdev->internal.bdev_name, bdev, bdev->name);
6027 	if (ret != 0) {
6028 		free(bdev_name);
6029 		return ret;
6030 	}
6031 
6032 	/* If the user didn't specify a uuid, generate one. */
6033 	if (spdk_mem_all_zero(&bdev->uuid, sizeof(bdev->uuid))) {
6034 		spdk_uuid_generate(&bdev->uuid);
6035 	}
6036 
6037 	/* Add the UUID alias only if it's different than the name */
6038 	spdk_uuid_fmt_lower(uuid, sizeof(uuid), &bdev->uuid);
6039 	if (strcmp(bdev->name, uuid) != 0) {
6040 		ret = spdk_bdev_alias_add(bdev, uuid);
6041 		if (ret != 0) {
6042 			SPDK_ERRLOG("Unable to add uuid:%s alias for bdev %s\n", uuid, bdev->name);
6043 			bdev_name_del(&bdev->internal.bdev_name);
6044 			free(bdev_name);
6045 			return ret;
6046 		}
6047 	}
6048 
6049 	if (spdk_bdev_get_buf_align(bdev) > 1) {
6050 		if (bdev->split_on_optimal_io_boundary) {
6051 			bdev->optimal_io_boundary = spdk_min(bdev->optimal_io_boundary,
6052 							     SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen);
6053 		} else {
6054 			bdev->split_on_optimal_io_boundary = true;
6055 			bdev->optimal_io_boundary = SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen;
6056 		}
6057 	}
6058 
6059 	/* If the user didn't specify a write unit size, set it to one. */
6060 	if (bdev->write_unit_size == 0) {
6061 		bdev->write_unit_size = 1;
6062 	}
6063 
6064 	/* Set ACWU value to 1 if bdev module did not set it (does not support it natively) */
6065 	if (bdev->acwu == 0) {
6066 		bdev->acwu = 1;
6067 	}
6068 
6069 	if (bdev->phys_blocklen == 0) {
6070 		bdev->phys_blocklen = spdk_bdev_get_data_block_size(bdev);
6071 	}
6072 
6073 	bdev->internal.reset_in_progress = NULL;
6074 
6075 	spdk_io_device_register(__bdev_to_io_dev(bdev),
6076 				bdev_channel_create, bdev_channel_destroy,
6077 				sizeof(struct spdk_bdev_channel),
6078 				bdev_name);
6079 
6080 	free(bdev_name);
6081 
6082 	pthread_mutex_init(&bdev->internal.mutex, NULL);
6083 
6084 	SPDK_DEBUGLOG(bdev, "Inserting bdev %s into list\n", bdev->name);
6085 	TAILQ_INSERT_TAIL(&g_bdev_mgr.bdevs, bdev, internal.link);
6086 
6087 	return 0;
6088 }
6089 
6090 static void
6091 bdev_destroy_cb(void *io_device)
6092 {
6093 	int			rc;
6094 	struct spdk_bdev	*bdev;
6095 	spdk_bdev_unregister_cb	cb_fn;
6096 	void			*cb_arg;
6097 
6098 	bdev = __bdev_from_io_dev(io_device);
6099 	cb_fn = bdev->internal.unregister_cb;
6100 	cb_arg = bdev->internal.unregister_ctx;
6101 
6102 	pthread_mutex_destroy(&bdev->internal.mutex);
6103 	free(bdev->internal.qos);
6104 
6105 	rc = bdev->fn_table->destruct(bdev->ctxt);
6106 	if (rc < 0) {
6107 		SPDK_ERRLOG("destruct failed\n");
6108 	}
6109 	if (rc <= 0 && cb_fn != NULL) {
6110 		cb_fn(cb_arg, rc);
6111 	}
6112 }
6113 
6114 static void
6115 bdev_register_finished(void *arg)
6116 {
6117 	struct spdk_bdev *bdev = arg;
6118 
6119 	spdk_notify_send("bdev_register", spdk_bdev_get_name(bdev));
6120 }
6121 
6122 int
6123 spdk_bdev_register(struct spdk_bdev *bdev)
6124 {
6125 	int rc = bdev_register(bdev);
6126 
6127 	if (rc == 0) {
6128 		/* Examine configuration before initializing I/O */
6129 		bdev_examine(bdev);
6130 
6131 		spdk_bdev_wait_for_examine(bdev_register_finished, bdev);
6132 	}
6133 
6134 	return rc;
6135 }
6136 
6137 void
6138 spdk_bdev_destruct_done(struct spdk_bdev *bdev, int bdeverrno)
6139 {
6140 	if (bdev->internal.unregister_cb != NULL) {
6141 		bdev->internal.unregister_cb(bdev->internal.unregister_ctx, bdeverrno);
6142 	}
6143 }
6144 
6145 static void
6146 _remove_notify(void *arg)
6147 {
6148 	struct spdk_bdev_desc *desc = arg;
6149 
6150 	pthread_mutex_lock(&desc->mutex);
6151 	desc->refs--;
6152 
6153 	if (!desc->closed) {
6154 		pthread_mutex_unlock(&desc->mutex);
6155 		desc->callback.event_fn(SPDK_BDEV_EVENT_REMOVE, desc->bdev, desc->callback.ctx);
6156 		return;
6157 	} else if (0 == desc->refs) {
6158 		/* This descriptor was closed after this remove_notify message was sent.
6159 		 * spdk_bdev_close() could not free the descriptor since this message was
6160 		 * in flight, so we free it now using bdev_desc_free().
6161 		 */
6162 		pthread_mutex_unlock(&desc->mutex);
6163 		bdev_desc_free(desc);
6164 		return;
6165 	}
6166 	pthread_mutex_unlock(&desc->mutex);
6167 }
6168 
6169 /* Must be called while holding g_bdev_mgr.mutex and bdev->internal.mutex.
6170  * returns: 0 - bdev removed and ready to be destructed.
6171  *          -EBUSY - bdev can't be destructed yet.  */
6172 static int
6173 bdev_unregister_unsafe(struct spdk_bdev *bdev)
6174 {
6175 	struct spdk_bdev_desc	*desc, *tmp;
6176 	int			rc = 0;
6177 	char			uuid[SPDK_UUID_STRING_LEN];
6178 
6179 	/* Notify each descriptor about hotremoval */
6180 	TAILQ_FOREACH_SAFE(desc, &bdev->internal.open_descs, link, tmp) {
6181 		rc = -EBUSY;
6182 		pthread_mutex_lock(&desc->mutex);
6183 		/*
6184 		 * Defer invocation of the event_cb to a separate message that will
6185 		 *  run later on its thread.  This ensures this context unwinds and
6186 		 *  we don't recursively unregister this bdev again if the event_cb
6187 		 *  immediately closes its descriptor.
6188 		 */
6189 		desc->refs++;
6190 		spdk_thread_send_msg(desc->thread, _remove_notify, desc);
6191 		pthread_mutex_unlock(&desc->mutex);
6192 	}
6193 
6194 	/* If there are no descriptors, proceed removing the bdev */
6195 	if (rc == 0) {
6196 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
6197 		SPDK_DEBUGLOG(bdev, "Removing bdev %s from list done\n", bdev->name);
6198 
6199 		/* Delete the name and the UUID alias */
6200 		spdk_uuid_fmt_lower(uuid, sizeof(uuid), &bdev->uuid);
6201 		bdev_name_del_unsafe(&bdev->internal.bdev_name);
6202 		bdev_alias_del(bdev, uuid, bdev_name_del_unsafe);
6203 
6204 		spdk_notify_send("bdev_unregister", spdk_bdev_get_name(bdev));
6205 
6206 		if (bdev->internal.reset_in_progress != NULL) {
6207 			/* If reset is in progress, let the completion callback for reset
6208 			 * unregister the bdev.
6209 			 */
6210 			rc = -EBUSY;
6211 		}
6212 	}
6213 
6214 	return rc;
6215 }
6216 
6217 static void
6218 bdev_unregister_abort_channel(struct spdk_io_channel_iter *i)
6219 {
6220 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
6221 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(io_ch);
6222 
6223 	bdev_channel_abort_queued_ios(bdev_ch);
6224 	spdk_for_each_channel_continue(i, 0);
6225 }
6226 
6227 static void
6228 bdev_unregister(struct spdk_io_channel_iter *i, int status)
6229 {
6230 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
6231 	int rc;
6232 
6233 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6234 	pthread_mutex_lock(&bdev->internal.mutex);
6235 	/*
6236 	 * Set the status to REMOVING after completing to abort channels. Otherwise,
6237 	 * the last spdk_bdev_close() may call spdk_io_device_unregister() while
6238 	 * spdk_for_each_channel() is executed and spdk_io_device_unregister() may fail.
6239 	 */
6240 	bdev->internal.status = SPDK_BDEV_STATUS_REMOVING;
6241 	rc = bdev_unregister_unsafe(bdev);
6242 	pthread_mutex_unlock(&bdev->internal.mutex);
6243 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6244 
6245 	if (rc == 0) {
6246 		spdk_io_device_unregister(__bdev_to_io_dev(bdev), bdev_destroy_cb);
6247 	}
6248 }
6249 
6250 void
6251 spdk_bdev_unregister(struct spdk_bdev *bdev, spdk_bdev_unregister_cb cb_fn, void *cb_arg)
6252 {
6253 	struct spdk_thread	*thread;
6254 
6255 	SPDK_DEBUGLOG(bdev, "Removing bdev %s from list\n", bdev->name);
6256 
6257 	thread = spdk_get_thread();
6258 	if (!thread) {
6259 		/* The user called this from a non-SPDK thread. */
6260 		if (cb_fn != NULL) {
6261 			cb_fn(cb_arg, -ENOTSUP);
6262 		}
6263 		return;
6264 	}
6265 
6266 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6267 	if (bdev->internal.status == SPDK_BDEV_STATUS_UNREGISTERING ||
6268 	    bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
6269 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
6270 		if (cb_fn) {
6271 			cb_fn(cb_arg, -EBUSY);
6272 		}
6273 		return;
6274 	}
6275 
6276 	pthread_mutex_lock(&bdev->internal.mutex);
6277 	bdev->internal.status = SPDK_BDEV_STATUS_UNREGISTERING;
6278 	bdev->internal.unregister_cb = cb_fn;
6279 	bdev->internal.unregister_ctx = cb_arg;
6280 	pthread_mutex_unlock(&bdev->internal.mutex);
6281 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6282 
6283 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
6284 			      bdev_unregister_abort_channel,
6285 			      bdev,
6286 			      bdev_unregister);
6287 }
6288 
6289 static void
6290 _tmp_bdev_event_cb(enum spdk_bdev_event_type type, struct spdk_bdev *bdev, void *ctx)
6291 {
6292 	SPDK_NOTICELOG("Unexpected event type: %d\n", type);
6293 }
6294 
6295 int
6296 spdk_bdev_unregister_by_name(const char *bdev_name, struct spdk_bdev_module *module,
6297 			     spdk_bdev_unregister_cb cb_fn, void *cb_arg)
6298 {
6299 	struct spdk_bdev_desc *desc;
6300 	struct spdk_bdev *bdev;
6301 	int rc;
6302 
6303 	rc = spdk_bdev_open_ext(bdev_name, false, _tmp_bdev_event_cb, NULL, &desc);
6304 	if (rc != 0) {
6305 		SPDK_ERRLOG("Failed to open bdev with name: %s\n", bdev_name);
6306 		return rc;
6307 	}
6308 
6309 	bdev = spdk_bdev_desc_get_bdev(desc);
6310 
6311 	if (bdev->module != module) {
6312 		spdk_bdev_close(desc);
6313 		SPDK_ERRLOG("Bdev %s was not registered by the specified module.\n",
6314 			    bdev_name);
6315 		return -ENODEV;
6316 	}
6317 
6318 	spdk_bdev_unregister(bdev, cb_fn, cb_arg);
6319 
6320 	spdk_bdev_close(desc);
6321 
6322 	return 0;
6323 }
6324 
6325 static int
6326 bdev_start_qos(struct spdk_bdev *bdev)
6327 {
6328 	struct set_qos_limit_ctx *ctx;
6329 
6330 	/* Enable QoS */
6331 	if (bdev->internal.qos && bdev->internal.qos->thread == NULL) {
6332 		ctx = calloc(1, sizeof(*ctx));
6333 		if (ctx == NULL) {
6334 			SPDK_ERRLOG("Failed to allocate memory for QoS context\n");
6335 			return -ENOMEM;
6336 		}
6337 		ctx->bdev = bdev;
6338 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
6339 				      bdev_enable_qos_msg, ctx,
6340 				      bdev_enable_qos_done);
6341 	}
6342 
6343 	return 0;
6344 }
6345 
6346 static int
6347 bdev_open(struct spdk_bdev *bdev, bool write, struct spdk_bdev_desc *desc)
6348 {
6349 	struct spdk_thread *thread;
6350 	int rc = 0;
6351 
6352 	thread = spdk_get_thread();
6353 	if (!thread) {
6354 		SPDK_ERRLOG("Cannot open bdev from non-SPDK thread.\n");
6355 		return -ENOTSUP;
6356 	}
6357 
6358 	SPDK_DEBUGLOG(bdev, "Opening descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
6359 		      spdk_get_thread());
6360 
6361 	desc->bdev = bdev;
6362 	desc->thread = thread;
6363 	desc->write = write;
6364 
6365 	pthread_mutex_lock(&bdev->internal.mutex);
6366 	if (bdev->internal.status == SPDK_BDEV_STATUS_UNREGISTERING ||
6367 	    bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
6368 		pthread_mutex_unlock(&bdev->internal.mutex);
6369 		return -ENODEV;
6370 	}
6371 
6372 	if (write && bdev->internal.claim_module) {
6373 		SPDK_ERRLOG("Could not open %s - %s module already claimed it\n",
6374 			    bdev->name, bdev->internal.claim_module->name);
6375 		pthread_mutex_unlock(&bdev->internal.mutex);
6376 		return -EPERM;
6377 	}
6378 
6379 	rc = bdev_start_qos(bdev);
6380 	if (rc != 0) {
6381 		SPDK_ERRLOG("Failed to start QoS on bdev %s\n", bdev->name);
6382 		pthread_mutex_unlock(&bdev->internal.mutex);
6383 		return rc;
6384 	}
6385 
6386 	TAILQ_INSERT_TAIL(&bdev->internal.open_descs, desc, link);
6387 
6388 	pthread_mutex_unlock(&bdev->internal.mutex);
6389 
6390 	return 0;
6391 }
6392 
6393 static int
6394 bdev_desc_alloc(struct spdk_bdev *bdev, spdk_bdev_event_cb_t event_cb, void *event_ctx,
6395 		struct spdk_bdev_desc **_desc)
6396 {
6397 	struct spdk_bdev_desc *desc;
6398 	unsigned int event_id;
6399 
6400 	desc = calloc(1, sizeof(*desc));
6401 	if (desc == NULL) {
6402 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
6403 		return -ENOMEM;
6404 	}
6405 
6406 	TAILQ_INIT(&desc->pending_media_events);
6407 	TAILQ_INIT(&desc->free_media_events);
6408 
6409 	desc->memory_domains_supported = spdk_bdev_get_memory_domains(bdev, NULL, 0) > 0;
6410 	desc->callback.event_fn = event_cb;
6411 	desc->callback.ctx = event_ctx;
6412 	pthread_mutex_init(&desc->mutex, NULL);
6413 
6414 	if (bdev->media_events) {
6415 		desc->media_events_buffer = calloc(MEDIA_EVENT_POOL_SIZE,
6416 						   sizeof(*desc->media_events_buffer));
6417 		if (desc->media_events_buffer == NULL) {
6418 			SPDK_ERRLOG("Failed to initialize media event pool\n");
6419 			bdev_desc_free(desc);
6420 			return -ENOMEM;
6421 		}
6422 
6423 		for (event_id = 0; event_id < MEDIA_EVENT_POOL_SIZE; ++event_id) {
6424 			TAILQ_INSERT_TAIL(&desc->free_media_events,
6425 					  &desc->media_events_buffer[event_id], tailq);
6426 		}
6427 	}
6428 
6429 	*_desc = desc;
6430 
6431 	return 0;
6432 }
6433 
6434 int
6435 spdk_bdev_open_ext(const char *bdev_name, bool write, spdk_bdev_event_cb_t event_cb,
6436 		   void *event_ctx, struct spdk_bdev_desc **_desc)
6437 {
6438 	struct spdk_bdev_desc *desc;
6439 	struct spdk_bdev *bdev;
6440 	int rc;
6441 
6442 	if (event_cb == NULL) {
6443 		SPDK_ERRLOG("Missing event callback function\n");
6444 		return -EINVAL;
6445 	}
6446 
6447 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6448 
6449 	bdev = bdev_get_by_name(bdev_name);
6450 
6451 	if (bdev == NULL) {
6452 		SPDK_NOTICELOG("Currently unable to find bdev with name: %s\n", bdev_name);
6453 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
6454 		return -ENODEV;
6455 	}
6456 
6457 	rc = bdev_desc_alloc(bdev, event_cb, event_ctx, &desc);
6458 	if (rc != 0) {
6459 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
6460 		return rc;
6461 	}
6462 
6463 	rc = bdev_open(bdev, write, desc);
6464 	if (rc != 0) {
6465 		bdev_desc_free(desc);
6466 		desc = NULL;
6467 	}
6468 
6469 	*_desc = desc;
6470 
6471 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6472 
6473 	return rc;
6474 }
6475 
6476 static void
6477 bdev_close(struct spdk_bdev *bdev, struct spdk_bdev_desc *desc)
6478 {
6479 	int rc;
6480 
6481 	pthread_mutex_lock(&bdev->internal.mutex);
6482 	pthread_mutex_lock(&desc->mutex);
6483 
6484 	TAILQ_REMOVE(&bdev->internal.open_descs, desc, link);
6485 
6486 	desc->closed = true;
6487 
6488 	if (0 == desc->refs) {
6489 		pthread_mutex_unlock(&desc->mutex);
6490 		bdev_desc_free(desc);
6491 	} else {
6492 		pthread_mutex_unlock(&desc->mutex);
6493 	}
6494 
6495 	/* If no more descriptors, kill QoS channel */
6496 	if (bdev->internal.qos && TAILQ_EMPTY(&bdev->internal.open_descs)) {
6497 		SPDK_DEBUGLOG(bdev, "Closed last descriptor for bdev %s on thread %p. Stopping QoS.\n",
6498 			      bdev->name, spdk_get_thread());
6499 
6500 		if (bdev_qos_destroy(bdev)) {
6501 			/* There isn't anything we can do to recover here. Just let the
6502 			 * old QoS poller keep running. The QoS handling won't change
6503 			 * cores when the user allocates a new channel, but it won't break. */
6504 			SPDK_ERRLOG("Unable to shut down QoS poller. It will continue running on the current thread.\n");
6505 		}
6506 	}
6507 
6508 	spdk_bdev_set_qd_sampling_period(bdev, 0);
6509 
6510 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING && TAILQ_EMPTY(&bdev->internal.open_descs)) {
6511 		rc = bdev_unregister_unsafe(bdev);
6512 		pthread_mutex_unlock(&bdev->internal.mutex);
6513 
6514 		if (rc == 0) {
6515 			spdk_io_device_unregister(__bdev_to_io_dev(bdev), bdev_destroy_cb);
6516 		}
6517 	} else {
6518 		pthread_mutex_unlock(&bdev->internal.mutex);
6519 	}
6520 }
6521 
6522 void
6523 spdk_bdev_close(struct spdk_bdev_desc *desc)
6524 {
6525 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
6526 
6527 	SPDK_DEBUGLOG(bdev, "Closing descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
6528 		      spdk_get_thread());
6529 
6530 	assert(desc->thread == spdk_get_thread());
6531 
6532 	spdk_poller_unregister(&desc->io_timeout_poller);
6533 
6534 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6535 
6536 	bdev_close(bdev, desc);
6537 
6538 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6539 }
6540 
6541 int
6542 spdk_bdev_module_claim_bdev(struct spdk_bdev *bdev, struct spdk_bdev_desc *desc,
6543 			    struct spdk_bdev_module *module)
6544 {
6545 	if (bdev->internal.claim_module != NULL) {
6546 		SPDK_ERRLOG("bdev %s already claimed by module %s\n", bdev->name,
6547 			    bdev->internal.claim_module->name);
6548 		return -EPERM;
6549 	}
6550 
6551 	if (desc && !desc->write) {
6552 		desc->write = true;
6553 	}
6554 
6555 	bdev->internal.claim_module = module;
6556 	return 0;
6557 }
6558 
6559 void
6560 spdk_bdev_module_release_bdev(struct spdk_bdev *bdev)
6561 {
6562 	assert(bdev->internal.claim_module != NULL);
6563 	bdev->internal.claim_module = NULL;
6564 }
6565 
6566 struct spdk_bdev *
6567 spdk_bdev_desc_get_bdev(struct spdk_bdev_desc *desc)
6568 {
6569 	assert(desc != NULL);
6570 	return desc->bdev;
6571 }
6572 
6573 int
6574 spdk_for_each_bdev(void *ctx, spdk_for_each_bdev_fn fn)
6575 {
6576 	struct spdk_bdev *bdev, *tmp;
6577 	struct spdk_bdev_desc *desc;
6578 	int rc = 0;
6579 
6580 	assert(fn != NULL);
6581 
6582 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6583 	bdev = spdk_bdev_first();
6584 	while (bdev != NULL) {
6585 		rc = bdev_desc_alloc(bdev, _tmp_bdev_event_cb, NULL, &desc);
6586 		if (rc != 0) {
6587 			break;
6588 		}
6589 		rc = bdev_open(bdev, false, desc);
6590 		if (rc != 0) {
6591 			bdev_desc_free(desc);
6592 			break;
6593 		}
6594 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
6595 
6596 		rc = fn(ctx, bdev);
6597 
6598 		pthread_mutex_lock(&g_bdev_mgr.mutex);
6599 		tmp = spdk_bdev_next(bdev);
6600 		bdev_close(bdev, desc);
6601 		if (rc != 0) {
6602 			break;
6603 		}
6604 		bdev = tmp;
6605 	}
6606 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6607 
6608 	return rc;
6609 }
6610 
6611 int
6612 spdk_for_each_bdev_leaf(void *ctx, spdk_for_each_bdev_fn fn)
6613 {
6614 	struct spdk_bdev *bdev, *tmp;
6615 	struct spdk_bdev_desc *desc;
6616 	int rc = 0;
6617 
6618 	assert(fn != NULL);
6619 
6620 	pthread_mutex_lock(&g_bdev_mgr.mutex);
6621 	bdev = spdk_bdev_first_leaf();
6622 	while (bdev != NULL) {
6623 		rc = bdev_desc_alloc(bdev, _tmp_bdev_event_cb, NULL, &desc);
6624 		if (rc != 0) {
6625 			break;
6626 		}
6627 		rc = bdev_open(bdev, false, desc);
6628 		if (rc != 0) {
6629 			bdev_desc_free(desc);
6630 			break;
6631 		}
6632 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
6633 
6634 		rc = fn(ctx, bdev);
6635 
6636 		pthread_mutex_lock(&g_bdev_mgr.mutex);
6637 		tmp = spdk_bdev_next_leaf(bdev);
6638 		bdev_close(bdev, desc);
6639 		if (rc != 0) {
6640 			break;
6641 		}
6642 		bdev = tmp;
6643 	}
6644 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
6645 
6646 	return rc;
6647 }
6648 
6649 void
6650 spdk_bdev_io_get_iovec(struct spdk_bdev_io *bdev_io, struct iovec **iovp, int *iovcntp)
6651 {
6652 	struct iovec *iovs;
6653 	int iovcnt;
6654 
6655 	if (bdev_io == NULL) {
6656 		return;
6657 	}
6658 
6659 	switch (bdev_io->type) {
6660 	case SPDK_BDEV_IO_TYPE_READ:
6661 	case SPDK_BDEV_IO_TYPE_WRITE:
6662 	case SPDK_BDEV_IO_TYPE_ZCOPY:
6663 		iovs = bdev_io->u.bdev.iovs;
6664 		iovcnt = bdev_io->u.bdev.iovcnt;
6665 		break;
6666 	default:
6667 		iovs = NULL;
6668 		iovcnt = 0;
6669 		break;
6670 	}
6671 
6672 	if (iovp) {
6673 		*iovp = iovs;
6674 	}
6675 	if (iovcntp) {
6676 		*iovcntp = iovcnt;
6677 	}
6678 }
6679 
6680 void *
6681 spdk_bdev_io_get_md_buf(struct spdk_bdev_io *bdev_io)
6682 {
6683 	if (bdev_io == NULL) {
6684 		return NULL;
6685 	}
6686 
6687 	if (!spdk_bdev_is_md_separate(bdev_io->bdev)) {
6688 		return NULL;
6689 	}
6690 
6691 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ ||
6692 	    bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
6693 		return bdev_io->u.bdev.md_buf;
6694 	}
6695 
6696 	return NULL;
6697 }
6698 
6699 void *
6700 spdk_bdev_io_get_cb_arg(struct spdk_bdev_io *bdev_io)
6701 {
6702 	if (bdev_io == NULL) {
6703 		assert(false);
6704 		return NULL;
6705 	}
6706 
6707 	return bdev_io->internal.caller_ctx;
6708 }
6709 
6710 void
6711 spdk_bdev_module_list_add(struct spdk_bdev_module *bdev_module)
6712 {
6713 
6714 	if (spdk_bdev_module_list_find(bdev_module->name)) {
6715 		SPDK_ERRLOG("ERROR: module '%s' already registered.\n", bdev_module->name);
6716 		assert(false);
6717 	}
6718 
6719 	/*
6720 	 * Modules with examine callbacks must be initialized first, so they are
6721 	 *  ready to handle examine callbacks from later modules that will
6722 	 *  register physical bdevs.
6723 	 */
6724 	if (bdev_module->examine_config != NULL || bdev_module->examine_disk != NULL) {
6725 		TAILQ_INSERT_HEAD(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
6726 	} else {
6727 		TAILQ_INSERT_TAIL(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
6728 	}
6729 }
6730 
6731 struct spdk_bdev_module *
6732 spdk_bdev_module_list_find(const char *name)
6733 {
6734 	struct spdk_bdev_module *bdev_module;
6735 
6736 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
6737 		if (strcmp(name, bdev_module->name) == 0) {
6738 			break;
6739 		}
6740 	}
6741 
6742 	return bdev_module;
6743 }
6744 
6745 static void
6746 bdev_write_zero_buffer_next(void *_bdev_io)
6747 {
6748 	struct spdk_bdev_io *bdev_io = _bdev_io;
6749 	uint64_t num_bytes, num_blocks;
6750 	void *md_buf = NULL;
6751 	int rc;
6752 
6753 	num_bytes = spdk_min(_bdev_get_block_size_with_md(bdev_io->bdev) *
6754 			     bdev_io->u.bdev.split_remaining_num_blocks,
6755 			     ZERO_BUFFER_SIZE);
6756 	num_blocks = num_bytes / _bdev_get_block_size_with_md(bdev_io->bdev);
6757 
6758 	if (spdk_bdev_is_md_separate(bdev_io->bdev)) {
6759 		md_buf = (char *)g_bdev_mgr.zero_buffer +
6760 			 spdk_bdev_get_block_size(bdev_io->bdev) * num_blocks;
6761 	}
6762 
6763 	rc = bdev_write_blocks_with_md(bdev_io->internal.desc,
6764 				       spdk_io_channel_from_ctx(bdev_io->internal.ch),
6765 				       g_bdev_mgr.zero_buffer, md_buf,
6766 				       bdev_io->u.bdev.split_current_offset_blocks, num_blocks,
6767 				       bdev_write_zero_buffer_done, bdev_io);
6768 	if (rc == 0) {
6769 		bdev_io->u.bdev.split_remaining_num_blocks -= num_blocks;
6770 		bdev_io->u.bdev.split_current_offset_blocks += num_blocks;
6771 	} else if (rc == -ENOMEM) {
6772 		bdev_queue_io_wait_with_cb(bdev_io, bdev_write_zero_buffer_next);
6773 	} else {
6774 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
6775 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
6776 	}
6777 }
6778 
6779 static void
6780 bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
6781 {
6782 	struct spdk_bdev_io *parent_io = cb_arg;
6783 
6784 	spdk_bdev_free_io(bdev_io);
6785 
6786 	if (!success) {
6787 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
6788 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
6789 		return;
6790 	}
6791 
6792 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
6793 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
6794 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
6795 		return;
6796 	}
6797 
6798 	bdev_write_zero_buffer_next(parent_io);
6799 }
6800 
6801 static void
6802 bdev_set_qos_limit_done(struct set_qos_limit_ctx *ctx, int status)
6803 {
6804 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
6805 	ctx->bdev->internal.qos_mod_in_progress = false;
6806 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
6807 
6808 	if (ctx->cb_fn) {
6809 		ctx->cb_fn(ctx->cb_arg, status);
6810 	}
6811 	free(ctx);
6812 }
6813 
6814 static void
6815 bdev_disable_qos_done(void *cb_arg)
6816 {
6817 	struct set_qos_limit_ctx *ctx = cb_arg;
6818 	struct spdk_bdev *bdev = ctx->bdev;
6819 	struct spdk_bdev_io *bdev_io;
6820 	struct spdk_bdev_qos *qos;
6821 
6822 	pthread_mutex_lock(&bdev->internal.mutex);
6823 	qos = bdev->internal.qos;
6824 	bdev->internal.qos = NULL;
6825 	pthread_mutex_unlock(&bdev->internal.mutex);
6826 
6827 	while (!TAILQ_EMPTY(&qos->queued)) {
6828 		/* Send queued I/O back to their original thread for resubmission. */
6829 		bdev_io = TAILQ_FIRST(&qos->queued);
6830 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
6831 
6832 		if (bdev_io->internal.io_submit_ch) {
6833 			/*
6834 			 * Channel was changed when sending it to the QoS thread - change it back
6835 			 *  before sending it back to the original thread.
6836 			 */
6837 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
6838 			bdev_io->internal.io_submit_ch = NULL;
6839 		}
6840 
6841 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
6842 				     _bdev_io_submit, bdev_io);
6843 	}
6844 
6845 	if (qos->thread != NULL) {
6846 		spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
6847 		spdk_poller_unregister(&qos->poller);
6848 	}
6849 
6850 	free(qos);
6851 
6852 	bdev_set_qos_limit_done(ctx, 0);
6853 }
6854 
6855 static void
6856 bdev_disable_qos_msg_done(struct spdk_io_channel_iter *i, int status)
6857 {
6858 	void *io_device = spdk_io_channel_iter_get_io_device(i);
6859 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
6860 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6861 	struct spdk_thread *thread;
6862 
6863 	pthread_mutex_lock(&bdev->internal.mutex);
6864 	thread = bdev->internal.qos->thread;
6865 	pthread_mutex_unlock(&bdev->internal.mutex);
6866 
6867 	if (thread != NULL) {
6868 		spdk_thread_send_msg(thread, bdev_disable_qos_done, ctx);
6869 	} else {
6870 		bdev_disable_qos_done(ctx);
6871 	}
6872 }
6873 
6874 static void
6875 bdev_disable_qos_msg(struct spdk_io_channel_iter *i)
6876 {
6877 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
6878 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
6879 
6880 	bdev_ch->flags &= ~BDEV_CH_QOS_ENABLED;
6881 
6882 	spdk_for_each_channel_continue(i, 0);
6883 }
6884 
6885 static void
6886 bdev_update_qos_rate_limit_msg(void *cb_arg)
6887 {
6888 	struct set_qos_limit_ctx *ctx = cb_arg;
6889 	struct spdk_bdev *bdev = ctx->bdev;
6890 
6891 	pthread_mutex_lock(&bdev->internal.mutex);
6892 	bdev_qos_update_max_quota_per_timeslice(bdev->internal.qos);
6893 	pthread_mutex_unlock(&bdev->internal.mutex);
6894 
6895 	bdev_set_qos_limit_done(ctx, 0);
6896 }
6897 
6898 static void
6899 bdev_enable_qos_msg(struct spdk_io_channel_iter *i)
6900 {
6901 	void *io_device = spdk_io_channel_iter_get_io_device(i);
6902 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
6903 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
6904 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
6905 
6906 	pthread_mutex_lock(&bdev->internal.mutex);
6907 	bdev_enable_qos(bdev, bdev_ch);
6908 	pthread_mutex_unlock(&bdev->internal.mutex);
6909 	spdk_for_each_channel_continue(i, 0);
6910 }
6911 
6912 static void
6913 bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status)
6914 {
6915 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6916 
6917 	bdev_set_qos_limit_done(ctx, status);
6918 }
6919 
6920 static void
6921 bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
6922 {
6923 	int i;
6924 
6925 	assert(bdev->internal.qos != NULL);
6926 
6927 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6928 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
6929 			bdev->internal.qos->rate_limits[i].limit = limits[i];
6930 
6931 			if (limits[i] == 0) {
6932 				bdev->internal.qos->rate_limits[i].limit =
6933 					SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
6934 			}
6935 		}
6936 	}
6937 }
6938 
6939 void
6940 spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits,
6941 			      void (*cb_fn)(void *cb_arg, int status), void *cb_arg)
6942 {
6943 	struct set_qos_limit_ctx	*ctx;
6944 	uint32_t			limit_set_complement;
6945 	uint64_t			min_limit_per_sec;
6946 	int				i;
6947 	bool				disable_rate_limit = true;
6948 
6949 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6950 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
6951 			continue;
6952 		}
6953 
6954 		if (limits[i] > 0) {
6955 			disable_rate_limit = false;
6956 		}
6957 
6958 		if (bdev_qos_is_iops_rate_limit(i) == true) {
6959 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
6960 		} else {
6961 			/* Change from megabyte to byte rate limit */
6962 			limits[i] = limits[i] * 1024 * 1024;
6963 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
6964 		}
6965 
6966 		limit_set_complement = limits[i] % min_limit_per_sec;
6967 		if (limit_set_complement) {
6968 			SPDK_ERRLOG("Requested rate limit %" PRIu64 " is not a multiple of %" PRIu64 "\n",
6969 				    limits[i], min_limit_per_sec);
6970 			limits[i] += min_limit_per_sec - limit_set_complement;
6971 			SPDK_ERRLOG("Round up the rate limit to %" PRIu64 "\n", limits[i]);
6972 		}
6973 	}
6974 
6975 	ctx = calloc(1, sizeof(*ctx));
6976 	if (ctx == NULL) {
6977 		cb_fn(cb_arg, -ENOMEM);
6978 		return;
6979 	}
6980 
6981 	ctx->cb_fn = cb_fn;
6982 	ctx->cb_arg = cb_arg;
6983 	ctx->bdev = bdev;
6984 
6985 	pthread_mutex_lock(&bdev->internal.mutex);
6986 	if (bdev->internal.qos_mod_in_progress) {
6987 		pthread_mutex_unlock(&bdev->internal.mutex);
6988 		free(ctx);
6989 		cb_fn(cb_arg, -EAGAIN);
6990 		return;
6991 	}
6992 	bdev->internal.qos_mod_in_progress = true;
6993 
6994 	if (disable_rate_limit == true && bdev->internal.qos) {
6995 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6996 			if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED &&
6997 			    (bdev->internal.qos->rate_limits[i].limit > 0 &&
6998 			     bdev->internal.qos->rate_limits[i].limit !=
6999 			     SPDK_BDEV_QOS_LIMIT_NOT_DEFINED)) {
7000 				disable_rate_limit = false;
7001 				break;
7002 			}
7003 		}
7004 	}
7005 
7006 	if (disable_rate_limit == false) {
7007 		if (bdev->internal.qos == NULL) {
7008 			bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
7009 			if (!bdev->internal.qos) {
7010 				pthread_mutex_unlock(&bdev->internal.mutex);
7011 				SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
7012 				bdev_set_qos_limit_done(ctx, -ENOMEM);
7013 				return;
7014 			}
7015 		}
7016 
7017 		if (bdev->internal.qos->thread == NULL) {
7018 			/* Enabling */
7019 			bdev_set_qos_rate_limits(bdev, limits);
7020 
7021 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
7022 					      bdev_enable_qos_msg, ctx,
7023 					      bdev_enable_qos_done);
7024 		} else {
7025 			/* Updating */
7026 			bdev_set_qos_rate_limits(bdev, limits);
7027 
7028 			spdk_thread_send_msg(bdev->internal.qos->thread,
7029 					     bdev_update_qos_rate_limit_msg, ctx);
7030 		}
7031 	} else {
7032 		if (bdev->internal.qos != NULL) {
7033 			bdev_set_qos_rate_limits(bdev, limits);
7034 
7035 			/* Disabling */
7036 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
7037 					      bdev_disable_qos_msg, ctx,
7038 					      bdev_disable_qos_msg_done);
7039 		} else {
7040 			pthread_mutex_unlock(&bdev->internal.mutex);
7041 			bdev_set_qos_limit_done(ctx, 0);
7042 			return;
7043 		}
7044 	}
7045 
7046 	pthread_mutex_unlock(&bdev->internal.mutex);
7047 }
7048 
7049 struct spdk_bdev_histogram_ctx {
7050 	spdk_bdev_histogram_status_cb cb_fn;
7051 	void *cb_arg;
7052 	struct spdk_bdev *bdev;
7053 	int status;
7054 };
7055 
7056 static void
7057 bdev_histogram_disable_channel_cb(struct spdk_io_channel_iter *i, int status)
7058 {
7059 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7060 
7061 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
7062 	ctx->bdev->internal.histogram_in_progress = false;
7063 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
7064 	ctx->cb_fn(ctx->cb_arg, ctx->status);
7065 	free(ctx);
7066 }
7067 
7068 static void
7069 bdev_histogram_disable_channel(struct spdk_io_channel_iter *i)
7070 {
7071 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7072 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7073 
7074 	if (ch->histogram != NULL) {
7075 		spdk_histogram_data_free(ch->histogram);
7076 		ch->histogram = NULL;
7077 	}
7078 	spdk_for_each_channel_continue(i, 0);
7079 }
7080 
7081 static void
7082 bdev_histogram_enable_channel_cb(struct spdk_io_channel_iter *i, int status)
7083 {
7084 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7085 
7086 	if (status != 0) {
7087 		ctx->status = status;
7088 		ctx->bdev->internal.histogram_enabled = false;
7089 		spdk_for_each_channel(__bdev_to_io_dev(ctx->bdev), bdev_histogram_disable_channel, ctx,
7090 				      bdev_histogram_disable_channel_cb);
7091 	} else {
7092 		pthread_mutex_lock(&ctx->bdev->internal.mutex);
7093 		ctx->bdev->internal.histogram_in_progress = false;
7094 		pthread_mutex_unlock(&ctx->bdev->internal.mutex);
7095 		ctx->cb_fn(ctx->cb_arg, ctx->status);
7096 		free(ctx);
7097 	}
7098 }
7099 
7100 static void
7101 bdev_histogram_enable_channel(struct spdk_io_channel_iter *i)
7102 {
7103 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7104 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7105 	int status = 0;
7106 
7107 	if (ch->histogram == NULL) {
7108 		ch->histogram = spdk_histogram_data_alloc();
7109 		if (ch->histogram == NULL) {
7110 			status = -ENOMEM;
7111 		}
7112 	}
7113 
7114 	spdk_for_each_channel_continue(i, status);
7115 }
7116 
7117 void
7118 spdk_bdev_histogram_enable(struct spdk_bdev *bdev, spdk_bdev_histogram_status_cb cb_fn,
7119 			   void *cb_arg, bool enable)
7120 {
7121 	struct spdk_bdev_histogram_ctx *ctx;
7122 
7123 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_ctx));
7124 	if (ctx == NULL) {
7125 		cb_fn(cb_arg, -ENOMEM);
7126 		return;
7127 	}
7128 
7129 	ctx->bdev = bdev;
7130 	ctx->status = 0;
7131 	ctx->cb_fn = cb_fn;
7132 	ctx->cb_arg = cb_arg;
7133 
7134 	pthread_mutex_lock(&bdev->internal.mutex);
7135 	if (bdev->internal.histogram_in_progress) {
7136 		pthread_mutex_unlock(&bdev->internal.mutex);
7137 		free(ctx);
7138 		cb_fn(cb_arg, -EAGAIN);
7139 		return;
7140 	}
7141 
7142 	bdev->internal.histogram_in_progress = true;
7143 	pthread_mutex_unlock(&bdev->internal.mutex);
7144 
7145 	bdev->internal.histogram_enabled = enable;
7146 
7147 	if (enable) {
7148 		/* Allocate histogram for each channel */
7149 		spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_enable_channel, ctx,
7150 				      bdev_histogram_enable_channel_cb);
7151 	} else {
7152 		spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_disable_channel, ctx,
7153 				      bdev_histogram_disable_channel_cb);
7154 	}
7155 }
7156 
7157 struct spdk_bdev_histogram_data_ctx {
7158 	spdk_bdev_histogram_data_cb cb_fn;
7159 	void *cb_arg;
7160 	struct spdk_bdev *bdev;
7161 	/** merged histogram data from all channels */
7162 	struct spdk_histogram_data	*histogram;
7163 };
7164 
7165 static void
7166 bdev_histogram_get_channel_cb(struct spdk_io_channel_iter *i, int status)
7167 {
7168 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7169 
7170 	ctx->cb_fn(ctx->cb_arg, status, ctx->histogram);
7171 	free(ctx);
7172 }
7173 
7174 static void
7175 bdev_histogram_get_channel(struct spdk_io_channel_iter *i)
7176 {
7177 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7178 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7179 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7180 	int status = 0;
7181 
7182 	if (ch->histogram == NULL) {
7183 		status = -EFAULT;
7184 	} else {
7185 		spdk_histogram_data_merge(ctx->histogram, ch->histogram);
7186 	}
7187 
7188 	spdk_for_each_channel_continue(i, status);
7189 }
7190 
7191 void
7192 spdk_bdev_histogram_get(struct spdk_bdev *bdev, struct spdk_histogram_data *histogram,
7193 			spdk_bdev_histogram_data_cb cb_fn,
7194 			void *cb_arg)
7195 {
7196 	struct spdk_bdev_histogram_data_ctx *ctx;
7197 
7198 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_data_ctx));
7199 	if (ctx == NULL) {
7200 		cb_fn(cb_arg, -ENOMEM, NULL);
7201 		return;
7202 	}
7203 
7204 	ctx->bdev = bdev;
7205 	ctx->cb_fn = cb_fn;
7206 	ctx->cb_arg = cb_arg;
7207 
7208 	ctx->histogram = histogram;
7209 
7210 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_get_channel, ctx,
7211 			      bdev_histogram_get_channel_cb);
7212 }
7213 
7214 size_t
7215 spdk_bdev_get_media_events(struct spdk_bdev_desc *desc, struct spdk_bdev_media_event *events,
7216 			   size_t max_events)
7217 {
7218 	struct media_event_entry *entry;
7219 	size_t num_events = 0;
7220 
7221 	for (; num_events < max_events; ++num_events) {
7222 		entry = TAILQ_FIRST(&desc->pending_media_events);
7223 		if (entry == NULL) {
7224 			break;
7225 		}
7226 
7227 		events[num_events] = entry->event;
7228 		TAILQ_REMOVE(&desc->pending_media_events, entry, tailq);
7229 		TAILQ_INSERT_TAIL(&desc->free_media_events, entry, tailq);
7230 	}
7231 
7232 	return num_events;
7233 }
7234 
7235 int
7236 spdk_bdev_push_media_events(struct spdk_bdev *bdev, const struct spdk_bdev_media_event *events,
7237 			    size_t num_events)
7238 {
7239 	struct spdk_bdev_desc *desc;
7240 	struct media_event_entry *entry;
7241 	size_t event_id;
7242 	int rc = 0;
7243 
7244 	assert(bdev->media_events);
7245 
7246 	pthread_mutex_lock(&bdev->internal.mutex);
7247 	TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
7248 		if (desc->write) {
7249 			break;
7250 		}
7251 	}
7252 
7253 	if (desc == NULL || desc->media_events_buffer == NULL) {
7254 		rc = -ENODEV;
7255 		goto out;
7256 	}
7257 
7258 	for (event_id = 0; event_id < num_events; ++event_id) {
7259 		entry = TAILQ_FIRST(&desc->free_media_events);
7260 		if (entry == NULL) {
7261 			break;
7262 		}
7263 
7264 		TAILQ_REMOVE(&desc->free_media_events, entry, tailq);
7265 		TAILQ_INSERT_TAIL(&desc->pending_media_events, entry, tailq);
7266 		entry->event = events[event_id];
7267 	}
7268 
7269 	rc = event_id;
7270 out:
7271 	pthread_mutex_unlock(&bdev->internal.mutex);
7272 	return rc;
7273 }
7274 
7275 void
7276 spdk_bdev_notify_media_management(struct spdk_bdev *bdev)
7277 {
7278 	struct spdk_bdev_desc *desc;
7279 
7280 	pthread_mutex_lock(&bdev->internal.mutex);
7281 	TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
7282 		if (!TAILQ_EMPTY(&desc->pending_media_events)) {
7283 			desc->callback.event_fn(SPDK_BDEV_EVENT_MEDIA_MANAGEMENT, bdev,
7284 						desc->callback.ctx);
7285 		}
7286 	}
7287 	pthread_mutex_unlock(&bdev->internal.mutex);
7288 }
7289 
7290 struct locked_lba_range_ctx {
7291 	struct lba_range		range;
7292 	struct spdk_bdev		*bdev;
7293 	struct lba_range		*current_range;
7294 	struct lba_range		*owner_range;
7295 	struct spdk_poller		*poller;
7296 	lock_range_cb			cb_fn;
7297 	void				*cb_arg;
7298 };
7299 
7300 static void
7301 bdev_lock_error_cleanup_cb(struct spdk_io_channel_iter *i, int status)
7302 {
7303 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7304 
7305 	ctx->cb_fn(ctx->cb_arg, -ENOMEM);
7306 	free(ctx);
7307 }
7308 
7309 static void bdev_unlock_lba_range_get_channel(struct spdk_io_channel_iter *i);
7310 
7311 static void
7312 bdev_lock_lba_range_cb(struct spdk_io_channel_iter *i, int status)
7313 {
7314 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7315 	struct spdk_bdev *bdev = ctx->bdev;
7316 
7317 	if (status == -ENOMEM) {
7318 		/* One of the channels could not allocate a range object.
7319 		 * So we have to go back and clean up any ranges that were
7320 		 * allocated successfully before we return error status to
7321 		 * the caller.  We can reuse the unlock function to do that
7322 		 * clean up.
7323 		 */
7324 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
7325 				      bdev_unlock_lba_range_get_channel, ctx,
7326 				      bdev_lock_error_cleanup_cb);
7327 		return;
7328 	}
7329 
7330 	/* All channels have locked this range and no I/O overlapping the range
7331 	 * are outstanding!  Set the owner_ch for the range object for the
7332 	 * locking channel, so that this channel will know that it is allowed
7333 	 * to write to this range.
7334 	 */
7335 	ctx->owner_range->owner_ch = ctx->range.owner_ch;
7336 	ctx->cb_fn(ctx->cb_arg, status);
7337 
7338 	/* Don't free the ctx here.  Its range is in the bdev's global list of
7339 	 * locked ranges still, and will be removed and freed when this range
7340 	 * is later unlocked.
7341 	 */
7342 }
7343 
7344 static int
7345 bdev_lock_lba_range_check_io(void *_i)
7346 {
7347 	struct spdk_io_channel_iter *i = _i;
7348 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7349 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7350 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7351 	struct lba_range *range = ctx->current_range;
7352 	struct spdk_bdev_io *bdev_io;
7353 
7354 	spdk_poller_unregister(&ctx->poller);
7355 
7356 	/* The range is now in the locked_ranges, so no new IO can be submitted to this
7357 	 * range.  But we need to wait until any outstanding IO overlapping with this range
7358 	 * are completed.
7359 	 */
7360 	TAILQ_FOREACH(bdev_io, &ch->io_submitted, internal.ch_link) {
7361 		if (bdev_io_range_is_locked(bdev_io, range)) {
7362 			ctx->poller = SPDK_POLLER_REGISTER(bdev_lock_lba_range_check_io, i, 100);
7363 			return SPDK_POLLER_BUSY;
7364 		}
7365 	}
7366 
7367 	spdk_for_each_channel_continue(i, 0);
7368 	return SPDK_POLLER_BUSY;
7369 }
7370 
7371 static void
7372 bdev_lock_lba_range_get_channel(struct spdk_io_channel_iter *i)
7373 {
7374 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7375 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7376 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7377 	struct lba_range *range;
7378 
7379 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
7380 		if (range->length == ctx->range.length &&
7381 		    range->offset == ctx->range.offset &&
7382 		    range->locked_ctx == ctx->range.locked_ctx) {
7383 			/* This range already exists on this channel, so don't add
7384 			 * it again.  This can happen when a new channel is created
7385 			 * while the for_each_channel operation is in progress.
7386 			 * Do not check for outstanding I/O in that case, since the
7387 			 * range was locked before any I/O could be submitted to the
7388 			 * new channel.
7389 			 */
7390 			spdk_for_each_channel_continue(i, 0);
7391 			return;
7392 		}
7393 	}
7394 
7395 	range = calloc(1, sizeof(*range));
7396 	if (range == NULL) {
7397 		spdk_for_each_channel_continue(i, -ENOMEM);
7398 		return;
7399 	}
7400 
7401 	range->length = ctx->range.length;
7402 	range->offset = ctx->range.offset;
7403 	range->locked_ctx = ctx->range.locked_ctx;
7404 	ctx->current_range = range;
7405 	if (ctx->range.owner_ch == ch) {
7406 		/* This is the range object for the channel that will hold
7407 		 * the lock.  Store it in the ctx object so that we can easily
7408 		 * set its owner_ch after the lock is finally acquired.
7409 		 */
7410 		ctx->owner_range = range;
7411 	}
7412 	TAILQ_INSERT_TAIL(&ch->locked_ranges, range, tailq);
7413 	bdev_lock_lba_range_check_io(i);
7414 }
7415 
7416 static void
7417 bdev_lock_lba_range_ctx(struct spdk_bdev *bdev, struct locked_lba_range_ctx *ctx)
7418 {
7419 	assert(spdk_get_thread() == spdk_io_channel_get_thread(ctx->range.owner_ch->channel));
7420 
7421 	/* We will add a copy of this range to each channel now. */
7422 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_lock_lba_range_get_channel, ctx,
7423 			      bdev_lock_lba_range_cb);
7424 }
7425 
7426 static bool
7427 bdev_lba_range_overlaps_tailq(struct lba_range *range, lba_range_tailq_t *tailq)
7428 {
7429 	struct lba_range *r;
7430 
7431 	TAILQ_FOREACH(r, tailq, tailq) {
7432 		if (bdev_lba_range_overlapped(range, r)) {
7433 			return true;
7434 		}
7435 	}
7436 	return false;
7437 }
7438 
7439 static int
7440 bdev_lock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
7441 		    uint64_t offset, uint64_t length,
7442 		    lock_range_cb cb_fn, void *cb_arg)
7443 {
7444 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
7445 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7446 	struct locked_lba_range_ctx *ctx;
7447 
7448 	if (cb_arg == NULL) {
7449 		SPDK_ERRLOG("cb_arg must not be NULL\n");
7450 		return -EINVAL;
7451 	}
7452 
7453 	ctx = calloc(1, sizeof(*ctx));
7454 	if (ctx == NULL) {
7455 		return -ENOMEM;
7456 	}
7457 
7458 	ctx->range.offset = offset;
7459 	ctx->range.length = length;
7460 	ctx->range.owner_ch = ch;
7461 	ctx->range.locked_ctx = cb_arg;
7462 	ctx->bdev = bdev;
7463 	ctx->cb_fn = cb_fn;
7464 	ctx->cb_arg = cb_arg;
7465 
7466 	pthread_mutex_lock(&bdev->internal.mutex);
7467 	if (bdev_lba_range_overlaps_tailq(&ctx->range, &bdev->internal.locked_ranges)) {
7468 		/* There is an active lock overlapping with this range.
7469 		 * Put it on the pending list until this range no
7470 		 * longer overlaps with another.
7471 		 */
7472 		TAILQ_INSERT_TAIL(&bdev->internal.pending_locked_ranges, &ctx->range, tailq);
7473 	} else {
7474 		TAILQ_INSERT_TAIL(&bdev->internal.locked_ranges, &ctx->range, tailq);
7475 		bdev_lock_lba_range_ctx(bdev, ctx);
7476 	}
7477 	pthread_mutex_unlock(&bdev->internal.mutex);
7478 	return 0;
7479 }
7480 
7481 static void
7482 bdev_lock_lba_range_ctx_msg(void *_ctx)
7483 {
7484 	struct locked_lba_range_ctx *ctx = _ctx;
7485 
7486 	bdev_lock_lba_range_ctx(ctx->bdev, ctx);
7487 }
7488 
7489 static void
7490 bdev_unlock_lba_range_cb(struct spdk_io_channel_iter *i, int status)
7491 {
7492 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7493 	struct locked_lba_range_ctx *pending_ctx;
7494 	struct spdk_bdev_channel *ch = ctx->range.owner_ch;
7495 	struct spdk_bdev *bdev = ch->bdev;
7496 	struct lba_range *range, *tmp;
7497 
7498 	pthread_mutex_lock(&bdev->internal.mutex);
7499 	/* Check if there are any pending locked ranges that overlap with this range
7500 	 * that was just unlocked.  If there are, check that it doesn't overlap with any
7501 	 * other locked ranges before calling bdev_lock_lba_range_ctx which will start
7502 	 * the lock process.
7503 	 */
7504 	TAILQ_FOREACH_SAFE(range, &bdev->internal.pending_locked_ranges, tailq, tmp) {
7505 		if (bdev_lba_range_overlapped(range, &ctx->range) &&
7506 		    !bdev_lba_range_overlaps_tailq(range, &bdev->internal.locked_ranges)) {
7507 			TAILQ_REMOVE(&bdev->internal.pending_locked_ranges, range, tailq);
7508 			pending_ctx = SPDK_CONTAINEROF(range, struct locked_lba_range_ctx, range);
7509 			TAILQ_INSERT_TAIL(&bdev->internal.locked_ranges, range, tailq);
7510 			spdk_thread_send_msg(spdk_io_channel_get_thread(pending_ctx->range.owner_ch->channel),
7511 					     bdev_lock_lba_range_ctx_msg, pending_ctx);
7512 		}
7513 	}
7514 	pthread_mutex_unlock(&bdev->internal.mutex);
7515 
7516 	ctx->cb_fn(ctx->cb_arg, status);
7517 	free(ctx);
7518 }
7519 
7520 static void
7521 bdev_unlock_lba_range_get_channel(struct spdk_io_channel_iter *i)
7522 {
7523 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
7524 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7525 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
7526 	TAILQ_HEAD(, spdk_bdev_io) io_locked;
7527 	struct spdk_bdev_io *bdev_io;
7528 	struct lba_range *range;
7529 
7530 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
7531 		if (ctx->range.offset == range->offset &&
7532 		    ctx->range.length == range->length &&
7533 		    ctx->range.locked_ctx == range->locked_ctx) {
7534 			TAILQ_REMOVE(&ch->locked_ranges, range, tailq);
7535 			free(range);
7536 			break;
7537 		}
7538 	}
7539 
7540 	/* Note: we should almost always be able to assert that the range specified
7541 	 * was found.  But there are some very rare corner cases where a new channel
7542 	 * gets created simultaneously with a range unlock, where this function
7543 	 * would execute on that new channel and wouldn't have the range.
7544 	 * We also use this to clean up range allocations when a later allocation
7545 	 * fails in the locking path.
7546 	 * So we can't actually assert() here.
7547 	 */
7548 
7549 	/* Swap the locked IO into a temporary list, and then try to submit them again.
7550 	 * We could hyper-optimize this to only resubmit locked I/O that overlap
7551 	 * with the range that was just unlocked, but this isn't a performance path so
7552 	 * we go for simplicity here.
7553 	 */
7554 	TAILQ_INIT(&io_locked);
7555 	TAILQ_SWAP(&ch->io_locked, &io_locked, spdk_bdev_io, internal.ch_link);
7556 	while (!TAILQ_EMPTY(&io_locked)) {
7557 		bdev_io = TAILQ_FIRST(&io_locked);
7558 		TAILQ_REMOVE(&io_locked, bdev_io, internal.ch_link);
7559 		bdev_io_submit(bdev_io);
7560 	}
7561 
7562 	spdk_for_each_channel_continue(i, 0);
7563 }
7564 
7565 static int
7566 bdev_unlock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
7567 		      uint64_t offset, uint64_t length,
7568 		      lock_range_cb cb_fn, void *cb_arg)
7569 {
7570 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
7571 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
7572 	struct locked_lba_range_ctx *ctx;
7573 	struct lba_range *range;
7574 	bool range_found = false;
7575 
7576 	/* Let's make sure the specified channel actually has a lock on
7577 	 * the specified range.  Note that the range must match exactly.
7578 	 */
7579 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
7580 		if (range->offset == offset && range->length == length &&
7581 		    range->owner_ch == ch && range->locked_ctx == cb_arg) {
7582 			range_found = true;
7583 			break;
7584 		}
7585 	}
7586 
7587 	if (!range_found) {
7588 		return -EINVAL;
7589 	}
7590 
7591 	pthread_mutex_lock(&bdev->internal.mutex);
7592 	/* We confirmed that this channel has locked the specified range.  To
7593 	 * start the unlock the process, we find the range in the bdev's locked_ranges
7594 	 * and remove it.  This ensures new channels don't inherit the locked range.
7595 	 * Then we will send a message to each channel (including the one specified
7596 	 * here) to remove the range from its per-channel list.
7597 	 */
7598 	TAILQ_FOREACH(range, &bdev->internal.locked_ranges, tailq) {
7599 		if (range->offset == offset && range->length == length &&
7600 		    range->locked_ctx == cb_arg) {
7601 			break;
7602 		}
7603 	}
7604 	if (range == NULL) {
7605 		assert(false);
7606 		pthread_mutex_unlock(&bdev->internal.mutex);
7607 		return -EINVAL;
7608 	}
7609 	TAILQ_REMOVE(&bdev->internal.locked_ranges, range, tailq);
7610 	ctx = SPDK_CONTAINEROF(range, struct locked_lba_range_ctx, range);
7611 	pthread_mutex_unlock(&bdev->internal.mutex);
7612 
7613 	ctx->cb_fn = cb_fn;
7614 	ctx->cb_arg = cb_arg;
7615 
7616 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_unlock_lba_range_get_channel, ctx,
7617 			      bdev_unlock_lba_range_cb);
7618 	return 0;
7619 }
7620 
7621 int
7622 spdk_bdev_get_memory_domains(struct spdk_bdev *bdev, struct spdk_memory_domain **domains,
7623 			     int array_size)
7624 {
7625 	if (!bdev) {
7626 		return -EINVAL;
7627 	}
7628 
7629 	if (bdev->fn_table->get_memory_domains) {
7630 		return bdev->fn_table->get_memory_domains(bdev->ctxt, domains, array_size);
7631 	}
7632 
7633 	return 0;
7634 }
7635 
7636 SPDK_LOG_REGISTER_COMPONENT(bdev)
7637 
7638 SPDK_TRACE_REGISTER_FN(bdev_trace, "bdev", TRACE_GROUP_BDEV)
7639 {
7640 	struct spdk_trace_tpoint_opts opts[] = {
7641 		{
7642 			"BDEV_IO_START", TRACE_BDEV_IO_START,
7643 			OWNER_BDEV, OBJECT_BDEV_IO, 1,
7644 			{
7645 				{ "type", SPDK_TRACE_ARG_TYPE_INT, 8 },
7646 				{ "ctx", SPDK_TRACE_ARG_TYPE_PTR, 8 },
7647 				{ "offset", SPDK_TRACE_ARG_TYPE_INT, 8 },
7648 				{ "len", SPDK_TRACE_ARG_TYPE_INT, 8 }
7649 			}
7650 		},
7651 		{
7652 			"BDEV_IO_DONE", TRACE_BDEV_IO_DONE,
7653 			OWNER_BDEV, OBJECT_BDEV_IO, 0,
7654 			{{ "ctx", SPDK_TRACE_ARG_TYPE_PTR, 8 }}
7655 		},
7656 		{
7657 			"BDEV_IOCH_CREATE", TRACE_BDEV_IOCH_CREATE,
7658 			OWNER_BDEV, OBJECT_NONE, 1,
7659 			{
7660 				{ "name", SPDK_TRACE_ARG_TYPE_STR, 40 },
7661 				{ "thread_id", SPDK_TRACE_ARG_TYPE_INT, 8}
7662 			}
7663 		},
7664 		{
7665 			"BDEV_IOCH_DESTROY", TRACE_BDEV_IOCH_DESTROY,
7666 			OWNER_BDEV, OBJECT_NONE, 0,
7667 			{
7668 				{ "name", SPDK_TRACE_ARG_TYPE_STR, 40 },
7669 				{ "thread_id", SPDK_TRACE_ARG_TYPE_INT, 8}
7670 			}
7671 		},
7672 	};
7673 
7674 
7675 	spdk_trace_register_owner(OWNER_BDEV, 'b');
7676 	spdk_trace_register_object(OBJECT_BDEV_IO, 'i');
7677 	spdk_trace_register_description_ext(opts, SPDK_COUNTOF(opts));
7678 }
7679