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