xref: /spdk/lib/bdev/bdev.c (revision 7a9ecf8284accbb14e99cf8533e561d5f9820f76)
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_last_block_bytes = blocklen - to_last_block_bytes;
1700 				to_next_boundary_bytes += to_last_block_bytes;
1701 				while (to_last_block_bytes > 0 && iovcnt > 0) {
1702 					iov_len = spdk_min(to_last_block_bytes,
1703 							   bdev_io->child_iov[child_iovpos].iov_len);
1704 					bdev_io->child_iov[child_iovpos].iov_len -= iov_len;
1705 					if (bdev_io->child_iov[child_iovpos].iov_len == 0) {
1706 						child_iovpos--;
1707 						iovcnt--;
1708 					}
1709 					to_last_block_bytes -= iov_len;
1710 				}
1711 
1712 				assert(to_last_block_bytes == 0);
1713 			}
1714 			to_next_boundary -= to_next_boundary_bytes / blocklen;
1715 		}
1716 
1717 		bdev_io->u.bdev.split_outstanding++;
1718 
1719 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
1720 			rc = _spdk_bdev_readv_blocks_with_md(bdev_io->internal.desc,
1721 							     spdk_io_channel_from_ctx(bdev_io->internal.ch),
1722 							     iov, iovcnt, md_buf, current_offset,
1723 							     to_next_boundary,
1724 							     _spdk_bdev_io_split_done, bdev_io);
1725 		} else {
1726 			rc = _spdk_bdev_writev_blocks_with_md(bdev_io->internal.desc,
1727 							      spdk_io_channel_from_ctx(bdev_io->internal.ch),
1728 							      iov, iovcnt, md_buf, current_offset,
1729 							      to_next_boundary,
1730 							      _spdk_bdev_io_split_done, bdev_io);
1731 		}
1732 
1733 		if (rc == 0) {
1734 			current_offset += to_next_boundary;
1735 			remaining -= to_next_boundary;
1736 			bdev_io->u.bdev.split_current_offset_blocks = current_offset;
1737 			bdev_io->u.bdev.split_remaining_num_blocks = remaining;
1738 		} else {
1739 			bdev_io->u.bdev.split_outstanding--;
1740 			if (rc == -ENOMEM) {
1741 				if (bdev_io->u.bdev.split_outstanding == 0) {
1742 					/* No I/O is outstanding. Hence we should wait here. */
1743 					_spdk_bdev_queue_io_wait_with_cb(bdev_io,
1744 									 _spdk_bdev_io_split);
1745 				}
1746 			} else {
1747 				bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1748 				if (bdev_io->u.bdev.split_outstanding == 0) {
1749 					bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
1750 				}
1751 			}
1752 
1753 			return;
1754 		}
1755 	}
1756 }
1757 
1758 static void
1759 _spdk_bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
1760 {
1761 	struct spdk_bdev_io *parent_io = cb_arg;
1762 
1763 	spdk_bdev_free_io(bdev_io);
1764 
1765 	if (!success) {
1766 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1767 	}
1768 	parent_io->u.bdev.split_outstanding--;
1769 	if (parent_io->u.bdev.split_outstanding != 0) {
1770 		return;
1771 	}
1772 
1773 	/*
1774 	 * Parent I/O finishes when all blocks are consumed.
1775 	 */
1776 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
1777 		parent_io->internal.cb(parent_io, parent_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
1778 				       parent_io->internal.caller_ctx);
1779 		return;
1780 	}
1781 
1782 	/*
1783 	 * Continue with the splitting process.  This function will complete the parent I/O if the
1784 	 * splitting is done.
1785 	 */
1786 	_spdk_bdev_io_split(parent_io);
1787 }
1788 
1789 static void
1790 _spdk_bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
1791 			       bool success);
1792 
1793 static void
1794 spdk_bdev_io_split(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io)
1795 {
1796 	assert(_spdk_bdev_io_type_can_split(bdev_io->type));
1797 
1798 	bdev_io->u.bdev.split_current_offset_blocks = bdev_io->u.bdev.offset_blocks;
1799 	bdev_io->u.bdev.split_remaining_num_blocks = bdev_io->u.bdev.num_blocks;
1800 	bdev_io->u.bdev.split_outstanding = 0;
1801 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
1802 
1803 	if (_is_buf_allocated(bdev_io->u.bdev.iovs)) {
1804 		_spdk_bdev_io_split(bdev_io);
1805 	} else {
1806 		assert(bdev_io->type == SPDK_BDEV_IO_TYPE_READ);
1807 		spdk_bdev_io_get_buf(bdev_io, _spdk_bdev_io_split_get_buf_cb,
1808 				     bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
1809 	}
1810 }
1811 
1812 static void
1813 _spdk_bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
1814 			       bool success)
1815 {
1816 	if (!success) {
1817 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1818 		return;
1819 	}
1820 
1821 	spdk_bdev_io_split(ch, bdev_io);
1822 }
1823 
1824 /* Explicitly mark this inline, since it's used as a function pointer and otherwise won't
1825  *  be inlined, at least on some compilers.
1826  */
1827 static inline void
1828 _spdk_bdev_io_submit(void *ctx)
1829 {
1830 	struct spdk_bdev_io *bdev_io = ctx;
1831 	struct spdk_bdev *bdev = bdev_io->bdev;
1832 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1833 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1834 	uint64_t tsc;
1835 
1836 	tsc = spdk_get_ticks();
1837 	bdev_io->internal.submit_tsc = tsc;
1838 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_START, 0, 0, (uintptr_t)bdev_io, bdev_io->type);
1839 
1840 	if (spdk_likely(bdev_ch->flags == 0)) {
1841 		_spdk_bdev_io_do_submit(bdev_ch, bdev_io);
1842 		return;
1843 	}
1844 
1845 	bdev_ch->io_outstanding++;
1846 	shared_resource->io_outstanding++;
1847 	bdev_io->internal.in_submit_request = true;
1848 	if (bdev_ch->flags & BDEV_CH_RESET_IN_PROGRESS) {
1849 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1850 	} else if (bdev_ch->flags & BDEV_CH_QOS_ENABLED) {
1851 		bdev_ch->io_outstanding--;
1852 		shared_resource->io_outstanding--;
1853 		TAILQ_INSERT_TAIL(&bdev->internal.qos->queued, bdev_io, internal.link);
1854 		_spdk_bdev_qos_io_submit(bdev_ch, bdev->internal.qos);
1855 	} else {
1856 		SPDK_ERRLOG("unknown bdev_ch flag %x found\n", bdev_ch->flags);
1857 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1858 	}
1859 	bdev_io->internal.in_submit_request = false;
1860 }
1861 
1862 void
1863 spdk_bdev_io_submit(struct spdk_bdev_io *bdev_io)
1864 {
1865 	struct spdk_bdev *bdev = bdev_io->bdev;
1866 	struct spdk_thread *thread = spdk_bdev_io_get_thread(bdev_io);
1867 
1868 	assert(thread != NULL);
1869 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
1870 
1871 	if (bdev->split_on_optimal_io_boundary && _spdk_bdev_io_should_split(bdev_io)) {
1872 		spdk_bdev_io_split(NULL, bdev_io);
1873 		return;
1874 	}
1875 
1876 	if (bdev_io->internal.ch->flags & BDEV_CH_QOS_ENABLED) {
1877 		if ((thread == bdev->internal.qos->thread) || !bdev->internal.qos->thread) {
1878 			_spdk_bdev_io_submit(bdev_io);
1879 		} else {
1880 			bdev_io->internal.io_submit_ch = bdev_io->internal.ch;
1881 			bdev_io->internal.ch = bdev->internal.qos->ch;
1882 			spdk_thread_send_msg(bdev->internal.qos->thread, _spdk_bdev_io_submit, bdev_io);
1883 		}
1884 	} else {
1885 		_spdk_bdev_io_submit(bdev_io);
1886 	}
1887 }
1888 
1889 static void
1890 spdk_bdev_io_submit_reset(struct spdk_bdev_io *bdev_io)
1891 {
1892 	struct spdk_bdev *bdev = bdev_io->bdev;
1893 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
1894 	struct spdk_io_channel *ch = bdev_ch->channel;
1895 
1896 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
1897 
1898 	bdev_io->internal.in_submit_request = true;
1899 	bdev->fn_table->submit_request(ch, bdev_io);
1900 	bdev_io->internal.in_submit_request = false;
1901 }
1902 
1903 void
1904 spdk_bdev_io_init(struct spdk_bdev_io *bdev_io,
1905 		  struct spdk_bdev *bdev, void *cb_arg,
1906 		  spdk_bdev_io_completion_cb cb)
1907 {
1908 	bdev_io->bdev = bdev;
1909 	bdev_io->internal.caller_ctx = cb_arg;
1910 	bdev_io->internal.cb = cb;
1911 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
1912 	bdev_io->internal.in_submit_request = false;
1913 	bdev_io->internal.buf = NULL;
1914 	bdev_io->internal.io_submit_ch = NULL;
1915 	bdev_io->internal.orig_iovs = NULL;
1916 	bdev_io->internal.orig_iovcnt = 0;
1917 	bdev_io->internal.orig_md_buf = NULL;
1918 }
1919 
1920 static bool
1921 _spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
1922 {
1923 	return bdev->fn_table->io_type_supported(bdev->ctxt, io_type);
1924 }
1925 
1926 bool
1927 spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
1928 {
1929 	bool supported;
1930 
1931 	supported = _spdk_bdev_io_type_supported(bdev, io_type);
1932 
1933 	if (!supported) {
1934 		switch (io_type) {
1935 		case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
1936 			/* The bdev layer will emulate write zeroes as long as write is supported. */
1937 			supported = _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
1938 			break;
1939 		case SPDK_BDEV_IO_TYPE_ZCOPY:
1940 			/* Zero copy can be emulated with regular read and write */
1941 			supported = _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_READ) &&
1942 				    _spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
1943 			break;
1944 		default:
1945 			break;
1946 		}
1947 	}
1948 
1949 	return supported;
1950 }
1951 
1952 int
1953 spdk_bdev_dump_info_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
1954 {
1955 	if (bdev->fn_table->dump_info_json) {
1956 		return bdev->fn_table->dump_info_json(bdev->ctxt, w);
1957 	}
1958 
1959 	return 0;
1960 }
1961 
1962 static void
1963 spdk_bdev_qos_update_max_quota_per_timeslice(struct spdk_bdev_qos *qos)
1964 {
1965 	uint32_t max_per_timeslice = 0;
1966 	int i;
1967 
1968 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1969 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
1970 			qos->rate_limits[i].max_per_timeslice = 0;
1971 			continue;
1972 		}
1973 
1974 		max_per_timeslice = qos->rate_limits[i].limit *
1975 				    SPDK_BDEV_QOS_TIMESLICE_IN_USEC / SPDK_SEC_TO_USEC;
1976 
1977 		qos->rate_limits[i].max_per_timeslice = spdk_max(max_per_timeslice,
1978 							qos->rate_limits[i].min_per_timeslice);
1979 
1980 		qos->rate_limits[i].remaining_this_timeslice = qos->rate_limits[i].max_per_timeslice;
1981 	}
1982 
1983 	_spdk_bdev_qos_set_ops(qos);
1984 }
1985 
1986 static int
1987 spdk_bdev_channel_poll_qos(void *arg)
1988 {
1989 	struct spdk_bdev_qos *qos = arg;
1990 	uint64_t now = spdk_get_ticks();
1991 	int i;
1992 
1993 	if (now < (qos->last_timeslice + qos->timeslice_size)) {
1994 		/* We received our callback earlier than expected - return
1995 		 *  immediately and wait to do accounting until at least one
1996 		 *  timeslice has actually expired.  This should never happen
1997 		 *  with a well-behaved timer implementation.
1998 		 */
1999 		return 0;
2000 	}
2001 
2002 	/* Reset for next round of rate limiting */
2003 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2004 		/* We may have allowed the IOs or bytes to slightly overrun in the last
2005 		 * timeslice. remaining_this_timeslice is signed, so if it's negative
2006 		 * here, we'll account for the overrun so that the next timeslice will
2007 		 * be appropriately reduced.
2008 		 */
2009 		if (qos->rate_limits[i].remaining_this_timeslice > 0) {
2010 			qos->rate_limits[i].remaining_this_timeslice = 0;
2011 		}
2012 	}
2013 
2014 	while (now >= (qos->last_timeslice + qos->timeslice_size)) {
2015 		qos->last_timeslice += qos->timeslice_size;
2016 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2017 			qos->rate_limits[i].remaining_this_timeslice +=
2018 				qos->rate_limits[i].max_per_timeslice;
2019 		}
2020 	}
2021 
2022 	return _spdk_bdev_qos_io_submit(qos->ch, qos);
2023 }
2024 
2025 static void
2026 _spdk_bdev_channel_destroy_resource(struct spdk_bdev_channel *ch)
2027 {
2028 	struct spdk_bdev_shared_resource *shared_resource;
2029 
2030 	spdk_put_io_channel(ch->channel);
2031 
2032 	shared_resource = ch->shared_resource;
2033 
2034 	assert(ch->io_outstanding == 0);
2035 	assert(shared_resource->ref > 0);
2036 	shared_resource->ref--;
2037 	if (shared_resource->ref == 0) {
2038 		assert(shared_resource->io_outstanding == 0);
2039 		TAILQ_REMOVE(&shared_resource->mgmt_ch->shared_resources, shared_resource, link);
2040 		spdk_put_io_channel(spdk_io_channel_from_ctx(shared_resource->mgmt_ch));
2041 		free(shared_resource);
2042 	}
2043 }
2044 
2045 /* Caller must hold bdev->internal.mutex. */
2046 static void
2047 _spdk_bdev_enable_qos(struct spdk_bdev *bdev, struct spdk_bdev_channel *ch)
2048 {
2049 	struct spdk_bdev_qos	*qos = bdev->internal.qos;
2050 	int			i;
2051 
2052 	/* Rate limiting on this bdev enabled */
2053 	if (qos) {
2054 		if (qos->ch == NULL) {
2055 			struct spdk_io_channel *io_ch;
2056 
2057 			SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Selecting channel %p as QoS channel for bdev %s on thread %p\n", ch,
2058 				      bdev->name, spdk_get_thread());
2059 
2060 			/* No qos channel has been selected, so set one up */
2061 
2062 			/* Take another reference to ch */
2063 			io_ch = spdk_get_io_channel(__bdev_to_io_dev(bdev));
2064 			assert(io_ch != NULL);
2065 			qos->ch = ch;
2066 
2067 			qos->thread = spdk_io_channel_get_thread(io_ch);
2068 
2069 			TAILQ_INIT(&qos->queued);
2070 
2071 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2072 				if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
2073 					qos->rate_limits[i].min_per_timeslice =
2074 						SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE;
2075 				} else {
2076 					qos->rate_limits[i].min_per_timeslice =
2077 						SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE;
2078 				}
2079 
2080 				if (qos->rate_limits[i].limit == 0) {
2081 					qos->rate_limits[i].limit = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
2082 				}
2083 			}
2084 			spdk_bdev_qos_update_max_quota_per_timeslice(qos);
2085 			qos->timeslice_size =
2086 				SPDK_BDEV_QOS_TIMESLICE_IN_USEC * spdk_get_ticks_hz() / SPDK_SEC_TO_USEC;
2087 			qos->last_timeslice = spdk_get_ticks();
2088 			qos->poller = spdk_poller_register(spdk_bdev_channel_poll_qos,
2089 							   qos,
2090 							   SPDK_BDEV_QOS_TIMESLICE_IN_USEC);
2091 		}
2092 
2093 		ch->flags |= BDEV_CH_QOS_ENABLED;
2094 	}
2095 }
2096 
2097 static int
2098 spdk_bdev_channel_create(void *io_device, void *ctx_buf)
2099 {
2100 	struct spdk_bdev		*bdev = __bdev_from_io_dev(io_device);
2101 	struct spdk_bdev_channel	*ch = ctx_buf;
2102 	struct spdk_io_channel		*mgmt_io_ch;
2103 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
2104 	struct spdk_bdev_shared_resource *shared_resource;
2105 
2106 	ch->bdev = bdev;
2107 	ch->channel = bdev->fn_table->get_io_channel(bdev->ctxt);
2108 	if (!ch->channel) {
2109 		return -1;
2110 	}
2111 
2112 	assert(ch->histogram == NULL);
2113 	if (bdev->internal.histogram_enabled) {
2114 		ch->histogram = spdk_histogram_data_alloc();
2115 		if (ch->histogram == NULL) {
2116 			SPDK_ERRLOG("Could not allocate histogram\n");
2117 		}
2118 	}
2119 
2120 	mgmt_io_ch = spdk_get_io_channel(&g_bdev_mgr);
2121 	if (!mgmt_io_ch) {
2122 		spdk_put_io_channel(ch->channel);
2123 		return -1;
2124 	}
2125 
2126 	mgmt_ch = spdk_io_channel_get_ctx(mgmt_io_ch);
2127 	TAILQ_FOREACH(shared_resource, &mgmt_ch->shared_resources, link) {
2128 		if (shared_resource->shared_ch == ch->channel) {
2129 			spdk_put_io_channel(mgmt_io_ch);
2130 			shared_resource->ref++;
2131 			break;
2132 		}
2133 	}
2134 
2135 	if (shared_resource == NULL) {
2136 		shared_resource = calloc(1, sizeof(*shared_resource));
2137 		if (shared_resource == NULL) {
2138 			spdk_put_io_channel(ch->channel);
2139 			spdk_put_io_channel(mgmt_io_ch);
2140 			return -1;
2141 		}
2142 
2143 		shared_resource->mgmt_ch = mgmt_ch;
2144 		shared_resource->io_outstanding = 0;
2145 		TAILQ_INIT(&shared_resource->nomem_io);
2146 		shared_resource->nomem_threshold = 0;
2147 		shared_resource->shared_ch = ch->channel;
2148 		shared_resource->ref = 1;
2149 		TAILQ_INSERT_TAIL(&mgmt_ch->shared_resources, shared_resource, link);
2150 	}
2151 
2152 	memset(&ch->stat, 0, sizeof(ch->stat));
2153 	ch->stat.ticks_rate = spdk_get_ticks_hz();
2154 	ch->io_outstanding = 0;
2155 	TAILQ_INIT(&ch->queued_resets);
2156 	ch->flags = 0;
2157 	ch->shared_resource = shared_resource;
2158 
2159 #ifdef SPDK_CONFIG_VTUNE
2160 	{
2161 		char *name;
2162 		__itt_init_ittlib(NULL, 0);
2163 		name = spdk_sprintf_alloc("spdk_bdev_%s_%p", ch->bdev->name, ch);
2164 		if (!name) {
2165 			_spdk_bdev_channel_destroy_resource(ch);
2166 			return -1;
2167 		}
2168 		ch->handle = __itt_string_handle_create(name);
2169 		free(name);
2170 		ch->start_tsc = spdk_get_ticks();
2171 		ch->interval_tsc = spdk_get_ticks_hz() / 100;
2172 		memset(&ch->prev_stat, 0, sizeof(ch->prev_stat));
2173 	}
2174 #endif
2175 
2176 	pthread_mutex_lock(&bdev->internal.mutex);
2177 	_spdk_bdev_enable_qos(bdev, ch);
2178 	pthread_mutex_unlock(&bdev->internal.mutex);
2179 
2180 	return 0;
2181 }
2182 
2183 /*
2184  * Abort I/O that are waiting on a data buffer.  These types of I/O are
2185  *  linked using the spdk_bdev_io internal.buf_link TAILQ_ENTRY.
2186  */
2187 static void
2188 _spdk_bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_channel *ch)
2189 {
2190 	bdev_io_stailq_t tmp;
2191 	struct spdk_bdev_io *bdev_io;
2192 
2193 	STAILQ_INIT(&tmp);
2194 
2195 	while (!STAILQ_EMPTY(queue)) {
2196 		bdev_io = STAILQ_FIRST(queue);
2197 		STAILQ_REMOVE_HEAD(queue, internal.buf_link);
2198 		if (bdev_io->internal.ch == ch) {
2199 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2200 		} else {
2201 			STAILQ_INSERT_TAIL(&tmp, bdev_io, internal.buf_link);
2202 		}
2203 	}
2204 
2205 	STAILQ_SWAP(&tmp, queue, spdk_bdev_io);
2206 }
2207 
2208 /*
2209  * Abort I/O that are queued waiting for submission.  These types of I/O are
2210  *  linked using the spdk_bdev_io link TAILQ_ENTRY.
2211  */
2212 static void
2213 _spdk_bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_channel *ch)
2214 {
2215 	struct spdk_bdev_io *bdev_io, *tmp;
2216 
2217 	TAILQ_FOREACH_SAFE(bdev_io, queue, internal.link, tmp) {
2218 		if (bdev_io->internal.ch == ch) {
2219 			TAILQ_REMOVE(queue, bdev_io, internal.link);
2220 			/*
2221 			 * spdk_bdev_io_complete() assumes that the completed I/O had
2222 			 *  been submitted to the bdev module.  Since in this case it
2223 			 *  hadn't, bump io_outstanding to account for the decrement
2224 			 *  that spdk_bdev_io_complete() will do.
2225 			 */
2226 			if (bdev_io->type != SPDK_BDEV_IO_TYPE_RESET) {
2227 				ch->io_outstanding++;
2228 				ch->shared_resource->io_outstanding++;
2229 			}
2230 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2231 		}
2232 	}
2233 }
2234 
2235 static void
2236 spdk_bdev_qos_channel_destroy(void *cb_arg)
2237 {
2238 	struct spdk_bdev_qos *qos = cb_arg;
2239 
2240 	spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
2241 	spdk_poller_unregister(&qos->poller);
2242 
2243 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Free QoS %p.\n", qos);
2244 
2245 	free(qos);
2246 }
2247 
2248 static int
2249 spdk_bdev_qos_destroy(struct spdk_bdev *bdev)
2250 {
2251 	int i;
2252 
2253 	/*
2254 	 * Cleanly shutting down the QoS poller is tricky, because
2255 	 * during the asynchronous operation the user could open
2256 	 * a new descriptor and create a new channel, spawning
2257 	 * a new QoS poller.
2258 	 *
2259 	 * The strategy is to create a new QoS structure here and swap it
2260 	 * in. The shutdown path then continues to refer to the old one
2261 	 * until it completes and then releases it.
2262 	 */
2263 	struct spdk_bdev_qos *new_qos, *old_qos;
2264 
2265 	old_qos = bdev->internal.qos;
2266 
2267 	new_qos = calloc(1, sizeof(*new_qos));
2268 	if (!new_qos) {
2269 		SPDK_ERRLOG("Unable to allocate memory to shut down QoS.\n");
2270 		return -ENOMEM;
2271 	}
2272 
2273 	/* Copy the old QoS data into the newly allocated structure */
2274 	memcpy(new_qos, old_qos, sizeof(*new_qos));
2275 
2276 	/* Zero out the key parts of the QoS structure */
2277 	new_qos->ch = NULL;
2278 	new_qos->thread = NULL;
2279 	new_qos->poller = NULL;
2280 	TAILQ_INIT(&new_qos->queued);
2281 	/*
2282 	 * The limit member of spdk_bdev_qos_limit structure is not zeroed.
2283 	 * It will be used later for the new QoS structure.
2284 	 */
2285 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2286 		new_qos->rate_limits[i].remaining_this_timeslice = 0;
2287 		new_qos->rate_limits[i].min_per_timeslice = 0;
2288 		new_qos->rate_limits[i].max_per_timeslice = 0;
2289 	}
2290 
2291 	bdev->internal.qos = new_qos;
2292 
2293 	if (old_qos->thread == NULL) {
2294 		free(old_qos);
2295 	} else {
2296 		spdk_thread_send_msg(old_qos->thread, spdk_bdev_qos_channel_destroy,
2297 				     old_qos);
2298 	}
2299 
2300 	/* It is safe to continue with destroying the bdev even though the QoS channel hasn't
2301 	 * been destroyed yet. The destruction path will end up waiting for the final
2302 	 * channel to be put before it releases resources. */
2303 
2304 	return 0;
2305 }
2306 
2307 static void
2308 _spdk_bdev_io_stat_add(struct spdk_bdev_io_stat *total, struct spdk_bdev_io_stat *add)
2309 {
2310 	total->bytes_read += add->bytes_read;
2311 	total->num_read_ops += add->num_read_ops;
2312 	total->bytes_written += add->bytes_written;
2313 	total->num_write_ops += add->num_write_ops;
2314 	total->bytes_unmapped += add->bytes_unmapped;
2315 	total->num_unmap_ops += add->num_unmap_ops;
2316 	total->read_latency_ticks += add->read_latency_ticks;
2317 	total->write_latency_ticks += add->write_latency_ticks;
2318 	total->unmap_latency_ticks += add->unmap_latency_ticks;
2319 }
2320 
2321 static void
2322 spdk_bdev_channel_destroy(void *io_device, void *ctx_buf)
2323 {
2324 	struct spdk_bdev_channel	*ch = ctx_buf;
2325 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
2326 	struct spdk_bdev_shared_resource *shared_resource = ch->shared_resource;
2327 
2328 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Destroying channel %p for bdev %s on thread %p\n", ch, ch->bdev->name,
2329 		      spdk_get_thread());
2330 
2331 	/* This channel is going away, so add its statistics into the bdev so that they don't get lost. */
2332 	pthread_mutex_lock(&ch->bdev->internal.mutex);
2333 	_spdk_bdev_io_stat_add(&ch->bdev->internal.stat, &ch->stat);
2334 	pthread_mutex_unlock(&ch->bdev->internal.mutex);
2335 
2336 	mgmt_ch = shared_resource->mgmt_ch;
2337 
2338 	_spdk_bdev_abort_queued_io(&ch->queued_resets, ch);
2339 	_spdk_bdev_abort_queued_io(&shared_resource->nomem_io, ch);
2340 	_spdk_bdev_abort_buf_io(&mgmt_ch->need_buf_small, ch);
2341 	_spdk_bdev_abort_buf_io(&mgmt_ch->need_buf_large, ch);
2342 
2343 	if (ch->histogram) {
2344 		spdk_histogram_data_free(ch->histogram);
2345 	}
2346 
2347 	_spdk_bdev_channel_destroy_resource(ch);
2348 }
2349 
2350 int
2351 spdk_bdev_alias_add(struct spdk_bdev *bdev, const char *alias)
2352 {
2353 	struct spdk_bdev_alias *tmp;
2354 
2355 	if (alias == NULL) {
2356 		SPDK_ERRLOG("Empty alias passed\n");
2357 		return -EINVAL;
2358 	}
2359 
2360 	if (spdk_bdev_get_by_name(alias)) {
2361 		SPDK_ERRLOG("Bdev name/alias: %s already exists\n", alias);
2362 		return -EEXIST;
2363 	}
2364 
2365 	tmp = calloc(1, sizeof(*tmp));
2366 	if (tmp == NULL) {
2367 		SPDK_ERRLOG("Unable to allocate alias\n");
2368 		return -ENOMEM;
2369 	}
2370 
2371 	tmp->alias = strdup(alias);
2372 	if (tmp->alias == NULL) {
2373 		free(tmp);
2374 		SPDK_ERRLOG("Unable to allocate alias\n");
2375 		return -ENOMEM;
2376 	}
2377 
2378 	TAILQ_INSERT_TAIL(&bdev->aliases, tmp, tailq);
2379 
2380 	return 0;
2381 }
2382 
2383 int
2384 spdk_bdev_alias_del(struct spdk_bdev *bdev, const char *alias)
2385 {
2386 	struct spdk_bdev_alias *tmp;
2387 
2388 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
2389 		if (strcmp(alias, tmp->alias) == 0) {
2390 			TAILQ_REMOVE(&bdev->aliases, tmp, tailq);
2391 			free(tmp->alias);
2392 			free(tmp);
2393 			return 0;
2394 		}
2395 	}
2396 
2397 	SPDK_INFOLOG(SPDK_LOG_BDEV, "Alias %s does not exists\n", alias);
2398 
2399 	return -ENOENT;
2400 }
2401 
2402 void
2403 spdk_bdev_alias_del_all(struct spdk_bdev *bdev)
2404 {
2405 	struct spdk_bdev_alias *p, *tmp;
2406 
2407 	TAILQ_FOREACH_SAFE(p, &bdev->aliases, tailq, tmp) {
2408 		TAILQ_REMOVE(&bdev->aliases, p, tailq);
2409 		free(p->alias);
2410 		free(p);
2411 	}
2412 }
2413 
2414 struct spdk_io_channel *
2415 spdk_bdev_get_io_channel(struct spdk_bdev_desc *desc)
2416 {
2417 	return spdk_get_io_channel(__bdev_to_io_dev(spdk_bdev_desc_get_bdev(desc)));
2418 }
2419 
2420 const char *
2421 spdk_bdev_get_name(const struct spdk_bdev *bdev)
2422 {
2423 	return bdev->name;
2424 }
2425 
2426 const char *
2427 spdk_bdev_get_product_name(const struct spdk_bdev *bdev)
2428 {
2429 	return bdev->product_name;
2430 }
2431 
2432 const struct spdk_bdev_aliases_list *
2433 spdk_bdev_get_aliases(const struct spdk_bdev *bdev)
2434 {
2435 	return &bdev->aliases;
2436 }
2437 
2438 uint32_t
2439 spdk_bdev_get_block_size(const struct spdk_bdev *bdev)
2440 {
2441 	return bdev->blocklen;
2442 }
2443 
2444 uint32_t
2445 spdk_bdev_get_write_unit_size(const struct spdk_bdev *bdev)
2446 {
2447 	return bdev->write_unit_size;
2448 }
2449 
2450 uint64_t
2451 spdk_bdev_get_num_blocks(const struct spdk_bdev *bdev)
2452 {
2453 	return bdev->blockcnt;
2454 }
2455 
2456 const char *
2457 spdk_bdev_get_qos_rpc_type(enum spdk_bdev_qos_rate_limit_type type)
2458 {
2459 	return qos_rpc_type[type];
2460 }
2461 
2462 void
2463 spdk_bdev_get_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
2464 {
2465 	int i;
2466 
2467 	memset(limits, 0, sizeof(*limits) * SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
2468 
2469 	pthread_mutex_lock(&bdev->internal.mutex);
2470 	if (bdev->internal.qos) {
2471 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2472 			if (bdev->internal.qos->rate_limits[i].limit !=
2473 			    SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
2474 				limits[i] = bdev->internal.qos->rate_limits[i].limit;
2475 				if (_spdk_bdev_qos_is_iops_rate_limit(i) == false) {
2476 					/* Change from Byte to Megabyte which is user visible. */
2477 					limits[i] = limits[i] / 1024 / 1024;
2478 				}
2479 			}
2480 		}
2481 	}
2482 	pthread_mutex_unlock(&bdev->internal.mutex);
2483 }
2484 
2485 size_t
2486 spdk_bdev_get_buf_align(const struct spdk_bdev *bdev)
2487 {
2488 	return 1 << bdev->required_alignment;
2489 }
2490 
2491 uint32_t
2492 spdk_bdev_get_optimal_io_boundary(const struct spdk_bdev *bdev)
2493 {
2494 	return bdev->optimal_io_boundary;
2495 }
2496 
2497 bool
2498 spdk_bdev_has_write_cache(const struct spdk_bdev *bdev)
2499 {
2500 	return bdev->write_cache;
2501 }
2502 
2503 const struct spdk_uuid *
2504 spdk_bdev_get_uuid(const struct spdk_bdev *bdev)
2505 {
2506 	return &bdev->uuid;
2507 }
2508 
2509 uint32_t
2510 spdk_bdev_get_md_size(const struct spdk_bdev *bdev)
2511 {
2512 	return bdev->md_len;
2513 }
2514 
2515 bool
2516 spdk_bdev_is_md_interleaved(const struct spdk_bdev *bdev)
2517 {
2518 	return (bdev->md_len != 0) && bdev->md_interleave;
2519 }
2520 
2521 bool
2522 spdk_bdev_is_md_separate(const struct spdk_bdev *bdev)
2523 {
2524 	return (bdev->md_len != 0) && !bdev->md_interleave;
2525 }
2526 
2527 bool
2528 spdk_bdev_is_zoned(const struct spdk_bdev *bdev)
2529 {
2530 	return bdev->zoned;
2531 }
2532 
2533 uint32_t
2534 spdk_bdev_get_data_block_size(const struct spdk_bdev *bdev)
2535 {
2536 	if (spdk_bdev_is_md_interleaved(bdev)) {
2537 		return bdev->blocklen - bdev->md_len;
2538 	} else {
2539 		return bdev->blocklen;
2540 	}
2541 }
2542 
2543 static uint32_t
2544 _bdev_get_block_size_with_md(const struct spdk_bdev *bdev)
2545 {
2546 	if (!spdk_bdev_is_md_interleaved(bdev)) {
2547 		return bdev->blocklen + bdev->md_len;
2548 	} else {
2549 		return bdev->blocklen;
2550 	}
2551 }
2552 
2553 enum spdk_dif_type spdk_bdev_get_dif_type(const struct spdk_bdev *bdev)
2554 {
2555 	if (bdev->md_len != 0) {
2556 		return bdev->dif_type;
2557 	} else {
2558 		return SPDK_DIF_DISABLE;
2559 	}
2560 }
2561 
2562 bool
2563 spdk_bdev_is_dif_head_of_md(const struct spdk_bdev *bdev)
2564 {
2565 	if (spdk_bdev_get_dif_type(bdev) != SPDK_DIF_DISABLE) {
2566 		return bdev->dif_is_head_of_md;
2567 	} else {
2568 		return false;
2569 	}
2570 }
2571 
2572 bool
2573 spdk_bdev_is_dif_check_enabled(const struct spdk_bdev *bdev,
2574 			       enum spdk_dif_check_type check_type)
2575 {
2576 	if (spdk_bdev_get_dif_type(bdev) == SPDK_DIF_DISABLE) {
2577 		return false;
2578 	}
2579 
2580 	switch (check_type) {
2581 	case SPDK_DIF_CHECK_TYPE_REFTAG:
2582 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_REFTAG_CHECK) != 0;
2583 	case SPDK_DIF_CHECK_TYPE_APPTAG:
2584 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_APPTAG_CHECK) != 0;
2585 	case SPDK_DIF_CHECK_TYPE_GUARD:
2586 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_GUARD_CHECK) != 0;
2587 	default:
2588 		return false;
2589 	}
2590 }
2591 
2592 uint64_t
2593 spdk_bdev_get_qd(const struct spdk_bdev *bdev)
2594 {
2595 	return bdev->internal.measured_queue_depth;
2596 }
2597 
2598 uint64_t
2599 spdk_bdev_get_qd_sampling_period(const struct spdk_bdev *bdev)
2600 {
2601 	return bdev->internal.period;
2602 }
2603 
2604 uint64_t
2605 spdk_bdev_get_weighted_io_time(const struct spdk_bdev *bdev)
2606 {
2607 	return bdev->internal.weighted_io_time;
2608 }
2609 
2610 uint64_t
2611 spdk_bdev_get_io_time(const struct spdk_bdev *bdev)
2612 {
2613 	return bdev->internal.io_time;
2614 }
2615 
2616 static void
2617 _calculate_measured_qd_cpl(struct spdk_io_channel_iter *i, int status)
2618 {
2619 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
2620 
2621 	bdev->internal.measured_queue_depth = bdev->internal.temporary_queue_depth;
2622 
2623 	if (bdev->internal.measured_queue_depth) {
2624 		bdev->internal.io_time += bdev->internal.period;
2625 		bdev->internal.weighted_io_time += bdev->internal.period * bdev->internal.measured_queue_depth;
2626 	}
2627 }
2628 
2629 static void
2630 _calculate_measured_qd(struct spdk_io_channel_iter *i)
2631 {
2632 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
2633 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
2634 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(io_ch);
2635 
2636 	bdev->internal.temporary_queue_depth += ch->io_outstanding;
2637 	spdk_for_each_channel_continue(i, 0);
2638 }
2639 
2640 static int
2641 spdk_bdev_calculate_measured_queue_depth(void *ctx)
2642 {
2643 	struct spdk_bdev *bdev = ctx;
2644 	bdev->internal.temporary_queue_depth = 0;
2645 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _calculate_measured_qd, bdev,
2646 			      _calculate_measured_qd_cpl);
2647 	return 0;
2648 }
2649 
2650 void
2651 spdk_bdev_set_qd_sampling_period(struct spdk_bdev *bdev, uint64_t period)
2652 {
2653 	bdev->internal.period = period;
2654 
2655 	if (bdev->internal.qd_poller != NULL) {
2656 		spdk_poller_unregister(&bdev->internal.qd_poller);
2657 		bdev->internal.measured_queue_depth = UINT64_MAX;
2658 	}
2659 
2660 	if (period != 0) {
2661 		bdev->internal.qd_poller = spdk_poller_register(spdk_bdev_calculate_measured_queue_depth, bdev,
2662 					   period);
2663 	}
2664 }
2665 
2666 static void
2667 _spdk_bdev_desc_free(struct spdk_bdev_desc *desc)
2668 {
2669 	pthread_mutex_destroy(&desc->mutex);
2670 	free(desc);
2671 }
2672 
2673 static void
2674 _resize_notify(void *arg)
2675 {
2676 	struct spdk_bdev_desc *desc = arg;
2677 
2678 	pthread_mutex_lock(&desc->mutex);
2679 	desc->refs--;
2680 	if (!desc->closed) {
2681 		pthread_mutex_unlock(&desc->mutex);
2682 		desc->callback.event_fn(SPDK_BDEV_EVENT_RESIZE,
2683 					desc->bdev,
2684 					desc->callback.ctx);
2685 		return;
2686 	} else if (0 == desc->refs) {
2687 		/* This descriptor was closed after this resize_notify message was sent.
2688 		 * spdk_bdev_close() could not free the descriptor since this message was
2689 		 * in flight, so we free it now using _spdk_bdev_desc_free().
2690 		 */
2691 		pthread_mutex_unlock(&desc->mutex);
2692 		_spdk_bdev_desc_free(desc);
2693 		return;
2694 	}
2695 	pthread_mutex_unlock(&desc->mutex);
2696 }
2697 
2698 int
2699 spdk_bdev_notify_blockcnt_change(struct spdk_bdev *bdev, uint64_t size)
2700 {
2701 	struct spdk_bdev_desc *desc;
2702 	int ret;
2703 
2704 	pthread_mutex_lock(&bdev->internal.mutex);
2705 
2706 	/* bdev has open descriptors */
2707 	if (!TAILQ_EMPTY(&bdev->internal.open_descs) &&
2708 	    bdev->blockcnt > size) {
2709 		ret = -EBUSY;
2710 	} else {
2711 		bdev->blockcnt = size;
2712 		TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
2713 			pthread_mutex_lock(&desc->mutex);
2714 			if (desc->callback.open_with_ext && !desc->closed) {
2715 				desc->refs++;
2716 				spdk_thread_send_msg(desc->thread, _resize_notify, desc);
2717 			}
2718 			pthread_mutex_unlock(&desc->mutex);
2719 		}
2720 		ret = 0;
2721 	}
2722 
2723 	pthread_mutex_unlock(&bdev->internal.mutex);
2724 
2725 	return ret;
2726 }
2727 
2728 /*
2729  * Convert I/O offset and length from bytes to blocks.
2730  *
2731  * Returns zero on success or non-zero if the byte parameters aren't divisible by the block size.
2732  */
2733 static uint64_t
2734 spdk_bdev_bytes_to_blocks(struct spdk_bdev *bdev, uint64_t offset_bytes, uint64_t *offset_blocks,
2735 			  uint64_t num_bytes, uint64_t *num_blocks)
2736 {
2737 	uint32_t block_size = bdev->blocklen;
2738 	uint8_t shift_cnt;
2739 
2740 	/* Avoid expensive div operations if possible. These spdk_u32 functions are very cheap. */
2741 	if (spdk_likely(spdk_u32_is_pow2(block_size))) {
2742 		shift_cnt = spdk_u32log2(block_size);
2743 		*offset_blocks = offset_bytes >> shift_cnt;
2744 		*num_blocks = num_bytes >> shift_cnt;
2745 		return (offset_bytes - (*offset_blocks << shift_cnt)) |
2746 		       (num_bytes - (*num_blocks << shift_cnt));
2747 	} else {
2748 		*offset_blocks = offset_bytes / block_size;
2749 		*num_blocks = num_bytes / block_size;
2750 		return (offset_bytes % block_size) | (num_bytes % block_size);
2751 	}
2752 }
2753 
2754 static bool
2755 spdk_bdev_io_valid_blocks(struct spdk_bdev *bdev, uint64_t offset_blocks, uint64_t num_blocks)
2756 {
2757 	/* Return failure if offset_blocks + num_blocks is less than offset_blocks; indicates there
2758 	 * has been an overflow and hence the offset has been wrapped around */
2759 	if (offset_blocks + num_blocks < offset_blocks) {
2760 		return false;
2761 	}
2762 
2763 	/* Return failure if offset_blocks + num_blocks exceeds the size of the bdev */
2764 	if (offset_blocks + num_blocks > bdev->blockcnt) {
2765 		return false;
2766 	}
2767 
2768 	return true;
2769 }
2770 
2771 static bool
2772 _bdev_io_check_md_buf(const struct iovec *iovs, const void *md_buf)
2773 {
2774 	return _is_buf_allocated(iovs) == (md_buf != NULL);
2775 }
2776 
2777 static int
2778 _spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf,
2779 			       void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
2780 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2781 {
2782 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2783 	struct spdk_bdev_io *bdev_io;
2784 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2785 
2786 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2787 		return -EINVAL;
2788 	}
2789 
2790 	bdev_io = spdk_bdev_get_io(channel);
2791 	if (!bdev_io) {
2792 		return -ENOMEM;
2793 	}
2794 
2795 	bdev_io->internal.ch = channel;
2796 	bdev_io->internal.desc = desc;
2797 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
2798 	bdev_io->u.bdev.iovs = &bdev_io->iov;
2799 	bdev_io->u.bdev.iovs[0].iov_base = buf;
2800 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
2801 	bdev_io->u.bdev.iovcnt = 1;
2802 	bdev_io->u.bdev.md_buf = md_buf;
2803 	bdev_io->u.bdev.num_blocks = num_blocks;
2804 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2805 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2806 
2807 	spdk_bdev_io_submit(bdev_io);
2808 	return 0;
2809 }
2810 
2811 int
2812 spdk_bdev_read(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2813 	       void *buf, uint64_t offset, uint64_t nbytes,
2814 	       spdk_bdev_io_completion_cb cb, void *cb_arg)
2815 {
2816 	uint64_t offset_blocks, num_blocks;
2817 
2818 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2819 				      nbytes, &num_blocks) != 0) {
2820 		return -EINVAL;
2821 	}
2822 
2823 	return spdk_bdev_read_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
2824 }
2825 
2826 int
2827 spdk_bdev_read_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2828 		      void *buf, uint64_t offset_blocks, uint64_t num_blocks,
2829 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
2830 {
2831 	return _spdk_bdev_read_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
2832 					      cb, cb_arg);
2833 }
2834 
2835 int
2836 spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2837 			      void *buf, void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
2838 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
2839 {
2840 	struct iovec iov = {
2841 		.iov_base = buf,
2842 	};
2843 
2844 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
2845 		return -EINVAL;
2846 	}
2847 
2848 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
2849 		return -EINVAL;
2850 	}
2851 
2852 	return _spdk_bdev_read_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
2853 					      cb, cb_arg);
2854 }
2855 
2856 int
2857 spdk_bdev_readv(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2858 		struct iovec *iov, int iovcnt,
2859 		uint64_t offset, uint64_t nbytes,
2860 		spdk_bdev_io_completion_cb cb, void *cb_arg)
2861 {
2862 	uint64_t offset_blocks, num_blocks;
2863 
2864 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2865 				      nbytes, &num_blocks) != 0) {
2866 		return -EINVAL;
2867 	}
2868 
2869 	return spdk_bdev_readv_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
2870 }
2871 
2872 static int
2873 _spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2874 				struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
2875 				uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg)
2876 {
2877 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2878 	struct spdk_bdev_io *bdev_io;
2879 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2880 
2881 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2882 		return -EINVAL;
2883 	}
2884 
2885 	bdev_io = spdk_bdev_get_io(channel);
2886 	if (!bdev_io) {
2887 		return -ENOMEM;
2888 	}
2889 
2890 	bdev_io->internal.ch = channel;
2891 	bdev_io->internal.desc = desc;
2892 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
2893 	bdev_io->u.bdev.iovs = iov;
2894 	bdev_io->u.bdev.iovcnt = iovcnt;
2895 	bdev_io->u.bdev.md_buf = md_buf;
2896 	bdev_io->u.bdev.num_blocks = num_blocks;
2897 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2898 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2899 
2900 	spdk_bdev_io_submit(bdev_io);
2901 	return 0;
2902 }
2903 
2904 int spdk_bdev_readv_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2905 			   struct iovec *iov, int iovcnt,
2906 			   uint64_t offset_blocks, uint64_t num_blocks,
2907 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
2908 {
2909 	return _spdk_bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
2910 					       num_blocks, cb, cb_arg);
2911 }
2912 
2913 int
2914 spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2915 			       struct iovec *iov, int iovcnt, void *md_buf,
2916 			       uint64_t offset_blocks, uint64_t num_blocks,
2917 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2918 {
2919 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
2920 		return -EINVAL;
2921 	}
2922 
2923 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
2924 		return -EINVAL;
2925 	}
2926 
2927 	return _spdk_bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
2928 					       num_blocks, cb, cb_arg);
2929 }
2930 
2931 static int
2932 _spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2933 				void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
2934 				spdk_bdev_io_completion_cb cb, void *cb_arg)
2935 {
2936 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2937 	struct spdk_bdev_io *bdev_io;
2938 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
2939 
2940 	if (!desc->write) {
2941 		return -EBADF;
2942 	}
2943 
2944 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
2945 		return -EINVAL;
2946 	}
2947 
2948 	bdev_io = spdk_bdev_get_io(channel);
2949 	if (!bdev_io) {
2950 		return -ENOMEM;
2951 	}
2952 
2953 	bdev_io->internal.ch = channel;
2954 	bdev_io->internal.desc = desc;
2955 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
2956 	bdev_io->u.bdev.iovs = &bdev_io->iov;
2957 	bdev_io->u.bdev.iovs[0].iov_base = buf;
2958 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
2959 	bdev_io->u.bdev.iovcnt = 1;
2960 	bdev_io->u.bdev.md_buf = md_buf;
2961 	bdev_io->u.bdev.num_blocks = num_blocks;
2962 	bdev_io->u.bdev.offset_blocks = offset_blocks;
2963 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
2964 
2965 	spdk_bdev_io_submit(bdev_io);
2966 	return 0;
2967 }
2968 
2969 int
2970 spdk_bdev_write(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2971 		void *buf, uint64_t offset, uint64_t nbytes,
2972 		spdk_bdev_io_completion_cb cb, void *cb_arg)
2973 {
2974 	uint64_t offset_blocks, num_blocks;
2975 
2976 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
2977 				      nbytes, &num_blocks) != 0) {
2978 		return -EINVAL;
2979 	}
2980 
2981 	return spdk_bdev_write_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
2982 }
2983 
2984 int
2985 spdk_bdev_write_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2986 		       void *buf, uint64_t offset_blocks, uint64_t num_blocks,
2987 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
2988 {
2989 	return _spdk_bdev_write_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
2990 					       cb, cb_arg);
2991 }
2992 
2993 int
2994 spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
2995 			       void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
2996 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
2997 {
2998 	struct iovec iov = {
2999 		.iov_base = buf,
3000 	};
3001 
3002 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3003 		return -EINVAL;
3004 	}
3005 
3006 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
3007 		return -EINVAL;
3008 	}
3009 
3010 	return _spdk_bdev_write_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
3011 					       cb, cb_arg);
3012 }
3013 
3014 static int
3015 _spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3016 				 struct iovec *iov, int iovcnt, void *md_buf,
3017 				 uint64_t offset_blocks, uint64_t num_blocks,
3018 				 spdk_bdev_io_completion_cb cb, void *cb_arg)
3019 {
3020 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3021 	struct spdk_bdev_io *bdev_io;
3022 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3023 
3024 	if (!desc->write) {
3025 		return -EBADF;
3026 	}
3027 
3028 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3029 		return -EINVAL;
3030 	}
3031 
3032 	bdev_io = spdk_bdev_get_io(channel);
3033 	if (!bdev_io) {
3034 		return -ENOMEM;
3035 	}
3036 
3037 	bdev_io->internal.ch = channel;
3038 	bdev_io->internal.desc = desc;
3039 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3040 	bdev_io->u.bdev.iovs = iov;
3041 	bdev_io->u.bdev.iovcnt = iovcnt;
3042 	bdev_io->u.bdev.md_buf = md_buf;
3043 	bdev_io->u.bdev.num_blocks = num_blocks;
3044 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3045 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3046 
3047 	spdk_bdev_io_submit(bdev_io);
3048 	return 0;
3049 }
3050 
3051 int
3052 spdk_bdev_writev(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3053 		 struct iovec *iov, int iovcnt,
3054 		 uint64_t offset, uint64_t len,
3055 		 spdk_bdev_io_completion_cb cb, void *cb_arg)
3056 {
3057 	uint64_t offset_blocks, num_blocks;
3058 
3059 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3060 				      len, &num_blocks) != 0) {
3061 		return -EINVAL;
3062 	}
3063 
3064 	return spdk_bdev_writev_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
3065 }
3066 
3067 int
3068 spdk_bdev_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3069 			struct iovec *iov, int iovcnt,
3070 			uint64_t offset_blocks, uint64_t num_blocks,
3071 			spdk_bdev_io_completion_cb cb, void *cb_arg)
3072 {
3073 	return _spdk_bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
3074 						num_blocks, cb, cb_arg);
3075 }
3076 
3077 int
3078 spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3079 				struct iovec *iov, int iovcnt, void *md_buf,
3080 				uint64_t offset_blocks, uint64_t num_blocks,
3081 				spdk_bdev_io_completion_cb cb, void *cb_arg)
3082 {
3083 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3084 		return -EINVAL;
3085 	}
3086 
3087 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
3088 		return -EINVAL;
3089 	}
3090 
3091 	return _spdk_bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
3092 						num_blocks, cb, cb_arg);
3093 }
3094 
3095 static void
3096 bdev_zcopy_get_buf(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success)
3097 {
3098 	if (!success) {
3099 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3100 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NOMEM;
3101 		bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
3102 		return;
3103 	}
3104 
3105 	if (bdev_io->u.bdev.zcopy.populate) {
3106 		/* Read the real data into the buffer */
3107 		bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
3108 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3109 		spdk_bdev_io_submit(bdev_io);
3110 		return;
3111 	}
3112 
3113 	/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3114 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3115 	bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
3116 }
3117 
3118 int
3119 spdk_bdev_zcopy_start(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3120 		      uint64_t offset_blocks, uint64_t num_blocks,
3121 		      bool populate,
3122 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
3123 {
3124 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3125 	struct spdk_bdev_io *bdev_io;
3126 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3127 
3128 	if (!desc->write) {
3129 		return -EBADF;
3130 	}
3131 
3132 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3133 		return -EINVAL;
3134 	}
3135 
3136 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3137 		return -ENOTSUP;
3138 	}
3139 
3140 	bdev_io = spdk_bdev_get_io(channel);
3141 	if (!bdev_io) {
3142 		return -ENOMEM;
3143 	}
3144 
3145 	bdev_io->internal.ch = channel;
3146 	bdev_io->internal.desc = desc;
3147 	bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
3148 	bdev_io->u.bdev.num_blocks = num_blocks;
3149 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3150 	bdev_io->u.bdev.iovs = NULL;
3151 	bdev_io->u.bdev.iovcnt = 0;
3152 	bdev_io->u.bdev.zcopy.populate = populate ? 1 : 0;
3153 	bdev_io->u.bdev.zcopy.commit = 0;
3154 	bdev_io->u.bdev.zcopy.start = 1;
3155 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3156 
3157 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3158 		spdk_bdev_io_submit(bdev_io);
3159 	} else {
3160 		/* Emulate zcopy by allocating a buffer */
3161 		spdk_bdev_io_get_buf(bdev_io, bdev_zcopy_get_buf,
3162 				     bdev_io->u.bdev.num_blocks * bdev->blocklen);
3163 	}
3164 
3165 	return 0;
3166 }
3167 
3168 int
3169 spdk_bdev_zcopy_end(struct spdk_bdev_io *bdev_io, bool commit,
3170 		    spdk_bdev_io_completion_cb cb, void *cb_arg)
3171 {
3172 	struct spdk_bdev *bdev = bdev_io->bdev;
3173 
3174 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
3175 		/* This can happen if the zcopy was emulated in start */
3176 		if (bdev_io->u.bdev.zcopy.start != 1) {
3177 			return -EINVAL;
3178 		}
3179 		bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
3180 	}
3181 
3182 	if (bdev_io->type != SPDK_BDEV_IO_TYPE_ZCOPY) {
3183 		return -EINVAL;
3184 	}
3185 
3186 	bdev_io->u.bdev.zcopy.commit = commit ? 1 : 0;
3187 	bdev_io->u.bdev.zcopy.start = 0;
3188 	bdev_io->internal.caller_ctx = cb_arg;
3189 	bdev_io->internal.cb = cb;
3190 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3191 
3192 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
3193 		spdk_bdev_io_submit(bdev_io);
3194 		return 0;
3195 	}
3196 
3197 	if (!bdev_io->u.bdev.zcopy.commit) {
3198 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
3199 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3200 		bdev_io->internal.cb(bdev_io, true, bdev_io->internal.caller_ctx);
3201 		return 0;
3202 	}
3203 
3204 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3205 	spdk_bdev_io_submit(bdev_io);
3206 
3207 	return 0;
3208 }
3209 
3210 int
3211 spdk_bdev_write_zeroes(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3212 		       uint64_t offset, uint64_t len,
3213 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3214 {
3215 	uint64_t offset_blocks, num_blocks;
3216 
3217 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3218 				      len, &num_blocks) != 0) {
3219 		return -EINVAL;
3220 	}
3221 
3222 	return spdk_bdev_write_zeroes_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3223 }
3224 
3225 int
3226 spdk_bdev_write_zeroes_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3227 			      uint64_t offset_blocks, uint64_t num_blocks,
3228 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3229 {
3230 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3231 	struct spdk_bdev_io *bdev_io;
3232 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3233 
3234 	if (!desc->write) {
3235 		return -EBADF;
3236 	}
3237 
3238 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3239 		return -EINVAL;
3240 	}
3241 
3242 	if (!_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES) &&
3243 	    !_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE)) {
3244 		return -ENOTSUP;
3245 	}
3246 
3247 	bdev_io = spdk_bdev_get_io(channel);
3248 
3249 	if (!bdev_io) {
3250 		return -ENOMEM;
3251 	}
3252 
3253 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE_ZEROES;
3254 	bdev_io->internal.ch = channel;
3255 	bdev_io->internal.desc = desc;
3256 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3257 	bdev_io->u.bdev.num_blocks = num_blocks;
3258 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3259 
3260 	if (_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES)) {
3261 		spdk_bdev_io_submit(bdev_io);
3262 		return 0;
3263 	}
3264 
3265 	assert(_spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE));
3266 	assert(_bdev_get_block_size_with_md(bdev) <= ZERO_BUFFER_SIZE);
3267 	bdev_io->u.bdev.split_remaining_num_blocks = num_blocks;
3268 	bdev_io->u.bdev.split_current_offset_blocks = offset_blocks;
3269 	_spdk_bdev_write_zero_buffer_next(bdev_io);
3270 
3271 	return 0;
3272 }
3273 
3274 int
3275 spdk_bdev_unmap(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3276 		uint64_t offset, uint64_t nbytes,
3277 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3278 {
3279 	uint64_t offset_blocks, num_blocks;
3280 
3281 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3282 				      nbytes, &num_blocks) != 0) {
3283 		return -EINVAL;
3284 	}
3285 
3286 	return spdk_bdev_unmap_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3287 }
3288 
3289 int
3290 spdk_bdev_unmap_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3291 		       uint64_t offset_blocks, uint64_t num_blocks,
3292 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3293 {
3294 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3295 	struct spdk_bdev_io *bdev_io;
3296 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3297 
3298 	if (!desc->write) {
3299 		return -EBADF;
3300 	}
3301 
3302 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3303 		return -EINVAL;
3304 	}
3305 
3306 	if (num_blocks == 0) {
3307 		SPDK_ERRLOG("Can't unmap 0 bytes\n");
3308 		return -EINVAL;
3309 	}
3310 
3311 	bdev_io = spdk_bdev_get_io(channel);
3312 	if (!bdev_io) {
3313 		return -ENOMEM;
3314 	}
3315 
3316 	bdev_io->internal.ch = channel;
3317 	bdev_io->internal.desc = desc;
3318 	bdev_io->type = SPDK_BDEV_IO_TYPE_UNMAP;
3319 
3320 	bdev_io->u.bdev.iovs = &bdev_io->iov;
3321 	bdev_io->u.bdev.iovs[0].iov_base = NULL;
3322 	bdev_io->u.bdev.iovs[0].iov_len = 0;
3323 	bdev_io->u.bdev.iovcnt = 1;
3324 
3325 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3326 	bdev_io->u.bdev.num_blocks = num_blocks;
3327 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3328 
3329 	spdk_bdev_io_submit(bdev_io);
3330 	return 0;
3331 }
3332 
3333 int
3334 spdk_bdev_flush(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3335 		uint64_t offset, uint64_t length,
3336 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3337 {
3338 	uint64_t offset_blocks, num_blocks;
3339 
3340 	if (spdk_bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3341 				      length, &num_blocks) != 0) {
3342 		return -EINVAL;
3343 	}
3344 
3345 	return spdk_bdev_flush_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
3346 }
3347 
3348 int
3349 spdk_bdev_flush_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3350 		       uint64_t offset_blocks, uint64_t num_blocks,
3351 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3352 {
3353 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3354 	struct spdk_bdev_io *bdev_io;
3355 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3356 
3357 	if (!desc->write) {
3358 		return -EBADF;
3359 	}
3360 
3361 	if (!spdk_bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3362 		return -EINVAL;
3363 	}
3364 
3365 	bdev_io = spdk_bdev_get_io(channel);
3366 	if (!bdev_io) {
3367 		return -ENOMEM;
3368 	}
3369 
3370 	bdev_io->internal.ch = channel;
3371 	bdev_io->internal.desc = desc;
3372 	bdev_io->type = SPDK_BDEV_IO_TYPE_FLUSH;
3373 	bdev_io->u.bdev.iovs = NULL;
3374 	bdev_io->u.bdev.iovcnt = 0;
3375 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3376 	bdev_io->u.bdev.num_blocks = num_blocks;
3377 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3378 
3379 	spdk_bdev_io_submit(bdev_io);
3380 	return 0;
3381 }
3382 
3383 static void
3384 _spdk_bdev_reset_dev(struct spdk_io_channel_iter *i, int status)
3385 {
3386 	struct spdk_bdev_channel *ch = spdk_io_channel_iter_get_ctx(i);
3387 	struct spdk_bdev_io *bdev_io;
3388 
3389 	bdev_io = TAILQ_FIRST(&ch->queued_resets);
3390 	TAILQ_REMOVE(&ch->queued_resets, bdev_io, internal.link);
3391 	spdk_bdev_io_submit_reset(bdev_io);
3392 }
3393 
3394 static void
3395 _spdk_bdev_reset_freeze_channel(struct spdk_io_channel_iter *i)
3396 {
3397 	struct spdk_io_channel		*ch;
3398 	struct spdk_bdev_channel	*channel;
3399 	struct spdk_bdev_mgmt_channel	*mgmt_channel;
3400 	struct spdk_bdev_shared_resource *shared_resource;
3401 	bdev_io_tailq_t			tmp_queued;
3402 
3403 	TAILQ_INIT(&tmp_queued);
3404 
3405 	ch = spdk_io_channel_iter_get_channel(i);
3406 	channel = spdk_io_channel_get_ctx(ch);
3407 	shared_resource = channel->shared_resource;
3408 	mgmt_channel = shared_resource->mgmt_ch;
3409 
3410 	channel->flags |= BDEV_CH_RESET_IN_PROGRESS;
3411 
3412 	if ((channel->flags & BDEV_CH_QOS_ENABLED) != 0) {
3413 		/* The QoS object is always valid and readable while
3414 		 * the channel flag is set, so the lock here should not
3415 		 * be necessary. We're not in the fast path though, so
3416 		 * just take it anyway. */
3417 		pthread_mutex_lock(&channel->bdev->internal.mutex);
3418 		if (channel->bdev->internal.qos->ch == channel) {
3419 			TAILQ_SWAP(&channel->bdev->internal.qos->queued, &tmp_queued, spdk_bdev_io, internal.link);
3420 		}
3421 		pthread_mutex_unlock(&channel->bdev->internal.mutex);
3422 	}
3423 
3424 	_spdk_bdev_abort_queued_io(&shared_resource->nomem_io, channel);
3425 	_spdk_bdev_abort_buf_io(&mgmt_channel->need_buf_small, channel);
3426 	_spdk_bdev_abort_buf_io(&mgmt_channel->need_buf_large, channel);
3427 	_spdk_bdev_abort_queued_io(&tmp_queued, channel);
3428 
3429 	spdk_for_each_channel_continue(i, 0);
3430 }
3431 
3432 static void
3433 _spdk_bdev_start_reset(void *ctx)
3434 {
3435 	struct spdk_bdev_channel *ch = ctx;
3436 
3437 	spdk_for_each_channel(__bdev_to_io_dev(ch->bdev), _spdk_bdev_reset_freeze_channel,
3438 			      ch, _spdk_bdev_reset_dev);
3439 }
3440 
3441 static void
3442 _spdk_bdev_channel_start_reset(struct spdk_bdev_channel *ch)
3443 {
3444 	struct spdk_bdev *bdev = ch->bdev;
3445 
3446 	assert(!TAILQ_EMPTY(&ch->queued_resets));
3447 
3448 	pthread_mutex_lock(&bdev->internal.mutex);
3449 	if (bdev->internal.reset_in_progress == NULL) {
3450 		bdev->internal.reset_in_progress = TAILQ_FIRST(&ch->queued_resets);
3451 		/*
3452 		 * Take a channel reference for the target bdev for the life of this
3453 		 *  reset.  This guards against the channel getting destroyed while
3454 		 *  spdk_for_each_channel() calls related to this reset IO are in
3455 		 *  progress.  We will release the reference when this reset is
3456 		 *  completed.
3457 		 */
3458 		bdev->internal.reset_in_progress->u.reset.ch_ref = spdk_get_io_channel(__bdev_to_io_dev(bdev));
3459 		_spdk_bdev_start_reset(ch);
3460 	}
3461 	pthread_mutex_unlock(&bdev->internal.mutex);
3462 }
3463 
3464 int
3465 spdk_bdev_reset(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3466 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3467 {
3468 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3469 	struct spdk_bdev_io *bdev_io;
3470 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3471 
3472 	bdev_io = spdk_bdev_get_io(channel);
3473 	if (!bdev_io) {
3474 		return -ENOMEM;
3475 	}
3476 
3477 	bdev_io->internal.ch = channel;
3478 	bdev_io->internal.desc = desc;
3479 	bdev_io->type = SPDK_BDEV_IO_TYPE_RESET;
3480 	bdev_io->u.reset.ch_ref = NULL;
3481 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3482 
3483 	pthread_mutex_lock(&bdev->internal.mutex);
3484 	TAILQ_INSERT_TAIL(&channel->queued_resets, bdev_io, internal.link);
3485 	pthread_mutex_unlock(&bdev->internal.mutex);
3486 
3487 	_spdk_bdev_channel_start_reset(channel);
3488 
3489 	return 0;
3490 }
3491 
3492 void
3493 spdk_bdev_get_io_stat(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
3494 		      struct spdk_bdev_io_stat *stat)
3495 {
3496 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3497 
3498 	*stat = channel->stat;
3499 }
3500 
3501 static void
3502 _spdk_bdev_get_device_stat_done(struct spdk_io_channel_iter *i, int status)
3503 {
3504 	void *io_device = spdk_io_channel_iter_get_io_device(i);
3505 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
3506 
3507 	bdev_iostat_ctx->cb(__bdev_from_io_dev(io_device), bdev_iostat_ctx->stat,
3508 			    bdev_iostat_ctx->cb_arg, 0);
3509 	free(bdev_iostat_ctx);
3510 }
3511 
3512 static void
3513 _spdk_bdev_get_each_channel_stat(struct spdk_io_channel_iter *i)
3514 {
3515 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
3516 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
3517 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3518 
3519 	_spdk_bdev_io_stat_add(bdev_iostat_ctx->stat, &channel->stat);
3520 	spdk_for_each_channel_continue(i, 0);
3521 }
3522 
3523 void
3524 spdk_bdev_get_device_stat(struct spdk_bdev *bdev, struct spdk_bdev_io_stat *stat,
3525 			  spdk_bdev_get_device_stat_cb cb, void *cb_arg)
3526 {
3527 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx;
3528 
3529 	assert(bdev != NULL);
3530 	assert(stat != NULL);
3531 	assert(cb != NULL);
3532 
3533 	bdev_iostat_ctx = calloc(1, sizeof(struct spdk_bdev_iostat_ctx));
3534 	if (bdev_iostat_ctx == NULL) {
3535 		SPDK_ERRLOG("Unable to allocate memory for spdk_bdev_iostat_ctx\n");
3536 		cb(bdev, stat, cb_arg, -ENOMEM);
3537 		return;
3538 	}
3539 
3540 	bdev_iostat_ctx->stat = stat;
3541 	bdev_iostat_ctx->cb = cb;
3542 	bdev_iostat_ctx->cb_arg = cb_arg;
3543 
3544 	/* Start with the statistics from previously deleted channels. */
3545 	pthread_mutex_lock(&bdev->internal.mutex);
3546 	_spdk_bdev_io_stat_add(bdev_iostat_ctx->stat, &bdev->internal.stat);
3547 	pthread_mutex_unlock(&bdev->internal.mutex);
3548 
3549 	/* Then iterate and add the statistics from each existing channel. */
3550 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
3551 			      _spdk_bdev_get_each_channel_stat,
3552 			      bdev_iostat_ctx,
3553 			      _spdk_bdev_get_device_stat_done);
3554 }
3555 
3556 int
3557 spdk_bdev_nvme_admin_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3558 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
3559 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3560 {
3561 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3562 	struct spdk_bdev_io *bdev_io;
3563 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3564 
3565 	if (!desc->write) {
3566 		return -EBADF;
3567 	}
3568 
3569 	bdev_io = spdk_bdev_get_io(channel);
3570 	if (!bdev_io) {
3571 		return -ENOMEM;
3572 	}
3573 
3574 	bdev_io->internal.ch = channel;
3575 	bdev_io->internal.desc = desc;
3576 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_ADMIN;
3577 	bdev_io->u.nvme_passthru.cmd = *cmd;
3578 	bdev_io->u.nvme_passthru.buf = buf;
3579 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3580 	bdev_io->u.nvme_passthru.md_buf = NULL;
3581 	bdev_io->u.nvme_passthru.md_len = 0;
3582 
3583 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3584 
3585 	spdk_bdev_io_submit(bdev_io);
3586 	return 0;
3587 }
3588 
3589 int
3590 spdk_bdev_nvme_io_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3591 			   const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
3592 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
3593 {
3594 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3595 	struct spdk_bdev_io *bdev_io;
3596 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3597 
3598 	if (!desc->write) {
3599 		/*
3600 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
3601 		 *  to easily determine if the command is a read or write, but for now just
3602 		 *  do not allow io_passthru with a read-only descriptor.
3603 		 */
3604 		return -EBADF;
3605 	}
3606 
3607 	bdev_io = spdk_bdev_get_io(channel);
3608 	if (!bdev_io) {
3609 		return -ENOMEM;
3610 	}
3611 
3612 	bdev_io->internal.ch = channel;
3613 	bdev_io->internal.desc = desc;
3614 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO;
3615 	bdev_io->u.nvme_passthru.cmd = *cmd;
3616 	bdev_io->u.nvme_passthru.buf = buf;
3617 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3618 	bdev_io->u.nvme_passthru.md_buf = NULL;
3619 	bdev_io->u.nvme_passthru.md_len = 0;
3620 
3621 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3622 
3623 	spdk_bdev_io_submit(bdev_io);
3624 	return 0;
3625 }
3626 
3627 int
3628 spdk_bdev_nvme_io_passthru_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3629 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes, void *md_buf, size_t md_len,
3630 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3631 {
3632 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3633 	struct spdk_bdev_io *bdev_io;
3634 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3635 
3636 	if (!desc->write) {
3637 		/*
3638 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
3639 		 *  to easily determine if the command is a read or write, but for now just
3640 		 *  do not allow io_passthru with a read-only descriptor.
3641 		 */
3642 		return -EBADF;
3643 	}
3644 
3645 	bdev_io = spdk_bdev_get_io(channel);
3646 	if (!bdev_io) {
3647 		return -ENOMEM;
3648 	}
3649 
3650 	bdev_io->internal.ch = channel;
3651 	bdev_io->internal.desc = desc;
3652 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO_MD;
3653 	bdev_io->u.nvme_passthru.cmd = *cmd;
3654 	bdev_io->u.nvme_passthru.buf = buf;
3655 	bdev_io->u.nvme_passthru.nbytes = nbytes;
3656 	bdev_io->u.nvme_passthru.md_buf = md_buf;
3657 	bdev_io->u.nvme_passthru.md_len = md_len;
3658 
3659 	spdk_bdev_io_init(bdev_io, bdev, cb_arg, cb);
3660 
3661 	spdk_bdev_io_submit(bdev_io);
3662 	return 0;
3663 }
3664 
3665 int
3666 spdk_bdev_queue_io_wait(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
3667 			struct spdk_bdev_io_wait_entry *entry)
3668 {
3669 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3670 	struct spdk_bdev_mgmt_channel *mgmt_ch = channel->shared_resource->mgmt_ch;
3671 
3672 	if (bdev != entry->bdev) {
3673 		SPDK_ERRLOG("bdevs do not match\n");
3674 		return -EINVAL;
3675 	}
3676 
3677 	if (mgmt_ch->per_thread_cache_count > 0) {
3678 		SPDK_ERRLOG("Cannot queue io_wait if spdk_bdev_io available in per-thread cache\n");
3679 		return -EINVAL;
3680 	}
3681 
3682 	TAILQ_INSERT_TAIL(&mgmt_ch->io_wait_queue, entry, link);
3683 	return 0;
3684 }
3685 
3686 static void
3687 _spdk_bdev_ch_retry_io(struct spdk_bdev_channel *bdev_ch)
3688 {
3689 	struct spdk_bdev *bdev = bdev_ch->bdev;
3690 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
3691 	struct spdk_bdev_io *bdev_io;
3692 
3693 	if (shared_resource->io_outstanding > shared_resource->nomem_threshold) {
3694 		/*
3695 		 * Allow some more I/O to complete before retrying the nomem_io queue.
3696 		 *  Some drivers (such as nvme) cannot immediately take a new I/O in
3697 		 *  the context of a completion, because the resources for the I/O are
3698 		 *  not released until control returns to the bdev poller.  Also, we
3699 		 *  may require several small I/O to complete before a larger I/O
3700 		 *  (that requires splitting) can be submitted.
3701 		 */
3702 		return;
3703 	}
3704 
3705 	while (!TAILQ_EMPTY(&shared_resource->nomem_io)) {
3706 		bdev_io = TAILQ_FIRST(&shared_resource->nomem_io);
3707 		TAILQ_REMOVE(&shared_resource->nomem_io, bdev_io, internal.link);
3708 		bdev_io->internal.ch->io_outstanding++;
3709 		shared_resource->io_outstanding++;
3710 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
3711 		bdev->fn_table->submit_request(spdk_bdev_io_get_io_channel(bdev_io), bdev_io);
3712 		if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
3713 			break;
3714 		}
3715 	}
3716 }
3717 
3718 static inline void
3719 _spdk_bdev_io_complete(void *ctx)
3720 {
3721 	struct spdk_bdev_io *bdev_io = ctx;
3722 	uint64_t tsc, tsc_diff;
3723 
3724 	if (spdk_unlikely(bdev_io->internal.in_submit_request || bdev_io->internal.io_submit_ch)) {
3725 		/*
3726 		 * Send the completion to the thread that originally submitted the I/O,
3727 		 * which may not be the current thread in the case of QoS.
3728 		 */
3729 		if (bdev_io->internal.io_submit_ch) {
3730 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
3731 			bdev_io->internal.io_submit_ch = NULL;
3732 		}
3733 
3734 		/*
3735 		 * Defer completion to avoid potential infinite recursion if the
3736 		 * user's completion callback issues a new I/O.
3737 		 */
3738 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
3739 				     _spdk_bdev_io_complete, bdev_io);
3740 		return;
3741 	}
3742 
3743 	tsc = spdk_get_ticks();
3744 	tsc_diff = tsc - bdev_io->internal.submit_tsc;
3745 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io, 0);
3746 
3747 	if (bdev_io->internal.ch->histogram) {
3748 		spdk_histogram_data_tally(bdev_io->internal.ch->histogram, tsc_diff);
3749 	}
3750 
3751 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
3752 		switch (bdev_io->type) {
3753 		case SPDK_BDEV_IO_TYPE_READ:
3754 			bdev_io->internal.ch->stat.bytes_read += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3755 			bdev_io->internal.ch->stat.num_read_ops++;
3756 			bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
3757 			break;
3758 		case SPDK_BDEV_IO_TYPE_WRITE:
3759 			bdev_io->internal.ch->stat.bytes_written += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3760 			bdev_io->internal.ch->stat.num_write_ops++;
3761 			bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
3762 			break;
3763 		case SPDK_BDEV_IO_TYPE_UNMAP:
3764 			bdev_io->internal.ch->stat.bytes_unmapped += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
3765 			bdev_io->internal.ch->stat.num_unmap_ops++;
3766 			bdev_io->internal.ch->stat.unmap_latency_ticks += tsc_diff;
3767 		default:
3768 			break;
3769 		}
3770 	}
3771 
3772 #ifdef SPDK_CONFIG_VTUNE
3773 	uint64_t now_tsc = spdk_get_ticks();
3774 	if (now_tsc > (bdev_io->internal.ch->start_tsc + bdev_io->internal.ch->interval_tsc)) {
3775 		uint64_t data[5];
3776 
3777 		data[0] = bdev_io->internal.ch->stat.num_read_ops - bdev_io->internal.ch->prev_stat.num_read_ops;
3778 		data[1] = bdev_io->internal.ch->stat.bytes_read - bdev_io->internal.ch->prev_stat.bytes_read;
3779 		data[2] = bdev_io->internal.ch->stat.num_write_ops - bdev_io->internal.ch->prev_stat.num_write_ops;
3780 		data[3] = bdev_io->internal.ch->stat.bytes_written - bdev_io->internal.ch->prev_stat.bytes_written;
3781 		data[4] = bdev_io->bdev->fn_table->get_spin_time ?
3782 			  bdev_io->bdev->fn_table->get_spin_time(spdk_bdev_io_get_io_channel(bdev_io)) : 0;
3783 
3784 		__itt_metadata_add(g_bdev_mgr.domain, __itt_null, bdev_io->internal.ch->handle,
3785 				   __itt_metadata_u64, 5, data);
3786 
3787 		bdev_io->internal.ch->prev_stat = bdev_io->internal.ch->stat;
3788 		bdev_io->internal.ch->start_tsc = now_tsc;
3789 	}
3790 #endif
3791 
3792 	assert(bdev_io->internal.cb != NULL);
3793 	assert(spdk_get_thread() == spdk_bdev_io_get_thread(bdev_io));
3794 
3795 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
3796 			     bdev_io->internal.caller_ctx);
3797 }
3798 
3799 static void
3800 _spdk_bdev_reset_complete(struct spdk_io_channel_iter *i, int status)
3801 {
3802 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
3803 
3804 	if (bdev_io->u.reset.ch_ref != NULL) {
3805 		spdk_put_io_channel(bdev_io->u.reset.ch_ref);
3806 		bdev_io->u.reset.ch_ref = NULL;
3807 	}
3808 
3809 	_spdk_bdev_io_complete(bdev_io);
3810 }
3811 
3812 static void
3813 _spdk_bdev_unfreeze_channel(struct spdk_io_channel_iter *i)
3814 {
3815 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
3816 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
3817 
3818 	ch->flags &= ~BDEV_CH_RESET_IN_PROGRESS;
3819 	if (!TAILQ_EMPTY(&ch->queued_resets)) {
3820 		_spdk_bdev_channel_start_reset(ch);
3821 	}
3822 
3823 	spdk_for_each_channel_continue(i, 0);
3824 }
3825 
3826 void
3827 spdk_bdev_io_complete(struct spdk_bdev_io *bdev_io, enum spdk_bdev_io_status status)
3828 {
3829 	struct spdk_bdev *bdev = bdev_io->bdev;
3830 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
3831 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
3832 
3833 	bdev_io->internal.status = status;
3834 
3835 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_RESET)) {
3836 		bool unlock_channels = false;
3837 
3838 		if (status == SPDK_BDEV_IO_STATUS_NOMEM) {
3839 			SPDK_ERRLOG("NOMEM returned for reset\n");
3840 		}
3841 		pthread_mutex_lock(&bdev->internal.mutex);
3842 		if (bdev_io == bdev->internal.reset_in_progress) {
3843 			bdev->internal.reset_in_progress = NULL;
3844 			unlock_channels = true;
3845 		}
3846 		pthread_mutex_unlock(&bdev->internal.mutex);
3847 
3848 		if (unlock_channels) {
3849 			spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_unfreeze_channel,
3850 					      bdev_io, _spdk_bdev_reset_complete);
3851 			return;
3852 		}
3853 	} else {
3854 		_bdev_io_unset_bounce_buf(bdev_io);
3855 
3856 		assert(bdev_ch->io_outstanding > 0);
3857 		assert(shared_resource->io_outstanding > 0);
3858 		bdev_ch->io_outstanding--;
3859 		shared_resource->io_outstanding--;
3860 
3861 		if (spdk_unlikely(status == SPDK_BDEV_IO_STATUS_NOMEM)) {
3862 			TAILQ_INSERT_HEAD(&shared_resource->nomem_io, bdev_io, internal.link);
3863 			/*
3864 			 * Wait for some of the outstanding I/O to complete before we
3865 			 *  retry any of the nomem_io.  Normally we will wait for
3866 			 *  NOMEM_THRESHOLD_COUNT I/O to complete but for low queue
3867 			 *  depth channels we will instead wait for half to complete.
3868 			 */
3869 			shared_resource->nomem_threshold = spdk_max((int64_t)shared_resource->io_outstanding / 2,
3870 							   (int64_t)shared_resource->io_outstanding - NOMEM_THRESHOLD_COUNT);
3871 			return;
3872 		}
3873 
3874 		if (spdk_unlikely(!TAILQ_EMPTY(&shared_resource->nomem_io))) {
3875 			_spdk_bdev_ch_retry_io(bdev_ch);
3876 		}
3877 	}
3878 
3879 	_spdk_bdev_io_complete(bdev_io);
3880 }
3881 
3882 void
3883 spdk_bdev_io_complete_scsi_status(struct spdk_bdev_io *bdev_io, enum spdk_scsi_status sc,
3884 				  enum spdk_scsi_sense sk, uint8_t asc, uint8_t ascq)
3885 {
3886 	if (sc == SPDK_SCSI_STATUS_GOOD) {
3887 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3888 	} else {
3889 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SCSI_ERROR;
3890 		bdev_io->internal.error.scsi.sc = sc;
3891 		bdev_io->internal.error.scsi.sk = sk;
3892 		bdev_io->internal.error.scsi.asc = asc;
3893 		bdev_io->internal.error.scsi.ascq = ascq;
3894 	}
3895 
3896 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
3897 }
3898 
3899 void
3900 spdk_bdev_io_get_scsi_status(const struct spdk_bdev_io *bdev_io,
3901 			     int *sc, int *sk, int *asc, int *ascq)
3902 {
3903 	assert(sc != NULL);
3904 	assert(sk != NULL);
3905 	assert(asc != NULL);
3906 	assert(ascq != NULL);
3907 
3908 	switch (bdev_io->internal.status) {
3909 	case SPDK_BDEV_IO_STATUS_SUCCESS:
3910 		*sc = SPDK_SCSI_STATUS_GOOD;
3911 		*sk = SPDK_SCSI_SENSE_NO_SENSE;
3912 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
3913 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
3914 		break;
3915 	case SPDK_BDEV_IO_STATUS_NVME_ERROR:
3916 		spdk_scsi_nvme_translate(bdev_io, sc, sk, asc, ascq);
3917 		break;
3918 	case SPDK_BDEV_IO_STATUS_SCSI_ERROR:
3919 		*sc = bdev_io->internal.error.scsi.sc;
3920 		*sk = bdev_io->internal.error.scsi.sk;
3921 		*asc = bdev_io->internal.error.scsi.asc;
3922 		*ascq = bdev_io->internal.error.scsi.ascq;
3923 		break;
3924 	default:
3925 		*sc = SPDK_SCSI_STATUS_CHECK_CONDITION;
3926 		*sk = SPDK_SCSI_SENSE_ABORTED_COMMAND;
3927 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
3928 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
3929 		break;
3930 	}
3931 }
3932 
3933 void
3934 spdk_bdev_io_complete_nvme_status(struct spdk_bdev_io *bdev_io, int sct, int sc)
3935 {
3936 	if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_SUCCESS) {
3937 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3938 	} else {
3939 		bdev_io->internal.error.nvme.sct = sct;
3940 		bdev_io->internal.error.nvme.sc = sc;
3941 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NVME_ERROR;
3942 	}
3943 
3944 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
3945 }
3946 
3947 void
3948 spdk_bdev_io_get_nvme_status(const struct spdk_bdev_io *bdev_io, int *sct, int *sc)
3949 {
3950 	assert(sct != NULL);
3951 	assert(sc != NULL);
3952 
3953 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
3954 		*sct = bdev_io->internal.error.nvme.sct;
3955 		*sc = bdev_io->internal.error.nvme.sc;
3956 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
3957 		*sct = SPDK_NVME_SCT_GENERIC;
3958 		*sc = SPDK_NVME_SC_SUCCESS;
3959 	} else {
3960 		*sct = SPDK_NVME_SCT_GENERIC;
3961 		*sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3962 	}
3963 }
3964 
3965 struct spdk_thread *
3966 spdk_bdev_io_get_thread(struct spdk_bdev_io *bdev_io)
3967 {
3968 	return spdk_io_channel_get_thread(bdev_io->internal.ch->channel);
3969 }
3970 
3971 struct spdk_io_channel *
3972 spdk_bdev_io_get_io_channel(struct spdk_bdev_io *bdev_io)
3973 {
3974 	return bdev_io->internal.ch->channel;
3975 }
3976 
3977 static void
3978 _spdk_bdev_qos_config_limit(struct spdk_bdev *bdev, uint64_t *limits)
3979 {
3980 	uint64_t	min_qos_set;
3981 	int		i;
3982 
3983 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3984 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3985 			break;
3986 		}
3987 	}
3988 
3989 	if (i == SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES) {
3990 		SPDK_ERRLOG("Invalid rate limits set.\n");
3991 		return;
3992 	}
3993 
3994 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3995 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3996 			continue;
3997 		}
3998 
3999 		if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
4000 			min_qos_set = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
4001 		} else {
4002 			min_qos_set = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
4003 		}
4004 
4005 		if (limits[i] == 0 || limits[i] % min_qos_set) {
4006 			SPDK_ERRLOG("Assigned limit %" PRIu64 " on bdev %s is not multiple of %" PRIu64 "\n",
4007 				    limits[i], bdev->name, min_qos_set);
4008 			SPDK_ERRLOG("Failed to enable QoS on this bdev %s\n", bdev->name);
4009 			return;
4010 		}
4011 	}
4012 
4013 	if (!bdev->internal.qos) {
4014 		bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
4015 		if (!bdev->internal.qos) {
4016 			SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
4017 			return;
4018 		}
4019 	}
4020 
4021 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4022 		bdev->internal.qos->rate_limits[i].limit = limits[i];
4023 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Bdev:%s QoS type:%d set:%lu\n",
4024 			      bdev->name, i, limits[i]);
4025 	}
4026 
4027 	return;
4028 }
4029 
4030 static void
4031 _spdk_bdev_qos_config(struct spdk_bdev *bdev)
4032 {
4033 	struct spdk_conf_section	*sp = NULL;
4034 	const char			*val = NULL;
4035 	int				i = 0, j = 0;
4036 	uint64_t			limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES] = {};
4037 	bool				config_qos = false;
4038 
4039 	sp = spdk_conf_find_section(NULL, "QoS");
4040 	if (!sp) {
4041 		return;
4042 	}
4043 
4044 	while (j < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES) {
4045 		limits[j] = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
4046 
4047 		i = 0;
4048 		while (true) {
4049 			val = spdk_conf_section_get_nmval(sp, qos_conf_type[j], i, 0);
4050 			if (!val) {
4051 				break;
4052 			}
4053 
4054 			if (strcmp(bdev->name, val) != 0) {
4055 				i++;
4056 				continue;
4057 			}
4058 
4059 			val = spdk_conf_section_get_nmval(sp, qos_conf_type[j], i, 1);
4060 			if (val) {
4061 				if (_spdk_bdev_qos_is_iops_rate_limit(j) == true) {
4062 					limits[j] = strtoull(val, NULL, 10);
4063 				} else {
4064 					limits[j] = strtoull(val, NULL, 10) * 1024 * 1024;
4065 				}
4066 				config_qos = true;
4067 			}
4068 
4069 			break;
4070 		}
4071 
4072 		j++;
4073 	}
4074 
4075 	if (config_qos == true) {
4076 		_spdk_bdev_qos_config_limit(bdev, limits);
4077 	}
4078 
4079 	return;
4080 }
4081 
4082 static int
4083 spdk_bdev_init(struct spdk_bdev *bdev)
4084 {
4085 	char *bdev_name;
4086 
4087 	assert(bdev->module != NULL);
4088 
4089 	if (!bdev->name) {
4090 		SPDK_ERRLOG("Bdev name is NULL\n");
4091 		return -EINVAL;
4092 	}
4093 
4094 	if (!strlen(bdev->name)) {
4095 		SPDK_ERRLOG("Bdev name must not be an empty string\n");
4096 		return -EINVAL;
4097 	}
4098 
4099 	if (spdk_bdev_get_by_name(bdev->name)) {
4100 		SPDK_ERRLOG("Bdev name:%s already exists\n", bdev->name);
4101 		return -EEXIST;
4102 	}
4103 
4104 	/* Users often register their own I/O devices using the bdev name. In
4105 	 * order to avoid conflicts, prepend bdev_. */
4106 	bdev_name = spdk_sprintf_alloc("bdev_%s", bdev->name);
4107 	if (!bdev_name) {
4108 		SPDK_ERRLOG("Unable to allocate memory for internal bdev name.\n");
4109 		return -ENOMEM;
4110 	}
4111 
4112 	bdev->internal.status = SPDK_BDEV_STATUS_READY;
4113 	bdev->internal.measured_queue_depth = UINT64_MAX;
4114 	bdev->internal.claim_module = NULL;
4115 	bdev->internal.qd_poller = NULL;
4116 	bdev->internal.qos = NULL;
4117 
4118 	/* If the user didn't specify a uuid, generate one. */
4119 	if (spdk_mem_all_zero(&bdev->uuid, sizeof(bdev->uuid))) {
4120 		spdk_uuid_generate(&bdev->uuid);
4121 	}
4122 
4123 	if (spdk_bdev_get_buf_align(bdev) > 1) {
4124 		if (bdev->split_on_optimal_io_boundary) {
4125 			bdev->optimal_io_boundary = spdk_min(bdev->optimal_io_boundary,
4126 							     SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen);
4127 		} else {
4128 			bdev->split_on_optimal_io_boundary = true;
4129 			bdev->optimal_io_boundary = SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen;
4130 		}
4131 	}
4132 
4133 	/* If the user didn't specify a write unit size, set it to one. */
4134 	if (bdev->write_unit_size == 0) {
4135 		bdev->write_unit_size = 1;
4136 	}
4137 
4138 	TAILQ_INIT(&bdev->internal.open_descs);
4139 
4140 	TAILQ_INIT(&bdev->aliases);
4141 
4142 	bdev->internal.reset_in_progress = NULL;
4143 
4144 	_spdk_bdev_qos_config(bdev);
4145 
4146 	spdk_io_device_register(__bdev_to_io_dev(bdev),
4147 				spdk_bdev_channel_create, spdk_bdev_channel_destroy,
4148 				sizeof(struct spdk_bdev_channel),
4149 				bdev_name);
4150 
4151 	free(bdev_name);
4152 
4153 	pthread_mutex_init(&bdev->internal.mutex, NULL);
4154 	return 0;
4155 }
4156 
4157 static void
4158 spdk_bdev_destroy_cb(void *io_device)
4159 {
4160 	int			rc;
4161 	struct spdk_bdev	*bdev;
4162 	spdk_bdev_unregister_cb	cb_fn;
4163 	void			*cb_arg;
4164 
4165 	bdev = __bdev_from_io_dev(io_device);
4166 	cb_fn = bdev->internal.unregister_cb;
4167 	cb_arg = bdev->internal.unregister_ctx;
4168 
4169 	rc = bdev->fn_table->destruct(bdev->ctxt);
4170 	if (rc < 0) {
4171 		SPDK_ERRLOG("destruct failed\n");
4172 	}
4173 	if (rc <= 0 && cb_fn != NULL) {
4174 		cb_fn(cb_arg, rc);
4175 	}
4176 }
4177 
4178 
4179 static void
4180 spdk_bdev_fini(struct spdk_bdev *bdev)
4181 {
4182 	pthread_mutex_destroy(&bdev->internal.mutex);
4183 
4184 	free(bdev->internal.qos);
4185 
4186 	spdk_io_device_unregister(__bdev_to_io_dev(bdev), spdk_bdev_destroy_cb);
4187 }
4188 
4189 static void
4190 spdk_bdev_start(struct spdk_bdev *bdev)
4191 {
4192 	struct spdk_bdev_module *module;
4193 	uint32_t action;
4194 
4195 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Inserting bdev %s into list\n", bdev->name);
4196 	TAILQ_INSERT_TAIL(&g_bdev_mgr.bdevs, bdev, internal.link);
4197 
4198 	/* Examine configuration before initializing I/O */
4199 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4200 		if (module->examine_config) {
4201 			action = module->internal.action_in_progress;
4202 			module->internal.action_in_progress++;
4203 			module->examine_config(bdev);
4204 			if (action != module->internal.action_in_progress) {
4205 				SPDK_ERRLOG("examine_config for module %s did not call spdk_bdev_module_examine_done()\n",
4206 					    module->name);
4207 			}
4208 		}
4209 	}
4210 
4211 	if (bdev->internal.claim_module) {
4212 		if (bdev->internal.claim_module->examine_disk) {
4213 			bdev->internal.claim_module->internal.action_in_progress++;
4214 			bdev->internal.claim_module->examine_disk(bdev);
4215 		}
4216 		return;
4217 	}
4218 
4219 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4220 		if (module->examine_disk) {
4221 			module->internal.action_in_progress++;
4222 			module->examine_disk(bdev);
4223 		}
4224 	}
4225 }
4226 
4227 int
4228 spdk_bdev_register(struct spdk_bdev *bdev)
4229 {
4230 	int rc = spdk_bdev_init(bdev);
4231 
4232 	if (rc == 0) {
4233 		spdk_bdev_start(bdev);
4234 	}
4235 
4236 	spdk_notify_send("bdev_register", spdk_bdev_get_name(bdev));
4237 	return rc;
4238 }
4239 
4240 int
4241 spdk_vbdev_register(struct spdk_bdev *vbdev, struct spdk_bdev **base_bdevs, int base_bdev_count)
4242 {
4243 	SPDK_ERRLOG("This function is deprecated.  Use spdk_bdev_register() instead.\n");
4244 	return spdk_bdev_register(vbdev);
4245 }
4246 
4247 void
4248 spdk_bdev_destruct_done(struct spdk_bdev *bdev, int bdeverrno)
4249 {
4250 	if (bdev->internal.unregister_cb != NULL) {
4251 		bdev->internal.unregister_cb(bdev->internal.unregister_ctx, bdeverrno);
4252 	}
4253 }
4254 
4255 static void
4256 _remove_notify(void *arg)
4257 {
4258 	struct spdk_bdev_desc *desc = arg;
4259 
4260 	pthread_mutex_lock(&desc->mutex);
4261 	desc->refs--;
4262 
4263 	if (!desc->closed) {
4264 		pthread_mutex_unlock(&desc->mutex);
4265 		if (desc->callback.open_with_ext) {
4266 			desc->callback.event_fn(SPDK_BDEV_EVENT_REMOVE, desc->bdev, desc->callback.ctx);
4267 		} else {
4268 			desc->callback.remove_fn(desc->callback.ctx);
4269 		}
4270 		return;
4271 	} else if (0 == desc->refs) {
4272 		/* This descriptor was closed after this remove_notify message was sent.
4273 		 * spdk_bdev_close() could not free the descriptor since this message was
4274 		 * in flight, so we free it now using _spdk_bdev_desc_free().
4275 		 */
4276 		pthread_mutex_unlock(&desc->mutex);
4277 		_spdk_bdev_desc_free(desc);
4278 		return;
4279 	}
4280 	pthread_mutex_unlock(&desc->mutex);
4281 }
4282 
4283 /* Must be called while holding bdev->internal.mutex.
4284  * returns: 0 - bdev removed and ready to be destructed.
4285  *          -EBUSY - bdev can't be destructed yet.  */
4286 static int
4287 spdk_bdev_unregister_unsafe(struct spdk_bdev *bdev)
4288 {
4289 	struct spdk_bdev_desc	*desc, *tmp;
4290 	int			rc = 0;
4291 
4292 	/* Notify each descriptor about hotremoval */
4293 	TAILQ_FOREACH_SAFE(desc, &bdev->internal.open_descs, link, tmp) {
4294 		rc = -EBUSY;
4295 		pthread_mutex_lock(&desc->mutex);
4296 		/*
4297 		 * Defer invocation of the event_cb to a separate message that will
4298 		 *  run later on its thread.  This ensures this context unwinds and
4299 		 *  we don't recursively unregister this bdev again if the event_cb
4300 		 *  immediately closes its descriptor.
4301 		 */
4302 		desc->refs++;
4303 		spdk_thread_send_msg(desc->thread, _remove_notify, desc);
4304 		pthread_mutex_unlock(&desc->mutex);
4305 	}
4306 
4307 	/* If there are no descriptors, proceed removing the bdev */
4308 	if (rc == 0) {
4309 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
4310 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Removing bdev %s from list done\n", bdev->name);
4311 		spdk_notify_send("bdev_unregister", spdk_bdev_get_name(bdev));
4312 	}
4313 
4314 	return rc;
4315 }
4316 
4317 void
4318 spdk_bdev_unregister(struct spdk_bdev *bdev, spdk_bdev_unregister_cb cb_fn, void *cb_arg)
4319 {
4320 	struct spdk_thread	*thread;
4321 	int			rc;
4322 
4323 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Removing bdev %s from list\n", bdev->name);
4324 
4325 	thread = spdk_get_thread();
4326 	if (!thread) {
4327 		/* The user called this from a non-SPDK thread. */
4328 		if (cb_fn != NULL) {
4329 			cb_fn(cb_arg, -ENOTSUP);
4330 		}
4331 		return;
4332 	}
4333 
4334 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4335 	pthread_mutex_lock(&bdev->internal.mutex);
4336 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
4337 		pthread_mutex_unlock(&bdev->internal.mutex);
4338 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4339 		if (cb_fn) {
4340 			cb_fn(cb_arg, -EBUSY);
4341 		}
4342 		return;
4343 	}
4344 
4345 	bdev->internal.status = SPDK_BDEV_STATUS_REMOVING;
4346 	bdev->internal.unregister_cb = cb_fn;
4347 	bdev->internal.unregister_ctx = cb_arg;
4348 
4349 	/* Call under lock. */
4350 	rc = spdk_bdev_unregister_unsafe(bdev);
4351 	pthread_mutex_unlock(&bdev->internal.mutex);
4352 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4353 
4354 	if (rc == 0) {
4355 		spdk_bdev_fini(bdev);
4356 	}
4357 }
4358 
4359 static void
4360 _spdk_bdev_dummy_event_cb(void *remove_ctx)
4361 {
4362 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Bdev remove event received with no remove callback specified");
4363 }
4364 
4365 static int
4366 _spdk_bdev_open(struct spdk_bdev *bdev, bool write, struct spdk_bdev_desc *desc)
4367 {
4368 	struct spdk_thread *thread;
4369 	struct set_qos_limit_ctx *ctx;
4370 
4371 	thread = spdk_get_thread();
4372 	if (!thread) {
4373 		SPDK_ERRLOG("Cannot open bdev from non-SPDK thread.\n");
4374 		return -ENOTSUP;
4375 	}
4376 
4377 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Opening descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
4378 		      spdk_get_thread());
4379 
4380 	desc->bdev = bdev;
4381 	desc->thread = thread;
4382 	desc->write = write;
4383 
4384 	pthread_mutex_lock(&bdev->internal.mutex);
4385 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
4386 		pthread_mutex_unlock(&bdev->internal.mutex);
4387 		return -ENODEV;
4388 	}
4389 
4390 	if (write && bdev->internal.claim_module) {
4391 		SPDK_ERRLOG("Could not open %s - %s module already claimed it\n",
4392 			    bdev->name, bdev->internal.claim_module->name);
4393 		pthread_mutex_unlock(&bdev->internal.mutex);
4394 		return -EPERM;
4395 	}
4396 
4397 	/* Enable QoS */
4398 	if (bdev->internal.qos && bdev->internal.qos->thread == NULL) {
4399 		ctx = calloc(1, sizeof(*ctx));
4400 		if (ctx == NULL) {
4401 			SPDK_ERRLOG("Failed to allocate memory for QoS context\n");
4402 			pthread_mutex_unlock(&bdev->internal.mutex);
4403 			return -ENOMEM;
4404 		}
4405 		ctx->bdev = bdev;
4406 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
4407 				      _spdk_bdev_enable_qos_msg, ctx,
4408 				      _spdk_bdev_enable_qos_done);
4409 	}
4410 
4411 	TAILQ_INSERT_TAIL(&bdev->internal.open_descs, desc, link);
4412 
4413 	pthread_mutex_unlock(&bdev->internal.mutex);
4414 
4415 	return 0;
4416 }
4417 
4418 int
4419 spdk_bdev_open(struct spdk_bdev *bdev, bool write, spdk_bdev_remove_cb_t remove_cb,
4420 	       void *remove_ctx, struct spdk_bdev_desc **_desc)
4421 {
4422 	struct spdk_bdev_desc *desc;
4423 	int rc;
4424 
4425 	desc = calloc(1, sizeof(*desc));
4426 	if (desc == NULL) {
4427 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
4428 		return -ENOMEM;
4429 	}
4430 
4431 	if (remove_cb == NULL) {
4432 		remove_cb = _spdk_bdev_dummy_event_cb;
4433 	}
4434 
4435 	desc->callback.open_with_ext = false;
4436 	desc->callback.remove_fn = remove_cb;
4437 	desc->callback.ctx = remove_ctx;
4438 	pthread_mutex_init(&desc->mutex, NULL);
4439 
4440 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4441 
4442 	rc = _spdk_bdev_open(bdev, write, desc);
4443 	if (rc != 0) {
4444 		_spdk_bdev_desc_free(desc);
4445 		desc = NULL;
4446 	}
4447 
4448 	*_desc = desc;
4449 
4450 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4451 
4452 	return rc;
4453 }
4454 
4455 int
4456 spdk_bdev_open_ext(const char *bdev_name, bool write, spdk_bdev_event_cb_t event_cb,
4457 		   void *event_ctx, struct spdk_bdev_desc **_desc)
4458 {
4459 	struct spdk_bdev_desc *desc;
4460 	struct spdk_bdev *bdev;
4461 	int rc;
4462 
4463 	if (event_cb == NULL) {
4464 		SPDK_ERRLOG("Missing event callback function\n");
4465 		return -EINVAL;
4466 	}
4467 
4468 	pthread_mutex_lock(&g_bdev_mgr.mutex);
4469 
4470 	bdev = spdk_bdev_get_by_name(bdev_name);
4471 
4472 	if (bdev == NULL) {
4473 		SPDK_ERRLOG("Failed to find bdev with name: %s\n", bdev_name);
4474 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4475 		return -EINVAL;
4476 	}
4477 
4478 	desc = calloc(1, sizeof(*desc));
4479 	if (desc == NULL) {
4480 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
4481 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
4482 		return -ENOMEM;
4483 	}
4484 
4485 	desc->callback.open_with_ext = true;
4486 	desc->callback.event_fn = event_cb;
4487 	desc->callback.ctx = event_ctx;
4488 	pthread_mutex_init(&desc->mutex, NULL);
4489 
4490 	rc = _spdk_bdev_open(bdev, write, desc);
4491 	if (rc != 0) {
4492 		_spdk_bdev_desc_free(desc);
4493 		desc = NULL;
4494 	}
4495 
4496 	*_desc = desc;
4497 
4498 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
4499 
4500 	return rc;
4501 }
4502 
4503 void
4504 spdk_bdev_close(struct spdk_bdev_desc *desc)
4505 {
4506 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4507 	int rc;
4508 
4509 	SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Closing descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
4510 		      spdk_get_thread());
4511 
4512 	assert(desc->thread == spdk_get_thread());
4513 
4514 	pthread_mutex_lock(&bdev->internal.mutex);
4515 	pthread_mutex_lock(&desc->mutex);
4516 
4517 	TAILQ_REMOVE(&bdev->internal.open_descs, desc, link);
4518 
4519 	desc->closed = true;
4520 
4521 	if (0 == desc->refs) {
4522 		pthread_mutex_unlock(&desc->mutex);
4523 		_spdk_bdev_desc_free(desc);
4524 	} else {
4525 		pthread_mutex_unlock(&desc->mutex);
4526 	}
4527 
4528 	/* If no more descriptors, kill QoS channel */
4529 	if (bdev->internal.qos && TAILQ_EMPTY(&bdev->internal.open_descs)) {
4530 		SPDK_DEBUGLOG(SPDK_LOG_BDEV, "Closed last descriptor for bdev %s on thread %p. Stopping QoS.\n",
4531 			      bdev->name, spdk_get_thread());
4532 
4533 		if (spdk_bdev_qos_destroy(bdev)) {
4534 			/* There isn't anything we can do to recover here. Just let the
4535 			 * old QoS poller keep running. The QoS handling won't change
4536 			 * cores when the user allocates a new channel, but it won't break. */
4537 			SPDK_ERRLOG("Unable to shut down QoS poller. It will continue running on the current thread.\n");
4538 		}
4539 	}
4540 
4541 	spdk_bdev_set_qd_sampling_period(bdev, 0);
4542 
4543 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING && TAILQ_EMPTY(&bdev->internal.open_descs)) {
4544 		rc = spdk_bdev_unregister_unsafe(bdev);
4545 		pthread_mutex_unlock(&bdev->internal.mutex);
4546 
4547 		if (rc == 0) {
4548 			spdk_bdev_fini(bdev);
4549 		}
4550 	} else {
4551 		pthread_mutex_unlock(&bdev->internal.mutex);
4552 	}
4553 }
4554 
4555 int
4556 spdk_bdev_module_claim_bdev(struct spdk_bdev *bdev, struct spdk_bdev_desc *desc,
4557 			    struct spdk_bdev_module *module)
4558 {
4559 	if (bdev->internal.claim_module != NULL) {
4560 		SPDK_ERRLOG("bdev %s already claimed by module %s\n", bdev->name,
4561 			    bdev->internal.claim_module->name);
4562 		return -EPERM;
4563 	}
4564 
4565 	if (desc && !desc->write) {
4566 		desc->write = true;
4567 	}
4568 
4569 	bdev->internal.claim_module = module;
4570 	return 0;
4571 }
4572 
4573 void
4574 spdk_bdev_module_release_bdev(struct spdk_bdev *bdev)
4575 {
4576 	assert(bdev->internal.claim_module != NULL);
4577 	bdev->internal.claim_module = NULL;
4578 }
4579 
4580 struct spdk_bdev *
4581 spdk_bdev_desc_get_bdev(struct spdk_bdev_desc *desc)
4582 {
4583 	assert(desc != NULL);
4584 	return desc->bdev;
4585 }
4586 
4587 void
4588 spdk_bdev_io_get_iovec(struct spdk_bdev_io *bdev_io, struct iovec **iovp, int *iovcntp)
4589 {
4590 	struct iovec *iovs;
4591 	int iovcnt;
4592 
4593 	if (bdev_io == NULL) {
4594 		return;
4595 	}
4596 
4597 	switch (bdev_io->type) {
4598 	case SPDK_BDEV_IO_TYPE_READ:
4599 	case SPDK_BDEV_IO_TYPE_WRITE:
4600 	case SPDK_BDEV_IO_TYPE_ZCOPY:
4601 		iovs = bdev_io->u.bdev.iovs;
4602 		iovcnt = bdev_io->u.bdev.iovcnt;
4603 		break;
4604 	default:
4605 		iovs = NULL;
4606 		iovcnt = 0;
4607 		break;
4608 	}
4609 
4610 	if (iovp) {
4611 		*iovp = iovs;
4612 	}
4613 	if (iovcntp) {
4614 		*iovcntp = iovcnt;
4615 	}
4616 }
4617 
4618 void *
4619 spdk_bdev_io_get_md_buf(struct spdk_bdev_io *bdev_io)
4620 {
4621 	if (bdev_io == NULL) {
4622 		return NULL;
4623 	}
4624 
4625 	if (!spdk_bdev_is_md_separate(bdev_io->bdev)) {
4626 		return NULL;
4627 	}
4628 
4629 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ ||
4630 	    bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
4631 		return bdev_io->u.bdev.md_buf;
4632 	}
4633 
4634 	return NULL;
4635 }
4636 
4637 void
4638 spdk_bdev_module_list_add(struct spdk_bdev_module *bdev_module)
4639 {
4640 
4641 	if (spdk_bdev_module_list_find(bdev_module->name)) {
4642 		SPDK_ERRLOG("ERROR: module '%s' already registered.\n", bdev_module->name);
4643 		assert(false);
4644 	}
4645 
4646 	/*
4647 	 * Modules with examine callbacks must be initialized first, so they are
4648 	 *  ready to handle examine callbacks from later modules that will
4649 	 *  register physical bdevs.
4650 	 */
4651 	if (bdev_module->examine_config != NULL || bdev_module->examine_disk != NULL) {
4652 		TAILQ_INSERT_HEAD(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
4653 	} else {
4654 		TAILQ_INSERT_TAIL(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
4655 	}
4656 }
4657 
4658 struct spdk_bdev_module *
4659 spdk_bdev_module_list_find(const char *name)
4660 {
4661 	struct spdk_bdev_module *bdev_module;
4662 
4663 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
4664 		if (strcmp(name, bdev_module->name) == 0) {
4665 			break;
4666 		}
4667 	}
4668 
4669 	return bdev_module;
4670 }
4671 
4672 static void
4673 _spdk_bdev_write_zero_buffer_next(void *_bdev_io)
4674 {
4675 	struct spdk_bdev_io *bdev_io = _bdev_io;
4676 	uint64_t num_bytes, num_blocks;
4677 	void *md_buf = NULL;
4678 	int rc;
4679 
4680 	num_bytes = spdk_min(_bdev_get_block_size_with_md(bdev_io->bdev) *
4681 			     bdev_io->u.bdev.split_remaining_num_blocks,
4682 			     ZERO_BUFFER_SIZE);
4683 	num_blocks = num_bytes / _bdev_get_block_size_with_md(bdev_io->bdev);
4684 
4685 	if (spdk_bdev_is_md_separate(bdev_io->bdev)) {
4686 		md_buf = (char *)g_bdev_mgr.zero_buffer +
4687 			 spdk_bdev_get_block_size(bdev_io->bdev) * num_blocks;
4688 	}
4689 
4690 	rc = _spdk_bdev_write_blocks_with_md(bdev_io->internal.desc,
4691 					     spdk_io_channel_from_ctx(bdev_io->internal.ch),
4692 					     g_bdev_mgr.zero_buffer, md_buf,
4693 					     bdev_io->u.bdev.split_current_offset_blocks, num_blocks,
4694 					     _spdk_bdev_write_zero_buffer_done, bdev_io);
4695 	if (rc == 0) {
4696 		bdev_io->u.bdev.split_remaining_num_blocks -= num_blocks;
4697 		bdev_io->u.bdev.split_current_offset_blocks += num_blocks;
4698 	} else if (rc == -ENOMEM) {
4699 		_spdk_bdev_queue_io_wait_with_cb(bdev_io, _spdk_bdev_write_zero_buffer_next);
4700 	} else {
4701 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4702 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
4703 	}
4704 }
4705 
4706 static void
4707 _spdk_bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4708 {
4709 	struct spdk_bdev_io *parent_io = cb_arg;
4710 
4711 	spdk_bdev_free_io(bdev_io);
4712 
4713 	if (!success) {
4714 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4715 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
4716 		return;
4717 	}
4718 
4719 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
4720 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4721 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
4722 		return;
4723 	}
4724 
4725 	_spdk_bdev_write_zero_buffer_next(parent_io);
4726 }
4727 
4728 static void
4729 _spdk_bdev_set_qos_limit_done(struct set_qos_limit_ctx *ctx, int status)
4730 {
4731 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
4732 	ctx->bdev->internal.qos_mod_in_progress = false;
4733 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
4734 
4735 	if (ctx->cb_fn) {
4736 		ctx->cb_fn(ctx->cb_arg, status);
4737 	}
4738 	free(ctx);
4739 }
4740 
4741 static void
4742 _spdk_bdev_disable_qos_done(void *cb_arg)
4743 {
4744 	struct set_qos_limit_ctx *ctx = cb_arg;
4745 	struct spdk_bdev *bdev = ctx->bdev;
4746 	struct spdk_bdev_io *bdev_io;
4747 	struct spdk_bdev_qos *qos;
4748 
4749 	pthread_mutex_lock(&bdev->internal.mutex);
4750 	qos = bdev->internal.qos;
4751 	bdev->internal.qos = NULL;
4752 	pthread_mutex_unlock(&bdev->internal.mutex);
4753 
4754 	while (!TAILQ_EMPTY(&qos->queued)) {
4755 		/* Send queued I/O back to their original thread for resubmission. */
4756 		bdev_io = TAILQ_FIRST(&qos->queued);
4757 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
4758 
4759 		if (bdev_io->internal.io_submit_ch) {
4760 			/*
4761 			 * Channel was changed when sending it to the QoS thread - change it back
4762 			 *  before sending it back to the original thread.
4763 			 */
4764 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
4765 			bdev_io->internal.io_submit_ch = NULL;
4766 		}
4767 
4768 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
4769 				     _spdk_bdev_io_submit, bdev_io);
4770 	}
4771 
4772 	if (qos->thread != NULL) {
4773 		spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
4774 		spdk_poller_unregister(&qos->poller);
4775 	}
4776 
4777 	free(qos);
4778 
4779 	_spdk_bdev_set_qos_limit_done(ctx, 0);
4780 }
4781 
4782 static void
4783 _spdk_bdev_disable_qos_msg_done(struct spdk_io_channel_iter *i, int status)
4784 {
4785 	void *io_device = spdk_io_channel_iter_get_io_device(i);
4786 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
4787 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4788 	struct spdk_thread *thread;
4789 
4790 	pthread_mutex_lock(&bdev->internal.mutex);
4791 	thread = bdev->internal.qos->thread;
4792 	pthread_mutex_unlock(&bdev->internal.mutex);
4793 
4794 	if (thread != NULL) {
4795 		spdk_thread_send_msg(thread, _spdk_bdev_disable_qos_done, ctx);
4796 	} else {
4797 		_spdk_bdev_disable_qos_done(ctx);
4798 	}
4799 }
4800 
4801 static void
4802 _spdk_bdev_disable_qos_msg(struct spdk_io_channel_iter *i)
4803 {
4804 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
4805 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
4806 
4807 	bdev_ch->flags &= ~BDEV_CH_QOS_ENABLED;
4808 
4809 	spdk_for_each_channel_continue(i, 0);
4810 }
4811 
4812 static void
4813 _spdk_bdev_update_qos_rate_limit_msg(void *cb_arg)
4814 {
4815 	struct set_qos_limit_ctx *ctx = cb_arg;
4816 	struct spdk_bdev *bdev = ctx->bdev;
4817 
4818 	pthread_mutex_lock(&bdev->internal.mutex);
4819 	spdk_bdev_qos_update_max_quota_per_timeslice(bdev->internal.qos);
4820 	pthread_mutex_unlock(&bdev->internal.mutex);
4821 
4822 	_spdk_bdev_set_qos_limit_done(ctx, 0);
4823 }
4824 
4825 static void
4826 _spdk_bdev_enable_qos_msg(struct spdk_io_channel_iter *i)
4827 {
4828 	void *io_device = spdk_io_channel_iter_get_io_device(i);
4829 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
4830 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
4831 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
4832 
4833 	pthread_mutex_lock(&bdev->internal.mutex);
4834 	_spdk_bdev_enable_qos(bdev, bdev_ch);
4835 	pthread_mutex_unlock(&bdev->internal.mutex);
4836 	spdk_for_each_channel_continue(i, 0);
4837 }
4838 
4839 static void
4840 _spdk_bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status)
4841 {
4842 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4843 
4844 	_spdk_bdev_set_qos_limit_done(ctx, status);
4845 }
4846 
4847 static void
4848 _spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
4849 {
4850 	int i;
4851 
4852 	assert(bdev->internal.qos != NULL);
4853 
4854 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4855 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
4856 			bdev->internal.qos->rate_limits[i].limit = limits[i];
4857 
4858 			if (limits[i] == 0) {
4859 				bdev->internal.qos->rate_limits[i].limit =
4860 					SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
4861 			}
4862 		}
4863 	}
4864 }
4865 
4866 void
4867 spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits,
4868 			      void (*cb_fn)(void *cb_arg, int status), void *cb_arg)
4869 {
4870 	struct set_qos_limit_ctx	*ctx;
4871 	uint32_t			limit_set_complement;
4872 	uint64_t			min_limit_per_sec;
4873 	int				i;
4874 	bool				disable_rate_limit = true;
4875 
4876 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4877 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
4878 			continue;
4879 		}
4880 
4881 		if (limits[i] > 0) {
4882 			disable_rate_limit = false;
4883 		}
4884 
4885 		if (_spdk_bdev_qos_is_iops_rate_limit(i) == true) {
4886 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
4887 		} else {
4888 			/* Change from megabyte to byte rate limit */
4889 			limits[i] = limits[i] * 1024 * 1024;
4890 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
4891 		}
4892 
4893 		limit_set_complement = limits[i] % min_limit_per_sec;
4894 		if (limit_set_complement) {
4895 			SPDK_ERRLOG("Requested rate limit %" PRIu64 " is not a multiple of %" PRIu64 "\n",
4896 				    limits[i], min_limit_per_sec);
4897 			limits[i] += min_limit_per_sec - limit_set_complement;
4898 			SPDK_ERRLOG("Round up the rate limit to %" PRIu64 "\n", limits[i]);
4899 		}
4900 	}
4901 
4902 	ctx = calloc(1, sizeof(*ctx));
4903 	if (ctx == NULL) {
4904 		cb_fn(cb_arg, -ENOMEM);
4905 		return;
4906 	}
4907 
4908 	ctx->cb_fn = cb_fn;
4909 	ctx->cb_arg = cb_arg;
4910 	ctx->bdev = bdev;
4911 
4912 	pthread_mutex_lock(&bdev->internal.mutex);
4913 	if (bdev->internal.qos_mod_in_progress) {
4914 		pthread_mutex_unlock(&bdev->internal.mutex);
4915 		free(ctx);
4916 		cb_fn(cb_arg, -EAGAIN);
4917 		return;
4918 	}
4919 	bdev->internal.qos_mod_in_progress = true;
4920 
4921 	if (disable_rate_limit == true && bdev->internal.qos) {
4922 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
4923 			if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED &&
4924 			    (bdev->internal.qos->rate_limits[i].limit > 0 &&
4925 			     bdev->internal.qos->rate_limits[i].limit !=
4926 			     SPDK_BDEV_QOS_LIMIT_NOT_DEFINED)) {
4927 				disable_rate_limit = false;
4928 				break;
4929 			}
4930 		}
4931 	}
4932 
4933 	if (disable_rate_limit == false) {
4934 		if (bdev->internal.qos == NULL) {
4935 			bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
4936 			if (!bdev->internal.qos) {
4937 				pthread_mutex_unlock(&bdev->internal.mutex);
4938 				SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
4939 				_spdk_bdev_set_qos_limit_done(ctx, -ENOMEM);
4940 				return;
4941 			}
4942 		}
4943 
4944 		if (bdev->internal.qos->thread == NULL) {
4945 			/* Enabling */
4946 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4947 
4948 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
4949 					      _spdk_bdev_enable_qos_msg, ctx,
4950 					      _spdk_bdev_enable_qos_done);
4951 		} else {
4952 			/* Updating */
4953 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4954 
4955 			spdk_thread_send_msg(bdev->internal.qos->thread,
4956 					     _spdk_bdev_update_qos_rate_limit_msg, ctx);
4957 		}
4958 	} else {
4959 		if (bdev->internal.qos != NULL) {
4960 			_spdk_bdev_set_qos_rate_limits(bdev, limits);
4961 
4962 			/* Disabling */
4963 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
4964 					      _spdk_bdev_disable_qos_msg, ctx,
4965 					      _spdk_bdev_disable_qos_msg_done);
4966 		} else {
4967 			pthread_mutex_unlock(&bdev->internal.mutex);
4968 			_spdk_bdev_set_qos_limit_done(ctx, 0);
4969 			return;
4970 		}
4971 	}
4972 
4973 	pthread_mutex_unlock(&bdev->internal.mutex);
4974 }
4975 
4976 struct spdk_bdev_histogram_ctx {
4977 	spdk_bdev_histogram_status_cb cb_fn;
4978 	void *cb_arg;
4979 	struct spdk_bdev *bdev;
4980 	int status;
4981 };
4982 
4983 static void
4984 _spdk_bdev_histogram_disable_channel_cb(struct spdk_io_channel_iter *i, int status)
4985 {
4986 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
4987 
4988 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
4989 	ctx->bdev->internal.histogram_in_progress = false;
4990 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
4991 	ctx->cb_fn(ctx->cb_arg, ctx->status);
4992 	free(ctx);
4993 }
4994 
4995 static void
4996 _spdk_bdev_histogram_disable_channel(struct spdk_io_channel_iter *i)
4997 {
4998 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
4999 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5000 
5001 	if (ch->histogram != NULL) {
5002 		spdk_histogram_data_free(ch->histogram);
5003 		ch->histogram = NULL;
5004 	}
5005 	spdk_for_each_channel_continue(i, 0);
5006 }
5007 
5008 static void
5009 _spdk_bdev_histogram_enable_channel_cb(struct spdk_io_channel_iter *i, int status)
5010 {
5011 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5012 
5013 	if (status != 0) {
5014 		ctx->status = status;
5015 		ctx->bdev->internal.histogram_enabled = false;
5016 		spdk_for_each_channel(__bdev_to_io_dev(ctx->bdev), _spdk_bdev_histogram_disable_channel, ctx,
5017 				      _spdk_bdev_histogram_disable_channel_cb);
5018 	} else {
5019 		pthread_mutex_lock(&ctx->bdev->internal.mutex);
5020 		ctx->bdev->internal.histogram_in_progress = false;
5021 		pthread_mutex_unlock(&ctx->bdev->internal.mutex);
5022 		ctx->cb_fn(ctx->cb_arg, ctx->status);
5023 		free(ctx);
5024 	}
5025 }
5026 
5027 static void
5028 _spdk_bdev_histogram_enable_channel(struct spdk_io_channel_iter *i)
5029 {
5030 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5031 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5032 	int status = 0;
5033 
5034 	if (ch->histogram == NULL) {
5035 		ch->histogram = spdk_histogram_data_alloc();
5036 		if (ch->histogram == NULL) {
5037 			status = -ENOMEM;
5038 		}
5039 	}
5040 
5041 	spdk_for_each_channel_continue(i, status);
5042 }
5043 
5044 void
5045 spdk_bdev_histogram_enable(struct spdk_bdev *bdev, spdk_bdev_histogram_status_cb cb_fn,
5046 			   void *cb_arg, bool enable)
5047 {
5048 	struct spdk_bdev_histogram_ctx *ctx;
5049 
5050 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_ctx));
5051 	if (ctx == NULL) {
5052 		cb_fn(cb_arg, -ENOMEM);
5053 		return;
5054 	}
5055 
5056 	ctx->bdev = bdev;
5057 	ctx->status = 0;
5058 	ctx->cb_fn = cb_fn;
5059 	ctx->cb_arg = cb_arg;
5060 
5061 	pthread_mutex_lock(&bdev->internal.mutex);
5062 	if (bdev->internal.histogram_in_progress) {
5063 		pthread_mutex_unlock(&bdev->internal.mutex);
5064 		free(ctx);
5065 		cb_fn(cb_arg, -EAGAIN);
5066 		return;
5067 	}
5068 
5069 	bdev->internal.histogram_in_progress = true;
5070 	pthread_mutex_unlock(&bdev->internal.mutex);
5071 
5072 	bdev->internal.histogram_enabled = enable;
5073 
5074 	if (enable) {
5075 		/* Allocate histogram for each channel */
5076 		spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_enable_channel, ctx,
5077 				      _spdk_bdev_histogram_enable_channel_cb);
5078 	} else {
5079 		spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_disable_channel, ctx,
5080 				      _spdk_bdev_histogram_disable_channel_cb);
5081 	}
5082 }
5083 
5084 struct spdk_bdev_histogram_data_ctx {
5085 	spdk_bdev_histogram_data_cb cb_fn;
5086 	void *cb_arg;
5087 	struct spdk_bdev *bdev;
5088 	/** merged histogram data from all channels */
5089 	struct spdk_histogram_data	*histogram;
5090 };
5091 
5092 static void
5093 _spdk_bdev_histogram_get_channel_cb(struct spdk_io_channel_iter *i, int status)
5094 {
5095 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5096 
5097 	ctx->cb_fn(ctx->cb_arg, status, ctx->histogram);
5098 	free(ctx);
5099 }
5100 
5101 static void
5102 _spdk_bdev_histogram_get_channel(struct spdk_io_channel_iter *i)
5103 {
5104 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5105 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5106 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
5107 	int status = 0;
5108 
5109 	if (ch->histogram == NULL) {
5110 		status = -EFAULT;
5111 	} else {
5112 		spdk_histogram_data_merge(ctx->histogram, ch->histogram);
5113 	}
5114 
5115 	spdk_for_each_channel_continue(i, status);
5116 }
5117 
5118 void
5119 spdk_bdev_histogram_get(struct spdk_bdev *bdev, struct spdk_histogram_data *histogram,
5120 			spdk_bdev_histogram_data_cb cb_fn,
5121 			void *cb_arg)
5122 {
5123 	struct spdk_bdev_histogram_data_ctx *ctx;
5124 
5125 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_data_ctx));
5126 	if (ctx == NULL) {
5127 		cb_fn(cb_arg, -ENOMEM, NULL);
5128 		return;
5129 	}
5130 
5131 	ctx->bdev = bdev;
5132 	ctx->cb_fn = cb_fn;
5133 	ctx->cb_arg = cb_arg;
5134 
5135 	ctx->histogram = histogram;
5136 
5137 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _spdk_bdev_histogram_get_channel, ctx,
5138 			      _spdk_bdev_histogram_get_channel_cb);
5139 }
5140 
5141 SPDK_LOG_REGISTER_COMPONENT("bdev", SPDK_LOG_BDEV)
5142 
5143 SPDK_TRACE_REGISTER_FN(bdev_trace, "bdev", TRACE_GROUP_BDEV)
5144 {
5145 	spdk_trace_register_owner(OWNER_BDEV, 'b');
5146 	spdk_trace_register_object(OBJECT_BDEV_IO, 'i');
5147 	spdk_trace_register_description("BDEV_IO_START", TRACE_BDEV_IO_START, OWNER_BDEV,
5148 					OBJECT_BDEV_IO, 1, 0, "type:   ");
5149 	spdk_trace_register_description("BDEV_IO_DONE", TRACE_BDEV_IO_DONE, OWNER_BDEV,
5150 					OBJECT_BDEV_IO, 0, 0, "");
5151 }
5152