xref: /spdk/lib/bdev/bdev.c (revision 7ed0ec6832d9a5cf49bdc35f8e9c00fa80a5f67b)
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 #include "spdk/conf.h"
38 
39 #include "spdk/config.h"
40 #include "spdk/env.h"
41 #include "spdk/event.h"
42 #include "spdk/thread.h"
43 #include "spdk/likely.h"
44 #include "spdk/queue.h"
45 #include "spdk/nvme_spec.h"
46 #include "spdk/scsi_spec.h"
47 #include "spdk/notify.h"
48 #include "spdk/util.h"
49 #include "spdk/trace.h"
50 
51 #include "spdk/bdev_module.h"
52 #include "spdk_internal/log.h"
53 #include "spdk/string.h"
54 
55 #include "bdev_internal.h"
56 
57 #ifdef SPDK_CONFIG_VTUNE
58 #include "ittnotify.h"
59 #include "ittnotify_types.h"
60 int __itt_init_ittlib(const char *, __itt_group_id);
61 #endif
62 
63 #define SPDK_BDEV_IO_POOL_SIZE			(64 * 1024 - 1)
64 #define SPDK_BDEV_IO_CACHE_SIZE			256
65 #define BUF_SMALL_POOL_SIZE			8191
66 #define BUF_LARGE_POOL_SIZE			1023
67 #define NOMEM_THRESHOLD_COUNT			8
68 #define ZERO_BUFFER_SIZE			0x100000
69 
70 #define OWNER_BDEV		0x2
71 
72 #define OBJECT_BDEV_IO		0x2
73 
74 #define TRACE_GROUP_BDEV	0x3
75 #define TRACE_BDEV_IO_START	SPDK_TPOINT_ID(TRACE_GROUP_BDEV, 0x0)
76 #define TRACE_BDEV_IO_DONE	SPDK_TPOINT_ID(TRACE_GROUP_BDEV, 0x1)
77 
78 #define SPDK_BDEV_QOS_TIMESLICE_IN_USEC		1000
79 #define SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE	1
80 #define SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE	512
81 #define SPDK_BDEV_QOS_MIN_IOS_PER_SEC		1000
82 #define SPDK_BDEV_QOS_MIN_BYTES_PER_SEC		(1024 * 1024)
83 #define SPDK_BDEV_QOS_LIMIT_NOT_DEFINED		UINT64_MAX
84 
85 #define SPDK_BDEV_POOL_ALIGNMENT 512
86 
87 static const char *qos_conf_type[] = {"Limit_IOPS",
88 				      "Limit_BPS", "Limit_Read_BPS", "Limit_Write_BPS"
89 				     };
90 static const char *qos_rpc_type[] = {"rw_ios_per_sec",
91 				     "rw_mbytes_per_sec", "r_mbytes_per_sec", "w_mbytes_per_sec"
92 				    };
93 
94 TAILQ_HEAD(spdk_bdev_list, spdk_bdev);
95 
96 struct spdk_bdev_mgr {
97 	struct spdk_mempool *bdev_io_pool;
98 
99 	struct spdk_mempool *buf_small_pool;
100 	struct spdk_mempool *buf_large_pool;
101 
102 	void *zero_buffer;
103 
104 	TAILQ_HEAD(bdev_module_list, spdk_bdev_module) bdev_modules;
105 
106 	struct spdk_bdev_list bdevs;
107 
108 	bool init_complete;
109 	bool module_init_complete;
110 
111 	pthread_mutex_t mutex;
112 
113 #ifdef SPDK_CONFIG_VTUNE
114 	__itt_domain	*domain;
115 #endif
116 };
117 
118 static struct spdk_bdev_mgr g_bdev_mgr = {
119 	.bdev_modules = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdev_modules),
120 	.bdevs = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdevs),
121 	.init_complete = false,
122 	.module_init_complete = false,
123 	.mutex = PTHREAD_MUTEX_INITIALIZER,
124 };
125 
126 
127 static struct spdk_bdev_opts	g_bdev_opts = {
128 	.bdev_io_pool_size = SPDK_BDEV_IO_POOL_SIZE,
129 	.bdev_io_cache_size = SPDK_BDEV_IO_CACHE_SIZE,
130 };
131 
132 static spdk_bdev_init_cb	g_init_cb_fn = NULL;
133 static void			*g_init_cb_arg = NULL;
134 
135 static spdk_bdev_fini_cb	g_fini_cb_fn = NULL;
136 static void			*g_fini_cb_arg = NULL;
137 static struct spdk_thread	*g_fini_thread = NULL;
138 
139 struct spdk_bdev_qos_limit {
140 	/** IOs or bytes allowed per second (i.e., 1s). */
141 	uint64_t limit;
142 
143 	/** Remaining IOs or bytes allowed in current timeslice (e.g., 1ms).
144 	 *  For remaining bytes, allowed to run negative if an I/O is submitted when
145 	 *  some bytes are remaining, but the I/O is bigger than that amount. The
146 	 *  excess will be deducted from the next timeslice.
147 	 */
148 	int64_t remaining_this_timeslice;
149 
150 	/** Minimum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
151 	uint32_t min_per_timeslice;
152 
153 	/** Maximum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
154 	uint32_t max_per_timeslice;
155 
156 	/** Function to check whether to queue the IO. */
157 	bool (*queue_io)(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
158 
159 	/** Function to update for the submitted IO. */
160 	void (*update_quota)(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
161 };
162 
163 struct spdk_bdev_qos {
164 	/** Types of structure of rate limits. */
165 	struct spdk_bdev_qos_limit rate_limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
166 
167 	/** The channel that all I/O are funneled through. */
168 	struct spdk_bdev_channel *ch;
169 
170 	/** The thread on which the poller is running. */
171 	struct spdk_thread *thread;
172 
173 	/** Queue of I/O waiting to be issued. */
174 	bdev_io_tailq_t queued;
175 
176 	/** Size of a timeslice in tsc ticks. */
177 	uint64_t timeslice_size;
178 
179 	/** Timestamp of start of last timeslice. */
180 	uint64_t last_timeslice;
181 
182 	/** Poller that processes queued I/O commands each time slice. */
183 	struct spdk_poller *poller;
184 };
185 
186 struct spdk_bdev_mgmt_channel {
187 	bdev_io_stailq_t need_buf_small;
188 	bdev_io_stailq_t need_buf_large;
189 
190 	/*
191 	 * Each thread keeps a cache of bdev_io - this allows
192 	 *  bdev threads which are *not* DPDK threads to still
193 	 *  benefit from a per-thread bdev_io cache.  Without
194 	 *  this, non-DPDK threads fetching from the mempool
195 	 *  incur a cmpxchg on get and put.
196 	 */
197 	bdev_io_stailq_t per_thread_cache;
198 	uint32_t	per_thread_cache_count;
199 	uint32_t	bdev_io_cache_size;
200 
201 	TAILQ_HEAD(, spdk_bdev_shared_resource)	shared_resources;
202 	TAILQ_HEAD(, spdk_bdev_io_wait_entry)	io_wait_queue;
203 };
204 
205 /*
206  * Per-module (or per-io_device) data. Multiple bdevs built on the same io_device
207  * will queue here their IO that awaits retry. It makes it possible to retry sending
208  * IO to one bdev after IO from other bdev completes.
209  */
210 struct spdk_bdev_shared_resource {
211 	/* The bdev management channel */
212 	struct spdk_bdev_mgmt_channel *mgmt_ch;
213 
214 	/*
215 	 * Count of I/O submitted to bdev module and waiting for completion.
216 	 * Incremented before submit_request() is called on an spdk_bdev_io.
217 	 */
218 	uint64_t		io_outstanding;
219 
220 	/*
221 	 * Queue of IO awaiting retry because of a previous NOMEM status returned
222 	 *  on this channel.
223 	 */
224 	bdev_io_tailq_t		nomem_io;
225 
226 	/*
227 	 * Threshold which io_outstanding must drop to before retrying nomem_io.
228 	 */
229 	uint64_t		nomem_threshold;
230 
231 	/* I/O channel allocated by a bdev module */
232 	struct spdk_io_channel	*shared_ch;
233 
234 	/* Refcount of bdev channels using this resource */
235 	uint32_t		ref;
236 
237 	TAILQ_ENTRY(spdk_bdev_shared_resource) link;
238 };
239 
240 #define BDEV_CH_RESET_IN_PROGRESS	(1 << 0)
241 #define BDEV_CH_QOS_ENABLED		(1 << 1)
242 
243 struct spdk_bdev_channel {
244 	struct spdk_bdev	*bdev;
245 
246 	/* The channel for the underlying device */
247 	struct spdk_io_channel	*channel;
248 
249 	/* Per io_device per thread data */
250 	struct spdk_bdev_shared_resource *shared_resource;
251 
252 	struct spdk_bdev_io_stat stat;
253 
254 	/*
255 	 * Count of I/O submitted through this channel and waiting for completion.
256 	 * Incremented before submit_request() is called on an spdk_bdev_io.
257 	 */
258 	uint64_t		io_outstanding;
259 
260 	bdev_io_tailq_t		queued_resets;
261 
262 	uint32_t		flags;
263 
264 	struct spdk_histogram_data *histogram;
265 
266 #ifdef SPDK_CONFIG_VTUNE
267 	uint64_t		start_tsc;
268 	uint64_t		interval_tsc;
269 	__itt_string_handle	*handle;
270 	struct spdk_bdev_io_stat prev_stat;
271 #endif
272 
273 };
274 
275 struct spdk_bdev_desc {
276 	struct spdk_bdev		*bdev;
277 	struct spdk_thread		*thread;
278 	struct {
279 		bool open_with_ext;
280 		union {
281 			spdk_bdev_remove_cb_t remove_fn;
282 			spdk_bdev_event_cb_t event_fn;
283 		};
284 		void *ctx;
285 	}				callback;
286 	bool				closed;
287 	bool				write;
288 	pthread_mutex_t			mutex;
289 	uint32_t			refs;
290 	TAILQ_ENTRY(spdk_bdev_desc)	link;
291 };
292 
293 struct spdk_bdev_iostat_ctx {
294 	struct spdk_bdev_io_stat *stat;
295 	spdk_bdev_get_device_stat_cb cb;
296 	void *cb_arg;
297 };
298 
299 struct set_qos_limit_ctx {
300 	void (*cb_fn)(void *cb_arg, int status);
301 	void *cb_arg;
302 	struct spdk_bdev *bdev;
303 };
304 
305 #define __bdev_to_io_dev(bdev)		(((char *)bdev) + 1)
306 #define __bdev_from_io_dev(io_dev)	((struct spdk_bdev *)(((char *)io_dev) - 1))
307 
308 static void _spdk_bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success,
309 		void *cb_arg);
310 static void _spdk_bdev_write_zero_buffer_next(void *_bdev_io);
311 
312 static void _spdk_bdev_enable_qos_msg(struct spdk_io_channel_iter *i);
313 static void _spdk_bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status);
314 
315 static int
316 _spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
317 				struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
318 				uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg);
319 static int
320 _spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
321 				 struct iovec *iov, int iovcnt, void *md_buf,
322 				 uint64_t offset_blocks, uint64_t num_blocks,
323 				 spdk_bdev_io_completion_cb cb, void *cb_arg);
324 
325 void
326 spdk_bdev_get_opts(struct spdk_bdev_opts *opts)
327 {
328 	*opts = g_bdev_opts;
329 }
330 
331 int
332 spdk_bdev_set_opts(struct spdk_bdev_opts *opts)
333 {
334 	uint32_t min_pool_size;
335 
336 	/*
337 	 * Add 1 to the thread count to account for the extra mgmt_ch that gets created during subsystem
338 	 *  initialization.  A second mgmt_ch will be created on the same thread when the application starts
339 	 *  but before the deferred put_io_channel event is executed for the first mgmt_ch.
340 	 */
341 	min_pool_size = opts->bdev_io_cache_size * (spdk_thread_get_count() + 1);
342 	if (opts->bdev_io_pool_size < min_pool_size) {
343 		SPDK_ERRLOG("bdev_io_pool_size %" PRIu32 " is not compatible with bdev_io_cache_size %" PRIu32
344 			    " and %" PRIu32 " threads\n", opts->bdev_io_pool_size, opts->bdev_io_cache_size,
345 			    spdk_thread_get_count());
346 		SPDK_ERRLOG("bdev_io_pool_size must be at least %" PRIu32 "\n", min_pool_size);
347 		return -1;
348 	}
349 
350 	g_bdev_opts = *opts;
351 	return 0;
352 }
353 
354 struct spdk_bdev *
355 spdk_bdev_first(void)
356 {
357 	struct spdk_bdev *bdev;
358 
359 	bdev = TAILQ_FIRST(&g_bdev_mgr.bdevs);
360 	if (bdev) {
361 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Starting bdev iteration at %s\n", bdev->name);
362 	}
363 
364 	return bdev;
365 }
366 
367 struct spdk_bdev *
368 spdk_bdev_next(struct spdk_bdev *prev)
369 {
370 	struct spdk_bdev *bdev;
371 
372 	bdev = TAILQ_NEXT(prev, internal.link);
373 	if (bdev) {
374 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Continuing bdev iteration at %s\n", bdev->name);
375 	}
376 
377 	return bdev;
378 }
379 
380 static struct spdk_bdev *
381 _bdev_next_leaf(struct spdk_bdev *bdev)
382 {
383 	while (bdev != NULL) {
384 		if (bdev->internal.claim_module == NULL) {
385 			return bdev;
386 		} else {
387 			bdev = TAILQ_NEXT(bdev, internal.link);
388 		}
389 	}
390 
391 	return bdev;
392 }
393 
394 struct spdk_bdev *
395 spdk_bdev_first_leaf(void)
396 {
397 	struct spdk_bdev *bdev;
398 
399 	bdev = _bdev_next_leaf(TAILQ_FIRST(&g_bdev_mgr.bdevs));
400 
401 	if (bdev) {
402 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Starting bdev iteration at %s\n", bdev->name);
403 	}
404 
405 	return bdev;
406 }
407 
408 struct spdk_bdev *
409 spdk_bdev_next_leaf(struct spdk_bdev *prev)
410 {
411 	struct spdk_bdev *bdev;
412 
413 	bdev = _bdev_next_leaf(TAILQ_NEXT(prev, internal.link));
414 
415 	if (bdev) {
416 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Continuing bdev iteration at %s\n", bdev->name);
417 	}
418 
419 	return bdev;
420 }
421 
422 struct spdk_bdev *
423 spdk_bdev_get_by_name(const char *bdev_name)
424 {
425 	struct spdk_bdev_alias *tmp;
426 	struct spdk_bdev *bdev = spdk_bdev_first();
427 
428 	while (bdev != NULL) {
429 		if (strcmp(bdev_name, bdev->name) == 0) {
430 			return bdev;
431 		}
432 
433 		TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
434 			if (strcmp(bdev_name, tmp->alias) == 0) {
435 				return bdev;
436 			}
437 		}
438 
439 		bdev = spdk_bdev_next(bdev);
440 	}
441 
442 	return NULL;
443 }
444 
445 void
446 spdk_bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len)
447 {
448 	struct iovec *iovs;
449 
450 	if (bdev_io->u.bdev.iovs == NULL) {
451 		bdev_io->u.bdev.iovs = &bdev_io->iov;
452 		bdev_io->u.bdev.iovcnt = 1;
453 	}
454 
455 	iovs = bdev_io->u.bdev.iovs;
456 
457 	assert(iovs != NULL);
458 	assert(bdev_io->u.bdev.iovcnt >= 1);
459 
460 	iovs[0].iov_base = buf;
461 	iovs[0].iov_len = len;
462 }
463 
464 void
465 spdk_bdev_io_set_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
466 {
467 	assert((len / spdk_bdev_get_md_size(bdev_io->bdev)) >= bdev_io->u.bdev.num_blocks);
468 	bdev_io->u.bdev.md_buf = md_buf;
469 }
470 
471 static bool
472 _is_buf_allocated(const struct iovec *iovs)
473 {
474 	if (iovs == NULL) {
475 		return false;
476 	}
477 
478 	return iovs[0].iov_base != NULL;
479 }
480 
481 static bool
482 _are_iovs_aligned(struct iovec *iovs, int iovcnt, uint32_t alignment)
483 {
484 	int i;
485 	uintptr_t iov_base;
486 
487 	if (spdk_likely(alignment == 1)) {
488 		return true;
489 	}
490 
491 	for (i = 0; i < iovcnt; i++) {
492 		iov_base = (uintptr_t)iovs[i].iov_base;
493 		if ((iov_base & (alignment - 1)) != 0) {
494 			return false;
495 		}
496 	}
497 
498 	return true;
499 }
500 
501 static void
502 _copy_iovs_to_buf(void *buf, size_t buf_len, struct iovec *iovs, int iovcnt)
503 {
504 	int i;
505 	size_t len;
506 
507 	for (i = 0; i < iovcnt; i++) {
508 		len = spdk_min(iovs[i].iov_len, buf_len);
509 		memcpy(buf, iovs[i].iov_base, len);
510 		buf += len;
511 		buf_len -= len;
512 	}
513 }
514 
515 static void
516 _copy_buf_to_iovs(struct iovec *iovs, int iovcnt, void *buf, size_t buf_len)
517 {
518 	int i;
519 	size_t len;
520 
521 	for (i = 0; i < iovcnt; i++) {
522 		len = spdk_min(iovs[i].iov_len, buf_len);
523 		memcpy(iovs[i].iov_base, buf, len);
524 		buf += len;
525 		buf_len -= len;
526 	}
527 }
528 
529 static void
530 _bdev_io_set_bounce_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len)
531 {
532 	/* save original iovec */
533 	bdev_io->internal.orig_iovs = bdev_io->u.bdev.iovs;
534 	bdev_io->internal.orig_iovcnt = bdev_io->u.bdev.iovcnt;
535 	/* set bounce iov */
536 	bdev_io->u.bdev.iovs = &bdev_io->internal.bounce_iov;
537 	bdev_io->u.bdev.iovcnt = 1;
538 	/* set bounce buffer for this operation */
539 	bdev_io->u.bdev.iovs[0].iov_base = buf;
540 	bdev_io->u.bdev.iovs[0].iov_len = len;
541 	/* if this is write path, copy data from original buffer to bounce buffer */
542 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
543 		_copy_iovs_to_buf(buf, len, bdev_io->internal.orig_iovs, bdev_io->internal.orig_iovcnt);
544 	}
545 }
546 
547 static void
548 _bdev_io_set_bounce_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
549 {
550 	/* save original md_buf */
551 	bdev_io->internal.orig_md_buf = bdev_io->u.bdev.md_buf;
552 	/* set bounce md_buf */
553 	bdev_io->u.bdev.md_buf = md_buf;
554 
555 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
556 		memcpy(md_buf, bdev_io->internal.orig_md_buf, len);
557 	}
558 }
559 
560 static void
561 _bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, uint64_t len)
562 {
563 	struct spdk_bdev *bdev = bdev_io->bdev;
564 	bool buf_allocated;
565 	uint64_t md_len, alignment;
566 	void *aligned_buf;
567 
568 	alignment = spdk_bdev_get_buf_align(bdev);
569 	buf_allocated = _is_buf_allocated(bdev_io->u.bdev.iovs);
570 	aligned_buf = (void *)(((uintptr_t)buf + (alignment - 1)) & ~(alignment - 1));
571 
572 	if (buf_allocated) {
573 		_bdev_io_set_bounce_buf(bdev_io, aligned_buf, len);
574 	} else {
575 		spdk_bdev_io_set_buf(bdev_io, aligned_buf, len);
576 	}
577 
578 	if (spdk_bdev_is_md_separate(bdev)) {
579 		aligned_buf = (char *)aligned_buf + len;
580 		md_len = bdev_io->u.bdev.num_blocks * bdev->md_len;
581 
582 		assert(((uintptr_t)aligned_buf & (alignment - 1)) == 0);
583 
584 		if (bdev_io->u.bdev.md_buf != NULL) {
585 			_bdev_io_set_bounce_md_buf(bdev_io, aligned_buf, md_len);
586 		} else {
587 			spdk_bdev_io_set_md_buf(bdev_io, aligned_buf, md_len);
588 		}
589 	}
590 
591 	bdev_io->internal.buf = buf;
592 	bdev_io->internal.get_buf_cb(spdk_bdev_io_get_io_channel(bdev_io), bdev_io, true);
593 }
594 
595 static void
596 spdk_bdev_io_put_buf(struct spdk_bdev_io *bdev_io)
597 {
598 	struct spdk_bdev *bdev = bdev_io->bdev;
599 	struct spdk_mempool *pool;
600 	struct spdk_bdev_io *tmp;
601 	bdev_io_stailq_t *stailq;
602 	struct spdk_bdev_mgmt_channel *ch;
603 	uint64_t buf_len, md_len, alignment;
604 	void *buf;
605 
606 	buf = bdev_io->internal.buf;
607 	buf_len = bdev_io->internal.buf_len;
608 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
609 	alignment = spdk_bdev_get_buf_align(bdev);
610 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
611 
612 	bdev_io->internal.buf = NULL;
613 
614 	if (buf_len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
615 	    SPDK_BDEV_POOL_ALIGNMENT) {
616 		pool = g_bdev_mgr.buf_small_pool;
617 		stailq = &ch->need_buf_small;
618 	} else {
619 		pool = g_bdev_mgr.buf_large_pool;
620 		stailq = &ch->need_buf_large;
621 	}
622 
623 	if (STAILQ_EMPTY(stailq)) {
624 		spdk_mempool_put(pool, buf);
625 	} else {
626 		tmp = STAILQ_FIRST(stailq);
627 		STAILQ_REMOVE_HEAD(stailq, internal.buf_link);
628 		_bdev_io_set_buf(tmp, buf, tmp->internal.buf_len);
629 	}
630 }
631 
632 static void
633 _bdev_io_unset_bounce_buf(struct spdk_bdev_io *bdev_io)
634 {
635 	if (spdk_likely(bdev_io->internal.orig_iovcnt == 0)) {
636 		assert(bdev_io->internal.orig_md_buf == NULL);
637 		return;
638 	}
639 
640 	/* if this is read path, copy data from bounce buffer to original buffer */
641 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
642 	    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
643 		_copy_buf_to_iovs(bdev_io->internal.orig_iovs,
644 				  bdev_io->internal.orig_iovcnt,
645 				  bdev_io->internal.bounce_iov.iov_base,
646 				  bdev_io->internal.bounce_iov.iov_len);
647 	}
648 	/* set orignal buffer for this io */
649 	bdev_io->u.bdev.iovcnt = bdev_io->internal.orig_iovcnt;
650 	bdev_io->u.bdev.iovs = bdev_io->internal.orig_iovs;
651 	/* disable bouncing buffer for this io */
652 	bdev_io->internal.orig_iovcnt = 0;
653 	bdev_io->internal.orig_iovs = NULL;
654 
655 	/* do the same for metadata buffer */
656 	if (spdk_unlikely(bdev_io->internal.orig_md_buf != NULL)) {
657 		assert(spdk_bdev_is_md_separate(bdev_io->bdev));
658 
659 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
660 		    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
661 			memcpy(bdev_io->internal.orig_md_buf, bdev_io->u.bdev.md_buf,
662 			       bdev_io->u.bdev.num_blocks * spdk_bdev_get_md_size(bdev_io->bdev));
663 		}
664 
665 		bdev_io->u.bdev.md_buf = bdev_io->internal.orig_md_buf;
666 		bdev_io->internal.orig_md_buf = NULL;
667 	}
668 
669 	spdk_bdev_io_put_buf(bdev_io);
670 }
671 
672 void
673 spdk_bdev_io_get_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_buf_cb cb, uint64_t len)
674 {
675 	struct spdk_bdev *bdev = bdev_io->bdev;
676 	struct spdk_mempool *pool;
677 	bdev_io_stailq_t *stailq;
678 	struct spdk_bdev_mgmt_channel *mgmt_ch;
679 	uint64_t alignment, md_len;
680 	void *buf;
681 
682 	assert(cb != NULL);
683 
684 	alignment = spdk_bdev_get_buf_align(bdev);
685 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
686 
687 	if (_is_buf_allocated(bdev_io->u.bdev.iovs) &&
688 	    _are_iovs_aligned(bdev_io->u.bdev.iovs, bdev_io->u.bdev.iovcnt, alignment)) {
689 		/* Buffer already present and aligned */
690 		cb(spdk_bdev_io_get_io_channel(bdev_io), bdev_io, true);
691 		return;
692 	}
693 
694 	if (len + alignment + md_len > SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
695 	    SPDK_BDEV_POOL_ALIGNMENT) {
696 		SPDK_ERRLOG("Length + alignment %" PRIu64 " is larger than allowed\n",
697 			    len + alignment);
698 		cb(spdk_bdev_io_get_io_channel(bdev_io), bdev_io, false);
699 		return;
700 	}
701 
702 	mgmt_ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
703 
704 	bdev_io->internal.buf_len = len;
705 	bdev_io->internal.get_buf_cb = cb;
706 
707 	if (len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
708 	    SPDK_BDEV_POOL_ALIGNMENT) {
709 		pool = g_bdev_mgr.buf_small_pool;
710 		stailq = &mgmt_ch->need_buf_small;
711 	} else {
712 		pool = g_bdev_mgr.buf_large_pool;
713 		stailq = &mgmt_ch->need_buf_large;
714 	}
715 
716 	buf = spdk_mempool_get(pool);
717 	if (!buf) {
718 		STAILQ_INSERT_TAIL(stailq, bdev_io, internal.buf_link);
719 	} else {
720 		_bdev_io_set_buf(bdev_io, buf, len);
721 	}
722 }
723 
724 static int
725 spdk_bdev_module_get_max_ctx_size(void)
726 {
727 	struct spdk_bdev_module *bdev_module;
728 	int max_bdev_module_size = 0;
729 
730 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
731 		if (bdev_module->get_ctx_size && bdev_module->get_ctx_size() > max_bdev_module_size) {
732 			max_bdev_module_size = bdev_module->get_ctx_size();
733 		}
734 	}
735 
736 	return max_bdev_module_size;
737 }
738 
739 void
740 spdk_bdev_config_text(FILE *fp)
741 {
742 	struct spdk_bdev_module *bdev_module;
743 
744 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
745 		if (bdev_module->config_text) {
746 			bdev_module->config_text(fp);
747 		}
748 	}
749 }
750 
751 static void
752 spdk_bdev_qos_config_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
753 {
754 	int i;
755 	struct spdk_bdev_qos *qos = bdev->internal.qos;
756 	uint64_t limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
757 
758 	if (!qos) {
759 		return;
760 	}
761 
762 	spdk_bdev_get_qos_rate_limits(bdev, limits);
763 
764 	spdk_json_write_object_begin(w);
765 	spdk_json_write_named_string(w, "method", "bdev_set_qos_limit");
766 
767 	spdk_json_write_named_object_begin(w, "params");
768 	spdk_json_write_named_string(w, "name", bdev->name);
769 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
770 		if (limits[i] > 0) {
771 			spdk_json_write_named_uint64(w, qos_rpc_type[i], limits[i]);
772 		}
773 	}
774 	spdk_json_write_object_end(w);
775 
776 	spdk_json_write_object_end(w);
777 }
778 
779 void
780 spdk_bdev_subsystem_config_json(struct spdk_json_write_ctx *w)
781 {
782 	struct spdk_bdev_module *bdev_module;
783 	struct spdk_bdev *bdev;
784 
785 	assert(w != NULL);
786 
787 	spdk_json_write_array_begin(w);
788 
789 	spdk_json_write_object_begin(w);
790 	spdk_json_write_named_string(w, "method", "bdev_set_options");
791 	spdk_json_write_named_object_begin(w, "params");
792 	spdk_json_write_named_uint32(w, "bdev_io_pool_size", g_bdev_opts.bdev_io_pool_size);
793 	spdk_json_write_named_uint32(w, "bdev_io_cache_size", g_bdev_opts.bdev_io_cache_size);
794 	spdk_json_write_object_end(w);
795 	spdk_json_write_object_end(w);
796 
797 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
798 		if (bdev_module->config_json) {
799 			bdev_module->config_json(w);
800 		}
801 	}
802 
803 	pthread_mutex_lock(&g_bdev_mgr.mutex);
804 
805 	TAILQ_FOREACH(bdev, &g_bdev_mgr.bdevs, internal.link) {
806 		if (bdev->fn_table->write_config_json) {
807 			bdev->fn_table->write_config_json(bdev, w);
808 		}
809 
810 		spdk_bdev_qos_config_json(bdev, w);
811 	}
812 
813 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
814 
815 	spdk_json_write_array_end(w);
816 }
817 
818 static int
819 spdk_bdev_mgmt_channel_create(void *io_device, void *ctx_buf)
820 {
821 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
822 	struct spdk_bdev_io *bdev_io;
823 	uint32_t i;
824 
825 	STAILQ_INIT(&ch->need_buf_small);
826 	STAILQ_INIT(&ch->need_buf_large);
827 
828 	STAILQ_INIT(&ch->per_thread_cache);
829 	ch->bdev_io_cache_size = g_bdev_opts.bdev_io_cache_size;
830 
831 	/* Pre-populate bdev_io cache to ensure this thread cannot be starved. */
832 	ch->per_thread_cache_count = 0;
833 	for (i = 0; i < ch->bdev_io_cache_size; i++) {
834 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
835 		assert(bdev_io != NULL);
836 		ch->per_thread_cache_count++;
837 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
838 	}
839 
840 	TAILQ_INIT(&ch->shared_resources);
841 	TAILQ_INIT(&ch->io_wait_queue);
842 
843 	return 0;
844 }
845 
846 static void
847 spdk_bdev_mgmt_channel_destroy(void *io_device, void *ctx_buf)
848 {
849 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
850 	struct spdk_bdev_io *bdev_io;
851 
852 	if (!STAILQ_EMPTY(&ch->need_buf_small) || !STAILQ_EMPTY(&ch->need_buf_large)) {
853 		SPDK_ERRLOG("Pending I/O list wasn't empty on mgmt channel free\n");
854 	}
855 
856 	if (!TAILQ_EMPTY(&ch->shared_resources)) {
857 		SPDK_ERRLOG("Module channel list wasn't empty on mgmt channel free\n");
858 	}
859 
860 	while (!STAILQ_EMPTY(&ch->per_thread_cache)) {
861 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
862 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
863 		ch->per_thread_cache_count--;
864 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
865 	}
866 
867 	assert(ch->per_thread_cache_count == 0);
868 }
869 
870 static void
871 spdk_bdev_init_complete(int rc)
872 {
873 	spdk_bdev_init_cb cb_fn = g_init_cb_fn;
874 	void *cb_arg = g_init_cb_arg;
875 	struct spdk_bdev_module *m;
876 
877 	g_bdev_mgr.init_complete = true;
878 	g_init_cb_fn = NULL;
879 	g_init_cb_arg = NULL;
880 
881 	/*
882 	 * For modules that need to know when subsystem init is complete,
883 	 * inform them now.
884 	 */
885 	if (rc == 0) {
886 		TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
887 			if (m->init_complete) {
888 				m->init_complete();
889 			}
890 		}
891 	}
892 
893 	cb_fn(cb_arg, rc);
894 }
895 
896 static void
897 spdk_bdev_module_action_complete(void)
898 {
899 	struct spdk_bdev_module *m;
900 
901 	/*
902 	 * Don't finish bdev subsystem initialization if
903 	 * module pre-initialization is still in progress, or
904 	 * the subsystem been already initialized.
905 	 */
906 	if (!g_bdev_mgr.module_init_complete || g_bdev_mgr.init_complete) {
907 		return;
908 	}
909 
910 	/*
911 	 * Check all bdev modules for inits/examinations in progress. If any
912 	 * exist, return immediately since we cannot finish bdev subsystem
913 	 * initialization until all are completed.
914 	 */
915 	TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
916 		if (m->internal.action_in_progress > 0) {
917 			return;
918 		}
919 	}
920 
921 	/*
922 	 * Modules already finished initialization - now that all
923 	 * the bdev modules have finished their asynchronous I/O
924 	 * processing, the entire bdev layer can be marked as complete.
925 	 */
926 	spdk_bdev_init_complete(0);
927 }
928 
929 static void
930 spdk_bdev_module_action_done(struct spdk_bdev_module *module)
931 {
932 	assert(module->internal.action_in_progress > 0);
933 	module->internal.action_in_progress--;
934 	spdk_bdev_module_action_complete();
935 }
936 
937 void
938 spdk_bdev_module_init_done(struct spdk_bdev_module *module)
939 {
940 	spdk_bdev_module_action_done(module);
941 }
942 
943 void
944 spdk_bdev_module_examine_done(struct spdk_bdev_module *module)
945 {
946 	spdk_bdev_module_action_done(module);
947 }
948 
949 /** The last initialized bdev module */
950 static struct spdk_bdev_module *g_resume_bdev_module = NULL;
951 
952 static void
953 spdk_bdev_init_failed(void *cb_arg)
954 {
955 	struct spdk_bdev_module *module = cb_arg;
956 
957 	module->internal.action_in_progress--;
958 	spdk_bdev_init_complete(-1);
959 }
960 
961 static int
962 spdk_bdev_modules_init(void)
963 {
964 	struct spdk_bdev_module *module;
965 	int rc = 0;
966 
967 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
968 		g_resume_bdev_module = module;
969 		if (module->async_init) {
970 			module->internal.action_in_progress = 1;
971 		}
972 		rc = module->module_init();
973 		if (rc != 0) {
974 			/* Bump action_in_progress to prevent other modules from completion of modules_init
975 			 * Send message to defer application shutdown until resources are cleaned up */
976 			module->internal.action_in_progress = 1;
977 			spdk_thread_send_msg(spdk_get_thread(), spdk_bdev_init_failed, module);
978 			return rc;
979 		}
980 	}
981 
982 	g_resume_bdev_module = NULL;
983 	return 0;
984 }
985 
986 void
987 spdk_bdev_initialize(spdk_bdev_init_cb cb_fn, void *cb_arg)
988 {
989 	struct spdk_conf_section *sp;
990 	struct spdk_bdev_opts bdev_opts;
991 	int32_t bdev_io_pool_size, bdev_io_cache_size;
992 	int cache_size;
993 	int rc = 0;
994 	char mempool_name[32];
995 
996 	assert(cb_fn != NULL);
997 
998 	sp = spdk_conf_find_section(NULL, "Bdev");
999 	if (sp != NULL) {
1000 		spdk_bdev_get_opts(&bdev_opts);
1001 
1002 		bdev_io_pool_size = spdk_conf_section_get_intval(sp, "BdevIoPoolSize");
1003 		if (bdev_io_pool_size >= 0) {
1004 			bdev_opts.bdev_io_pool_size = bdev_io_pool_size;
1005 		}
1006 
1007 		bdev_io_cache_size = spdk_conf_section_get_intval(sp, "BdevIoCacheSize");
1008 		if (bdev_io_cache_size >= 0) {
1009 			bdev_opts.bdev_io_cache_size = bdev_io_cache_size;
1010 		}
1011 
1012 		if (spdk_bdev_set_opts(&bdev_opts)) {
1013 			spdk_bdev_init_complete(-1);
1014 			return;
1015 		}
1016 
1017 		assert(memcmp(&bdev_opts, &g_bdev_opts, sizeof(bdev_opts)) == 0);
1018 	}
1019 
1020 	g_init_cb_fn = cb_fn;
1021 	g_init_cb_arg = cb_arg;
1022 
1023 	spdk_notify_type_register("bdev_register");
1024 	spdk_notify_type_register("bdev_unregister");
1025 
1026 	snprintf(mempool_name, sizeof(mempool_name), "bdev_io_%d", getpid());
1027 
1028 	g_bdev_mgr.bdev_io_pool = spdk_mempool_create(mempool_name,
1029 				  g_bdev_opts.bdev_io_pool_size,
1030 				  sizeof(struct spdk_bdev_io) +
1031 				  spdk_bdev_module_get_max_ctx_size(),
1032 				  0,
1033 				  SPDK_ENV_SOCKET_ID_ANY);
1034 
1035 	if (g_bdev_mgr.bdev_io_pool == NULL) {
1036 		SPDK_ERRLOG("could not allocate spdk_bdev_io pool\n");
1037 		spdk_bdev_init_complete(-1);
1038 		return;
1039 	}
1040 
1041 	/**
1042 	 * Ensure no more than half of the total buffers end up local caches, by
1043 	 *   using spdk_thread_get_count() to determine how many local caches we need
1044 	 *   to account for.
1045 	 */
1046 	cache_size = BUF_SMALL_POOL_SIZE / (2 * spdk_thread_get_count());
1047 	snprintf(mempool_name, sizeof(mempool_name), "buf_small_pool_%d", getpid());
1048 
1049 	g_bdev_mgr.buf_small_pool = spdk_mempool_create(mempool_name,
1050 				    BUF_SMALL_POOL_SIZE,
1051 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
1052 				    SPDK_BDEV_POOL_ALIGNMENT,
1053 				    cache_size,
1054 				    SPDK_ENV_SOCKET_ID_ANY);
1055 	if (!g_bdev_mgr.buf_small_pool) {
1056 		SPDK_ERRLOG("create rbuf small pool failed\n");
1057 		spdk_bdev_init_complete(-1);
1058 		return;
1059 	}
1060 
1061 	cache_size = BUF_LARGE_POOL_SIZE / (2 * spdk_thread_get_count());
1062 	snprintf(mempool_name, sizeof(mempool_name), "buf_large_pool_%d", getpid());
1063 
1064 	g_bdev_mgr.buf_large_pool = spdk_mempool_create(mempool_name,
1065 				    BUF_LARGE_POOL_SIZE,
1066 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
1067 				    SPDK_BDEV_POOL_ALIGNMENT,
1068 				    cache_size,
1069 				    SPDK_ENV_SOCKET_ID_ANY);
1070 	if (!g_bdev_mgr.buf_large_pool) {
1071 		SPDK_ERRLOG("create rbuf large pool failed\n");
1072 		spdk_bdev_init_complete(-1);
1073 		return;
1074 	}
1075 
1076 	g_bdev_mgr.zero_buffer = spdk_zmalloc(ZERO_BUFFER_SIZE, ZERO_BUFFER_SIZE,
1077 					      NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1078 	if (!g_bdev_mgr.zero_buffer) {
1079 		SPDK_ERRLOG("create bdev zero buffer failed\n");
1080 		spdk_bdev_init_complete(-1);
1081 		return;
1082 	}
1083 
1084 #ifdef SPDK_CONFIG_VTUNE
1085 	g_bdev_mgr.domain = __itt_domain_create("spdk_bdev");
1086 #endif
1087 
1088 	spdk_io_device_register(&g_bdev_mgr, spdk_bdev_mgmt_channel_create,
1089 				spdk_bdev_mgmt_channel_destroy,
1090 				sizeof(struct spdk_bdev_mgmt_channel),
1091 				"bdev_mgr");
1092 
1093 	rc = spdk_bdev_modules_init();
1094 	g_bdev_mgr.module_init_complete = true;
1095 	if (rc != 0) {
1096 		SPDK_ERRLOG("bdev modules init failed\n");
1097 		return;
1098 	}
1099 
1100 	spdk_bdev_module_action_complete();
1101 }
1102 
1103 static void
1104 spdk_bdev_mgr_unregister_cb(void *io_device)
1105 {
1106 	spdk_bdev_fini_cb cb_fn = g_fini_cb_fn;
1107 
1108 	if (spdk_mempool_count(g_bdev_mgr.bdev_io_pool) != g_bdev_opts.bdev_io_pool_size) {
1109 		SPDK_ERRLOG("bdev IO pool count is %zu but should be %u\n",
1110 			    spdk_mempool_count(g_bdev_mgr.bdev_io_pool),
1111 			    g_bdev_opts.bdev_io_pool_size);
1112 	}
1113 
1114 	if (spdk_mempool_count(g_bdev_mgr.buf_small_pool) != BUF_SMALL_POOL_SIZE) {
1115 		SPDK_ERRLOG("Small buffer pool count is %zu but should be %u\n",
1116 			    spdk_mempool_count(g_bdev_mgr.buf_small_pool),
1117 			    BUF_SMALL_POOL_SIZE);
1118 		assert(false);
1119 	}
1120 
1121 	if (spdk_mempool_count(g_bdev_mgr.buf_large_pool) != BUF_LARGE_POOL_SIZE) {
1122 		SPDK_ERRLOG("Large buffer pool count is %zu but should be %u\n",
1123 			    spdk_mempool_count(g_bdev_mgr.buf_large_pool),
1124 			    BUF_LARGE_POOL_SIZE);
1125 		assert(false);
1126 	}
1127 
1128 	spdk_mempool_free(g_bdev_mgr.bdev_io_pool);
1129 	spdk_mempool_free(g_bdev_mgr.buf_small_pool);
1130 	spdk_mempool_free(g_bdev_mgr.buf_large_pool);
1131 	spdk_free(g_bdev_mgr.zero_buffer);
1132 
1133 	cb_fn(g_fini_cb_arg);
1134 	g_fini_cb_fn = NULL;
1135 	g_fini_cb_arg = NULL;
1136 	g_bdev_mgr.init_complete = false;
1137 	g_bdev_mgr.module_init_complete = false;
1138 	pthread_mutex_destroy(&g_bdev_mgr.mutex);
1139 }
1140 
1141 static void
1142 spdk_bdev_module_finish_iter(void *arg)
1143 {
1144 	struct spdk_bdev_module *bdev_module;
1145 
1146 	/* FIXME: Handling initialization failures is broken now,
1147 	 * so we won't even try cleaning up after successfully
1148 	 * initialized modules. if module_init_complete is false,
1149 	 * just call spdk_bdev_mgr_unregister_cb
1150 	 */
1151 	if (!g_bdev_mgr.module_init_complete) {
1152 		spdk_bdev_mgr_unregister_cb(NULL);
1153 		return;
1154 	}
1155 
1156 	/* Start iterating from the last touched module */
1157 	if (!g_resume_bdev_module) {
1158 		bdev_module = TAILQ_LAST(&g_bdev_mgr.bdev_modules, bdev_module_list);
1159 	} else {
1160 		bdev_module = TAILQ_PREV(g_resume_bdev_module, bdev_module_list,
1161 					 internal.tailq);
1162 	}
1163 
1164 	while (bdev_module) {
1165 		if (bdev_module->async_fini) {
1166 			/* Save our place so we can resume later. We must
1167 			 * save the variable here, before calling module_fini()
1168 			 * below, because in some cases the module may immediately
1169 			 * call spdk_bdev_module_finish_done() and re-enter
1170 			 * this function to continue iterating. */
1171 			g_resume_bdev_module = bdev_module;
1172 		}
1173 
1174 		if (bdev_module->module_fini) {
1175 			bdev_module->module_fini();
1176 		}
1177 
1178 		if (bdev_module->async_fini) {
1179 			return;
1180 		}
1181 
1182 		bdev_module = TAILQ_PREV(bdev_module, bdev_module_list,
1183 					 internal.tailq);
1184 	}
1185 
1186 	g_resume_bdev_module = NULL;
1187 	spdk_io_device_unregister(&g_bdev_mgr, spdk_bdev_mgr_unregister_cb);
1188 }
1189 
1190 void
1191 spdk_bdev_module_finish_done(void)
1192 {
1193 	if (spdk_get_thread() != g_fini_thread) {
1194 		spdk_thread_send_msg(g_fini_thread, spdk_bdev_module_finish_iter, NULL);
1195 	} else {
1196 		spdk_bdev_module_finish_iter(NULL);
1197 	}
1198 }
1199 
1200 static void
1201 _spdk_bdev_finish_unregister_bdevs_iter(void *cb_arg, int bdeverrno)
1202 {
1203 	struct spdk_bdev *bdev = cb_arg;
1204 
1205 	if (bdeverrno && bdev) {
1206 		SPDK_WARNLOG("Unable to unregister bdev '%s' during spdk_bdev_finish()\n",
1207 			     bdev->name);
1208 
1209 		/*
1210 		 * Since the call to spdk_bdev_unregister() failed, we have no way to free this
1211 		 *  bdev; try to continue by manually removing this bdev from the list and continue
1212 		 *  with the next bdev in the list.
1213 		 */
1214 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
1215 	}
1216 
1217 	if (TAILQ_EMPTY(&g_bdev_mgr.bdevs)) {
1218 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Done unregistering bdevs\n");
1219 		/*
1220 		 * Bdev module finish need to be deferred as we might be in the middle of some context
1221 		 * (like bdev part free) that will use this bdev (or private bdev driver ctx data)
1222 		 * after returning.
1223 		 */
1224 		spdk_thread_send_msg(spdk_get_thread(), spdk_bdev_module_finish_iter, NULL);
1225 		return;
1226 	}
1227 
1228 	/*
1229 	 * Unregister last unclaimed bdev in the list, to ensure that bdev subsystem
1230 	 * shutdown proceeds top-down. The goal is to give virtual bdevs an opportunity
1231 	 * to detect clean shutdown as opposed to run-time hot removal of the underlying
1232 	 * base bdevs.
1233 	 *
1234 	 * Also, walk the list in the reverse order.
1235 	 */
1236 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1237 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1238 		if (bdev->internal.claim_module != NULL) {
1239 			SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Skipping claimed bdev '%s'(<-'%s').\n",
1240 				      bdev->name, bdev->internal.claim_module->name);
1241 			continue;
1242 		}
1243 
1244 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Unregistering bdev '%s'\n", bdev->name);
1245 		spdk_bdev_unregister(bdev, _spdk_bdev_finish_unregister_bdevs_iter, bdev);
1246 		return;
1247 	}
1248 
1249 	/*
1250 	 * If any bdev fails to unclaim underlying bdev properly, we may face the
1251 	 * case of bdev list consisting of claimed bdevs only (if claims are managed
1252 	 * correctly, this would mean there's a loop in the claims graph which is
1253 	 * clearly impossible). Warn and unregister last bdev on the list then.
1254 	 */
1255 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1256 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1257 		SPDK_WARNLOG("Unregistering claimed bdev '%s'!\n", bdev->name);
1258 		spdk_bdev_unregister(bdev, _spdk_bdev_finish_unregister_bdevs_iter, bdev);
1259 		return;
1260 	}
1261 }
1262 
1263 void
1264 spdk_bdev_finish(spdk_bdev_fini_cb cb_fn, void *cb_arg)
1265 {
1266 	struct spdk_bdev_module *m;
1267 
1268 	assert(cb_fn != NULL);
1269 
1270 	g_fini_thread = spdk_get_thread();
1271 
1272 	g_fini_cb_fn = cb_fn;
1273 	g_fini_cb_arg = cb_arg;
1274 
1275 	TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1276 		if (m->fini_start) {
1277 			m->fini_start();
1278 		}
1279 	}
1280 
1281 	_spdk_bdev_finish_unregister_bdevs_iter(NULL, 0);
1282 }
1283 
1284 struct spdk_bdev_io *
1285 spdk_bdev_get_io(struct spdk_bdev_channel *channel)
1286 {
1287 	struct spdk_bdev_mgmt_channel *ch = channel->shared_resource->mgmt_ch;
1288 	struct spdk_bdev_io *bdev_io;
1289 
1290 	if (ch->per_thread_cache_count > 0) {
1291 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
1292 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
1293 		ch->per_thread_cache_count--;
1294 	} else if (spdk_unlikely(!TAILQ_EMPTY(&ch->io_wait_queue))) {
1295 		/*
1296 		 * Don't try to look for bdev_ios in the global pool if there are
1297 		 * waiters on bdev_ios - we don't want this caller to jump the line.
1298 		 */
1299 		bdev_io = NULL;
1300 	} else {
1301 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
1302 	}
1303 
1304 	return bdev_io;
1305 }
1306 
1307 void
1308 spdk_bdev_free_io(struct spdk_bdev_io *bdev_io)
1309 {
1310 	struct spdk_bdev_mgmt_channel *ch;
1311 
1312 	assert(bdev_io != NULL);
1313 	assert(bdev_io->internal.status != SPDK_BDEV_IO_STATUS_PENDING);
1314 
1315 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
1316 
1317 	if (bdev_io->internal.buf != NULL) {
1318 		spdk_bdev_io_put_buf(bdev_io);
1319 	}
1320 
1321 	if (ch->per_thread_cache_count < ch->bdev_io_cache_size) {
1322 		ch->per_thread_cache_count++;
1323 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
1324 		while (ch->per_thread_cache_count > 0 && !TAILQ_EMPTY(&ch->io_wait_queue)) {
1325 			struct spdk_bdev_io_wait_entry *entry;
1326 
1327 			entry = TAILQ_FIRST(&ch->io_wait_queue);
1328 			TAILQ_REMOVE(&ch->io_wait_queue, entry, link);
1329 			entry->cb_fn(entry->cb_arg);
1330 		}
1331 	} else {
1332 		/* We should never have a full cache with entries on the io wait queue. */
1333 		assert(TAILQ_EMPTY(&ch->io_wait_queue));
1334 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
1335 	}
1336 }
1337 
1338 static bool
1339 _spdk_bdev_qos_is_iops_rate_limit(enum spdk_bdev_qos_rate_limit_type limit)
1340 {
1341 	assert(limit != SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
1342 
1343 	switch (limit) {
1344 	case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
1345 		return true;
1346 	case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
1347 	case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
1348 	case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
1349 		return false;
1350 	case SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES:
1351 	default:
1352 		return false;
1353 	}
1354 }
1355 
1356 static bool
1357 _spdk_bdev_qos_io_to_limit(struct spdk_bdev_io *bdev_io)
1358 {
1359 	switch (bdev_io->type) {
1360 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1361 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1362 	case SPDK_BDEV_IO_TYPE_READ:
1363 	case SPDK_BDEV_IO_TYPE_WRITE:
1364 		return true;
1365 	default:
1366 		return false;
1367 	}
1368 }
1369 
1370 static bool
1371 _spdk_bdev_is_read_io(struct spdk_bdev_io *bdev_io)
1372 {
1373 	switch (bdev_io->type) {
1374 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1375 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1376 		/* Bit 1 (0x2) set for read operation */
1377 		if (bdev_io->u.nvme_passthru.cmd.opc & SPDK_NVME_OPC_READ) {
1378 			return true;
1379 		} else {
1380 			return false;
1381 		}
1382 	case SPDK_BDEV_IO_TYPE_READ:
1383 		return true;
1384 	default:
1385 		return false;
1386 	}
1387 }
1388 
1389 static uint64_t
1390 _spdk_bdev_get_io_size_in_byte(struct spdk_bdev_io *bdev_io)
1391 {
1392 	struct spdk_bdev	*bdev = bdev_io->bdev;
1393 
1394 	switch (bdev_io->type) {
1395 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1396 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1397 		return bdev_io->u.nvme_passthru.nbytes;
1398 	case SPDK_BDEV_IO_TYPE_READ:
1399 	case SPDK_BDEV_IO_TYPE_WRITE:
1400 		return bdev_io->u.bdev.num_blocks * bdev->blocklen;
1401 	default:
1402 		return 0;
1403 	}
1404 }
1405 
1406 static bool
1407 _spdk_bdev_qos_rw_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1408 {
1409 	if (limit->max_per_timeslice > 0 && limit->remaining_this_timeslice <= 0) {
1410 		return true;
1411 	} else {
1412 		return false;
1413 	}
1414 }
1415 
1416 static bool
1417 _spdk_bdev_qos_r_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1418 {
1419 	if (_spdk_bdev_is_read_io(io) == false) {
1420 		return false;
1421 	}
1422 
1423 	return _spdk_bdev_qos_rw_queue_io(limit, io);
1424 }
1425 
1426 static bool
1427 _spdk_bdev_qos_w_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1428 {
1429 	if (_spdk_bdev_is_read_io(io) == true) {
1430 		return false;
1431 	}
1432 
1433 	return _spdk_bdev_qos_rw_queue_io(limit, io);
1434 }
1435 
1436 static void
1437 _spdk_bdev_qos_rw_iops_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1438 {
1439 	limit->remaining_this_timeslice--;
1440 }
1441 
1442 static void
1443 _spdk_bdev_qos_rw_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1444 {
1445 	limit->remaining_this_timeslice -= _spdk_bdev_get_io_size_in_byte(io);
1446 }
1447 
1448 static void
1449 _spdk_bdev_qos_r_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1450 {
1451 	if (_spdk_bdev_is_read_io(io) == false) {
1452 		return;
1453 	}
1454 
1455 	return _spdk_bdev_qos_rw_bps_update_quota(limit, io);
1456 }
1457 
1458 static void
1459 _spdk_bdev_qos_w_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1460 {
1461 	if (_spdk_bdev_is_read_io(io) == true) {
1462 		return;
1463 	}
1464 
1465 	return _spdk_bdev_qos_rw_bps_update_quota(limit, io);
1466 }
1467 
1468 static void
1469 _spdk_bdev_qos_set_ops(struct spdk_bdev_qos *qos)
1470 {
1471 	int i;
1472 
1473 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1474 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
1475 			qos->rate_limits[i].queue_io = NULL;
1476 			qos->rate_limits[i].update_quota = NULL;
1477 			continue;
1478 		}
1479 
1480 		switch (i) {
1481 		case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
1482 			qos->rate_limits[i].queue_io = _spdk_bdev_qos_rw_queue_io;
1483 			qos->rate_limits[i].update_quota = _spdk_bdev_qos_rw_iops_update_quota;
1484 			break;
1485 		case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
1486 			qos->rate_limits[i].queue_io = _spdk_bdev_qos_rw_queue_io;
1487 			qos->rate_limits[i].update_quota = _spdk_bdev_qos_rw_bps_update_quota;
1488 			break;
1489 		case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
1490 			qos->rate_limits[i].queue_io = _spdk_bdev_qos_r_queue_io;
1491 			qos->rate_limits[i].update_quota = _spdk_bdev_qos_r_bps_update_quota;
1492 			break;
1493 		case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
1494 			qos->rate_limits[i].queue_io = _spdk_bdev_qos_w_queue_io;
1495 			qos->rate_limits[i].update_quota = _spdk_bdev_qos_w_bps_update_quota;
1496 			break;
1497 		default:
1498 			break;
1499 		}
1500 	}
1501 }
1502 
1503 static inline void
1504 _spdk_bdev_io_do_submit(struct spdk_bdev_channel *bdev_ch, struct spdk_bdev_io *bdev_io)
1505 {
1506 	struct spdk_bdev *bdev = bdev_io->bdev;
1507 	struct spdk_io_channel *ch = bdev_ch->channel;
1508 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1509 
1510 	if (spdk_likely(TAILQ_EMPTY(&shared_resource->nomem_io))) {
1511 		bdev_ch->io_outstanding++;
1512 		shared_resource->io_outstanding++;
1513 		bdev_io->internal.in_submit_request = true;
1514 		bdev->fn_table->submit_request(ch, bdev_io);
1515 		bdev_io->internal.in_submit_request = false;
1516 	} else {
1517 		TAILQ_INSERT_TAIL(&shared_resource->nomem_io, bdev_io, internal.link);
1518 	}
1519 }
1520 
1521 static int
1522 _spdk_bdev_qos_io_submit(struct spdk_bdev_channel *ch, struct spdk_bdev_qos *qos)
1523 {
1524 	struct spdk_bdev_io		*bdev_io = NULL, *tmp = NULL;
1525 	int				i, submitted_ios = 0;
1526 
1527 	TAILQ_FOREACH_SAFE(bdev_io, &qos->queued, internal.link, tmp) {
1528 		if (_spdk_bdev_qos_io_to_limit(bdev_io) == true) {
1529 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1530 				if (!qos->rate_limits[i].queue_io) {
1531 					continue;
1532 				}
1533 
1534 				if (qos->rate_limits[i].queue_io(&qos->rate_limits[i],
1535 								 bdev_io) == true) {
1536 					return submitted_ios;
1537 				}
1538 			}
1539 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1540 				if (!qos->rate_limits[i].update_quota) {
1541 					continue;
1542 				}
1543 
1544 				qos->rate_limits[i].update_quota(&qos->rate_limits[i], bdev_io);
1545 			}
1546 		}
1547 
1548 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
1549 		_spdk_bdev_io_do_submit(ch, bdev_io);
1550 		submitted_ios++;
1551 	}
1552 
1553 	return submitted_ios;
1554 }
1555 
1556 static void
1557 _spdk_bdev_queue_io_wait_with_cb(struct spdk_bdev_io *bdev_io, spdk_bdev_io_wait_cb cb_fn)
1558 {
1559 	int rc;
1560 
1561 	bdev_io->internal.waitq_entry.bdev = bdev_io->bdev;
1562 	bdev_io->internal.waitq_entry.cb_fn = cb_fn;
1563 	bdev_io->internal.waitq_entry.cb_arg = bdev_io;
1564 	rc = spdk_bdev_queue_io_wait(bdev_io->bdev, spdk_io_channel_from_ctx(bdev_io->internal.ch),
1565 				     &bdev_io->internal.waitq_entry);
1566 	if (rc != 0) {
1567 		SPDK_ERRLOG("Queue IO failed, rc=%d\n", rc);
1568 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1569 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
1570 	}
1571 }
1572 
1573 static bool
1574 _spdk_bdev_io_type_can_split(uint8_t type)
1575 {
1576 	assert(type != SPDK_BDEV_IO_TYPE_INVALID);
1577 	assert(type < SPDK_BDEV_NUM_IO_TYPES);
1578 
1579 	/* Only split READ and WRITE I/O.  Theoretically other types of I/O like
1580 	 * UNMAP could be split, but these types of I/O are typically much larger
1581 	 * in size (sometimes the size of the entire block device), and the bdev
1582 	 * module can more efficiently split these types of I/O.  Plus those types
1583 	 * of I/O do not have a payload, which makes the splitting process simpler.
1584 	 */
1585 	if (type == SPDK_BDEV_IO_TYPE_READ || type == SPDK_BDEV_IO_TYPE_WRITE) {
1586 		return true;
1587 	} else {
1588 		return false;
1589 	}
1590 }
1591 
1592 static bool
1593 _spdk_bdev_io_should_split(struct spdk_bdev_io *bdev_io)
1594 {
1595 	uint64_t start_stripe, end_stripe;
1596 	uint32_t io_boundary = bdev_io->bdev->optimal_io_boundary;
1597 
1598 	if (io_boundary == 0) {
1599 		return false;
1600 	}
1601 
1602 	if (!_spdk_bdev_io_type_can_split(bdev_io->type)) {
1603 		return false;
1604 	}
1605 
1606 	start_stripe = bdev_io->u.bdev.offset_blocks;
1607 	end_stripe = start_stripe + bdev_io->u.bdev.num_blocks - 1;
1608 	/* Avoid expensive div operations if possible.  These spdk_u32 functions are very cheap. */
1609 	if (spdk_likely(spdk_u32_is_pow2(io_boundary))) {
1610 		start_stripe >>= spdk_u32log2(io_boundary);
1611 		end_stripe >>= spdk_u32log2(io_boundary);
1612 	} else {
1613 		start_stripe /= io_boundary;
1614 		end_stripe /= io_boundary;
1615 	}
1616 	return (start_stripe != end_stripe);
1617 }
1618 
1619 static uint32_t
1620 _to_next_boundary(uint64_t offset, uint32_t boundary)
1621 {
1622 	return (boundary - (offset % boundary));
1623 }
1624 
1625 static void
1626 _spdk_bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
1627 
1628 static void
1629 _spdk_bdev_io_split(void *_bdev_io)
1630 {
1631 	struct spdk_bdev_io *bdev_io = _bdev_io;
1632 	uint64_t current_offset, remaining;
1633 	uint32_t blocklen, to_next_boundary, to_next_boundary_bytes, to_last_block_bytes;
1634 	struct iovec *parent_iov, *iov;
1635 	uint64_t parent_iov_offset, iov_len;
1636 	uint32_t parent_iovpos, parent_iovcnt, child_iovcnt, iovcnt;
1637 	void *md_buf = NULL;
1638 	int rc;
1639 
1640 	remaining = bdev_io->u.bdev.split_remaining_num_blocks;
1641 	current_offset = bdev_io->u.bdev.split_current_offset_blocks;
1642 	blocklen = bdev_io->bdev->blocklen;
1643 	parent_iov_offset = (current_offset - bdev_io->u.bdev.offset_blocks) * blocklen;
1644 	parent_iovcnt = bdev_io->u.bdev.iovcnt;
1645 
1646 	for (parent_iovpos = 0; parent_iovpos < parent_iovcnt; parent_iovpos++) {
1647 		parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
1648 		if (parent_iov_offset < parent_iov->iov_len) {
1649 			break;
1650 		}
1651 		parent_iov_offset -= parent_iov->iov_len;
1652 	}
1653 
1654 	child_iovcnt = 0;
1655 	while (remaining > 0 && parent_iovpos < parent_iovcnt && child_iovcnt < BDEV_IO_NUM_CHILD_IOV) {
1656 		to_next_boundary = _to_next_boundary(current_offset, bdev_io->bdev->optimal_io_boundary);
1657 		to_next_boundary = spdk_min(remaining, to_next_boundary);
1658 		to_next_boundary_bytes = to_next_boundary * blocklen;
1659 		iov = &bdev_io->child_iov[child_iovcnt];
1660 		iovcnt = 0;
1661 
1662 		if (bdev_io->u.bdev.md_buf) {
1663 			assert((parent_iov_offset % blocklen) > 0);
1664 			md_buf = (char *)bdev_io->u.bdev.md_buf + (parent_iov_offset / blocklen) *
1665 				 spdk_bdev_get_md_size(bdev_io->bdev);
1666 		}
1667 
1668 		while (to_next_boundary_bytes > 0 && parent_iovpos < parent_iovcnt &&
1669 		       child_iovcnt < BDEV_IO_NUM_CHILD_IOV) {
1670 			parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
1671 			iov_len = spdk_min(to_next_boundary_bytes, parent_iov->iov_len - parent_iov_offset);
1672 			to_next_boundary_bytes -= iov_len;
1673 
1674 			bdev_io->child_iov[child_iovcnt].iov_base = parent_iov->iov_base + parent_iov_offset;
1675 			bdev_io->child_iov[child_iovcnt].iov_len = iov_len;
1676 
1677 			if (iov_len < parent_iov->iov_len - parent_iov_offset) {
1678 				parent_iov_offset += iov_len;
1679 			} else {
1680 				parent_iovpos++;
1681 				parent_iov_offset = 0;
1682 			}
1683 			child_iovcnt++;
1684 			iovcnt++;
1685 		}
1686 
1687 		if (to_next_boundary_bytes > 0) {
1688 			/* We had to stop this child I/O early because we ran out of
1689 			 * child_iov space.  Ensure the iovs to be aligned with block
1690 			 * size and then adjust to_next_boundary before starting the
1691 			 * child I/O.
1692 			 */
1693 			assert(child_iovcnt == BDEV_IO_NUM_CHILD_IOV);
1694 			to_last_block_bytes = to_next_boundary_bytes % blocklen;
1695 			if (to_last_block_bytes != 0) {
1696 				uint32_t child_iovpos = child_iovcnt - 1;
1697 				/* don't decrease child_iovcnt so the loop will naturally end */
1698 
1699 				to_next_boundary_bytes += _to_next_boundary(to_next_boundary_bytes, blocklen);
1700 				while (to_last_block_bytes > 0 && iovcnt > 0) {
1701 					iov_len = spdk_min(to_last_block_bytes,
1702 							   bdev_io->child_iov[child_iovpos].iov_len);
1703 					bdev_io->child_iov[child_iovpos].iov_len -= iov_len;
1704 					if (bdev_io->child_iov[child_iovpos].iov_len == 0) {
1705 						child_iovpos--;
1706 						iovcnt--;
1707 					}
1708 					to_last_block_bytes -= iov_len;
1709 				}
1710 
1711 				assert(to_last_block_bytes == 0);
1712 			}
1713 			to_next_boundary -= to_next_boundary_bytes / blocklen;
1714 		}
1715 
1716 		bdev_io->u.bdev.split_outstanding++;
1717 
1718 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
1719 			rc = _spdk_bdev_readv_blocks_with_md(bdev_io->internal.desc,
1720 							     spdk_io_channel_from_ctx(bdev_io->internal.ch),
1721 							     iov, iovcnt, md_buf, current_offset,
1722 							     to_next_boundary,
1723 							     _spdk_bdev_io_split_done, bdev_io);
1724 		} else {
1725 			rc = _spdk_bdev_writev_blocks_with_md(bdev_io->internal.desc,
1726 							      spdk_io_channel_from_ctx(bdev_io->internal.ch),
1727 							      iov, iovcnt, md_buf, current_offset,
1728 							      to_next_boundary,
1729 							      _spdk_bdev_io_split_done, bdev_io);
1730 		}
1731 
1732 		if (rc == 0) {
1733 			current_offset += to_next_boundary;
1734 			remaining -= to_next_boundary;
1735 			bdev_io->u.bdev.split_current_offset_blocks = current_offset;
1736 			bdev_io->u.bdev.split_remaining_num_blocks = remaining;
1737 		} else {
1738 			bdev_io->u.bdev.split_outstanding--;
1739 			if (rc == -ENOMEM) {
1740 				if (bdev_io->u.bdev.split_outstanding == 0) {
1741 					/* No I/O is outstanding. Hence we should wait here. */
1742 					_spdk_bdev_queue_io_wait_with_cb(bdev_io,
1743 									 _spdk_bdev_io_split);
1744 				}
1745 			} else {
1746 				bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1747 				if (bdev_io->u.bdev.split_outstanding == 0) {
1748 					bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
1749 				}
1750 			}
1751 
1752 			return;
1753 		}
1754 	}
1755 }
1756 
1757 static void
1758 _spdk_bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
1759 {
1760 	struct spdk_bdev_io *parent_io = cb_arg;
1761 
1762 	spdk_bdev_free_io(bdev_io);
1763 
1764 	if (!success) {
1765 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1766 	}
1767 	parent_io->u.bdev.split_outstanding--;
1768 	if (parent_io->u.bdev.split_outstanding != 0) {
1769 		return;
1770 	}
1771 
1772 	/*
1773 	 * Parent I/O finishes when all blocks are consumed.
1774 	 */
1775 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
1776 		parent_io->internal.cb(parent_io, parent_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
1777 				       parent_io->internal.caller_ctx);
1778 		return;
1779 	}
1780 
1781 	/*
1782 	 * Continue with the splitting process.  This function will complete the parent I/O if the
1783 	 * splitting is done.
1784 	 */
1785 	_spdk_bdev_io_split(parent_io);
1786 }
1787 
1788 static void
1789 _spdk_bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
1790 			       bool success);
1791 
1792 static void
1793 spdk_bdev_io_split(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io)
1794 {
1795 	assert(_spdk_bdev_io_type_can_split(bdev_io->type));
1796 
1797 	bdev_io->u.bdev.split_current_offset_blocks = bdev_io->u.bdev.offset_blocks;
1798 	bdev_io->u.bdev.split_remaining_num_blocks = bdev_io->u.bdev.num_blocks;
1799 	bdev_io->u.bdev.split_outstanding = 0;
1800 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
1801 
1802 	if (_is_buf_allocated(bdev_io->u.bdev.iovs)) {
1803 		_spdk_bdev_io_split(bdev_io);
1804 	} else {
1805 		assert(bdev_io->type == SPDK_BDEV_IO_TYPE_READ);
1806 		spdk_bdev_io_get_buf(bdev_io, _spdk_bdev_io_split_get_buf_cb,
1807 				     bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
1808 	}
1809 }
1810 
1811 static void
1812 _spdk_bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
1813 			       bool success)
1814 {
1815 	if (!success) {
1816 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1817 		return;
1818 	}
1819 
1820 	spdk_bdev_io_split(ch, bdev_io);
1821 }
1822 
1823 /* Explicitly mark this inline, since it's used as a function pointer and otherwise won't
1824  *  be inlined, at least on some compilers.
1825  */
1826 static inline void
1827 _spdk_bdev_io_submit(void *ctx)
1828 {
1829 	struct spdk_bdev_io *bdev_io = ctx;
1830 	struct spdk_bdev *bdev = bdev_io->bdev;
1831 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1832 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1833 	uint64_t tsc;
1834 
1835 	tsc = spdk_get_ticks();
1836 	bdev_io->internal.submit_tsc = tsc;
1837 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_START, 0, 0, (uintptr_t)bdev_io, bdev_io->type);
1838 
1839 	if (spdk_likely(bdev_ch->flags == 0)) {
1840 		_spdk_bdev_io_do_submit(bdev_ch, bdev_io);
1841 		return;
1842 	}
1843 
1844 	bdev_ch->io_outstanding++;
1845 	shared_resource->io_outstanding++;
1846 	bdev_io->internal.in_submit_request = true;
1847 	if (bdev_ch->flags & BDEV_CH_RESET_IN_PROGRESS) {
1848 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1849 	} else if (bdev_ch->flags & BDEV_CH_QOS_ENABLED) {
1850 		bdev_ch->io_outstanding--;
1851 		shared_resource->io_outstanding--;
1852 		TAILQ_INSERT_TAIL(&bdev->internal.qos->queued, bdev_io, internal.link);
1853 		_spdk_bdev_qos_io_submit(bdev_ch, bdev->internal.qos);
1854 	} else {
1855 		SPDK_ERRLOG("unknown bdev_ch flag %x found\n", bdev_ch->flags);
1856 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1857 	}
1858 	bdev_io->internal.in_submit_request = false;
1859 }
1860 
1861 void
1862 spdk_bdev_io_submit(struct spdk_bdev_io *bdev_io)
1863 {
1864 	struct spdk_bdev *bdev = bdev_io->bdev;
1865 	struct spdk_thread *thread = spdk_bdev_io_get_thread(bdev_io);
1866 
1867 	assert(thread != NULL);
1868 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
1869 
1870 	if (bdev->split_on_optimal_io_boundary && _spdk_bdev_io_should_split(bdev_io)) {
1871 		spdk_bdev_io_split(NULL, bdev_io);
1872 		return;
1873 	}
1874 
1875 	if (bdev_io->internal.ch->flags & BDEV_CH_QOS_ENABLED) {
1876 		if ((thread == bdev->internal.qos->thread) || !bdev->internal.qos->thread) {
1877 			_spdk_bdev_io_submit(bdev_io);
1878 		} else {
1879 			bdev_io->internal.io_submit_ch = bdev_io->internal.ch;
1880 			bdev_io->internal.ch = bdev->internal.qos->ch;
1881 			spdk_thread_send_msg(bdev->internal.qos->thread, _spdk_bdev_io_submit, bdev_io);
1882 		}
1883 	} else {
1884 		_spdk_bdev_io_submit(bdev_io);
1885 	}
1886 }
1887 
1888 static void
1889 spdk_bdev_io_submit_reset(struct spdk_bdev_io *bdev_io)
1890 {
1891 	struct spdk_bdev *bdev = bdev_io->bdev;
1892 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1893 	struct spdk_io_channel *ch = bdev_ch->channel;
1894 
1895 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
1896 
1897 	bdev_io->internal.in_submit_request = true;
1898 	bdev->fn_table->submit_request(ch, bdev_io);
1899 	bdev_io->internal.in_submit_request = false;
1900 }
1901 
1902 void
1903 spdk_bdev_io_init(struct spdk_bdev_io *bdev_io,
1904 		  struct spdk_bdev *bdev, void *cb_arg,
1905 		  spdk_bdev_io_completion_cb cb)
1906 {
1907 	bdev_io->bdev = bdev;
1908 	bdev_io->internal.caller_ctx = cb_arg;
1909 	bdev_io->internal.cb = cb;
1910 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
1911 	bdev_io->internal.in_submit_request = false;
1912 	bdev_io->internal.buf = NULL;
1913 	bdev_io->internal.io_submit_ch = NULL;
1914 	bdev_io->internal.orig_iovs = NULL;
1915 	bdev_io->internal.orig_iovcnt = 0;
1916 	bdev_io->internal.orig_md_buf = NULL;
1917 }
1918 
1919 static bool
1920 _spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
1921 {
1922 	return bdev->fn_table->io_type_supported(bdev->ctxt, io_type);
1923 }
1924 
1925 bool
1926 spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
1927 {
1928 	bool supported;
1929 
1930 	supported = _spdk_bdev_io_type_supported(bdev, io_type);
1931 
1932 	if (!supported) {
1933 		switch (io_type) {
1934 		case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
1935 			/* The bdev layer will emulate write zeroes as long as write is supported. */
1936 			supported = _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
1937 			break;
1938 		case SPDK_BDEV_IO_TYPE_ZCOPY:
1939 			/* Zero copy can be emulated with regular read and write */
1940 			supported = _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_READ) &&
1941 				    _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
1942 			break;
1943 		default:
1944 			break;
1945 		}
1946 	}
1947 
1948 	return supported;
1949 }
1950 
1951 int
1952 spdk_bdev_dump_info_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
1953 {
1954 	if (bdev->fn_table->dump_info_json) {
1955 		return bdev->fn_table->dump_info_json(bdev->ctxt, w);
1956 	}
1957 
1958 	return 0;
1959 }
1960 
1961 static void
1962 spdk_bdev_qos_update_max_quota_per_timeslice(struct spdk_bdev_qos *qos)
1963 {
1964 	uint32_t max_per_timeslice = 0;
1965 	int i;
1966 
1967 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1968 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
1969 			qos->rate_limits[i].max_per_timeslice = 0;
1970 			continue;
1971 		}
1972 
1973 		max_per_timeslice = qos->rate_limits[i].limit *
1974 				    SPDK_BDEV_QOS_TIMESLICE_IN_USEC / SPDK_SEC_TO_USEC;
1975 
1976 		qos->rate_limits[i].max_per_timeslice = spdk_max(max_per_timeslice,
1977 							qos->rate_limits[i].min_per_timeslice);
1978 
1979 		qos->rate_limits[i].remaining_this_timeslice = qos->rate_limits[i].max_per_timeslice;
1980 	}
1981 
1982 	_spdk_bdev_qos_set_ops(qos);
1983 }
1984 
1985 static int
1986 spdk_bdev_channel_poll_qos(void *arg)
1987 {
1988 	struct spdk_bdev_qos *qos = arg;
1989 	uint64_t now = spdk_get_ticks();
1990 	int i;
1991 
1992 	if (now < (qos->last_timeslice + qos->timeslice_size)) {
1993 		/* We received our callback earlier than expected - return
1994 		 *  immediately and wait to do accounting until at least one
1995 		 *  timeslice has actually expired.  This should never happen
1996 		 *  with a well-behaved timer implementation.
1997 		 */
1998 		return 0;
1999 	}
2000 
2001 	/* Reset for next round of rate limiting */
2002 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2003 		/* We may have allowed the IOs or bytes to slightly overrun in the last
2004 		 * timeslice. remaining_this_timeslice is signed, so if it's negative
2005 		 * here, we'll account for the overrun so that the next timeslice will
2006 		 * be appropriately reduced.
2007 		 */
2008 		if (qos->rate_limits[i].remaining_this_timeslice > 0) {
2009 			qos->rate_limits[i].remaining_this_timeslice = 0;
2010 		}
2011 	}
2012 
2013 	while (now >= (qos->last_timeslice + qos->timeslice_size)) {
2014 		qos->last_timeslice += qos->timeslice_size;
2015 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2016 			qos->rate_limits[i].remaining_this_timeslice +=
2017 				qos->rate_limits[i].max_per_timeslice;
2018 		}
2019 	}
2020 
2021 	return _spdk_bdev_qos_io_submit(qos->ch, qos);
2022 }
2023 
2024 static void
2025 _spdk_bdev_channel_destroy_resource(struct spdk_bdev_channel *ch)
2026 {
2027 	struct spdk_bdev_shared_resource *shared_resource;
2028 
2029 	spdk_put_io_channel(ch->channel);
2030 
2031 	shared_resource = ch->shared_resource;
2032 
2033 	assert(ch->io_outstanding == 0);
2034 	assert(shared_resource->ref > 0);
2035 	shared_resource->ref--;
2036 	if (shared_resource->ref == 0) {
2037 		assert(shared_resource->io_outstanding == 0);
2038 		TAILQ_REMOVE(&shared_resource->mgmt_ch->shared_resources, shared_resource, link);
2039 		spdk_put_io_channel(spdk_io_channel_from_ctx(shared_resource->mgmt_ch));
2040 		free(shared_resource);
2041 	}
2042 }
2043 
2044 /* Caller must hold bdev->internal.mutex. */
2045 static void
2046 _spdk_bdev_enable_qos(struct spdk_bdev *bdev, struct spdk_bdev_channel *ch)
2047 {
2048 	struct spdk_bdev_qos	*qos = bdev->internal.qos;
2049 	int			i;
2050 
2051 	/* Rate limiting on this bdev enabled */
2052 	if (qos) {
2053 		if (qos->ch == NULL) {
2054 			struct spdk_io_channel *io_ch;
2055 
2056 			SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Selecting channel %p as QoS channel for bdev %s on thread %p\n", ch,
2057 				      bdev->name, spdk_get_thread());
2058 
2059 			/* No qos channel has been selected, so set one up */
2060 
2061 			/* Take another reference to ch */
2062 			io_ch = spdk_get_io_channel(__bdev_to_io_dev(bdev));
2063 			assert(io_ch != NULL);
2064 			qos->ch = ch;
2065 
2066 			qos->thread = spdk_io_channel_get_thread(io_ch);
2067 
2068 			TAILQ_INIT(&qos->queued);
2069 
2070 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2071 				if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
2072 					qos->rate_limits[i].min_per_timeslice =
2073 						SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE;
2074 				} else {
2075 					qos->rate_limits[i].min_per_timeslice =
2076 						SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE;
2077 				}
2078 
2079 				if (qos->rate_limits[i].limit == 0) {
2080 					qos->rate_limits[i].limit = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
2081 				}
2082 			}
2083 			spdk_bdev_qos_update_max_quota_per_timeslice(qos);
2084 			qos->timeslice_size =
2085 				SPDK_BDEV_QOS_TIMESLICE_IN_USEC * spdk_get_ticks_hz() / SPDK_SEC_TO_USEC;
2086 			qos->last_timeslice = spdk_get_ticks();
2087 			qos->poller = spdk_poller_register(spdk_bdev_channel_poll_qos,
2088 							   qos,
2089 							   SPDK_BDEV_QOS_TIMESLICE_IN_USEC);
2090 		}
2091 
2092 		ch->flags |= BDEV_CH_QOS_ENABLED;
2093 	}
2094 }
2095 
2096 static int
2097 spdk_bdev_channel_create(void *io_device, void *ctx_buf)
2098 {
2099 	struct spdk_bdev		*bdev = __bdev_from_io_dev(io_device);
2100 	struct spdk_bdev_channel	*ch = ctx_buf;
2101 	struct spdk_io_channel		*mgmt_io_ch;
2102 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
2103 	struct spdk_bdev_shared_resource *shared_resource;
2104 
2105 	ch->bdev = bdev;
2106 	ch->channel = bdev->fn_table->get_io_channel(bdev->ctxt);
2107 	if (!ch->channel) {
2108 		return -1;
2109 	}
2110 
2111 	assert(ch->histogram == NULL);
2112 	if (bdev->internal.histogram_enabled) {
2113 		ch->histogram = spdk_histogram_data_alloc();
2114 		if (ch->histogram == NULL) {
2115 			SPDK_ERRLOG("Could not allocate histogram\n");
2116 		}
2117 	}
2118 
2119 	mgmt_io_ch = spdk_get_io_channel(&g_bdev_mgr);
2120 	if (!mgmt_io_ch) {
2121 		spdk_put_io_channel(ch->channel);
2122 		return -1;
2123 	}
2124 
2125 	mgmt_ch = spdk_io_channel_get_ctx(mgmt_io_ch);
2126 	TAILQ_FOREACH(shared_resource, &mgmt_ch->shared_resources, link) {
2127 		if (shared_resource->shared_ch == ch->channel) {
2128 			spdk_put_io_channel(mgmt_io_ch);
2129 			shared_resource->ref++;
2130 			break;
2131 		}
2132 	}
2133 
2134 	if (shared_resource == NULL) {
2135 		shared_resource = calloc(1, sizeof(*shared_resource));
2136 		if (shared_resource == NULL) {
2137 			spdk_put_io_channel(ch->channel);
2138 			spdk_put_io_channel(mgmt_io_ch);
2139 			return -1;
2140 		}
2141 
2142 		shared_resource->mgmt_ch = mgmt_ch;
2143 		shared_resource->io_outstanding = 0;
2144 		TAILQ_INIT(&shared_resource->nomem_io);
2145 		shared_resource->nomem_threshold = 0;
2146 		shared_resource->shared_ch = ch->channel;
2147 		shared_resource->ref = 1;
2148 		TAILQ_INSERT_TAIL(&mgmt_ch->shared_resources, shared_resource, link);
2149 	}
2150 
2151 	memset(&ch->stat, 0, sizeof(ch->stat));
2152 	ch->stat.ticks_rate = spdk_get_ticks_hz();
2153 	ch->io_outstanding = 0;
2154 	TAILQ_INIT(&ch->queued_resets);
2155 	ch->flags = 0;
2156 	ch->shared_resource = shared_resource;
2157 
2158 #ifdef SPDK_CONFIG_VTUNE
2159 	{
2160 		char *name;
2161 		__itt_init_ittlib(NULL, 0);
2162 		name = spdk_sprintf_alloc("spdk_bdev_%s_%p", ch->bdev->name, ch);
2163 		if (!name) {
2164 			_spdk_bdev_channel_destroy_resource(ch);
2165 			return -1;
2166 		}
2167 		ch->handle = __itt_string_handle_create(name);
2168 		free(name);
2169 		ch->start_tsc = spdk_get_ticks();
2170 		ch->interval_tsc = spdk_get_ticks_hz() / 100;
2171 		memset(&ch->prev_stat, 0, sizeof(ch->prev_stat));
2172 	}
2173 #endif
2174 
2175 	pthread_mutex_lock(&bdev->internal.mutex);
2176 	_spdk_bdev_enable_qos(bdev, ch);
2177 	pthread_mutex_unlock(&bdev->internal.mutex);
2178 
2179 	return 0;
2180 }
2181 
2182 /*
2183  * Abort I/O that are waiting on a data buffer.  These types of I/O are
2184  *  linked using the spdk_bdev_io internal.buf_link TAILQ_ENTRY.
2185  */
2186 static void
2187 _spdk_bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_channel *ch)
2188 {
2189 	bdev_io_stailq_t tmp;
2190 	struct spdk_bdev_io *bdev_io;
2191 
2192 	STAILQ_INIT(&tmp);
2193 
2194 	while (!STAILQ_EMPTY(queue)) {
2195 		bdev_io = STAILQ_FIRST(queue);
2196 		STAILQ_REMOVE_HEAD(queue, internal.buf_link);
2197 		if (bdev_io->internal.ch == ch) {
2198 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2199 		} else {
2200 			STAILQ_INSERT_TAIL(&tmp, bdev_io, internal.buf_link);
2201 		}
2202 	}
2203 
2204 	STAILQ_SWAP(&tmp, queue, spdk_bdev_io);
2205 }
2206 
2207 /*
2208  * Abort I/O that are queued waiting for submission.  These types of I/O are
2209  *  linked using the spdk_bdev_io link TAILQ_ENTRY.
2210  */
2211 static void
2212 _spdk_bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_channel *ch)
2213 {
2214 	struct spdk_bdev_io *bdev_io, *tmp;
2215 
2216 	TAILQ_FOREACH_SAFE(bdev_io, queue, internal.link, tmp) {
2217 		if (bdev_io->internal.ch == ch) {
2218 			TAILQ_REMOVE(queue, bdev_io, internal.link);
2219 			/*
2220 			 * spdk_bdev_io_complete() assumes that the completed I/O had
2221 			 *  been submitted to the bdev module.  Since in this case it
2222 			 *  hadn't, bump io_outstanding to account for the decrement
2223 			 *  that spdk_bdev_io_complete() will do.
2224 			 */
2225 			if (bdev_io->type != SPDK_BDEV_IO_TYPE_RESET) {
2226 				ch->io_outstanding++;
2227 				ch->shared_resource->io_outstanding++;
2228 			}
2229 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2230 		}
2231 	}
2232 }
2233 
2234 static void
2235 spdk_bdev_qos_channel_destroy(void *cb_arg)
2236 {
2237 	struct spdk_bdev_qos *qos = cb_arg;
2238 
2239 	spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
2240 	spdk_poller_unregister(&qos->poller);
2241 
2242 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Free QoS %p.\n", qos);
2243 
2244 	free(qos);
2245 }
2246 
2247 static int
2248 spdk_bdev_qos_destroy(struct spdk_bdev *bdev)
2249 {
2250 	int i;
2251 
2252 	/*
2253 	 * Cleanly shutting down the QoS poller is tricky, because
2254 	 * during the asynchronous operation the user could open
2255 	 * a new descriptor and create a new channel, spawning
2256 	 * a new QoS poller.
2257 	 *
2258 	 * The strategy is to create a new QoS structure here and swap it
2259 	 * in. The shutdown path then continues to refer to the old one
2260 	 * until it completes and then releases it.
2261 	 */
2262 	struct spdk_bdev_qos *new_qos, *old_qos;
2263 
2264 	old_qos = bdev->internal.qos;
2265 
2266 	new_qos = calloc(1, sizeof(*new_qos));
2267 	if (!new_qos) {
2268 		SPDK_ERRLOG("Unable to allocate memory to shut down QoS.\n");
2269 		return -ENOMEM;
2270 	}
2271 
2272 	/* Copy the old QoS data into the newly allocated structure */
2273 	memcpy(new_qos, old_qos, sizeof(*new_qos));
2274 
2275 	/* Zero out the key parts of the QoS structure */
2276 	new_qos->ch = NULL;
2277 	new_qos->thread = NULL;
2278 	new_qos->poller = NULL;
2279 	TAILQ_INIT(&new_qos->queued);
2280 	/*
2281 	 * The limit member of spdk_bdev_qos_limit structure is not zeroed.
2282 	 * It will be used later for the new QoS structure.
2283 	 */
2284 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2285 		new_qos->rate_limits[i].remaining_this_timeslice = 0;
2286 		new_qos->rate_limits[i].min_per_timeslice = 0;
2287 		new_qos->rate_limits[i].max_per_timeslice = 0;
2288 	}
2289 
2290 	bdev->internal.qos = new_qos;
2291 
2292 	if (old_qos->thread == NULL) {
2293 		free(old_qos);
2294 	} else {
2295 		spdk_thread_send_msg(old_qos->thread, spdk_bdev_qos_channel_destroy,
2296 				     old_qos);
2297 	}
2298 
2299 	/* It is safe to continue with destroying the bdev even though the QoS channel hasn't
2300 	 * been destroyed yet. The destruction path will end up waiting for the final
2301 	 * channel to be put before it releases resources. */
2302 
2303 	return 0;
2304 }
2305 
2306 static void
2307 _spdk_bdev_io_stat_add(struct spdk_bdev_io_stat *total, struct spdk_bdev_io_stat *add)
2308 {
2309 	total->bytes_read += add->bytes_read;
2310 	total->num_read_ops += add->num_read_ops;
2311 	total->bytes_written += add->bytes_written;
2312 	total->num_write_ops += add->num_write_ops;
2313 	total->bytes_unmapped += add->bytes_unmapped;
2314 	total->num_unmap_ops += add->num_unmap_ops;
2315 	total->read_latency_ticks += add->read_latency_ticks;
2316 	total->write_latency_ticks += add->write_latency_ticks;
2317 	total->unmap_latency_ticks += add->unmap_latency_ticks;
2318 }
2319 
2320 static void
2321 spdk_bdev_channel_destroy(void *io_device, void *ctx_buf)
2322 {
2323 	struct spdk_bdev_channel	*ch = ctx_buf;
2324 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
2325 	struct spdk_bdev_shared_resource *shared_resource = ch->shared_resource;
2326 
2327 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Destroying channel %p for bdev %s on thread %p\n", ch, ch->bdev->name,
2328 		      spdk_get_thread());
2329 
2330 	/* This channel is going away, so add its statistics into the bdev so that they don't get lost. */
2331 	pthread_mutex_lock(&ch->bdev->internal.mutex);
2332 	_spdk_bdev_io_stat_add(&ch->bdev->internal.stat, &ch->stat);
2333 	pthread_mutex_unlock(&ch->bdev->internal.mutex);
2334 
2335 	mgmt_ch = shared_resource->mgmt_ch;
2336 
2337 	_spdk_bdev_abort_queued_io(&ch->queued_resets, ch);
2338 	_spdk_bdev_abort_queued_io(&shared_resource->nomem_io, ch);
2339 	_spdk_bdev_abort_buf_io(&mgmt_ch->need_buf_small, ch);
2340 	_spdk_bdev_abort_buf_io(&mgmt_ch->need_buf_large, ch);
2341 
2342 	if (ch->histogram) {
2343 		spdk_histogram_data_free(ch->histogram);
2344 	}
2345 
2346 	_spdk_bdev_channel_destroy_resource(ch);
2347 }
2348 
2349 int
2350 spdk_bdev_alias_add(struct spdk_bdev *bdev, const char *alias)
2351 {
2352 	struct spdk_bdev_alias *tmp;
2353 
2354 	if (alias == NULL) {
2355 		SPDK_ERRLOG("Empty alias passed\n");
2356 		return -EINVAL;
2357 	}
2358 
2359 	if (spdk_bdev_get_by_name(alias)) {
2360 		SPDK_ERRLOG("Bdev name/alias: %s already exists\n", alias);
2361 		return -EEXIST;
2362 	}
2363 
2364 	tmp = calloc(1, sizeof(*tmp));
2365 	if (tmp == NULL) {
2366 		SPDK_ERRLOG("Unable to allocate alias\n");
2367 		return -ENOMEM;
2368 	}
2369 
2370 	tmp->alias = strdup(alias);
2371 	if (tmp->alias == NULL) {
2372 		free(tmp);
2373 		SPDK_ERRLOG("Unable to allocate alias\n");
2374 		return -ENOMEM;
2375 	}
2376 
2377 	TAILQ_INSERT_TAIL(&bdev->aliases, tmp, tailq);
2378 
2379 	return 0;
2380 }
2381 
2382 int
2383 spdk_bdev_alias_del(struct spdk_bdev *bdev, const char *alias)
2384 {
2385 	struct spdk_bdev_alias *tmp;
2386 
2387 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
2388 		if (strcmp(alias, tmp->alias) == 0) {
2389 			TAILQ_REMOVE(&bdev->aliases, tmp, tailq);
2390 			free(tmp->alias);
2391 			free(tmp);
2392 			return 0;
2393 		}
2394 	}
2395 
2396 	SPDK_INFOLOG(SPDK_LOG_BDEV, "Alias %s does not exists\n", alias);
2397 
2398 	return -ENOENT;
2399 }
2400 
2401 void
2402 spdk_bdev_alias_del_all(struct spdk_bdev *bdev)
2403 {
2404 	struct spdk_bdev_alias *p, *tmp;
2405 
2406 	TAILQ_FOREACH_SAFE(p, &bdev->aliases, tailq, tmp) {
2407 		TAILQ_REMOVE(&bdev->aliases, p, tailq);
2408 		free(p->alias);
2409 		free(p);
2410 	}
2411 }
2412 
2413 struct spdk_io_channel *
2414 spdk_bdev_get_io_channel(struct spdk_bdev_desc *desc)
2415 {
2416 	return spdk_get_io_channel(__bdev_to_io_dev(spdk_bdev_desc_get_bdev(desc)));
2417 }
2418 
2419 const char *
2420 spdk_bdev_get_name(const struct spdk_bdev *bdev)
2421 {
2422 	return bdev->name;
2423 }
2424 
2425 const char *
2426 spdk_bdev_get_product_name(const struct spdk_bdev *bdev)
2427 {
2428 	return bdev->product_name;
2429 }
2430 
2431 const struct spdk_bdev_aliases_list *
2432 spdk_bdev_get_aliases(const struct spdk_bdev *bdev)
2433 {
2434 	return &bdev->aliases;
2435 }
2436 
2437 uint32_t
2438 spdk_bdev_get_block_size(const struct spdk_bdev *bdev)
2439 {
2440 	return bdev->blocklen;
2441 }
2442 
2443 uint32_t
2444 spdk_bdev_get_write_unit_size(const struct spdk_bdev *bdev)
2445 {
2446 	return bdev->write_unit_size;
2447 }
2448 
2449 uint64_t
2450 spdk_bdev_get_num_blocks(const struct spdk_bdev *bdev)
2451 {
2452 	return bdev->blockcnt;
2453 }
2454 
2455 const char *
2456 spdk_bdev_get_qos_rpc_type(enum spdk_bdev_qos_rate_limit_type type)
2457 {
2458 	return qos_rpc_type[type];
2459 }
2460 
2461 void
2462 spdk_bdev_get_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
2463 {
2464 	int i;
2465 
2466 	memset(limits, 0, sizeof(*limits) * SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
2467 
2468 	pthread_mutex_lock(&bdev->internal.mutex);
2469 	if (bdev->internal.qos) {
2470 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2471 			if (bdev->internal.qos->rate_limits[i].limit !=
2472 			    SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
2473 				limits[i] = bdev->internal.qos->rate_limits[i].limit;
2474 				if (_spdk_bdev_qos_is_iops_rate_limit(i) == false) {
2475 					/* Change from Byte to Megabyte which is user visible. */
2476 					limits[i] = limits[i] / 1024 / 1024;
2477 				}
2478 			}
2479 		}
2480 	}
2481 	pthread_mutex_unlock(&bdev->internal.mutex);
2482 }
2483 
2484 size_t
2485 spdk_bdev_get_buf_align(const struct spdk_bdev *bdev)
2486 {
2487 	return 1 << bdev->required_alignment;
2488 }
2489 
2490 uint32_t
2491 spdk_bdev_get_optimal_io_boundary(const struct spdk_bdev *bdev)
2492 {
2493 	return bdev->optimal_io_boundary;
2494 }
2495 
2496 bool
2497 spdk_bdev_has_write_cache(const struct spdk_bdev *bdev)
2498 {
2499 	return bdev->write_cache;
2500 }
2501 
2502 const struct spdk_uuid *
2503 spdk_bdev_get_uuid(const struct spdk_bdev *bdev)
2504 {
2505 	return &bdev->uuid;
2506 }
2507 
2508 uint32_t
2509 spdk_bdev_get_md_size(const struct spdk_bdev *bdev)
2510 {
2511 	return bdev->md_len;
2512 }
2513 
2514 bool
2515 spdk_bdev_is_md_interleaved(const struct spdk_bdev *bdev)
2516 {
2517 	return (bdev->md_len != 0) && bdev->md_interleave;
2518 }
2519 
2520 bool
2521 spdk_bdev_is_md_separate(const struct spdk_bdev *bdev)
2522 {
2523 	return (bdev->md_len != 0) && !bdev->md_interleave;
2524 }
2525 
2526 bool
2527 spdk_bdev_is_zoned(const struct spdk_bdev *bdev)
2528 {
2529 	return bdev->zoned;
2530 }
2531 
2532 uint32_t
2533 spdk_bdev_get_data_block_size(const struct spdk_bdev *bdev)
2534 {
2535 	if (spdk_bdev_is_md_interleaved(bdev)) {
2536 		return bdev->blocklen - bdev->md_len;
2537 	} else {
2538 		return bdev->blocklen;
2539 	}
2540 }
2541 
2542 static uint32_t
2543 _bdev_get_block_size_with_md(const struct spdk_bdev *bdev)
2544 {
2545 	if (!spdk_bdev_is_md_interleaved(bdev)) {
2546 		return bdev->blocklen + bdev->md_len;
2547 	} else {
2548 		return bdev->blocklen;
2549 	}
2550 }
2551 
2552 enum spdk_dif_type spdk_bdev_get_dif_type(const struct spdk_bdev *bdev)
2553 {
2554 	if (bdev->md_len != 0) {
2555 		return bdev->dif_type;
2556 	} else {
2557 		return SPDK_DIF_DISABLE;
2558 	}
2559 }
2560 
2561 bool
2562 spdk_bdev_is_dif_head_of_md(const struct spdk_bdev *bdev)
2563 {
2564 	if (spdk_bdev_get_dif_type(bdev) != SPDK_DIF_DISABLE) {
2565 		return bdev->dif_is_head_of_md;
2566 	} else {
2567 		return false;
2568 	}
2569 }
2570 
2571 bool
2572 spdk_bdev_is_dif_check_enabled(const struct spdk_bdev *bdev,
2573 			       enum spdk_dif_check_type check_type)
2574 {
2575 	if (spdk_bdev_get_dif_type(bdev) == SPDK_DIF_DISABLE) {
2576 		return false;
2577 	}
2578 
2579 	switch (check_type) {
2580 	case SPDK_DIF_CHECK_TYPE_REFTAG:
2581 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_REFTAG_CHECK) != 0;
2582 	case SPDK_DIF_CHECK_TYPE_APPTAG:
2583 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_APPTAG_CHECK) != 0;
2584 	case SPDK_DIF_CHECK_TYPE_GUARD:
2585 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_GUARD_CHECK) != 0;
2586 	default:
2587 		return false;
2588 	}
2589 }
2590 
2591 uint64_t
2592 spdk_bdev_get_qd(const struct spdk_bdev *bdev)
2593 {
2594 	return bdev->internal.measured_queue_depth;
2595 }
2596 
2597 uint64_t
2598 spdk_bdev_get_qd_sampling_period(const struct spdk_bdev *bdev)
2599 {
2600 	return bdev->internal.period;
2601 }
2602 
2603 uint64_t
2604 spdk_bdev_get_weighted_io_time(const struct spdk_bdev *bdev)
2605 {
2606 	return bdev->internal.weighted_io_time;
2607 }
2608 
2609 uint64_t
2610 spdk_bdev_get_io_time(const struct spdk_bdev *bdev)
2611 {
2612 	return bdev->internal.io_time;
2613 }
2614 
2615 static void
2616 _calculate_measured_qd_cpl(struct spdk_io_channel_iter *i, int status)
2617 {
2618 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
2619 
2620 	bdev->internal.measured_queue_depth = bdev->internal.temporary_queue_depth;
2621 
2622 	if (bdev->internal.measured_queue_depth) {
2623 		bdev->internal.io_time += bdev->internal.period;
2624 		bdev->internal.weighted_io_time += bdev->internal.period * bdev->internal.measured_queue_depth;
2625 	}
2626 }
2627 
2628 static void
2629 _calculate_measured_qd(struct spdk_io_channel_iter *i)
2630 {
2631 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
2632 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
2633 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(io_ch);
2634 
2635 	bdev->internal.temporary_queue_depth += ch->io_outstanding;
2636 	spdk_for_each_channel_continue(i, 0);
2637 }
2638 
2639 static int
2640 spdk_bdev_calculate_measured_queue_depth(void *ctx)
2641 {
2642 	struct spdk_bdev *bdev = ctx;
2643 	bdev->internal.temporary_queue_depth = 0;
2644 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _calculate_measured_qd, bdev,
2645 			      _calculate_measured_qd_cpl);
2646 	return 0;
2647 }
2648 
2649 void
2650 spdk_bdev_set_qd_sampling_period(struct spdk_bdev *bdev, uint64_t period)
2651 {
2652 	bdev->internal.period = period;
2653 
2654 	if (bdev->internal.qd_poller != NULL) {
2655 		spdk_poller_unregister(&bdev->internal.qd_poller);
2656 		bdev->internal.measured_queue_depth = UINT64_MAX;
2657 	}
2658 
2659 	if (period != 0) {
2660 		bdev->internal.qd_poller = spdk_poller_register(spdk_bdev_calculate_measured_queue_depth, bdev,
2661 					   period);
2662 	}
2663 }
2664 
2665 static void
2666 _spdk_bdev_desc_free(struct spdk_bdev_desc *desc)
2667 {
2668 	pthread_mutex_destroy(&desc->mutex);
2669 	free(desc);
2670 }
2671 
2672 static void
2673 _resize_notify(void *arg)
2674 {
2675 	struct spdk_bdev_desc *desc = arg;
2676 
2677 	pthread_mutex_lock(&desc->mutex);
2678 	desc->refs--;
2679 	if (!desc->closed) {
2680 		pthread_mutex_unlock(&desc->mutex);
2681 		desc->callback.event_fn(SPDK_BDEV_EVENT_RESIZE,
2682 					desc->bdev,
2683 					desc->callback.ctx);
2684 		return;
2685 	} else if (0 == desc->refs) {
2686 		/* This descriptor was closed after this resize_notify message was sent.
2687 		 * spdk_bdev_close() could not free the descriptor since this message was
2688 		 * in flight, so we free it now using _spdk_bdev_desc_free().
2689 		 */
2690 		pthread_mutex_unlock(&desc->mutex);
2691 		_spdk_bdev_desc_free(desc);
2692 		return;
2693 	}
2694 	pthread_mutex_unlock(&desc->mutex);
2695 }
2696 
2697 int
2698 spdk_bdev_notify_blockcnt_change(struct spdk_bdev *bdev, uint64_t size)
2699 {
2700 	struct spdk_bdev_desc *desc;
2701 	int ret;
2702 
2703 	pthread_mutex_lock(&bdev->internal.mutex);
2704 
2705 	/* bdev has open descriptors */
2706 	if (!TAILQ_EMPTY(&bdev->internal.open_descs) &&
2707 	    bdev->blockcnt > size) {
2708 		ret = -EBUSY;
2709 	} else {
2710 		bdev->blockcnt = size;
2711 		TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
2712 			pthread_mutex_lock(&desc->mutex);
2713 			if (desc->callback.open_with_ext && !desc->closed) {
2714 				desc->refs++;
2715 				spdk_thread_send_msg(desc->thread, _resize_notify, desc);
2716 			}
2717 			pthread_mutex_unlock(&desc->mutex);
2718 		}
2719 		ret = 0;
2720 	}
2721 
2722 	pthread_mutex_unlock(&bdev->internal.mutex);
2723 
2724 	return ret;
2725 }
2726 
2727 /*
2728  * Convert I/O offset and length from bytes to blocks.
2729  *
2730  * Returns zero on success or non-zero if the byte parameters aren't divisible by the block size.
2731  */
2732 static uint64_t
2733 spdk_bdev_bytes_to_blocks(struct spdk_bdev *bdev, uint64_t offset_bytes, uint64_t *offset_blocks,
2734 			  uint64_t num_bytes, uint64_t *num_blocks)
2735 {
2736 	uint32_t block_size = bdev->blocklen;
2737 	uint8_t shift_cnt;
2738 
2739 	/* Avoid expensive div operations if possible. These spdk_u32 functions are very cheap. */
2740 	if (spdk_likely(spdk_u32_is_pow2(block_size))) {
2741 		shift_cnt = spdk_u32log2(block_size);
2742 		*offset_blocks = offset_bytes >> shift_cnt;
2743 		*num_blocks = num_bytes >> shift_cnt;
2744 		return (offset_bytes - (*offset_blocks << shift_cnt)) |
2745 		       (num_bytes - (*num_blocks << shift_cnt));
2746 	} else {
2747 		*offset_blocks = offset_bytes / block_size;
2748 		*num_blocks = num_bytes / block_size;
2749 		return (offset_bytes % block_size) | (num_bytes % block_size);
2750 	}
2751 }
2752 
2753 static bool
2754 spdk_bdev_io_valid_blocks(struct spdk_bdev *bdev, uint64_t offset_blocks, uint64_t num_blocks)
2755 {
2756 	/* Return failure if offset_blocks + num_blocks is less than offset_blocks; indicates there
2757 	 * has been an overflow and hence the offset has been wrapped around */
2758 	if (offset_blocks + num_blocks < offset_blocks) {
2759 		return false;
2760 	}
2761 
2762 	/* Return failure if offset_blocks + num_blocks exceeds the size of the bdev */
2763 	if (offset_blocks + num_blocks > bdev->blockcnt) {
2764 		return false;
2765 	}
2766 
2767 	return true;
2768 }
2769 
2770 static bool
2771 _bdev_io_check_md_buf(const struct iovec *iovs, const void *md_buf)
2772 {
2773 	return _is_buf_allocated(iovs) == (md_buf != NULL);
2774 }
2775 
2776 static int
2777 _spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf,
2778 			       void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
2779 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2780 {
2781 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2782 	struct spdk_bdev_io *bdev_io;
2783 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2784 
2785 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2786 		return -EINVAL;
2787 	}
2788 
2789 	bdev_io = spdk_bdev_get_io(channel);
2790 	if (!bdev_io) {
2791 		return -ENOMEM;
2792 	}
2793 
2794 	bdev_io->internal.ch = channel;
2795 	bdev_io->internal.desc = desc;
2796 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
2797 	bdev_io->u.bdev.iovs = &bdev_io->iov;
2798 	bdev_io->u.bdev.iovs[0].iov_base = buf;
2799 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
2800 	bdev_io->u.bdev.iovcnt = 1;
2801 	bdev_io->u.bdev.md_buf = md_buf;
2802 	bdev_io->u.bdev.num_blocks = num_blocks;
2803 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2804 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2805 
2806 	spdk_bdev_io_submit(bdev_io);
2807 	return 0;
2808 }
2809 
2810 int
2811 spdk_bdev_read(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2812 	       void *buf, uint64_t offset, uint64_t nbytes,
2813 	       spdk_bdev_io_completion_cb cb, void *cb_arg)
2814 {
2815 	uint64_t offset_blocks, num_blocks;
2816 
2817 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2818 				      nbytes, &num_blocks) != 0) {
2819 		return -EINVAL;
2820 	}
2821 
2822 	return spdk_bdev_read_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
2823 }
2824 
2825 int
2826 spdk_bdev_read_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2827 		      void *buf, uint64_t offset_blocks, uint64_t num_blocks,
2828 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
2829 {
2830 	return _spdk_bdev_read_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
2831 					      cb, cb_arg);
2832 }
2833 
2834 int
2835 spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2836 			      void *buf, void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
2837 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
2838 {
2839 	struct iovec iov = {
2840 		.iov_base = buf,
2841 	};
2842 
2843 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
2844 		return -EINVAL;
2845 	}
2846 
2847 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
2848 		return -EINVAL;
2849 	}
2850 
2851 	return _spdk_bdev_read_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
2852 					      cb, cb_arg);
2853 }
2854 
2855 int
2856 spdk_bdev_readv(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2857 		struct iovec *iov, int iovcnt,
2858 		uint64_t offset, uint64_t nbytes,
2859 		spdk_bdev_io_completion_cb cb, void *cb_arg)
2860 {
2861 	uint64_t offset_blocks, num_blocks;
2862 
2863 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2864 				      nbytes, &num_blocks) != 0) {
2865 		return -EINVAL;
2866 	}
2867 
2868 	return spdk_bdev_readv_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
2869 }
2870 
2871 static int
2872 _spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2873 				struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
2874 				uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg)
2875 {
2876 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2877 	struct spdk_bdev_io *bdev_io;
2878 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2879 
2880 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2881 		return -EINVAL;
2882 	}
2883 
2884 	bdev_io = spdk_bdev_get_io(channel);
2885 	if (!bdev_io) {
2886 		return -ENOMEM;
2887 	}
2888 
2889 	bdev_io->internal.ch = channel;
2890 	bdev_io->internal.desc = desc;
2891 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
2892 	bdev_io->u.bdev.iovs = iov;
2893 	bdev_io->u.bdev.iovcnt = iovcnt;
2894 	bdev_io->u.bdev.md_buf = md_buf;
2895 	bdev_io->u.bdev.num_blocks = num_blocks;
2896 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2897 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2898 
2899 	spdk_bdev_io_submit(bdev_io);
2900 	return 0;
2901 }
2902 
2903 int spdk_bdev_readv_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2904 			   struct iovec *iov, int iovcnt,
2905 			   uint64_t offset_blocks, uint64_t num_blocks,
2906 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
2907 {
2908 	return _spdk_bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
2909 					       num_blocks, cb, cb_arg);
2910 }
2911 
2912 int
2913 spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2914 			       struct iovec *iov, int iovcnt, void *md_buf,
2915 			       uint64_t offset_blocks, uint64_t num_blocks,
2916 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2917 {
2918 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
2919 		return -EINVAL;
2920 	}
2921 
2922 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
2923 		return -EINVAL;
2924 	}
2925 
2926 	return _spdk_bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
2927 					       num_blocks, cb, cb_arg);
2928 }
2929 
2930 static int
2931 _spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2932 				void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
2933 				spdk_bdev_io_completion_cb cb, void *cb_arg)
2934 {
2935 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2936 	struct spdk_bdev_io *bdev_io;
2937 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2938 
2939 	if (!desc->write) {
2940 		return -EBADF;
2941 	}
2942 
2943 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2944 		return -EINVAL;
2945 	}
2946 
2947 	bdev_io = spdk_bdev_get_io(channel);
2948 	if (!bdev_io) {
2949 		return -ENOMEM;
2950 	}
2951 
2952 	bdev_io->internal.ch = channel;
2953 	bdev_io->internal.desc = desc;
2954 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
2955 	bdev_io->u.bdev.iovs = &bdev_io->iov;
2956 	bdev_io->u.bdev.iovs[0].iov_base = buf;
2957 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
2958 	bdev_io->u.bdev.iovcnt = 1;
2959 	bdev_io->u.bdev.md_buf = md_buf;
2960 	bdev_io->u.bdev.num_blocks = num_blocks;
2961 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2962 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2963 
2964 	spdk_bdev_io_submit(bdev_io);
2965 	return 0;
2966 }
2967 
2968 int
2969 spdk_bdev_write(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2970 		void *buf, uint64_t offset, uint64_t nbytes,
2971 		spdk_bdev_io_completion_cb cb, void *cb_arg)
2972 {
2973 	uint64_t offset_blocks, num_blocks;
2974 
2975 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2976 				      nbytes, &num_blocks) != 0) {
2977 		return -EINVAL;
2978 	}
2979 
2980 	return spdk_bdev_write_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
2981 }
2982 
2983 int
2984 spdk_bdev_write_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2985 		       void *buf, uint64_t offset_blocks, uint64_t num_blocks,
2986 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
2987 {
2988 	return _spdk_bdev_write_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
2989 					       cb, cb_arg);
2990 }
2991 
2992 int
2993 spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2994 			       void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
2995 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2996 {
2997 	struct iovec iov = {
2998 		.iov_base = buf,
2999 	};
3000 
3001 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3002 		return -EINVAL;
3003 	}
3004 
3005 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
3006 		return -EINVAL;
3007 	}
3008 
3009 	return _spdk_bdev_write_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
3010 					       cb, cb_arg);
3011 }
3012 
3013 static int
3014 _spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3015 				 struct iovec *iov, int iovcnt, void *md_buf,
3016 				 uint64_t offset_blocks, uint64_t num_blocks,
3017 				 spdk_bdev_io_completion_cb cb, void *cb_arg)
3018 {
3019 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3020 	struct spdk_bdev_io *bdev_io;
3021 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3022 
3023 	if (!desc->write) {
3024 		return -EBADF;
3025 	}
3026 
3027 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3028 		return -EINVAL;
3029 	}
3030 
3031 	bdev_io = spdk_bdev_get_io(channel);
3032 	if (!bdev_io) {
3033 		return -ENOMEM;
3034 	}
3035 
3036 	bdev_io->internal.ch = channel;
3037 	bdev_io->internal.desc = desc;
3038 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3039 	bdev_io->u.bdev.iovs = iov;
3040 	bdev_io->u.bdev.iovcnt = iovcnt;
3041 	bdev_io->u.bdev.md_buf = md_buf;
3042 	bdev_io->u.bdev.num_blocks = num_blocks;
3043 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3044 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3045 
3046 	spdk_bdev_io_submit(bdev_io);
3047 	return 0;
3048 }
3049 
3050 int
3051 spdk_bdev_writev(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3052 		 struct iovec *iov, int iovcnt,
3053 		 uint64_t offset, uint64_t len,
3054 		 spdk_bdev_io_completion_cb cb, void *cb_arg)
3055 {
3056 	uint64_t offset_blocks, num_blocks;
3057 
3058 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3059 				      len, &num_blocks) != 0) {
3060 		return -EINVAL;
3061 	}
3062 
3063 	return spdk_bdev_writev_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
3064 }
3065 
3066 int
3067 spdk_bdev_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3068 			struct iovec *iov, int iovcnt,
3069 			uint64_t offset_blocks, uint64_t num_blocks,
3070 			spdk_bdev_io_completion_cb cb, void *cb_arg)
3071 {
3072 	return _spdk_bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
3073 						num_blocks, cb, cb_arg);
3074 }
3075 
3076 int
3077 spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3078 				struct iovec *iov, int iovcnt, void *md_buf,
3079 				uint64_t offset_blocks, uint64_t num_blocks,
3080 				spdk_bdev_io_completion_cb cb, void *cb_arg)
3081 {
3082 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3083 		return -EINVAL;
3084 	}
3085 
3086 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
3087 		return -EINVAL;
3088 	}
3089 
3090 	return _spdk_bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
3091 						num_blocks, cb, cb_arg);
3092 }
3093 
3094 static void
3095 bdev_zcopy_get_buf(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success)
3096 {
3097 	if (!success) {
3098 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3099 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NOMEM;
3100 		bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
3101 		return;
3102 	}
3103 
3104 	if (bdev_io->u.bdev.zcopy.populate) {
3105 		/* Read the real data into the buffer */
3106 		bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
3107 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3108 		spdk_bdev_io_submit(bdev_io);
3109 		return;
3110 	}
3111 
3112 	/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3113 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3114 	bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
3115 }
3116 
3117 int
3118 spdk_bdev_zcopy_start(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3119 		      uint64_t offset_blocks, uint64_t num_blocks,
3120 		      bool populate,
3121 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
3122 {
3123 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3124 	struct spdk_bdev_io *bdev_io;
3125 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3126 
3127 	if (!desc->write) {
3128 		return -EBADF;
3129 	}
3130 
3131 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3132 		return -EINVAL;
3133 	}
3134 
3135 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3136 		return -ENOTSUP;
3137 	}
3138 
3139 	bdev_io = spdk_bdev_get_io(channel);
3140 	if (!bdev_io) {
3141 		return -ENOMEM;
3142 	}
3143 
3144 	bdev_io->internal.ch = channel;
3145 	bdev_io->internal.desc = desc;
3146 	bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
3147 	bdev_io->u.bdev.num_blocks = num_blocks;
3148 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3149 	bdev_io->u.bdev.iovs = NULL;
3150 	bdev_io->u.bdev.iovcnt = 0;
3151 	bdev_io->u.bdev.zcopy.populate = populate ? 1 : 0;
3152 	bdev_io->u.bdev.zcopy.commit = 0;
3153 	bdev_io->u.bdev.zcopy.start = 1;
3154 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3155 
3156 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3157 		spdk_bdev_io_submit(bdev_io);
3158 	} else {
3159 		/* Emulate zcopy by allocating a buffer */
3160 		spdk_bdev_io_get_buf(bdev_io, bdev_zcopy_get_buf,
3161 				     bdev_io->u.bdev.num_blocks * bdev->blocklen);
3162 	}
3163 
3164 	return 0;
3165 }
3166 
3167 int
3168 spdk_bdev_zcopy_end(struct spdk_bdev_io *bdev_io, bool commit,
3169 		    spdk_bdev_io_completion_cb cb, void *cb_arg)
3170 {
3171 	struct spdk_bdev *bdev = bdev_io->bdev;
3172 
3173 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
3174 		/* This can happen if the zcopy was emulated in start */
3175 		if (bdev_io->u.bdev.zcopy.start != 1) {
3176 			return -EINVAL;
3177 		}
3178 		bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
3179 	}
3180 
3181 	if (bdev_io->type != SPDK_BDEV_IO_TYPE_ZCOPY) {
3182 		return -EINVAL;
3183 	}
3184 
3185 	bdev_io->u.bdev.zcopy.commit = commit ? 1 : 0;
3186 	bdev_io->u.bdev.zcopy.start = 0;
3187 	bdev_io->internal.caller_ctx = cb_arg;
3188 	bdev_io->internal.cb = cb;
3189 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3190 
3191 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3192 		spdk_bdev_io_submit(bdev_io);
3193 		return 0;
3194 	}
3195 
3196 	if (!bdev_io->u.bdev.zcopy.commit) {
3197 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3198 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3199 		bdev_io->internal.cb(bdev_io, true, bdev_io->internal.caller_ctx);
3200 		return 0;
3201 	}
3202 
3203 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3204 	spdk_bdev_io_submit(bdev_io);
3205 
3206 	return 0;
3207 }
3208 
3209 int
3210 spdk_bdev_write_zeroes(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3211 		       uint64_t offset, uint64_t len,
3212 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3213 {
3214 	uint64_t offset_blocks, num_blocks;
3215 
3216 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3217 				      len, &num_blocks) != 0) {
3218 		return -EINVAL;
3219 	}
3220 
3221 	return spdk_bdev_write_zeroes_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3222 }
3223 
3224 int
3225 spdk_bdev_write_zeroes_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3226 			      uint64_t offset_blocks, uint64_t num_blocks,
3227 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3228 {
3229 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3230 	struct spdk_bdev_io *bdev_io;
3231 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3232 
3233 	if (!desc->write) {
3234 		return -EBADF;
3235 	}
3236 
3237 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3238 		return -EINVAL;
3239 	}
3240 
3241 	if (!_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES) &&
3242 	    !_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE)) {
3243 		return -ENOTSUP;
3244 	}
3245 
3246 	bdev_io = spdk_bdev_get_io(channel);
3247 
3248 	if (!bdev_io) {
3249 		return -ENOMEM;
3250 	}
3251 
3252 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE_ZEROES;
3253 	bdev_io->internal.ch = channel;
3254 	bdev_io->internal.desc = desc;
3255 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3256 	bdev_io->u.bdev.num_blocks = num_blocks;
3257 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3258 
3259 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES)) {
3260 		spdk_bdev_io_submit(bdev_io);
3261 		return 0;
3262 	}
3263 
3264 	assert(_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE));
3265 	assert(_bdev_get_block_size_with_md(bdev) <= ZERO_BUFFER_SIZE);
3266 	bdev_io->u.bdev.split_remaining_num_blocks = num_blocks;
3267 	bdev_io->u.bdev.split_current_offset_blocks = offset_blocks;
3268 	_spdk_bdev_write_zero_buffer_next(bdev_io);
3269 
3270 	return 0;
3271 }
3272 
3273 int
3274 spdk_bdev_unmap(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3275 		uint64_t offset, uint64_t nbytes,
3276 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3277 {
3278 	uint64_t offset_blocks, num_blocks;
3279 
3280 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3281 				      nbytes, &num_blocks) != 0) {
3282 		return -EINVAL;
3283 	}
3284 
3285 	return spdk_bdev_unmap_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3286 }
3287 
3288 int
3289 spdk_bdev_unmap_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3290 		       uint64_t offset_blocks, uint64_t num_blocks,
3291 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3292 {
3293 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3294 	struct spdk_bdev_io *bdev_io;
3295 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3296 
3297 	if (!desc->write) {
3298 		return -EBADF;
3299 	}
3300 
3301 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3302 		return -EINVAL;
3303 	}
3304 
3305 	if (num_blocks == 0) {
3306 		SPDK_ERRLOG("Can't unmap 0 bytes\n");
3307 		return -EINVAL;
3308 	}
3309 
3310 	bdev_io = spdk_bdev_get_io(channel);
3311 	if (!bdev_io) {
3312 		return -ENOMEM;
3313 	}
3314 
3315 	bdev_io->internal.ch = channel;
3316 	bdev_io->internal.desc = desc;
3317 	bdev_io->type = SPDK_BDEV_IO_TYPE_UNMAP;
3318 
3319 	bdev_io->u.bdev.iovs = &bdev_io->iov;
3320 	bdev_io->u.bdev.iovs[0].iov_base = NULL;
3321 	bdev_io->u.bdev.iovs[0].iov_len = 0;
3322 	bdev_io->u.bdev.iovcnt = 1;
3323 
3324 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3325 	bdev_io->u.bdev.num_blocks = num_blocks;
3326 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3327 
3328 	spdk_bdev_io_submit(bdev_io);
3329 	return 0;
3330 }
3331 
3332 int
3333 spdk_bdev_flush(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3334 		uint64_t offset, uint64_t length,
3335 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3336 {
3337 	uint64_t offset_blocks, num_blocks;
3338 
3339 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3340 				      length, &num_blocks) != 0) {
3341 		return -EINVAL;
3342 	}
3343 
3344 	return spdk_bdev_flush_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3345 }
3346 
3347 int
3348 spdk_bdev_flush_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3349 		       uint64_t offset_blocks, uint64_t num_blocks,
3350 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3351 {
3352 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3353 	struct spdk_bdev_io *bdev_io;
3354 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3355 
3356 	if (!desc->write) {
3357 		return -EBADF;
3358 	}
3359 
3360 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3361 		return -EINVAL;
3362 	}
3363 
3364 	bdev_io = spdk_bdev_get_io(channel);
3365 	if (!bdev_io) {
3366 		return -ENOMEM;
3367 	}
3368 
3369 	bdev_io->internal.ch = channel;
3370 	bdev_io->internal.desc = desc;
3371 	bdev_io->type = SPDK_BDEV_IO_TYPE_FLUSH;
3372 	bdev_io->u.bdev.iovs = NULL;
3373 	bdev_io->u.bdev.iovcnt = 0;
3374 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3375 	bdev_io->u.bdev.num_blocks = num_blocks;
3376 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3377 
3378 	spdk_bdev_io_submit(bdev_io);
3379 	return 0;
3380 }
3381 
3382 static void
3383 _spdk_bdev_reset_dev(struct spdk_io_channel_iter *i, int status)
3384 {
3385 	struct spdk_bdev_channel *ch = spdk_io_channel_iter_get_ctx(i);
3386 	struct spdk_bdev_io *bdev_io;
3387 
3388 	bdev_io = TAILQ_FIRST(&ch->queued_resets);
3389 	TAILQ_REMOVE(&ch->queued_resets, bdev_io, internal.link);
3390 	spdk_bdev_io_submit_reset(bdev_io);
3391 }
3392 
3393 static void
3394 _spdk_bdev_reset_freeze_channel(struct spdk_io_channel_iter *i)
3395 {
3396 	struct spdk_io_channel		*ch;
3397 	struct spdk_bdev_channel	*channel;
3398 	struct spdk_bdev_mgmt_channel	*mgmt_channel;
3399 	struct spdk_bdev_shared_resource *shared_resource;
3400 	bdev_io_tailq_t			tmp_queued;
3401 
3402 	TAILQ_INIT(&tmp_queued);
3403 
3404 	ch = spdk_io_channel_iter_get_channel(i);
3405 	channel = spdk_io_channel_get_ctx(ch);
3406 	shared_resource = channel->shared_resource;
3407 	mgmt_channel = shared_resource->mgmt_ch;
3408 
3409 	channel->flags |= BDEV_CH_RESET_IN_PROGRESS;
3410 
3411 	if ((channel->flags & BDEV_CH_QOS_ENABLED) != 0) {
3412 		/* The QoS object is always valid and readable while
3413 		 * the channel flag is set, so the lock here should not
3414 		 * be necessary. We're not in the fast path though, so
3415 		 * just take it anyway. */
3416 		pthread_mutex_lock(&channel->bdev->internal.mutex);
3417 		if (channel->bdev->internal.qos->ch == channel) {
3418 			TAILQ_SWAP(&channel->bdev->internal.qos->queued, &tmp_queued, spdk_bdev_io, internal.link);
3419 		}
3420 		pthread_mutex_unlock(&channel->bdev->internal.mutex);
3421 	}
3422 
3423 	_spdk_bdev_abort_queued_io(&shared_resource->nomem_io, channel);
3424 	_spdk_bdev_abort_buf_io(&mgmt_channel->need_buf_small, channel);
3425 	_spdk_bdev_abort_buf_io(&mgmt_channel->need_buf_large, channel);
3426 	_spdk_bdev_abort_queued_io(&tmp_queued, channel);
3427 
3428 	spdk_for_each_channel_continue(i, 0);
3429 }
3430 
3431 static void
3432 _spdk_bdev_start_reset(void *ctx)
3433 {
3434 	struct spdk_bdev_channel *ch = ctx;
3435 
3436 	spdk_for_each_channel(__bdev_to_io_dev(ch->bdev), _spdk_bdev_reset_freeze_channel,
3437 			      ch, _spdk_bdev_reset_dev);
3438 }
3439 
3440 static void
3441 _spdk_bdev_channel_start_reset(struct spdk_bdev_channel *ch)
3442 {
3443 	struct spdk_bdev *bdev = ch->bdev;
3444 
3445 	assert(!TAILQ_EMPTY(&ch->queued_resets));
3446 
3447 	pthread_mutex_lock(&bdev->internal.mutex);
3448 	if (bdev->internal.reset_in_progress == NULL) {
3449 		bdev->internal.reset_in_progress = TAILQ_FIRST(&ch->queued_resets);
3450 		/*
3451 		 * Take a channel reference for the target bdev for the life of this
3452 		 *  reset.  This guards against the channel getting destroyed while
3453 		 *  spdk_for_each_channel() calls related to this reset IO are in
3454 		 *  progress.  We will release the reference when this reset is
3455 		 *  completed.
3456 		 */
3457 		bdev->internal.reset_in_progress->u.reset.ch_ref = spdk_get_io_channel(__bdev_to_io_dev(bdev));
3458 		_spdk_bdev_start_reset(ch);
3459 	}
3460 	pthread_mutex_unlock(&bdev->internal.mutex);
3461 }
3462 
3463 int
3464 spdk_bdev_reset(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3465 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3466 {
3467 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3468 	struct spdk_bdev_io *bdev_io;
3469 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3470 
3471 	bdev_io = spdk_bdev_get_io(channel);
3472 	if (!bdev_io) {
3473 		return -ENOMEM;
3474 	}
3475 
3476 	bdev_io->internal.ch = channel;
3477 	bdev_io->internal.desc = desc;
3478 	bdev_io->type = SPDK_BDEV_IO_TYPE_RESET;
3479 	bdev_io->u.reset.ch_ref = NULL;
3480 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3481 
3482 	pthread_mutex_lock(&bdev->internal.mutex);
3483 	TAILQ_INSERT_TAIL(&channel->queued_resets, bdev_io, internal.link);
3484 	pthread_mutex_unlock(&bdev->internal.mutex);
3485 
3486 	_spdk_bdev_channel_start_reset(channel);
3487 
3488 	return 0;
3489 }
3490 
3491 void
3492 spdk_bdev_get_io_stat(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
3493 		      struct spdk_bdev_io_stat *stat)
3494 {
3495 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3496 
3497 	*stat = channel->stat;
3498 }
3499 
3500 static void
3501 _spdk_bdev_get_device_stat_done(struct spdk_io_channel_iter *i, int status)
3502 {
3503 	void *io_device = spdk_io_channel_iter_get_io_device(i);
3504 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
3505 
3506 	bdev_iostat_ctx->cb(__bdev_from_io_dev(io_device), bdev_iostat_ctx->stat,
3507 			    bdev_iostat_ctx->cb_arg, 0);
3508 	free(bdev_iostat_ctx);
3509 }
3510 
3511 static void
3512 _spdk_bdev_get_each_channel_stat(struct spdk_io_channel_iter *i)
3513 {
3514 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
3515 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
3516 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3517 
3518 	_spdk_bdev_io_stat_add(bdev_iostat_ctx->stat, &channel->stat);
3519 	spdk_for_each_channel_continue(i, 0);
3520 }
3521 
3522 void
3523 spdk_bdev_get_device_stat(struct spdk_bdev *bdev, struct spdk_bdev_io_stat *stat,
3524 			  spdk_bdev_get_device_stat_cb cb, void *cb_arg)
3525 {
3526 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx;
3527 
3528 	assert(bdev != NULL);
3529 	assert(stat != NULL);
3530 	assert(cb != NULL);
3531 
3532 	bdev_iostat_ctx = calloc(1, sizeof(struct spdk_bdev_iostat_ctx));
3533 	if (bdev_iostat_ctx == NULL) {
3534 		SPDK_ERRLOG("Unable to allocate memory for spdk_bdev_iostat_ctx\n");
3535 		cb(bdev, stat, cb_arg, -ENOMEM);
3536 		return;
3537 	}
3538 
3539 	bdev_iostat_ctx->stat = stat;
3540 	bdev_iostat_ctx->cb = cb;
3541 	bdev_iostat_ctx->cb_arg = cb_arg;
3542 
3543 	/* Start with the statistics from previously deleted channels. */
3544 	pthread_mutex_lock(&bdev->internal.mutex);
3545 	_spdk_bdev_io_stat_add(bdev_iostat_ctx->stat, &bdev->internal.stat);
3546 	pthread_mutex_unlock(&bdev->internal.mutex);
3547 
3548 	/* Then iterate and add the statistics from each existing channel. */
3549 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
3550 			      _spdk_bdev_get_each_channel_stat,
3551 			      bdev_iostat_ctx,
3552 			      _spdk_bdev_get_device_stat_done);
3553 }
3554 
3555 int
3556 spdk_bdev_nvme_admin_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3557 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
3558 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3559 {
3560 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3561 	struct spdk_bdev_io *bdev_io;
3562 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3563 
3564 	if (!desc->write) {
3565 		return -EBADF;
3566 	}
3567 
3568 	bdev_io = spdk_bdev_get_io(channel);
3569 	if (!bdev_io) {
3570 		return -ENOMEM;
3571 	}
3572 
3573 	bdev_io->internal.ch = channel;
3574 	bdev_io->internal.desc = desc;
3575 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_ADMIN;
3576 	bdev_io->u.nvme_passthru.cmd = *cmd;
3577 	bdev_io->u.nvme_passthru.buf = buf;
3578 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3579 	bdev_io->u.nvme_passthru.md_buf = NULL;
3580 	bdev_io->u.nvme_passthru.md_len = 0;
3581 
3582 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3583 
3584 	spdk_bdev_io_submit(bdev_io);
3585 	return 0;
3586 }
3587 
3588 int
3589 spdk_bdev_nvme_io_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3590 			   const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
3591 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
3592 {
3593 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3594 	struct spdk_bdev_io *bdev_io;
3595 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3596 
3597 	if (!desc->write) {
3598 		/*
3599 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
3600 		 *  to easily determine if the command is a read or write, but for now just
3601 		 *  do not allow io_passthru with a read-only descriptor.
3602 		 */
3603 		return -EBADF;
3604 	}
3605 
3606 	bdev_io = spdk_bdev_get_io(channel);
3607 	if (!bdev_io) {
3608 		return -ENOMEM;
3609 	}
3610 
3611 	bdev_io->internal.ch = channel;
3612 	bdev_io->internal.desc = desc;
3613 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO;
3614 	bdev_io->u.nvme_passthru.cmd = *cmd;
3615 	bdev_io->u.nvme_passthru.buf = buf;
3616 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3617 	bdev_io->u.nvme_passthru.md_buf = NULL;
3618 	bdev_io->u.nvme_passthru.md_len = 0;
3619 
3620 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3621 
3622 	spdk_bdev_io_submit(bdev_io);
3623 	return 0;
3624 }
3625 
3626 int
3627 spdk_bdev_nvme_io_passthru_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3628 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes, void *md_buf, size_t md_len,
3629 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3630 {
3631 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3632 	struct spdk_bdev_io *bdev_io;
3633 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3634 
3635 	if (!desc->write) {
3636 		/*
3637 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
3638 		 *  to easily determine if the command is a read or write, but for now just
3639 		 *  do not allow io_passthru with a read-only descriptor.
3640 		 */
3641 		return -EBADF;
3642 	}
3643 
3644 	bdev_io = spdk_bdev_get_io(channel);
3645 	if (!bdev_io) {
3646 		return -ENOMEM;
3647 	}
3648 
3649 	bdev_io->internal.ch = channel;
3650 	bdev_io->internal.desc = desc;
3651 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO_MD;
3652 	bdev_io->u.nvme_passthru.cmd = *cmd;
3653 	bdev_io->u.nvme_passthru.buf = buf;
3654 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3655 	bdev_io->u.nvme_passthru.md_buf = md_buf;
3656 	bdev_io->u.nvme_passthru.md_len = md_len;
3657 
3658 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3659 
3660 	spdk_bdev_io_submit(bdev_io);
3661 	return 0;
3662 }
3663 
3664 int
3665 spdk_bdev_queue_io_wait(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
3666 			struct spdk_bdev_io_wait_entry *entry)
3667 {
3668 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3669 	struct spdk_bdev_mgmt_channel *mgmt_ch = channel->shared_resource->mgmt_ch;
3670 
3671 	if (bdev != entry->bdev) {
3672 		SPDK_ERRLOG("bdevs do not match\n");
3673 		return -EINVAL;
3674 	}
3675 
3676 	if (mgmt_ch->per_thread_cache_count > 0) {
3677 		SPDK_ERRLOG("Cannot queue io_wait if spdk_bdev_io available in per-thread cache\n");
3678 		return -EINVAL;
3679 	}
3680 
3681 	TAILQ_INSERT_TAIL(&mgmt_ch->io_wait_queue, entry, link);
3682 	return 0;
3683 }
3684 
3685 static void
3686 _spdk_bdev_ch_retry_io(struct spdk_bdev_channel *bdev_ch)
3687 {
3688 	struct spdk_bdev *bdev = bdev_ch->bdev;
3689 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
3690 	struct spdk_bdev_io *bdev_io;
3691 
3692 	if (shared_resource->io_outstanding > shared_resource->nomem_threshold) {
3693 		/*
3694 		 * Allow some more I/O to complete before retrying the nomem_io queue.
3695 		 *  Some drivers (such as nvme) cannot immediately take a new I/O in
3696 		 *  the context of a completion, because the resources for the I/O are
3697 		 *  not released until control returns to the bdev poller.  Also, we
3698 		 *  may require several small I/O to complete before a larger I/O
3699 		 *  (that requires splitting) can be submitted.
3700 		 */
3701 		return;
3702 	}
3703 
3704 	while (!TAILQ_EMPTY(&shared_resource->nomem_io)) {
3705 		bdev_io = TAILQ_FIRST(&shared_resource->nomem_io);
3706 		TAILQ_REMOVE(&shared_resource->nomem_io, bdev_io, internal.link);
3707 		bdev_io->internal.ch->io_outstanding++;
3708 		shared_resource->io_outstanding++;
3709 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3710 		bdev->fn_table->submit_request(spdk_bdev_io_get_io_channel(bdev_io), bdev_io);
3711 		if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
3712 			break;
3713 		}
3714 	}
3715 }
3716 
3717 static inline void
3718 _spdk_bdev_io_complete(void *ctx)
3719 {
3720 	struct spdk_bdev_io *bdev_io = ctx;
3721 	uint64_t tsc, tsc_diff;
3722 
3723 	if (spdk_unlikely(bdev_io->internal.in_submit_request || bdev_io->internal.io_submit_ch)) {
3724 		/*
3725 		 * Send the completion to the thread that originally submitted the I/O,
3726 		 * which may not be the current thread in the case of QoS.
3727 		 */
3728 		if (bdev_io->internal.io_submit_ch) {
3729 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
3730 			bdev_io->internal.io_submit_ch = NULL;
3731 		}
3732 
3733 		/*
3734 		 * Defer completion to avoid potential infinite recursion if the
3735 		 * user's completion callback issues a new I/O.
3736 		 */
3737 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
3738 				     _spdk_bdev_io_complete, bdev_io);
3739 		return;
3740 	}
3741 
3742 	tsc = spdk_get_ticks();
3743 	tsc_diff = tsc - bdev_io->internal.submit_tsc;
3744 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io, 0);
3745 
3746 	if (bdev_io->internal.ch->histogram) {
3747 		spdk_histogram_data_tally(bdev_io->internal.ch->histogram, tsc_diff);
3748 	}
3749 
3750 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
3751 		switch (bdev_io->type) {
3752 		case SPDK_BDEV_IO_TYPE_READ:
3753 			bdev_io->internal.ch->stat.bytes_read += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3754 			bdev_io->internal.ch->stat.num_read_ops++;
3755 			bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
3756 			break;
3757 		case SPDK_BDEV_IO_TYPE_WRITE:
3758 			bdev_io->internal.ch->stat.bytes_written += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3759 			bdev_io->internal.ch->stat.num_write_ops++;
3760 			bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
3761 			break;
3762 		case SPDK_BDEV_IO_TYPE_UNMAP:
3763 			bdev_io->internal.ch->stat.bytes_unmapped += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3764 			bdev_io->internal.ch->stat.num_unmap_ops++;
3765 			bdev_io->internal.ch->stat.unmap_latency_ticks += tsc_diff;
3766 		default:
3767 			break;
3768 		}
3769 	}
3770 
3771 #ifdef SPDK_CONFIG_VTUNE
3772 	uint64_t now_tsc = spdk_get_ticks();
3773 	if (now_tsc > (bdev_io->internal.ch->start_tsc + bdev_io->internal.ch->interval_tsc)) {
3774 		uint64_t data[5];
3775 
3776 		data[0] = bdev_io->internal.ch->stat.num_read_ops - bdev_io->internal.ch->prev_stat.num_read_ops;
3777 		data[1] = bdev_io->internal.ch->stat.bytes_read - bdev_io->internal.ch->prev_stat.bytes_read;
3778 		data[2] = bdev_io->internal.ch->stat.num_write_ops - bdev_io->internal.ch->prev_stat.num_write_ops;
3779 		data[3] = bdev_io->internal.ch->stat.bytes_written - bdev_io->internal.ch->prev_stat.bytes_written;
3780 		data[4] = bdev_io->bdev->fn_table->get_spin_time ?
3781 			  bdev_io->bdev->fn_table->get_spin_time(spdk_bdev_io_get_io_channel(bdev_io)) : 0;
3782 
3783 		__itt_metadata_add(g_bdev_mgr.domain, __itt_null, bdev_io->internal.ch->handle,
3784 				   __itt_metadata_u64, 5, data);
3785 
3786 		bdev_io->internal.ch->prev_stat = bdev_io->internal.ch->stat;
3787 		bdev_io->internal.ch->start_tsc = now_tsc;
3788 	}
3789 #endif
3790 
3791 	assert(bdev_io->internal.cb != NULL);
3792 	assert(spdk_get_thread() == spdk_bdev_io_get_thread(bdev_io));
3793 
3794 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
3795 			     bdev_io->internal.caller_ctx);
3796 }
3797 
3798 static void
3799 _spdk_bdev_reset_complete(struct spdk_io_channel_iter *i, int status)
3800 {
3801 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
3802 
3803 	if (bdev_io->u.reset.ch_ref != NULL) {
3804 		spdk_put_io_channel(bdev_io->u.reset.ch_ref);
3805 		bdev_io->u.reset.ch_ref = NULL;
3806 	}
3807 
3808 	_spdk_bdev_io_complete(bdev_io);
3809 }
3810 
3811 static void
3812 _spdk_bdev_unfreeze_channel(struct spdk_io_channel_iter *i)
3813 {
3814 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
3815 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
3816 
3817 	ch->flags &= ~BDEV_CH_RESET_IN_PROGRESS;
3818 	if (!TAILQ_EMPTY(&ch->queued_resets)) {
3819 		_spdk_bdev_channel_start_reset(ch);
3820 	}
3821 
3822 	spdk_for_each_channel_continue(i, 0);
3823 }
3824 
3825 void
3826 spdk_bdev_io_complete(struct spdk_bdev_io *bdev_io, enum spdk_bdev_io_status status)
3827 {
3828 	struct spdk_bdev *bdev = bdev_io->bdev;
3829 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
3830 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
3831 
3832 	bdev_io->internal.status = status;
3833 
3834 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_RESET)) {
3835 		bool unlock_channels = false;
3836 
3837 		if (status == SPDK_BDEV_IO_STATUS_NOMEM) {
3838 			SPDK_ERRLOG("NOMEM returned for reset\n");
3839 		}
3840 		pthread_mutex_lock(&bdev->internal.mutex);
3841 		if (bdev_io == bdev->internal.reset_in_progress) {
3842 			bdev->internal.reset_in_progress = NULL;
3843 			unlock_channels = true;
3844 		}
3845 		pthread_mutex_unlock(&bdev->internal.mutex);
3846 
3847 		if (unlock_channels) {
3848 			spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_unfreeze_channel,
3849 					      bdev_io, _spdk_bdev_reset_complete);
3850 			return;
3851 		}
3852 	} else {
3853 		_bdev_io_unset_bounce_buf(bdev_io);
3854 
3855 		assert(bdev_ch->io_outstanding > 0);
3856 		assert(shared_resource->io_outstanding > 0);
3857 		bdev_ch->io_outstanding--;
3858 		shared_resource->io_outstanding--;
3859 
3860 		if (spdk_unlikely(status == SPDK_BDEV_IO_STATUS_NOMEM)) {
3861 			TAILQ_INSERT_HEAD(&shared_resource->nomem_io, bdev_io, internal.link);
3862 			/*
3863 			 * Wait for some of the outstanding I/O to complete before we
3864 			 *  retry any of the nomem_io.  Normally we will wait for
3865 			 *  NOMEM_THRESHOLD_COUNT I/O to complete but for low queue
3866 			 *  depth channels we will instead wait for half to complete.
3867 			 */
3868 			shared_resource->nomem_threshold = spdk_max((int64_t)shared_resource->io_outstanding / 2,
3869 							   (int64_t)shared_resource->io_outstanding - NOMEM_THRESHOLD_COUNT);
3870 			return;
3871 		}
3872 
3873 		if (spdk_unlikely(!TAILQ_EMPTY(&shared_resource->nomem_io))) {
3874 			_spdk_bdev_ch_retry_io(bdev_ch);
3875 		}
3876 	}
3877 
3878 	_spdk_bdev_io_complete(bdev_io);
3879 }
3880 
3881 void
3882 spdk_bdev_io_complete_scsi_status(struct spdk_bdev_io *bdev_io, enum spdk_scsi_status sc,
3883 				  enum spdk_scsi_sense sk, uint8_t asc, uint8_t ascq)
3884 {
3885 	if (sc == SPDK_SCSI_STATUS_GOOD) {
3886 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3887 	} else {
3888 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SCSI_ERROR;
3889 		bdev_io->internal.error.scsi.sc = sc;
3890 		bdev_io->internal.error.scsi.sk = sk;
3891 		bdev_io->internal.error.scsi.asc = asc;
3892 		bdev_io->internal.error.scsi.ascq = ascq;
3893 	}
3894 
3895 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
3896 }
3897 
3898 void
3899 spdk_bdev_io_get_scsi_status(const struct spdk_bdev_io *bdev_io,
3900 			     int *sc, int *sk, int *asc, int *ascq)
3901 {
3902 	assert(sc != NULL);
3903 	assert(sk != NULL);
3904 	assert(asc != NULL);
3905 	assert(ascq != NULL);
3906 
3907 	switch (bdev_io->internal.status) {
3908 	case SPDK_BDEV_IO_STATUS_SUCCESS:
3909 		*sc = SPDK_SCSI_STATUS_GOOD;
3910 		*sk = SPDK_SCSI_SENSE_NO_SENSE;
3911 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
3912 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
3913 		break;
3914 	case SPDK_BDEV_IO_STATUS_NVME_ERROR:
3915 		spdk_scsi_nvme_translate(bdev_io, sc, sk, asc, ascq);
3916 		break;
3917 	case SPDK_BDEV_IO_STATUS_SCSI_ERROR:
3918 		*sc = bdev_io->internal.error.scsi.sc;
3919 		*sk = bdev_io->internal.error.scsi.sk;
3920 		*asc = bdev_io->internal.error.scsi.asc;
3921 		*ascq = bdev_io->internal.error.scsi.ascq;
3922 		break;
3923 	default:
3924 		*sc = SPDK_SCSI_STATUS_CHECK_CONDITION;
3925 		*sk = SPDK_SCSI_SENSE_ABORTED_COMMAND;
3926 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
3927 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
3928 		break;
3929 	}
3930 }
3931 
3932 void
3933 spdk_bdev_io_complete_nvme_status(struct spdk_bdev_io *bdev_io, int sct, int sc)
3934 {
3935 	if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_SUCCESS) {
3936 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3937 	} else {
3938 		bdev_io->internal.error.nvme.sct = sct;
3939 		bdev_io->internal.error.nvme.sc = sc;
3940 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NVME_ERROR;
3941 	}
3942 
3943 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
3944 }
3945 
3946 void
3947 spdk_bdev_io_get_nvme_status(const struct spdk_bdev_io *bdev_io, int *sct, int *sc)
3948 {
3949 	assert(sct != NULL);
3950 	assert(sc != NULL);
3951 
3952 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
3953 		*sct = bdev_io->internal.error.nvme.sct;
3954 		*sc = bdev_io->internal.error.nvme.sc;
3955 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
3956 		*sct = SPDK_NVME_SCT_GENERIC;
3957 		*sc = SPDK_NVME_SC_SUCCESS;
3958 	} else {
3959 		*sct = SPDK_NVME_SCT_GENERIC;
3960 		*sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3961 	}
3962 }
3963 
3964 struct spdk_thread *
3965 spdk_bdev_io_get_thread(struct spdk_bdev_io *bdev_io)
3966 {
3967 	return spdk_io_channel_get_thread(bdev_io->internal.ch->channel);
3968 }
3969 
3970 struct spdk_io_channel *
3971 spdk_bdev_io_get_io_channel(struct spdk_bdev_io *bdev_io)
3972 {
3973 	return bdev_io->internal.ch->channel;
3974 }
3975 
3976 static void
3977 _spdk_bdev_qos_config_limit(struct spdk_bdev *bdev, uint64_t *limits)
3978 {
3979 	uint64_t	min_qos_set;
3980 	int		i;
3981 
3982 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3983 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3984 			break;
3985 		}
3986 	}
3987 
3988 	if (i == SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES) {
3989 		SPDK_ERRLOG("Invalid rate limits set.\n");
3990 		return;
3991 	}
3992 
3993 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3994 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3995 			continue;
3996 		}
3997 
3998 		if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
3999 			min_qos_set = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
4000 		} else {
4001 			min_qos_set = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
4002 		}
4003 
4004 		if (limits[i] == 0 || limits[i] % min_qos_set) {
4005 			SPDK_ERRLOG("Assigned limit %" PRIu64 " on bdev %s is not multiple of %" PRIu64 "\n",
4006 				    limits[i], bdev->name, min_qos_set);
4007 			SPDK_ERRLOG("Failed to enable QoS on this bdev %s\n", bdev->name);
4008 			return;
4009 		}
4010 	}
4011 
4012 	if (!bdev->internal.qos) {
4013 		bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
4014 		if (!bdev->internal.qos) {
4015 			SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
4016 			return;
4017 		}
4018 	}
4019 
4020 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4021 		bdev->internal.qos->rate_limits[i].limit = limits[i];
4022 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Bdev:%s QoS type:%d set:%lu\n",
4023 			      bdev->name, i, limits[i]);
4024 	}
4025 
4026 	return;
4027 }
4028 
4029 static void
4030 _spdk_bdev_qos_config(struct spdk_bdev *bdev)
4031 {
4032 	struct spdk_conf_section	*sp = NULL;
4033 	const char			*val = NULL;
4034 	int				i = 0, j = 0;
4035 	uint64_t			limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES] = {};
4036 	bool				config_qos = false;
4037 
4038 	sp = spdk_conf_find_section(NULL, "QoS");
4039 	if (!sp) {
4040 		return;
4041 	}
4042 
4043 	while (j < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES) {
4044 		limits[j] = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
4045 
4046 		i = 0;
4047 		while (true) {
4048 			val = spdk_conf_section_get_nmval(sp, qos_conf_type[j], i, 0);
4049 			if (!val) {
4050 				break;
4051 			}
4052 
4053 			if (strcmp(bdev->name, val) != 0) {
4054 				i++;
4055 				continue;
4056 			}
4057 
4058 			val = spdk_conf_section_get_nmval(sp, qos_conf_type[j], i, 1);
4059 			if (val) {
4060 				if (_spdk_bdev_qos_is_iops_rate_limit(j) == true) {
4061 					limits[j] = strtoull(val, NULL, 10);
4062 				} else {
4063 					limits[j] = strtoull(val, NULL, 10) * 1024 * 1024;
4064 				}
4065 				config_qos = true;
4066 			}
4067 
4068 			break;
4069 		}
4070 
4071 		j++;
4072 	}
4073 
4074 	if (config_qos == true) {
4075 		_spdk_bdev_qos_config_limit(bdev, limits);
4076 	}
4077 
4078 	return;
4079 }
4080 
4081 static int
4082 spdk_bdev_init(struct spdk_bdev *bdev)
4083 {
4084 	char *bdev_name;
4085 
4086 	assert(bdev->module != NULL);
4087 
4088 	if (!bdev->name) {
4089 		SPDK_ERRLOG("Bdev name is NULL\n");
4090 		return -EINVAL;
4091 	}
4092 
4093 	if (!strlen(bdev->name)) {
4094 		SPDK_ERRLOG("Bdev name must not be an empty string\n");
4095 		return -EINVAL;
4096 	}
4097 
4098 	if (spdk_bdev_get_by_name(bdev->name)) {
4099 		SPDK_ERRLOG("Bdev name:%s already exists\n", bdev->name);
4100 		return -EEXIST;
4101 	}
4102 
4103 	/* Users often register their own I/O devices using the bdev name. In
4104 	 * order to avoid conflicts, prepend bdev_. */
4105 	bdev_name = spdk_sprintf_alloc("bdev_%s", bdev->name);
4106 	if (!bdev_name) {
4107 		SPDK_ERRLOG("Unable to allocate memory for internal bdev name.\n");
4108 		return -ENOMEM;
4109 	}
4110 
4111 	bdev->internal.status = SPDK_BDEV_STATUS_READY;
4112 	bdev->internal.measured_queue_depth = UINT64_MAX;
4113 	bdev->internal.claim_module = NULL;
4114 	bdev->internal.qd_poller = NULL;
4115 	bdev->internal.qos = NULL;
4116 
4117 	/* If the user didn't specify a uuid, generate one. */
4118 	if (spdk_mem_all_zero(&bdev->uuid, sizeof(bdev->uuid))) {
4119 		spdk_uuid_generate(&bdev->uuid);
4120 	}
4121 
4122 	if (spdk_bdev_get_buf_align(bdev) > 1) {
4123 		if (bdev->split_on_optimal_io_boundary) {
4124 			bdev->optimal_io_boundary = spdk_min(bdev->optimal_io_boundary,
4125 							     SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen);
4126 		} else {
4127 			bdev->split_on_optimal_io_boundary = true;
4128 			bdev->optimal_io_boundary = SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen;
4129 		}
4130 	}
4131 
4132 	/* If the user didn't specify a write unit size, set it to one. */
4133 	if (bdev->write_unit_size == 0) {
4134 		bdev->write_unit_size = 1;
4135 	}
4136 
4137 	TAILQ_INIT(&bdev->internal.open_descs);
4138 
4139 	TAILQ_INIT(&bdev->aliases);
4140 
4141 	bdev->internal.reset_in_progress = NULL;
4142 
4143 	_spdk_bdev_qos_config(bdev);
4144 
4145 	spdk_io_device_register(__bdev_to_io_dev(bdev),
4146 				spdk_bdev_channel_create, spdk_bdev_channel_destroy,
4147 				sizeof(struct spdk_bdev_channel),
4148 				bdev_name);
4149 
4150 	free(bdev_name);
4151 
4152 	pthread_mutex_init(&bdev->internal.mutex, NULL);
4153 	return 0;
4154 }
4155 
4156 static void
4157 spdk_bdev_destroy_cb(void *io_device)
4158 {
4159 	int			rc;
4160 	struct spdk_bdev	*bdev;
4161 	spdk_bdev_unregister_cb	cb_fn;
4162 	void			*cb_arg;
4163 
4164 	bdev = __bdev_from_io_dev(io_device);
4165 	cb_fn = bdev->internal.unregister_cb;
4166 	cb_arg = bdev->internal.unregister_ctx;
4167 
4168 	rc = bdev->fn_table->destruct(bdev->ctxt);
4169 	if (rc < 0) {
4170 		SPDK_ERRLOG("destruct failed\n");
4171 	}
4172 	if (rc <= 0 && cb_fn != NULL) {
4173 		cb_fn(cb_arg, rc);
4174 	}
4175 }
4176 
4177 
4178 static void
4179 spdk_bdev_fini(struct spdk_bdev *bdev)
4180 {
4181 	pthread_mutex_destroy(&bdev->internal.mutex);
4182 
4183 	free(bdev->internal.qos);
4184 
4185 	spdk_io_device_unregister(__bdev_to_io_dev(bdev), spdk_bdev_destroy_cb);
4186 }
4187 
4188 static void
4189 spdk_bdev_start(struct spdk_bdev *bdev)
4190 {
4191 	struct spdk_bdev_module *module;
4192 	uint32_t action;
4193 
4194 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Inserting bdev %s into list\n", bdev->name);
4195 	TAILQ_INSERT_TAIL(&g_bdev_mgr.bdevs, bdev, internal.link);
4196 
4197 	/* Examine configuration before initializing I/O */
4198 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4199 		if (module->examine_config) {
4200 			action = module->internal.action_in_progress;
4201 			module->internal.action_in_progress++;
4202 			module->examine_config(bdev);
4203 			if (action != module->internal.action_in_progress) {
4204 				SPDK_ERRLOG("examine_config for module %s did not call spdk_bdev_module_examine_done()\n",
4205 					    module->name);
4206 			}
4207 		}
4208 	}
4209 
4210 	if (bdev->internal.claim_module) {
4211 		if (bdev->internal.claim_module->examine_disk) {
4212 			bdev->internal.claim_module->internal.action_in_progress++;
4213 			bdev->internal.claim_module->examine_disk(bdev);
4214 		}
4215 		return;
4216 	}
4217 
4218 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4219 		if (module->examine_disk) {
4220 			module->internal.action_in_progress++;
4221 			module->examine_disk(bdev);
4222 		}
4223 	}
4224 }
4225 
4226 int
4227 spdk_bdev_register(struct spdk_bdev *bdev)
4228 {
4229 	int rc = spdk_bdev_init(bdev);
4230 
4231 	if (rc == 0) {
4232 		spdk_bdev_start(bdev);
4233 	}
4234 
4235 	spdk_notify_send("bdev_register", spdk_bdev_get_name(bdev));
4236 	return rc;
4237 }
4238 
4239 int
4240 spdk_vbdev_register(struct spdk_bdev *vbdev, struct spdk_bdev **base_bdevs, int base_bdev_count)
4241 {
4242 	SPDK_ERRLOG("This function is deprecated.  Use spdk_bdev_register() instead.\n");
4243 	return spdk_bdev_register(vbdev);
4244 }
4245 
4246 void
4247 spdk_bdev_destruct_done(struct spdk_bdev *bdev, int bdeverrno)
4248 {
4249 	if (bdev->internal.unregister_cb != NULL) {
4250 		bdev->internal.unregister_cb(bdev->internal.unregister_ctx, bdeverrno);
4251 	}
4252 }
4253 
4254 static void
4255 _remove_notify(void *arg)
4256 {
4257 	struct spdk_bdev_desc *desc = arg;
4258 
4259 	pthread_mutex_lock(&desc->mutex);
4260 	desc->refs--;
4261 
4262 	if (!desc->closed) {
4263 		pthread_mutex_unlock(&desc->mutex);
4264 		if (desc->callback.open_with_ext) {
4265 			desc->callback.event_fn(SPDK_BDEV_EVENT_REMOVE, desc->bdev, desc->callback.ctx);
4266 		} else {
4267 			desc->callback.remove_fn(desc->callback.ctx);
4268 		}
4269 		return;
4270 	} else if (0 == desc->refs) {
4271 		/* This descriptor was closed after this remove_notify message was sent.
4272 		 * spdk_bdev_close() could not free the descriptor since this message was
4273 		 * in flight, so we free it now using _spdk_bdev_desc_free().
4274 		 */
4275 		pthread_mutex_unlock(&desc->mutex);
4276 		_spdk_bdev_desc_free(desc);
4277 		return;
4278 	}
4279 	pthread_mutex_unlock(&desc->mutex);
4280 }
4281 
4282 /* Must be called while holding bdev->internal.mutex.
4283  * returns: 0 - bdev removed and ready to be destructed.
4284  *          -EBUSY - bdev can't be destructed yet.  */
4285 static int
4286 spdk_bdev_unregister_unsafe(struct spdk_bdev *bdev)
4287 {
4288 	struct spdk_bdev_desc	*desc, *tmp;
4289 	int			rc = 0;
4290 
4291 	/* Notify each descriptor about hotremoval */
4292 	TAILQ_FOREACH_SAFE(desc, &bdev->internal.open_descs, link, tmp) {
4293 		rc = -EBUSY;
4294 		pthread_mutex_lock(&desc->mutex);
4295 		/*
4296 		 * Defer invocation of the event_cb to a separate message that will
4297 		 *  run later on its thread.  This ensures this context unwinds and
4298 		 *  we don't recursively unregister this bdev again if the event_cb
4299 		 *  immediately closes its descriptor.
4300 		 */
4301 		desc->refs++;
4302 		spdk_thread_send_msg(desc->thread, _remove_notify, desc);
4303 		pthread_mutex_unlock(&desc->mutex);
4304 	}
4305 
4306 	/* If there are no descriptors, proceed removing the bdev */
4307 	if (rc == 0) {
4308 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
4309 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Removing bdev %s from list done\n", bdev->name);
4310 		spdk_notify_send("bdev_unregister", spdk_bdev_get_name(bdev));
4311 	}
4312 
4313 	return rc;
4314 }
4315 
4316 void
4317 spdk_bdev_unregister(struct spdk_bdev *bdev, spdk_bdev_unregister_cb cb_fn, void *cb_arg)
4318 {
4319 	struct spdk_thread	*thread;
4320 	int			rc;
4321 
4322 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Removing bdev %s from list\n", bdev->name);
4323 
4324 	thread = spdk_get_thread();
4325 	if (!thread) {
4326 		/* The user called this from a non-SPDK thread. */
4327 		if (cb_fn != NULL) {
4328 			cb_fn(cb_arg, -ENOTSUP);
4329 		}
4330 		return;
4331 	}
4332 
4333 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4334 	pthread_mutex_lock(&bdev->internal.mutex);
4335 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
4336 		pthread_mutex_unlock(&bdev->internal.mutex);
4337 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4338 		if (cb_fn) {
4339 			cb_fn(cb_arg, -EBUSY);
4340 		}
4341 		return;
4342 	}
4343 
4344 	bdev->internal.status = SPDK_BDEV_STATUS_REMOVING;
4345 	bdev->internal.unregister_cb = cb_fn;
4346 	bdev->internal.unregister_ctx = cb_arg;
4347 
4348 	/* Call under lock. */
4349 	rc = spdk_bdev_unregister_unsafe(bdev);
4350 	pthread_mutex_unlock(&bdev->internal.mutex);
4351 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4352 
4353 	if (rc == 0) {
4354 		spdk_bdev_fini(bdev);
4355 	}
4356 }
4357 
4358 static void
4359 _spdk_bdev_dummy_event_cb(void *remove_ctx)
4360 {
4361 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Bdev remove event received with no remove callback specified");
4362 }
4363 
4364 static int
4365 _spdk_bdev_open(struct spdk_bdev *bdev, bool write, struct spdk_bdev_desc *desc)
4366 {
4367 	struct spdk_thread *thread;
4368 	struct set_qos_limit_ctx *ctx;
4369 
4370 	thread = spdk_get_thread();
4371 	if (!thread) {
4372 		SPDK_ERRLOG("Cannot open bdev from non-SPDK thread.\n");
4373 		return -ENOTSUP;
4374 	}
4375 
4376 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Opening descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
4377 		      spdk_get_thread());
4378 
4379 	desc->bdev = bdev;
4380 	desc->thread = thread;
4381 	desc->write = write;
4382 
4383 	pthread_mutex_lock(&bdev->internal.mutex);
4384 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
4385 		pthread_mutex_unlock(&bdev->internal.mutex);
4386 		return -ENODEV;
4387 	}
4388 
4389 	if (write && bdev->internal.claim_module) {
4390 		SPDK_ERRLOG("Could not open %s - %s module already claimed it\n",
4391 			    bdev->name, bdev->internal.claim_module->name);
4392 		pthread_mutex_unlock(&bdev->internal.mutex);
4393 		return -EPERM;
4394 	}
4395 
4396 	/* Enable QoS */
4397 	if (bdev->internal.qos && bdev->internal.qos->thread == NULL) {
4398 		ctx = calloc(1, sizeof(*ctx));
4399 		if (ctx == NULL) {
4400 			SPDK_ERRLOG("Failed to allocate memory for QoS context\n");
4401 			pthread_mutex_unlock(&bdev->internal.mutex);
4402 			return -ENOMEM;
4403 		}
4404 		ctx->bdev = bdev;
4405 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
4406 				      _spdk_bdev_enable_qos_msg, ctx,
4407 				      _spdk_bdev_enable_qos_done);
4408 	}
4409 
4410 	TAILQ_INSERT_TAIL(&bdev->internal.open_descs, desc, link);
4411 
4412 	pthread_mutex_unlock(&bdev->internal.mutex);
4413 
4414 	return 0;
4415 }
4416 
4417 int
4418 spdk_bdev_open(struct spdk_bdev *bdev, bool write, spdk_bdev_remove_cb_t remove_cb,
4419 	       void *remove_ctx, struct spdk_bdev_desc **_desc)
4420 {
4421 	struct spdk_bdev_desc *desc;
4422 	int rc;
4423 
4424 	desc = calloc(1, sizeof(*desc));
4425 	if (desc == NULL) {
4426 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
4427 		return -ENOMEM;
4428 	}
4429 
4430 	if (remove_cb == NULL) {
4431 		remove_cb = _spdk_bdev_dummy_event_cb;
4432 	}
4433 
4434 	desc->callback.open_with_ext = false;
4435 	desc->callback.remove_fn = remove_cb;
4436 	desc->callback.ctx = remove_ctx;
4437 	pthread_mutex_init(&desc->mutex, NULL);
4438 
4439 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4440 
4441 	rc = _spdk_bdev_open(bdev, write, desc);
4442 	if (rc != 0) {
4443 		_spdk_bdev_desc_free(desc);
4444 		desc = NULL;
4445 	}
4446 
4447 	*_desc = desc;
4448 
4449 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4450 
4451 	return rc;
4452 }
4453 
4454 int
4455 spdk_bdev_open_ext(const char *bdev_name, bool write, spdk_bdev_event_cb_t event_cb,
4456 		   void *event_ctx, struct spdk_bdev_desc **_desc)
4457 {
4458 	struct spdk_bdev_desc *desc;
4459 	struct spdk_bdev *bdev;
4460 	int rc;
4461 
4462 	if (event_cb == NULL) {
4463 		SPDK_ERRLOG("Missing event callback function\n");
4464 		return -EINVAL;
4465 	}
4466 
4467 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4468 
4469 	bdev = spdk_bdev_get_by_name(bdev_name);
4470 
4471 	if (bdev == NULL) {
4472 		SPDK_ERRLOG("Failed to find bdev with name: %s\n", bdev_name);
4473 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4474 		return -EINVAL;
4475 	}
4476 
4477 	desc = calloc(1, sizeof(*desc));
4478 	if (desc == NULL) {
4479 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
4480 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4481 		return -ENOMEM;
4482 	}
4483 
4484 	desc->callback.open_with_ext = true;
4485 	desc->callback.event_fn = event_cb;
4486 	desc->callback.ctx = event_ctx;
4487 	pthread_mutex_init(&desc->mutex, NULL);
4488 
4489 	rc = _spdk_bdev_open(bdev, write, desc);
4490 	if (rc != 0) {
4491 		_spdk_bdev_desc_free(desc);
4492 		desc = NULL;
4493 	}
4494 
4495 	*_desc = desc;
4496 
4497 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4498 
4499 	return rc;
4500 }
4501 
4502 void
4503 spdk_bdev_close(struct spdk_bdev_desc *desc)
4504 {
4505 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4506 	int rc;
4507 
4508 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Closing descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
4509 		      spdk_get_thread());
4510 
4511 	assert(desc->thread == spdk_get_thread());
4512 
4513 	pthread_mutex_lock(&bdev->internal.mutex);
4514 	pthread_mutex_lock(&desc->mutex);
4515 
4516 	TAILQ_REMOVE(&bdev->internal.open_descs, desc, link);
4517 
4518 	desc->closed = true;
4519 
4520 	if (0 == desc->refs) {
4521 		pthread_mutex_unlock(&desc->mutex);
4522 		_spdk_bdev_desc_free(desc);
4523 	} else {
4524 		pthread_mutex_unlock(&desc->mutex);
4525 	}
4526 
4527 	/* If no more descriptors, kill QoS channel */
4528 	if (bdev->internal.qos && TAILQ_EMPTY(&bdev->internal.open_descs)) {
4529 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Closed last descriptor for bdev %s on thread %p. Stopping QoS.\n",
4530 			      bdev->name, spdk_get_thread());
4531 
4532 		if (spdk_bdev_qos_destroy(bdev)) {
4533 			/* There isn't anything we can do to recover here. Just let the
4534 			 * old QoS poller keep running. The QoS handling won't change
4535 			 * cores when the user allocates a new channel, but it won't break. */
4536 			SPDK_ERRLOG("Unable to shut down QoS poller. It will continue running on the current thread.\n");
4537 		}
4538 	}
4539 
4540 	spdk_bdev_set_qd_sampling_period(bdev, 0);
4541 
4542 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING && TAILQ_EMPTY(&bdev->internal.open_descs)) {
4543 		rc = spdk_bdev_unregister_unsafe(bdev);
4544 		pthread_mutex_unlock(&bdev->internal.mutex);
4545 
4546 		if (rc == 0) {
4547 			spdk_bdev_fini(bdev);
4548 		}
4549 	} else {
4550 		pthread_mutex_unlock(&bdev->internal.mutex);
4551 	}
4552 }
4553 
4554 int
4555 spdk_bdev_module_claim_bdev(struct spdk_bdev *bdev, struct spdk_bdev_desc *desc,
4556 			    struct spdk_bdev_module *module)
4557 {
4558 	if (bdev->internal.claim_module != NULL) {
4559 		SPDK_ERRLOG("bdev %s already claimed by module %s\n", bdev->name,
4560 			    bdev->internal.claim_module->name);
4561 		return -EPERM;
4562 	}
4563 
4564 	if (desc && !desc->write) {
4565 		desc->write = true;
4566 	}
4567 
4568 	bdev->internal.claim_module = module;
4569 	return 0;
4570 }
4571 
4572 void
4573 spdk_bdev_module_release_bdev(struct spdk_bdev *bdev)
4574 {
4575 	assert(bdev->internal.claim_module != NULL);
4576 	bdev->internal.claim_module = NULL;
4577 }
4578 
4579 struct spdk_bdev *
4580 spdk_bdev_desc_get_bdev(struct spdk_bdev_desc *desc)
4581 {
4582 	assert(desc != NULL);
4583 	return desc->bdev;
4584 }
4585 
4586 void
4587 spdk_bdev_io_get_iovec(struct spdk_bdev_io *bdev_io, struct iovec **iovp, int *iovcntp)
4588 {
4589 	struct iovec *iovs;
4590 	int iovcnt;
4591 
4592 	if (bdev_io == NULL) {
4593 		return;
4594 	}
4595 
4596 	switch (bdev_io->type) {
4597 	case SPDK_BDEV_IO_TYPE_READ:
4598 	case SPDK_BDEV_IO_TYPE_WRITE:
4599 	case SPDK_BDEV_IO_TYPE_ZCOPY:
4600 		iovs = bdev_io->u.bdev.iovs;
4601 		iovcnt = bdev_io->u.bdev.iovcnt;
4602 		break;
4603 	default:
4604 		iovs = NULL;
4605 		iovcnt = 0;
4606 		break;
4607 	}
4608 
4609 	if (iovp) {
4610 		*iovp = iovs;
4611 	}
4612 	if (iovcntp) {
4613 		*iovcntp = iovcnt;
4614 	}
4615 }
4616 
4617 void *
4618 spdk_bdev_io_get_md_buf(struct spdk_bdev_io *bdev_io)
4619 {
4620 	if (bdev_io == NULL) {
4621 		return NULL;
4622 	}
4623 
4624 	if (!spdk_bdev_is_md_separate(bdev_io->bdev)) {
4625 		return NULL;
4626 	}
4627 
4628 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ ||
4629 	    bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
4630 		return bdev_io->u.bdev.md_buf;
4631 	}
4632 
4633 	return NULL;
4634 }
4635 
4636 void
4637 spdk_bdev_module_list_add(struct spdk_bdev_module *bdev_module)
4638 {
4639 
4640 	if (spdk_bdev_module_list_find(bdev_module->name)) {
4641 		SPDK_ERRLOG("ERROR: module '%s' already registered.\n", bdev_module->name);
4642 		assert(false);
4643 	}
4644 
4645 	/*
4646 	 * Modules with examine callbacks must be initialized first, so they are
4647 	 *  ready to handle examine callbacks from later modules that will
4648 	 *  register physical bdevs.
4649 	 */
4650 	if (bdev_module->examine_config != NULL || bdev_module->examine_disk != NULL) {
4651 		TAILQ_INSERT_HEAD(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
4652 	} else {
4653 		TAILQ_INSERT_TAIL(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
4654 	}
4655 }
4656 
4657 struct spdk_bdev_module *
4658 spdk_bdev_module_list_find(const char *name)
4659 {
4660 	struct spdk_bdev_module *bdev_module;
4661 
4662 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4663 		if (strcmp(name, bdev_module->name) == 0) {
4664 			break;
4665 		}
4666 	}
4667 
4668 	return bdev_module;
4669 }
4670 
4671 static void
4672 _spdk_bdev_write_zero_buffer_next(void *_bdev_io)
4673 {
4674 	struct spdk_bdev_io *bdev_io = _bdev_io;
4675 	uint64_t num_bytes, num_blocks;
4676 	void *md_buf = NULL;
4677 	int rc;
4678 
4679 	num_bytes = spdk_min(_bdev_get_block_size_with_md(bdev_io->bdev) *
4680 			     bdev_io->u.bdev.split_remaining_num_blocks,
4681 			     ZERO_BUFFER_SIZE);
4682 	num_blocks = num_bytes / _bdev_get_block_size_with_md(bdev_io->bdev);
4683 
4684 	if (spdk_bdev_is_md_separate(bdev_io->bdev)) {
4685 		md_buf = (char *)g_bdev_mgr.zero_buffer +
4686 			 spdk_bdev_get_block_size(bdev_io->bdev) * num_blocks;
4687 	}
4688 
4689 	rc = _spdk_bdev_write_blocks_with_md(bdev_io->internal.desc,
4690 					     spdk_io_channel_from_ctx(bdev_io->internal.ch),
4691 					     g_bdev_mgr.zero_buffer, md_buf,
4692 					     bdev_io->u.bdev.split_current_offset_blocks, num_blocks,
4693 					     _spdk_bdev_write_zero_buffer_done, bdev_io);
4694 	if (rc == 0) {
4695 		bdev_io->u.bdev.split_remaining_num_blocks -= num_blocks;
4696 		bdev_io->u.bdev.split_current_offset_blocks += num_blocks;
4697 	} else if (rc == -ENOMEM) {
4698 		_spdk_bdev_queue_io_wait_with_cb(bdev_io, _spdk_bdev_write_zero_buffer_next);
4699 	} else {
4700 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4701 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
4702 	}
4703 }
4704 
4705 static void
4706 _spdk_bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4707 {
4708 	struct spdk_bdev_io *parent_io = cb_arg;
4709 
4710 	spdk_bdev_free_io(bdev_io);
4711 
4712 	if (!success) {
4713 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4714 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
4715 		return;
4716 	}
4717 
4718 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
4719 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4720 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
4721 		return;
4722 	}
4723 
4724 	_spdk_bdev_write_zero_buffer_next(parent_io);
4725 }
4726 
4727 static void
4728 _spdk_bdev_set_qos_limit_done(struct set_qos_limit_ctx *ctx, int status)
4729 {
4730 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
4731 	ctx->bdev->internal.qos_mod_in_progress = false;
4732 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
4733 
4734 	if (ctx->cb_fn) {
4735 		ctx->cb_fn(ctx->cb_arg, status);
4736 	}
4737 	free(ctx);
4738 }
4739 
4740 static void
4741 _spdk_bdev_disable_qos_done(void *cb_arg)
4742 {
4743 	struct set_qos_limit_ctx *ctx = cb_arg;
4744 	struct spdk_bdev *bdev = ctx->bdev;
4745 	struct spdk_bdev_io *bdev_io;
4746 	struct spdk_bdev_qos *qos;
4747 
4748 	pthread_mutex_lock(&bdev->internal.mutex);
4749 	qos = bdev->internal.qos;
4750 	bdev->internal.qos = NULL;
4751 	pthread_mutex_unlock(&bdev->internal.mutex);
4752 
4753 	while (!TAILQ_EMPTY(&qos->queued)) {
4754 		/* Send queued I/O back to their original thread for resubmission. */
4755 		bdev_io = TAILQ_FIRST(&qos->queued);
4756 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
4757 
4758 		if (bdev_io->internal.io_submit_ch) {
4759 			/*
4760 			 * Channel was changed when sending it to the QoS thread - change it back
4761 			 *  before sending it back to the original thread.
4762 			 */
4763 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
4764 			bdev_io->internal.io_submit_ch = NULL;
4765 		}
4766 
4767 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
4768 				     _spdk_bdev_io_submit, bdev_io);
4769 	}
4770 
4771 	if (qos->thread != NULL) {
4772 		spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
4773 		spdk_poller_unregister(&qos->poller);
4774 	}
4775 
4776 	free(qos);
4777 
4778 	_spdk_bdev_set_qos_limit_done(ctx, 0);
4779 }
4780 
4781 static void
4782 _spdk_bdev_disable_qos_msg_done(struct spdk_io_channel_iter *i, int status)
4783 {
4784 	void *io_device = spdk_io_channel_iter_get_io_device(i);
4785 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
4786 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4787 	struct spdk_thread *thread;
4788 
4789 	pthread_mutex_lock(&bdev->internal.mutex);
4790 	thread = bdev->internal.qos->thread;
4791 	pthread_mutex_unlock(&bdev->internal.mutex);
4792 
4793 	if (thread != NULL) {
4794 		spdk_thread_send_msg(thread, _spdk_bdev_disable_qos_done, ctx);
4795 	} else {
4796 		_spdk_bdev_disable_qos_done(ctx);
4797 	}
4798 }
4799 
4800 static void
4801 _spdk_bdev_disable_qos_msg(struct spdk_io_channel_iter *i)
4802 {
4803 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
4804 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
4805 
4806 	bdev_ch->flags &= ~BDEV_CH_QOS_ENABLED;
4807 
4808 	spdk_for_each_channel_continue(i, 0);
4809 }
4810 
4811 static void
4812 _spdk_bdev_update_qos_rate_limit_msg(void *cb_arg)
4813 {
4814 	struct set_qos_limit_ctx *ctx = cb_arg;
4815 	struct spdk_bdev *bdev = ctx->bdev;
4816 
4817 	pthread_mutex_lock(&bdev->internal.mutex);
4818 	spdk_bdev_qos_update_max_quota_per_timeslice(bdev->internal.qos);
4819 	pthread_mutex_unlock(&bdev->internal.mutex);
4820 
4821 	_spdk_bdev_set_qos_limit_done(ctx, 0);
4822 }
4823 
4824 static void
4825 _spdk_bdev_enable_qos_msg(struct spdk_io_channel_iter *i)
4826 {
4827 	void *io_device = spdk_io_channel_iter_get_io_device(i);
4828 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
4829 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
4830 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
4831 
4832 	pthread_mutex_lock(&bdev->internal.mutex);
4833 	_spdk_bdev_enable_qos(bdev, bdev_ch);
4834 	pthread_mutex_unlock(&bdev->internal.mutex);
4835 	spdk_for_each_channel_continue(i, 0);
4836 }
4837 
4838 static void
4839 _spdk_bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status)
4840 {
4841 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4842 
4843 	_spdk_bdev_set_qos_limit_done(ctx, status);
4844 }
4845 
4846 static void
4847 _spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
4848 {
4849 	int i;
4850 
4851 	assert(bdev->internal.qos != NULL);
4852 
4853 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4854 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
4855 			bdev->internal.qos->rate_limits[i].limit = limits[i];
4856 
4857 			if (limits[i] == 0) {
4858 				bdev->internal.qos->rate_limits[i].limit =
4859 					SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
4860 			}
4861 		}
4862 	}
4863 }
4864 
4865 void
4866 spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits,
4867 			      void (*cb_fn)(void *cb_arg, int status), void *cb_arg)
4868 {
4869 	struct set_qos_limit_ctx	*ctx;
4870 	uint32_t			limit_set_complement;
4871 	uint64_t			min_limit_per_sec;
4872 	int				i;
4873 	bool				disable_rate_limit = true;
4874 
4875 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4876 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
4877 			continue;
4878 		}
4879 
4880 		if (limits[i] > 0) {
4881 			disable_rate_limit = false;
4882 		}
4883 
4884 		if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
4885 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
4886 		} else {
4887 			/* Change from megabyte to byte rate limit */
4888 			limits[i] = limits[i] * 1024 * 1024;
4889 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
4890 		}
4891 
4892 		limit_set_complement = limits[i] % min_limit_per_sec;
4893 		if (limit_set_complement) {
4894 			SPDK_ERRLOG("Requested rate limit %" PRIu64 " is not a multiple of %" PRIu64 "\n",
4895 				    limits[i], min_limit_per_sec);
4896 			limits[i] += min_limit_per_sec - limit_set_complement;
4897 			SPDK_ERRLOG("Round up the rate limit to %" PRIu64 "\n", limits[i]);
4898 		}
4899 	}
4900 
4901 	ctx = calloc(1, sizeof(*ctx));
4902 	if (ctx == NULL) {
4903 		cb_fn(cb_arg, -ENOMEM);
4904 		return;
4905 	}
4906 
4907 	ctx->cb_fn = cb_fn;
4908 	ctx->cb_arg = cb_arg;
4909 	ctx->bdev = bdev;
4910 
4911 	pthread_mutex_lock(&bdev->internal.mutex);
4912 	if (bdev->internal.qos_mod_in_progress) {
4913 		pthread_mutex_unlock(&bdev->internal.mutex);
4914 		free(ctx);
4915 		cb_fn(cb_arg, -EAGAIN);
4916 		return;
4917 	}
4918 	bdev->internal.qos_mod_in_progress = true;
4919 
4920 	if (disable_rate_limit == true && bdev->internal.qos) {
4921 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4922 			if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED &&
4923 			    (bdev->internal.qos->rate_limits[i].limit > 0 &&
4924 			     bdev->internal.qos->rate_limits[i].limit !=
4925 			     SPDK_BDEV_QOS_LIMIT_NOT_DEFINED)) {
4926 				disable_rate_limit = false;
4927 				break;
4928 			}
4929 		}
4930 	}
4931 
4932 	if (disable_rate_limit == false) {
4933 		if (bdev->internal.qos == NULL) {
4934 			bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
4935 			if (!bdev->internal.qos) {
4936 				pthread_mutex_unlock(&bdev->internal.mutex);
4937 				SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
4938 				_spdk_bdev_set_qos_limit_done(ctx, -ENOMEM);
4939 				return;
4940 			}
4941 		}
4942 
4943 		if (bdev->internal.qos->thread == NULL) {
4944 			/* Enabling */
4945 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4946 
4947 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
4948 					      _spdk_bdev_enable_qos_msg, ctx,
4949 					      _spdk_bdev_enable_qos_done);
4950 		} else {
4951 			/* Updating */
4952 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4953 
4954 			spdk_thread_send_msg(bdev->internal.qos->thread,
4955 					     _spdk_bdev_update_qos_rate_limit_msg, ctx);
4956 		}
4957 	} else {
4958 		if (bdev->internal.qos != NULL) {
4959 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4960 
4961 			/* Disabling */
4962 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
4963 					      _spdk_bdev_disable_qos_msg, ctx,
4964 					      _spdk_bdev_disable_qos_msg_done);
4965 		} else {
4966 			pthread_mutex_unlock(&bdev->internal.mutex);
4967 			_spdk_bdev_set_qos_limit_done(ctx, 0);
4968 			return;
4969 		}
4970 	}
4971 
4972 	pthread_mutex_unlock(&bdev->internal.mutex);
4973 }
4974 
4975 struct spdk_bdev_histogram_ctx {
4976 	spdk_bdev_histogram_status_cb cb_fn;
4977 	void *cb_arg;
4978 	struct spdk_bdev *bdev;
4979 	int status;
4980 };
4981 
4982 static void
4983 _spdk_bdev_histogram_disable_channel_cb(struct spdk_io_channel_iter *i, int status)
4984 {
4985 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4986 
4987 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
4988 	ctx->bdev->internal.histogram_in_progress = false;
4989 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
4990 	ctx->cb_fn(ctx->cb_arg, ctx->status);
4991 	free(ctx);
4992 }
4993 
4994 static void
4995 _spdk_bdev_histogram_disable_channel(struct spdk_io_channel_iter *i)
4996 {
4997 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
4998 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
4999 
5000 	if (ch->histogram != NULL) {
5001 		spdk_histogram_data_free(ch->histogram);
5002 		ch->histogram = NULL;
5003 	}
5004 	spdk_for_each_channel_continue(i, 0);
5005 }
5006 
5007 static void
5008 _spdk_bdev_histogram_enable_channel_cb(struct spdk_io_channel_iter *i, int status)
5009 {
5010 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5011 
5012 	if (status != 0) {
5013 		ctx->status = status;
5014 		ctx->bdev->internal.histogram_enabled = false;
5015 		spdk_for_each_channel(__bdev_to_io_dev(ctx->bdev), _spdk_bdev_histogram_disable_channel, ctx,
5016 				      _spdk_bdev_histogram_disable_channel_cb);
5017 	} else {
5018 		pthread_mutex_lock(&ctx->bdev->internal.mutex);
5019 		ctx->bdev->internal.histogram_in_progress = false;
5020 		pthread_mutex_unlock(&ctx->bdev->internal.mutex);
5021 		ctx->cb_fn(ctx->cb_arg, ctx->status);
5022 		free(ctx);
5023 	}
5024 }
5025 
5026 static void
5027 _spdk_bdev_histogram_enable_channel(struct spdk_io_channel_iter *i)
5028 {
5029 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5030 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5031 	int status = 0;
5032 
5033 	if (ch->histogram == NULL) {
5034 		ch->histogram = spdk_histogram_data_alloc();
5035 		if (ch->histogram == NULL) {
5036 			status = -ENOMEM;
5037 		}
5038 	}
5039 
5040 	spdk_for_each_channel_continue(i, status);
5041 }
5042 
5043 void
5044 spdk_bdev_histogram_enable(struct spdk_bdev *bdev, spdk_bdev_histogram_status_cb cb_fn,
5045 			   void *cb_arg, bool enable)
5046 {
5047 	struct spdk_bdev_histogram_ctx *ctx;
5048 
5049 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_ctx));
5050 	if (ctx == NULL) {
5051 		cb_fn(cb_arg, -ENOMEM);
5052 		return;
5053 	}
5054 
5055 	ctx->bdev = bdev;
5056 	ctx->status = 0;
5057 	ctx->cb_fn = cb_fn;
5058 	ctx->cb_arg = cb_arg;
5059 
5060 	pthread_mutex_lock(&bdev->internal.mutex);
5061 	if (bdev->internal.histogram_in_progress) {
5062 		pthread_mutex_unlock(&bdev->internal.mutex);
5063 		free(ctx);
5064 		cb_fn(cb_arg, -EAGAIN);
5065 		return;
5066 	}
5067 
5068 	bdev->internal.histogram_in_progress = true;
5069 	pthread_mutex_unlock(&bdev->internal.mutex);
5070 
5071 	bdev->internal.histogram_enabled = enable;
5072 
5073 	if (enable) {
5074 		/* Allocate histogram for each channel */
5075 		spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_enable_channel, ctx,
5076 				      _spdk_bdev_histogram_enable_channel_cb);
5077 	} else {
5078 		spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_disable_channel, ctx,
5079 				      _spdk_bdev_histogram_disable_channel_cb);
5080 	}
5081 }
5082 
5083 struct spdk_bdev_histogram_data_ctx {
5084 	spdk_bdev_histogram_data_cb cb_fn;
5085 	void *cb_arg;
5086 	struct spdk_bdev *bdev;
5087 	/** merged histogram data from all channels */
5088 	struct spdk_histogram_data	*histogram;
5089 };
5090 
5091 static void
5092 _spdk_bdev_histogram_get_channel_cb(struct spdk_io_channel_iter *i, int status)
5093 {
5094 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5095 
5096 	ctx->cb_fn(ctx->cb_arg, status, ctx->histogram);
5097 	free(ctx);
5098 }
5099 
5100 static void
5101 _spdk_bdev_histogram_get_channel(struct spdk_io_channel_iter *i)
5102 {
5103 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5104 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5105 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5106 	int status = 0;
5107 
5108 	if (ch->histogram == NULL) {
5109 		status = -EFAULT;
5110 	} else {
5111 		spdk_histogram_data_merge(ctx->histogram, ch->histogram);
5112 	}
5113 
5114 	spdk_for_each_channel_continue(i, status);
5115 }
5116 
5117 void
5118 spdk_bdev_histogram_get(struct spdk_bdev *bdev, struct spdk_histogram_data *histogram,
5119 			spdk_bdev_histogram_data_cb cb_fn,
5120 			void *cb_arg)
5121 {
5122 	struct spdk_bdev_histogram_data_ctx *ctx;
5123 
5124 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_data_ctx));
5125 	if (ctx == NULL) {
5126 		cb_fn(cb_arg, -ENOMEM, NULL);
5127 		return;
5128 	}
5129 
5130 	ctx->bdev = bdev;
5131 	ctx->cb_fn = cb_fn;
5132 	ctx->cb_arg = cb_arg;
5133 
5134 	ctx->histogram = histogram;
5135 
5136 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_get_channel, ctx,
5137 			      _spdk_bdev_histogram_get_channel_cb);
5138 }
5139 
5140 SPDK_LOG_REGISTER_COMPONENT("bdev", SPDK_LOG_BDEV)
5141 
5142 SPDK_TRACE_REGISTER_FN(bdev_trace, "bdev", TRACE_GROUP_BDEV)
5143 {
5144 	spdk_trace_register_owner(OWNER_BDEV, 'b');
5145 	spdk_trace_register_object(OBJECT_BDEV_IO, 'i');
5146 	spdk_trace_register_description("BDEV_IO_START", TRACE_BDEV_IO_START, OWNER_BDEV,
5147 					OBJECT_BDEV_IO, 1, 0, "type:   ");
5148 	spdk_trace_register_description("BDEV_IO_DONE", TRACE_BDEV_IO_DONE, OWNER_BDEV,
5149 					OBJECT_BDEV_IO, 0, 0, "");
5150 }
5151