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