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