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