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