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