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