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