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