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