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