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