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