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