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