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