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