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