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