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