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