xref: /spdk/lib/bdev/bdev.c (revision 32999ab917f67af61872f868585fd3d78ad6fb8a)
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 
38 #include "spdk/config.h"
39 #include "spdk/env.h"
40 #include "spdk/thread.h"
41 #include "spdk/likely.h"
42 #include "spdk/queue.h"
43 #include "spdk/nvme_spec.h"
44 #include "spdk/scsi_spec.h"
45 #include "spdk/notify.h"
46 #include "spdk/util.h"
47 #include "spdk/trace.h"
48 
49 #include "spdk/bdev_module.h"
50 #include "spdk/log.h"
51 #include "spdk/string.h"
52 
53 #include "bdev_internal.h"
54 
55 #ifdef SPDK_CONFIG_VTUNE
56 #include "ittnotify.h"
57 #include "ittnotify_types.h"
58 int __itt_init_ittlib(const char *, __itt_group_id);
59 #endif
60 
61 #define SPDK_BDEV_IO_POOL_SIZE			(64 * 1024 - 1)
62 #define SPDK_BDEV_IO_CACHE_SIZE			256
63 #define SPDK_BDEV_AUTO_EXAMINE			true
64 #define BUF_SMALL_POOL_SIZE			8191
65 #define BUF_LARGE_POOL_SIZE			1023
66 #define NOMEM_THRESHOLD_COUNT			8
67 #define ZERO_BUFFER_SIZE			0x100000
68 
69 #define OWNER_BDEV		0x2
70 
71 #define OBJECT_BDEV_IO		0x2
72 
73 #define TRACE_GROUP_BDEV	0x3
74 #define TRACE_BDEV_IO_START	SPDK_TPOINT_ID(TRACE_GROUP_BDEV, 0x0)
75 #define TRACE_BDEV_IO_DONE	SPDK_TPOINT_ID(TRACE_GROUP_BDEV, 0x1)
76 
77 #define SPDK_BDEV_QOS_TIMESLICE_IN_USEC		1000
78 #define SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE	1
79 #define SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE	512
80 #define SPDK_BDEV_QOS_MIN_IOS_PER_SEC		1000
81 #define SPDK_BDEV_QOS_MIN_BYTES_PER_SEC		(1024 * 1024)
82 #define SPDK_BDEV_QOS_LIMIT_NOT_DEFINED		UINT64_MAX
83 #define SPDK_BDEV_IO_POLL_INTERVAL_IN_MSEC	1000
84 
85 #define SPDK_BDEV_POOL_ALIGNMENT 512
86 
87 static const char *qos_rpc_type[] = {"rw_ios_per_sec",
88 				     "rw_mbytes_per_sec", "r_mbytes_per_sec", "w_mbytes_per_sec"
89 				    };
90 
91 TAILQ_HEAD(spdk_bdev_list, spdk_bdev);
92 
93 struct spdk_bdev_mgr {
94 	struct spdk_mempool *bdev_io_pool;
95 
96 	struct spdk_mempool *buf_small_pool;
97 	struct spdk_mempool *buf_large_pool;
98 
99 	void *zero_buffer;
100 
101 	TAILQ_HEAD(bdev_module_list, spdk_bdev_module) bdev_modules;
102 
103 	struct spdk_bdev_list bdevs;
104 
105 	bool init_complete;
106 	bool module_init_complete;
107 
108 	pthread_mutex_t mutex;
109 
110 #ifdef SPDK_CONFIG_VTUNE
111 	__itt_domain	*domain;
112 #endif
113 };
114 
115 static struct spdk_bdev_mgr g_bdev_mgr = {
116 	.bdev_modules = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdev_modules),
117 	.bdevs = TAILQ_HEAD_INITIALIZER(g_bdev_mgr.bdevs),
118 	.init_complete = false,
119 	.module_init_complete = false,
120 	.mutex = PTHREAD_MUTEX_INITIALIZER,
121 };
122 
123 typedef void (*lock_range_cb)(void *ctx, int status);
124 
125 struct lba_range {
126 	uint64_t			offset;
127 	uint64_t			length;
128 	void				*locked_ctx;
129 	struct spdk_bdev_channel	*owner_ch;
130 	TAILQ_ENTRY(lba_range)		tailq;
131 };
132 
133 static struct spdk_bdev_opts	g_bdev_opts = {
134 	.bdev_io_pool_size = SPDK_BDEV_IO_POOL_SIZE,
135 	.bdev_io_cache_size = SPDK_BDEV_IO_CACHE_SIZE,
136 	.bdev_auto_examine = SPDK_BDEV_AUTO_EXAMINE,
137 	.small_buf_pool_size = BUF_SMALL_POOL_SIZE,
138 	.large_buf_pool_size = BUF_LARGE_POOL_SIZE,
139 };
140 
141 static spdk_bdev_init_cb	g_init_cb_fn = NULL;
142 static void			*g_init_cb_arg = NULL;
143 
144 static spdk_bdev_fini_cb	g_fini_cb_fn = NULL;
145 static void			*g_fini_cb_arg = NULL;
146 static struct spdk_thread	*g_fini_thread = NULL;
147 
148 struct spdk_bdev_qos_limit {
149 	/** IOs or bytes allowed per second (i.e., 1s). */
150 	uint64_t limit;
151 
152 	/** Remaining IOs or bytes allowed in current timeslice (e.g., 1ms).
153 	 *  For remaining bytes, allowed to run negative if an I/O is submitted when
154 	 *  some bytes are remaining, but the I/O is bigger than that amount. The
155 	 *  excess will be deducted from the next timeslice.
156 	 */
157 	int64_t remaining_this_timeslice;
158 
159 	/** Minimum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
160 	uint32_t min_per_timeslice;
161 
162 	/** Maximum allowed IOs or bytes to be issued in one timeslice (e.g., 1ms). */
163 	uint32_t max_per_timeslice;
164 
165 	/** Function to check whether to queue the IO. */
166 	bool (*queue_io)(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
167 
168 	/** Function to update for the submitted IO. */
169 	void (*update_quota)(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io);
170 };
171 
172 struct spdk_bdev_qos {
173 	/** Types of structure of rate limits. */
174 	struct spdk_bdev_qos_limit rate_limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
175 
176 	/** The channel that all I/O are funneled through. */
177 	struct spdk_bdev_channel *ch;
178 
179 	/** The thread on which the poller is running. */
180 	struct spdk_thread *thread;
181 
182 	/** Queue of I/O waiting to be issued. */
183 	bdev_io_tailq_t queued;
184 
185 	/** Size of a timeslice in tsc ticks. */
186 	uint64_t timeslice_size;
187 
188 	/** Timestamp of start of last timeslice. */
189 	uint64_t last_timeslice;
190 
191 	/** Poller that processes queued I/O commands each time slice. */
192 	struct spdk_poller *poller;
193 };
194 
195 struct spdk_bdev_mgmt_channel {
196 	bdev_io_stailq_t need_buf_small;
197 	bdev_io_stailq_t need_buf_large;
198 
199 	/*
200 	 * Each thread keeps a cache of bdev_io - this allows
201 	 *  bdev threads which are *not* DPDK threads to still
202 	 *  benefit from a per-thread bdev_io cache.  Without
203 	 *  this, non-DPDK threads fetching from the mempool
204 	 *  incur a cmpxchg on get and put.
205 	 */
206 	bdev_io_stailq_t per_thread_cache;
207 	uint32_t	per_thread_cache_count;
208 	uint32_t	bdev_io_cache_size;
209 
210 	TAILQ_HEAD(, spdk_bdev_shared_resource)	shared_resources;
211 	TAILQ_HEAD(, spdk_bdev_io_wait_entry)	io_wait_queue;
212 };
213 
214 /*
215  * Per-module (or per-io_device) data. Multiple bdevs built on the same io_device
216  * will queue here their IO that awaits retry. It makes it possible to retry sending
217  * IO to one bdev after IO from other bdev completes.
218  */
219 struct spdk_bdev_shared_resource {
220 	/* The bdev management channel */
221 	struct spdk_bdev_mgmt_channel *mgmt_ch;
222 
223 	/*
224 	 * Count of I/O submitted to bdev module and waiting for completion.
225 	 * Incremented before submit_request() is called on an spdk_bdev_io.
226 	 */
227 	uint64_t		io_outstanding;
228 
229 	/*
230 	 * Queue of IO awaiting retry because of a previous NOMEM status returned
231 	 *  on this channel.
232 	 */
233 	bdev_io_tailq_t		nomem_io;
234 
235 	/*
236 	 * Threshold which io_outstanding must drop to before retrying nomem_io.
237 	 */
238 	uint64_t		nomem_threshold;
239 
240 	/* I/O channel allocated by a bdev module */
241 	struct spdk_io_channel	*shared_ch;
242 
243 	/* Refcount of bdev channels using this resource */
244 	uint32_t		ref;
245 
246 	TAILQ_ENTRY(spdk_bdev_shared_resource) link;
247 };
248 
249 #define BDEV_CH_RESET_IN_PROGRESS	(1 << 0)
250 #define BDEV_CH_QOS_ENABLED		(1 << 1)
251 
252 struct spdk_bdev_channel {
253 	struct spdk_bdev	*bdev;
254 
255 	/* The channel for the underlying device */
256 	struct spdk_io_channel	*channel;
257 
258 	/* Per io_device per thread data */
259 	struct spdk_bdev_shared_resource *shared_resource;
260 
261 	struct spdk_bdev_io_stat stat;
262 
263 	/*
264 	 * Count of I/O submitted to the underlying dev module through this channel
265 	 * and waiting for completion.
266 	 */
267 	uint64_t		io_outstanding;
268 
269 	/*
270 	 * List of all submitted I/Os including I/O that are generated via splitting.
271 	 */
272 	bdev_io_tailq_t		io_submitted;
273 
274 	/*
275 	 * List of spdk_bdev_io that are currently queued because they write to a locked
276 	 * LBA range.
277 	 */
278 	bdev_io_tailq_t		io_locked;
279 
280 	uint32_t		flags;
281 
282 	struct spdk_histogram_data *histogram;
283 
284 #ifdef SPDK_CONFIG_VTUNE
285 	uint64_t		start_tsc;
286 	uint64_t		interval_tsc;
287 	__itt_string_handle	*handle;
288 	struct spdk_bdev_io_stat prev_stat;
289 #endif
290 
291 	bdev_io_tailq_t		queued_resets;
292 
293 	lba_range_tailq_t	locked_ranges;
294 };
295 
296 struct media_event_entry {
297 	struct spdk_bdev_media_event	event;
298 	TAILQ_ENTRY(media_event_entry)	tailq;
299 };
300 
301 #define MEDIA_EVENT_POOL_SIZE 64
302 
303 struct spdk_bdev_desc {
304 	struct spdk_bdev		*bdev;
305 	struct spdk_thread		*thread;
306 	struct {
307 		spdk_bdev_event_cb_t event_fn;
308 		void *ctx;
309 	}				callback;
310 	bool				closed;
311 	bool				write;
312 	pthread_mutex_t			mutex;
313 	uint32_t			refs;
314 	TAILQ_HEAD(, media_event_entry)	pending_media_events;
315 	TAILQ_HEAD(, media_event_entry)	free_media_events;
316 	struct media_event_entry	*media_events_buffer;
317 	TAILQ_ENTRY(spdk_bdev_desc)	link;
318 
319 	uint64_t		timeout_in_sec;
320 	spdk_bdev_io_timeout_cb	cb_fn;
321 	void			*cb_arg;
322 	struct spdk_poller	*io_timeout_poller;
323 };
324 
325 struct spdk_bdev_iostat_ctx {
326 	struct spdk_bdev_io_stat *stat;
327 	spdk_bdev_get_device_stat_cb cb;
328 	void *cb_arg;
329 };
330 
331 struct set_qos_limit_ctx {
332 	void (*cb_fn)(void *cb_arg, int status);
333 	void *cb_arg;
334 	struct spdk_bdev *bdev;
335 };
336 
337 #define __bdev_to_io_dev(bdev)		(((char *)bdev) + 1)
338 #define __bdev_from_io_dev(io_dev)	((struct spdk_bdev *)(((char *)io_dev) - 1))
339 
340 static void bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
341 static void bdev_write_zero_buffer_next(void *_bdev_io);
342 
343 static void bdev_enable_qos_msg(struct spdk_io_channel_iter *i);
344 static void bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status);
345 
346 static int
347 bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
348 			  struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
349 			  uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg);
350 static int
351 bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
352 			   struct iovec *iov, int iovcnt, void *md_buf,
353 			   uint64_t offset_blocks, uint64_t num_blocks,
354 			   spdk_bdev_io_completion_cb cb, void *cb_arg);
355 
356 static int
357 bdev_lock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
358 		    uint64_t offset, uint64_t length,
359 		    lock_range_cb cb_fn, void *cb_arg);
360 
361 static int
362 bdev_unlock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
363 		      uint64_t offset, uint64_t length,
364 		      lock_range_cb cb_fn, void *cb_arg);
365 
366 static inline void bdev_io_complete(void *ctx);
367 
368 static bool bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_io *bio_to_abort);
369 static bool bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_io *bio_to_abort);
370 
371 void
372 spdk_bdev_get_opts(struct spdk_bdev_opts *opts, size_t opts_size)
373 {
374 	if (!opts) {
375 		SPDK_ERRLOG("opts should not be NULL\n");
376 		return;
377 	}
378 
379 	if (!opts_size) {
380 		SPDK_ERRLOG("opts_size should not be zero value\n");
381 		return;
382 	}
383 
384 	opts->opts_size = opts_size;
385 
386 #define SET_FIELD(field) \
387 	if (offsetof(struct spdk_bdev_opts, field) + sizeof(opts->field) <= opts_size) { \
388 		opts->field = g_bdev_opts.field; \
389 	} \
390 
391 	SET_FIELD(bdev_io_pool_size);
392 	SET_FIELD(bdev_io_cache_size);
393 	SET_FIELD(bdev_auto_examine);
394 	SET_FIELD(small_buf_pool_size);
395 	SET_FIELD(large_buf_pool_size);
396 
397 	/* Do not remove this statement, you should always update this statement when you adding a new field,
398 	 * and do not forget to add the SET_FIELD statement for your added field. */
399 	SPDK_STATIC_ASSERT(sizeof(struct spdk_bdev_opts) == 32, "Incorrect size");
400 
401 #undef SET_FIELD
402 }
403 
404 int
405 spdk_bdev_set_opts(struct spdk_bdev_opts *opts)
406 {
407 	uint32_t min_pool_size;
408 
409 	if (!opts) {
410 		SPDK_ERRLOG("opts cannot be NULL\n");
411 		return -1;
412 	}
413 
414 	if (!opts->opts_size) {
415 		SPDK_ERRLOG("opts_size inside opts cannot be zero value\n");
416 		return -1;
417 	}
418 
419 	/*
420 	 * Add 1 to the thread count to account for the extra mgmt_ch that gets created during subsystem
421 	 *  initialization.  A second mgmt_ch will be created on the same thread when the application starts
422 	 *  but before the deferred put_io_channel event is executed for the first mgmt_ch.
423 	 */
424 	min_pool_size = opts->bdev_io_cache_size * (spdk_thread_get_count() + 1);
425 	if (opts->bdev_io_pool_size < min_pool_size) {
426 		SPDK_ERRLOG("bdev_io_pool_size %" PRIu32 " is not compatible with bdev_io_cache_size %" PRIu32
427 			    " and %" PRIu32 " threads\n", opts->bdev_io_pool_size, opts->bdev_io_cache_size,
428 			    spdk_thread_get_count());
429 		SPDK_ERRLOG("bdev_io_pool_size must be at least %" PRIu32 "\n", min_pool_size);
430 		return -1;
431 	}
432 
433 	if (opts->small_buf_pool_size < BUF_SMALL_POOL_SIZE) {
434 		SPDK_ERRLOG("small_buf_pool_size must be at least %" PRIu32 "\n", BUF_SMALL_POOL_SIZE);
435 		return -1;
436 	}
437 
438 	if (opts->large_buf_pool_size < BUF_LARGE_POOL_SIZE) {
439 		SPDK_ERRLOG("large_buf_pool_size must be at least %" PRIu32 "\n", BUF_LARGE_POOL_SIZE);
440 		return -1;
441 	}
442 
443 #define SET_FIELD(field) \
444         if (offsetof(struct spdk_bdev_opts, field) + sizeof(opts->field) <= opts->opts_size) { \
445                 g_bdev_opts.field = opts->field; \
446         } \
447 
448 	SET_FIELD(bdev_io_pool_size);
449 	SET_FIELD(bdev_io_cache_size);
450 	SET_FIELD(bdev_auto_examine);
451 	SET_FIELD(small_buf_pool_size);
452 	SET_FIELD(large_buf_pool_size);
453 
454 	g_bdev_opts.opts_size = opts->opts_size;
455 
456 #undef SET_FIELD
457 
458 	return 0;
459 }
460 
461 struct spdk_bdev_wait_for_examine_ctx {
462 	struct spdk_poller              *poller;
463 	spdk_bdev_wait_for_examine_cb	cb_fn;
464 	void				*cb_arg;
465 };
466 
467 static bool
468 bdev_module_all_actions_completed(void);
469 
470 static int
471 bdev_wait_for_examine_cb(void *arg)
472 {
473 	struct spdk_bdev_wait_for_examine_ctx *ctx = arg;
474 
475 	if (!bdev_module_all_actions_completed()) {
476 		return SPDK_POLLER_IDLE;
477 	}
478 
479 	spdk_poller_unregister(&ctx->poller);
480 	ctx->cb_fn(ctx->cb_arg);
481 	free(ctx);
482 
483 	return SPDK_POLLER_BUSY;
484 }
485 
486 int
487 spdk_bdev_wait_for_examine(spdk_bdev_wait_for_examine_cb cb_fn, void *cb_arg)
488 {
489 	struct spdk_bdev_wait_for_examine_ctx *ctx;
490 
491 	ctx = calloc(1, sizeof(*ctx));
492 	if (ctx == NULL) {
493 		return -ENOMEM;
494 	}
495 	ctx->cb_fn = cb_fn;
496 	ctx->cb_arg = cb_arg;
497 	ctx->poller = SPDK_POLLER_REGISTER(bdev_wait_for_examine_cb, ctx, 0);
498 
499 	return 0;
500 }
501 
502 struct spdk_bdev_examine_item {
503 	char *name;
504 	TAILQ_ENTRY(spdk_bdev_examine_item) link;
505 };
506 
507 TAILQ_HEAD(spdk_bdev_examine_allowlist, spdk_bdev_examine_item);
508 
509 struct spdk_bdev_examine_allowlist g_bdev_examine_allowlist = TAILQ_HEAD_INITIALIZER(
510 			g_bdev_examine_allowlist);
511 
512 static inline bool
513 bdev_examine_allowlist_check(const char *name)
514 {
515 	struct spdk_bdev_examine_item *item;
516 	TAILQ_FOREACH(item, &g_bdev_examine_allowlist, link) {
517 		if (strcmp(name, item->name) == 0) {
518 			return true;
519 		}
520 	}
521 	return false;
522 }
523 
524 static inline void
525 bdev_examine_allowlist_free(void)
526 {
527 	struct spdk_bdev_examine_item *item;
528 	while (!TAILQ_EMPTY(&g_bdev_examine_allowlist)) {
529 		item = TAILQ_FIRST(&g_bdev_examine_allowlist);
530 		TAILQ_REMOVE(&g_bdev_examine_allowlist, item, link);
531 		free(item->name);
532 		free(item);
533 	}
534 }
535 
536 static inline bool
537 bdev_in_examine_allowlist(struct spdk_bdev *bdev)
538 {
539 	struct spdk_bdev_alias *tmp;
540 	if (bdev_examine_allowlist_check(bdev->name)) {
541 		return true;
542 	}
543 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
544 		if (bdev_examine_allowlist_check(tmp->alias)) {
545 			return true;
546 		}
547 	}
548 	return false;
549 }
550 
551 static inline bool
552 bdev_ok_to_examine(struct spdk_bdev *bdev)
553 {
554 	if (g_bdev_opts.bdev_auto_examine) {
555 		return true;
556 	} else {
557 		return bdev_in_examine_allowlist(bdev);
558 	}
559 }
560 
561 static void
562 bdev_examine(struct spdk_bdev *bdev)
563 {
564 	struct spdk_bdev_module *module;
565 	uint32_t action;
566 
567 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
568 		if (module->examine_config && bdev_ok_to_examine(bdev)) {
569 			action = module->internal.action_in_progress;
570 			module->internal.action_in_progress++;
571 			module->examine_config(bdev);
572 			if (action != module->internal.action_in_progress) {
573 				SPDK_ERRLOG("examine_config for module %s did not call spdk_bdev_module_examine_done()\n",
574 					    module->name);
575 			}
576 		}
577 	}
578 
579 	if (bdev->internal.claim_module && bdev_ok_to_examine(bdev)) {
580 		if (bdev->internal.claim_module->examine_disk) {
581 			bdev->internal.claim_module->internal.action_in_progress++;
582 			bdev->internal.claim_module->examine_disk(bdev);
583 		}
584 		return;
585 	}
586 
587 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
588 		if (module->examine_disk && bdev_ok_to_examine(bdev)) {
589 			module->internal.action_in_progress++;
590 			module->examine_disk(bdev);
591 		}
592 	}
593 }
594 
595 int
596 spdk_bdev_examine(const char *name)
597 {
598 	struct spdk_bdev *bdev;
599 	struct spdk_bdev_examine_item *item;
600 
601 	if (g_bdev_opts.bdev_auto_examine) {
602 		SPDK_ERRLOG("Manual examine is not allowed if auto examine is enabled");
603 		return -EINVAL;
604 	}
605 
606 	if (bdev_examine_allowlist_check(name)) {
607 		SPDK_ERRLOG("Duplicate bdev name for manual examine: %s\n", name);
608 		return -EEXIST;
609 	}
610 
611 	item = calloc(1, sizeof(*item));
612 	if (!item) {
613 		return -ENOMEM;
614 	}
615 	item->name = strdup(name);
616 	if (!item->name) {
617 		free(item);
618 		return -ENOMEM;
619 	}
620 	TAILQ_INSERT_TAIL(&g_bdev_examine_allowlist, item, link);
621 
622 	bdev = spdk_bdev_get_by_name(name);
623 	if (bdev) {
624 		bdev_examine(bdev);
625 	}
626 	return 0;
627 }
628 
629 static inline void
630 bdev_examine_allowlist_config_json(struct spdk_json_write_ctx *w)
631 {
632 	struct spdk_bdev_examine_item *item;
633 	TAILQ_FOREACH(item, &g_bdev_examine_allowlist, link) {
634 		spdk_json_write_object_begin(w);
635 		spdk_json_write_named_string(w, "method", "bdev_examine");
636 		spdk_json_write_named_object_begin(w, "params");
637 		spdk_json_write_named_string(w, "name", item->name);
638 		spdk_json_write_object_end(w);
639 		spdk_json_write_object_end(w);
640 	}
641 }
642 
643 struct spdk_bdev *
644 spdk_bdev_first(void)
645 {
646 	struct spdk_bdev *bdev;
647 
648 	bdev = TAILQ_FIRST(&g_bdev_mgr.bdevs);
649 	if (bdev) {
650 		SPDK_DEBUGLOG(bdev, "Starting bdev iteration at %s\n", bdev->name);
651 	}
652 
653 	return bdev;
654 }
655 
656 struct spdk_bdev *
657 spdk_bdev_next(struct spdk_bdev *prev)
658 {
659 	struct spdk_bdev *bdev;
660 
661 	bdev = TAILQ_NEXT(prev, internal.link);
662 	if (bdev) {
663 		SPDK_DEBUGLOG(bdev, "Continuing bdev iteration at %s\n", bdev->name);
664 	}
665 
666 	return bdev;
667 }
668 
669 static struct spdk_bdev *
670 _bdev_next_leaf(struct spdk_bdev *bdev)
671 {
672 	while (bdev != NULL) {
673 		if (bdev->internal.claim_module == NULL) {
674 			return bdev;
675 		} else {
676 			bdev = TAILQ_NEXT(bdev, internal.link);
677 		}
678 	}
679 
680 	return bdev;
681 }
682 
683 struct spdk_bdev *
684 spdk_bdev_first_leaf(void)
685 {
686 	struct spdk_bdev *bdev;
687 
688 	bdev = _bdev_next_leaf(TAILQ_FIRST(&g_bdev_mgr.bdevs));
689 
690 	if (bdev) {
691 		SPDK_DEBUGLOG(bdev, "Starting bdev iteration at %s\n", bdev->name);
692 	}
693 
694 	return bdev;
695 }
696 
697 struct spdk_bdev *
698 spdk_bdev_next_leaf(struct spdk_bdev *prev)
699 {
700 	struct spdk_bdev *bdev;
701 
702 	bdev = _bdev_next_leaf(TAILQ_NEXT(prev, internal.link));
703 
704 	if (bdev) {
705 		SPDK_DEBUGLOG(bdev, "Continuing bdev iteration at %s\n", bdev->name);
706 	}
707 
708 	return bdev;
709 }
710 
711 struct spdk_bdev *
712 spdk_bdev_get_by_name(const char *bdev_name)
713 {
714 	struct spdk_bdev_alias *tmp;
715 	struct spdk_bdev *bdev = spdk_bdev_first();
716 
717 	while (bdev != NULL) {
718 		if (strcmp(bdev_name, bdev->name) == 0) {
719 			return bdev;
720 		}
721 
722 		TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
723 			if (strcmp(bdev_name, tmp->alias) == 0) {
724 				return bdev;
725 			}
726 		}
727 
728 		bdev = spdk_bdev_next(bdev);
729 	}
730 
731 	return NULL;
732 }
733 
734 void
735 spdk_bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len)
736 {
737 	struct iovec *iovs;
738 
739 	if (bdev_io->u.bdev.iovs == NULL) {
740 		bdev_io->u.bdev.iovs = &bdev_io->iov;
741 		bdev_io->u.bdev.iovcnt = 1;
742 	}
743 
744 	iovs = bdev_io->u.bdev.iovs;
745 
746 	assert(iovs != NULL);
747 	assert(bdev_io->u.bdev.iovcnt >= 1);
748 
749 	iovs[0].iov_base = buf;
750 	iovs[0].iov_len = len;
751 }
752 
753 void
754 spdk_bdev_io_set_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
755 {
756 	assert((len / spdk_bdev_get_md_size(bdev_io->bdev)) >= bdev_io->u.bdev.num_blocks);
757 	bdev_io->u.bdev.md_buf = md_buf;
758 }
759 
760 static bool
761 _is_buf_allocated(const struct iovec *iovs)
762 {
763 	if (iovs == NULL) {
764 		return false;
765 	}
766 
767 	return iovs[0].iov_base != NULL;
768 }
769 
770 static bool
771 _are_iovs_aligned(struct iovec *iovs, int iovcnt, uint32_t alignment)
772 {
773 	int i;
774 	uintptr_t iov_base;
775 
776 	if (spdk_likely(alignment == 1)) {
777 		return true;
778 	}
779 
780 	for (i = 0; i < iovcnt; i++) {
781 		iov_base = (uintptr_t)iovs[i].iov_base;
782 		if ((iov_base & (alignment - 1)) != 0) {
783 			return false;
784 		}
785 	}
786 
787 	return true;
788 }
789 
790 static void
791 _copy_iovs_to_buf(void *buf, size_t buf_len, struct iovec *iovs, int iovcnt)
792 {
793 	int i;
794 	size_t len;
795 
796 	for (i = 0; i < iovcnt; i++) {
797 		len = spdk_min(iovs[i].iov_len, buf_len);
798 		memcpy(buf, iovs[i].iov_base, len);
799 		buf += len;
800 		buf_len -= len;
801 	}
802 }
803 
804 static void
805 _copy_buf_to_iovs(struct iovec *iovs, int iovcnt, void *buf, size_t buf_len)
806 {
807 	int i;
808 	size_t len;
809 
810 	for (i = 0; i < iovcnt; i++) {
811 		len = spdk_min(iovs[i].iov_len, buf_len);
812 		memcpy(iovs[i].iov_base, buf, len);
813 		buf += len;
814 		buf_len -= len;
815 	}
816 }
817 
818 static void
819 _bdev_io_set_bounce_buf(struct spdk_bdev_io *bdev_io, void *buf, size_t len)
820 {
821 	/* save original iovec */
822 	bdev_io->internal.orig_iovs = bdev_io->u.bdev.iovs;
823 	bdev_io->internal.orig_iovcnt = bdev_io->u.bdev.iovcnt;
824 	/* set bounce iov */
825 	bdev_io->u.bdev.iovs = &bdev_io->internal.bounce_iov;
826 	bdev_io->u.bdev.iovcnt = 1;
827 	/* set bounce buffer for this operation */
828 	bdev_io->u.bdev.iovs[0].iov_base = buf;
829 	bdev_io->u.bdev.iovs[0].iov_len = len;
830 	/* if this is write path, copy data from original buffer to bounce buffer */
831 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
832 		_copy_iovs_to_buf(buf, len, bdev_io->internal.orig_iovs, bdev_io->internal.orig_iovcnt);
833 	}
834 }
835 
836 static void
837 _bdev_io_set_bounce_md_buf(struct spdk_bdev_io *bdev_io, void *md_buf, size_t len)
838 {
839 	/* save original md_buf */
840 	bdev_io->internal.orig_md_buf = bdev_io->u.bdev.md_buf;
841 	/* set bounce md_buf */
842 	bdev_io->u.bdev.md_buf = md_buf;
843 
844 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
845 		memcpy(md_buf, bdev_io->internal.orig_md_buf, len);
846 	}
847 }
848 
849 static void
850 bdev_io_get_buf_complete(struct spdk_bdev_io *bdev_io, void *buf, bool status)
851 {
852 	struct spdk_io_channel *ch = spdk_bdev_io_get_io_channel(bdev_io);
853 
854 	if (spdk_unlikely(bdev_io->internal.get_aux_buf_cb != NULL)) {
855 		bdev_io->internal.get_aux_buf_cb(ch, bdev_io, buf);
856 		bdev_io->internal.get_aux_buf_cb = NULL;
857 	} else {
858 		assert(bdev_io->internal.get_buf_cb != NULL);
859 		bdev_io->internal.buf = buf;
860 		bdev_io->internal.get_buf_cb(ch, bdev_io, status);
861 		bdev_io->internal.get_buf_cb = NULL;
862 	}
863 }
864 
865 static void
866 _bdev_io_set_buf(struct spdk_bdev_io *bdev_io, void *buf, uint64_t len)
867 {
868 	struct spdk_bdev *bdev = bdev_io->bdev;
869 	bool buf_allocated;
870 	uint64_t md_len, alignment;
871 	void *aligned_buf;
872 
873 	if (spdk_unlikely(bdev_io->internal.get_aux_buf_cb != NULL)) {
874 		bdev_io_get_buf_complete(bdev_io, buf, true);
875 		return;
876 	}
877 
878 	alignment = spdk_bdev_get_buf_align(bdev);
879 	buf_allocated = _is_buf_allocated(bdev_io->u.bdev.iovs);
880 	aligned_buf = (void *)(((uintptr_t)buf + (alignment - 1)) & ~(alignment - 1));
881 
882 	if (buf_allocated) {
883 		_bdev_io_set_bounce_buf(bdev_io, aligned_buf, len);
884 	} else {
885 		spdk_bdev_io_set_buf(bdev_io, aligned_buf, len);
886 	}
887 
888 	if (spdk_bdev_is_md_separate(bdev)) {
889 		aligned_buf = (char *)aligned_buf + len;
890 		md_len = bdev_io->u.bdev.num_blocks * bdev->md_len;
891 
892 		assert(((uintptr_t)aligned_buf & (alignment - 1)) == 0);
893 
894 		if (bdev_io->u.bdev.md_buf != NULL) {
895 			_bdev_io_set_bounce_md_buf(bdev_io, aligned_buf, md_len);
896 		} else {
897 			spdk_bdev_io_set_md_buf(bdev_io, aligned_buf, md_len);
898 		}
899 	}
900 	bdev_io_get_buf_complete(bdev_io, buf, true);
901 }
902 
903 static void
904 _bdev_io_put_buf(struct spdk_bdev_io *bdev_io, void *buf, uint64_t buf_len)
905 {
906 	struct spdk_bdev *bdev = bdev_io->bdev;
907 	struct spdk_mempool *pool;
908 	struct spdk_bdev_io *tmp;
909 	bdev_io_stailq_t *stailq;
910 	struct spdk_bdev_mgmt_channel *ch;
911 	uint64_t md_len, alignment;
912 
913 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
914 	alignment = spdk_bdev_get_buf_align(bdev);
915 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
916 
917 	if (buf_len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
918 	    SPDK_BDEV_POOL_ALIGNMENT) {
919 		pool = g_bdev_mgr.buf_small_pool;
920 		stailq = &ch->need_buf_small;
921 	} else {
922 		pool = g_bdev_mgr.buf_large_pool;
923 		stailq = &ch->need_buf_large;
924 	}
925 
926 	if (STAILQ_EMPTY(stailq)) {
927 		spdk_mempool_put(pool, buf);
928 	} else {
929 		tmp = STAILQ_FIRST(stailq);
930 		STAILQ_REMOVE_HEAD(stailq, internal.buf_link);
931 		_bdev_io_set_buf(tmp, buf, tmp->internal.buf_len);
932 	}
933 }
934 
935 static void
936 bdev_io_put_buf(struct spdk_bdev_io *bdev_io)
937 {
938 	assert(bdev_io->internal.buf != NULL);
939 	_bdev_io_put_buf(bdev_io, bdev_io->internal.buf, bdev_io->internal.buf_len);
940 	bdev_io->internal.buf = NULL;
941 }
942 
943 void
944 spdk_bdev_io_put_aux_buf(struct spdk_bdev_io *bdev_io, void *buf)
945 {
946 	uint64_t len = bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
947 
948 	assert(buf != NULL);
949 	_bdev_io_put_buf(bdev_io, buf, len);
950 }
951 
952 static void
953 _bdev_io_unset_bounce_buf(struct spdk_bdev_io *bdev_io)
954 {
955 	if (spdk_likely(bdev_io->internal.orig_iovcnt == 0)) {
956 		assert(bdev_io->internal.orig_md_buf == NULL);
957 		return;
958 	}
959 
960 	/* if this is read path, copy data from bounce buffer to original buffer */
961 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
962 	    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
963 		_copy_buf_to_iovs(bdev_io->internal.orig_iovs,
964 				  bdev_io->internal.orig_iovcnt,
965 				  bdev_io->internal.bounce_iov.iov_base,
966 				  bdev_io->internal.bounce_iov.iov_len);
967 	}
968 	/* set original buffer for this io */
969 	bdev_io->u.bdev.iovcnt = bdev_io->internal.orig_iovcnt;
970 	bdev_io->u.bdev.iovs = bdev_io->internal.orig_iovs;
971 	/* disable bouncing buffer for this io */
972 	bdev_io->internal.orig_iovcnt = 0;
973 	bdev_io->internal.orig_iovs = NULL;
974 
975 	/* do the same for metadata buffer */
976 	if (spdk_unlikely(bdev_io->internal.orig_md_buf != NULL)) {
977 		assert(spdk_bdev_is_md_separate(bdev_io->bdev));
978 
979 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ &&
980 		    bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
981 			memcpy(bdev_io->internal.orig_md_buf, bdev_io->u.bdev.md_buf,
982 			       bdev_io->u.bdev.num_blocks * spdk_bdev_get_md_size(bdev_io->bdev));
983 		}
984 
985 		bdev_io->u.bdev.md_buf = bdev_io->internal.orig_md_buf;
986 		bdev_io->internal.orig_md_buf = NULL;
987 	}
988 
989 	/* We want to free the bounce buffer here since we know we're done with it (as opposed
990 	 * to waiting for the conditional free of internal.buf in spdk_bdev_free_io()).
991 	 */
992 	bdev_io_put_buf(bdev_io);
993 }
994 
995 static void
996 bdev_io_get_buf(struct spdk_bdev_io *bdev_io, uint64_t len)
997 {
998 	struct spdk_bdev *bdev = bdev_io->bdev;
999 	struct spdk_mempool *pool;
1000 	bdev_io_stailq_t *stailq;
1001 	struct spdk_bdev_mgmt_channel *mgmt_ch;
1002 	uint64_t alignment, md_len;
1003 	void *buf;
1004 
1005 	alignment = spdk_bdev_get_buf_align(bdev);
1006 	md_len = spdk_bdev_is_md_separate(bdev) ? bdev_io->u.bdev.num_blocks * bdev->md_len : 0;
1007 
1008 	if (len + alignment + md_len > SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
1009 	    SPDK_BDEV_POOL_ALIGNMENT) {
1010 		SPDK_ERRLOG("Length + alignment %" PRIu64 " is larger than allowed\n",
1011 			    len + alignment);
1012 		bdev_io_get_buf_complete(bdev_io, NULL, false);
1013 		return;
1014 	}
1015 
1016 	mgmt_ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
1017 
1018 	bdev_io->internal.buf_len = len;
1019 
1020 	if (len + alignment + md_len <= SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
1021 	    SPDK_BDEV_POOL_ALIGNMENT) {
1022 		pool = g_bdev_mgr.buf_small_pool;
1023 		stailq = &mgmt_ch->need_buf_small;
1024 	} else {
1025 		pool = g_bdev_mgr.buf_large_pool;
1026 		stailq = &mgmt_ch->need_buf_large;
1027 	}
1028 
1029 	buf = spdk_mempool_get(pool);
1030 	if (!buf) {
1031 		STAILQ_INSERT_TAIL(stailq, bdev_io, internal.buf_link);
1032 	} else {
1033 		_bdev_io_set_buf(bdev_io, buf, len);
1034 	}
1035 }
1036 
1037 void
1038 spdk_bdev_io_get_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_buf_cb cb, uint64_t len)
1039 {
1040 	struct spdk_bdev *bdev = bdev_io->bdev;
1041 	uint64_t alignment;
1042 
1043 	assert(cb != NULL);
1044 	bdev_io->internal.get_buf_cb = cb;
1045 
1046 	alignment = spdk_bdev_get_buf_align(bdev);
1047 
1048 	if (_is_buf_allocated(bdev_io->u.bdev.iovs) &&
1049 	    _are_iovs_aligned(bdev_io->u.bdev.iovs, bdev_io->u.bdev.iovcnt, alignment)) {
1050 		/* Buffer already present and aligned */
1051 		cb(spdk_bdev_io_get_io_channel(bdev_io), bdev_io, true);
1052 		return;
1053 	}
1054 
1055 	bdev_io_get_buf(bdev_io, len);
1056 }
1057 
1058 void
1059 spdk_bdev_io_get_aux_buf(struct spdk_bdev_io *bdev_io, spdk_bdev_io_get_aux_buf_cb cb)
1060 {
1061 	uint64_t len = bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
1062 
1063 	assert(cb != NULL);
1064 	assert(bdev_io->internal.get_aux_buf_cb == NULL);
1065 	bdev_io->internal.get_aux_buf_cb = cb;
1066 	bdev_io_get_buf(bdev_io, len);
1067 }
1068 
1069 static int
1070 bdev_module_get_max_ctx_size(void)
1071 {
1072 	struct spdk_bdev_module *bdev_module;
1073 	int max_bdev_module_size = 0;
1074 
1075 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1076 		if (bdev_module->get_ctx_size && bdev_module->get_ctx_size() > max_bdev_module_size) {
1077 			max_bdev_module_size = bdev_module->get_ctx_size();
1078 		}
1079 	}
1080 
1081 	return max_bdev_module_size;
1082 }
1083 
1084 static void
1085 bdev_qos_config_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
1086 {
1087 	int i;
1088 	struct spdk_bdev_qos *qos = bdev->internal.qos;
1089 	uint64_t limits[SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES];
1090 
1091 	if (!qos) {
1092 		return;
1093 	}
1094 
1095 	spdk_bdev_get_qos_rate_limits(bdev, limits);
1096 
1097 	spdk_json_write_object_begin(w);
1098 	spdk_json_write_named_string(w, "method", "bdev_set_qos_limit");
1099 
1100 	spdk_json_write_named_object_begin(w, "params");
1101 	spdk_json_write_named_string(w, "name", bdev->name);
1102 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1103 		if (limits[i] > 0) {
1104 			spdk_json_write_named_uint64(w, qos_rpc_type[i], limits[i]);
1105 		}
1106 	}
1107 	spdk_json_write_object_end(w);
1108 
1109 	spdk_json_write_object_end(w);
1110 }
1111 
1112 void
1113 spdk_bdev_subsystem_config_json(struct spdk_json_write_ctx *w)
1114 {
1115 	struct spdk_bdev_module *bdev_module;
1116 	struct spdk_bdev *bdev;
1117 
1118 	assert(w != NULL);
1119 
1120 	spdk_json_write_array_begin(w);
1121 
1122 	spdk_json_write_object_begin(w);
1123 	spdk_json_write_named_string(w, "method", "bdev_set_options");
1124 	spdk_json_write_named_object_begin(w, "params");
1125 	spdk_json_write_named_uint32(w, "bdev_io_pool_size", g_bdev_opts.bdev_io_pool_size);
1126 	spdk_json_write_named_uint32(w, "bdev_io_cache_size", g_bdev_opts.bdev_io_cache_size);
1127 	spdk_json_write_named_bool(w, "bdev_auto_examine", g_bdev_opts.bdev_auto_examine);
1128 	spdk_json_write_object_end(w);
1129 	spdk_json_write_object_end(w);
1130 
1131 	bdev_examine_allowlist_config_json(w);
1132 
1133 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1134 		if (bdev_module->config_json) {
1135 			bdev_module->config_json(w);
1136 		}
1137 	}
1138 
1139 	pthread_mutex_lock(&g_bdev_mgr.mutex);
1140 
1141 	TAILQ_FOREACH(bdev, &g_bdev_mgr.bdevs, internal.link) {
1142 		if (bdev->fn_table->write_config_json) {
1143 			bdev->fn_table->write_config_json(bdev, w);
1144 		}
1145 
1146 		bdev_qos_config_json(bdev, w);
1147 	}
1148 
1149 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
1150 
1151 	/* This has to be last RPC in array to make sure all bdevs finished examine */
1152 	spdk_json_write_object_begin(w);
1153 	spdk_json_write_named_string(w, "method", "bdev_wait_for_examine");
1154 	spdk_json_write_object_end(w);
1155 
1156 	spdk_json_write_array_end(w);
1157 }
1158 
1159 static int
1160 bdev_mgmt_channel_create(void *io_device, void *ctx_buf)
1161 {
1162 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
1163 	struct spdk_bdev_io *bdev_io;
1164 	uint32_t i;
1165 
1166 	STAILQ_INIT(&ch->need_buf_small);
1167 	STAILQ_INIT(&ch->need_buf_large);
1168 
1169 	STAILQ_INIT(&ch->per_thread_cache);
1170 	ch->bdev_io_cache_size = g_bdev_opts.bdev_io_cache_size;
1171 
1172 	/* Pre-populate bdev_io cache to ensure this thread cannot be starved. */
1173 	ch->per_thread_cache_count = 0;
1174 	for (i = 0; i < ch->bdev_io_cache_size; i++) {
1175 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
1176 		assert(bdev_io != NULL);
1177 		ch->per_thread_cache_count++;
1178 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
1179 	}
1180 
1181 	TAILQ_INIT(&ch->shared_resources);
1182 	TAILQ_INIT(&ch->io_wait_queue);
1183 
1184 	return 0;
1185 }
1186 
1187 static void
1188 bdev_mgmt_channel_destroy(void *io_device, void *ctx_buf)
1189 {
1190 	struct spdk_bdev_mgmt_channel *ch = ctx_buf;
1191 	struct spdk_bdev_io *bdev_io;
1192 
1193 	if (!STAILQ_EMPTY(&ch->need_buf_small) || !STAILQ_EMPTY(&ch->need_buf_large)) {
1194 		SPDK_ERRLOG("Pending I/O list wasn't empty on mgmt channel free\n");
1195 	}
1196 
1197 	if (!TAILQ_EMPTY(&ch->shared_resources)) {
1198 		SPDK_ERRLOG("Module channel list wasn't empty on mgmt channel free\n");
1199 	}
1200 
1201 	while (!STAILQ_EMPTY(&ch->per_thread_cache)) {
1202 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
1203 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
1204 		ch->per_thread_cache_count--;
1205 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
1206 	}
1207 
1208 	assert(ch->per_thread_cache_count == 0);
1209 }
1210 
1211 static void
1212 bdev_init_complete(int rc)
1213 {
1214 	spdk_bdev_init_cb cb_fn = g_init_cb_fn;
1215 	void *cb_arg = g_init_cb_arg;
1216 	struct spdk_bdev_module *m;
1217 
1218 	g_bdev_mgr.init_complete = true;
1219 	g_init_cb_fn = NULL;
1220 	g_init_cb_arg = NULL;
1221 
1222 	/*
1223 	 * For modules that need to know when subsystem init is complete,
1224 	 * inform them now.
1225 	 */
1226 	if (rc == 0) {
1227 		TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1228 			if (m->init_complete) {
1229 				m->init_complete();
1230 			}
1231 		}
1232 	}
1233 
1234 	cb_fn(cb_arg, rc);
1235 }
1236 
1237 static bool
1238 bdev_module_all_actions_completed(void)
1239 {
1240 	struct spdk_bdev_module *m;
1241 
1242 	TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1243 		if (m->internal.action_in_progress > 0) {
1244 			return false;
1245 		}
1246 	}
1247 	return true;
1248 }
1249 
1250 static void
1251 bdev_module_action_complete(void)
1252 {
1253 	/*
1254 	 * Don't finish bdev subsystem initialization if
1255 	 * module pre-initialization is still in progress, or
1256 	 * the subsystem been already initialized.
1257 	 */
1258 	if (!g_bdev_mgr.module_init_complete || g_bdev_mgr.init_complete) {
1259 		return;
1260 	}
1261 
1262 	/*
1263 	 * Check all bdev modules for inits/examinations in progress. If any
1264 	 * exist, return immediately since we cannot finish bdev subsystem
1265 	 * initialization until all are completed.
1266 	 */
1267 	if (!bdev_module_all_actions_completed()) {
1268 		return;
1269 	}
1270 
1271 	/*
1272 	 * Modules already finished initialization - now that all
1273 	 * the bdev modules have finished their asynchronous I/O
1274 	 * processing, the entire bdev layer can be marked as complete.
1275 	 */
1276 	bdev_init_complete(0);
1277 }
1278 
1279 static void
1280 bdev_module_action_done(struct spdk_bdev_module *module)
1281 {
1282 	assert(module->internal.action_in_progress > 0);
1283 	module->internal.action_in_progress--;
1284 	bdev_module_action_complete();
1285 }
1286 
1287 void
1288 spdk_bdev_module_init_done(struct spdk_bdev_module *module)
1289 {
1290 	bdev_module_action_done(module);
1291 }
1292 
1293 void
1294 spdk_bdev_module_examine_done(struct spdk_bdev_module *module)
1295 {
1296 	bdev_module_action_done(module);
1297 }
1298 
1299 /** The last initialized bdev module */
1300 static struct spdk_bdev_module *g_resume_bdev_module = NULL;
1301 
1302 static void
1303 bdev_init_failed(void *cb_arg)
1304 {
1305 	struct spdk_bdev_module *module = cb_arg;
1306 
1307 	module->internal.action_in_progress--;
1308 	bdev_init_complete(-1);
1309 }
1310 
1311 static int
1312 bdev_modules_init(void)
1313 {
1314 	struct spdk_bdev_module *module;
1315 	int rc = 0;
1316 
1317 	TAILQ_FOREACH(module, &g_bdev_mgr.bdev_modules, internal.tailq) {
1318 		g_resume_bdev_module = module;
1319 		if (module->async_init) {
1320 			module->internal.action_in_progress = 1;
1321 		}
1322 		rc = module->module_init();
1323 		if (rc != 0) {
1324 			/* Bump action_in_progress to prevent other modules from completion of modules_init
1325 			 * Send message to defer application shutdown until resources are cleaned up */
1326 			module->internal.action_in_progress = 1;
1327 			spdk_thread_send_msg(spdk_get_thread(), bdev_init_failed, module);
1328 			return rc;
1329 		}
1330 	}
1331 
1332 	g_resume_bdev_module = NULL;
1333 	return 0;
1334 }
1335 
1336 void
1337 spdk_bdev_initialize(spdk_bdev_init_cb cb_fn, void *cb_arg)
1338 {
1339 	int cache_size;
1340 	int rc = 0;
1341 	char mempool_name[32];
1342 
1343 	assert(cb_fn != NULL);
1344 
1345 	g_init_cb_fn = cb_fn;
1346 	g_init_cb_arg = cb_arg;
1347 
1348 	spdk_notify_type_register("bdev_register");
1349 	spdk_notify_type_register("bdev_unregister");
1350 
1351 	snprintf(mempool_name, sizeof(mempool_name), "bdev_io_%d", getpid());
1352 
1353 	g_bdev_mgr.bdev_io_pool = spdk_mempool_create(mempool_name,
1354 				  g_bdev_opts.bdev_io_pool_size,
1355 				  sizeof(struct spdk_bdev_io) +
1356 				  bdev_module_get_max_ctx_size(),
1357 				  0,
1358 				  SPDK_ENV_SOCKET_ID_ANY);
1359 
1360 	if (g_bdev_mgr.bdev_io_pool == NULL) {
1361 		SPDK_ERRLOG("could not allocate spdk_bdev_io pool\n");
1362 		bdev_init_complete(-1);
1363 		return;
1364 	}
1365 
1366 	/**
1367 	 * Ensure no more than half of the total buffers end up local caches, by
1368 	 *   using spdk_env_get_core_count() to determine how many local caches we need
1369 	 *   to account for.
1370 	 */
1371 	cache_size = BUF_SMALL_POOL_SIZE / (2 * spdk_env_get_core_count());
1372 	snprintf(mempool_name, sizeof(mempool_name), "buf_small_pool_%d", getpid());
1373 
1374 	g_bdev_mgr.buf_small_pool = spdk_mempool_create(mempool_name,
1375 				    g_bdev_opts.small_buf_pool_size,
1376 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_SMALL_BUF_MAX_SIZE) +
1377 				    SPDK_BDEV_POOL_ALIGNMENT,
1378 				    cache_size,
1379 				    SPDK_ENV_SOCKET_ID_ANY);
1380 	if (!g_bdev_mgr.buf_small_pool) {
1381 		SPDK_ERRLOG("create rbuf small pool failed\n");
1382 		bdev_init_complete(-1);
1383 		return;
1384 	}
1385 
1386 	cache_size = BUF_LARGE_POOL_SIZE / (2 * spdk_env_get_core_count());
1387 	snprintf(mempool_name, sizeof(mempool_name), "buf_large_pool_%d", getpid());
1388 
1389 	g_bdev_mgr.buf_large_pool = spdk_mempool_create(mempool_name,
1390 				    g_bdev_opts.large_buf_pool_size,
1391 				    SPDK_BDEV_BUF_SIZE_WITH_MD(SPDK_BDEV_LARGE_BUF_MAX_SIZE) +
1392 				    SPDK_BDEV_POOL_ALIGNMENT,
1393 				    cache_size,
1394 				    SPDK_ENV_SOCKET_ID_ANY);
1395 	if (!g_bdev_mgr.buf_large_pool) {
1396 		SPDK_ERRLOG("create rbuf large pool failed\n");
1397 		bdev_init_complete(-1);
1398 		return;
1399 	}
1400 
1401 	g_bdev_mgr.zero_buffer = spdk_zmalloc(ZERO_BUFFER_SIZE, ZERO_BUFFER_SIZE,
1402 					      NULL, SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1403 	if (!g_bdev_mgr.zero_buffer) {
1404 		SPDK_ERRLOG("create bdev zero buffer failed\n");
1405 		bdev_init_complete(-1);
1406 		return;
1407 	}
1408 
1409 #ifdef SPDK_CONFIG_VTUNE
1410 	g_bdev_mgr.domain = __itt_domain_create("spdk_bdev");
1411 #endif
1412 
1413 	spdk_io_device_register(&g_bdev_mgr, bdev_mgmt_channel_create,
1414 				bdev_mgmt_channel_destroy,
1415 				sizeof(struct spdk_bdev_mgmt_channel),
1416 				"bdev_mgr");
1417 
1418 	rc = bdev_modules_init();
1419 	g_bdev_mgr.module_init_complete = true;
1420 	if (rc != 0) {
1421 		SPDK_ERRLOG("bdev modules init failed\n");
1422 		return;
1423 	}
1424 
1425 	bdev_module_action_complete();
1426 }
1427 
1428 static void
1429 bdev_mgr_unregister_cb(void *io_device)
1430 {
1431 	spdk_bdev_fini_cb cb_fn = g_fini_cb_fn;
1432 
1433 	if (g_bdev_mgr.bdev_io_pool) {
1434 		if (spdk_mempool_count(g_bdev_mgr.bdev_io_pool) != g_bdev_opts.bdev_io_pool_size) {
1435 			SPDK_ERRLOG("bdev IO pool count is %zu but should be %u\n",
1436 				    spdk_mempool_count(g_bdev_mgr.bdev_io_pool),
1437 				    g_bdev_opts.bdev_io_pool_size);
1438 		}
1439 
1440 		spdk_mempool_free(g_bdev_mgr.bdev_io_pool);
1441 	}
1442 
1443 	if (g_bdev_mgr.buf_small_pool) {
1444 		if (spdk_mempool_count(g_bdev_mgr.buf_small_pool) != g_bdev_opts.small_buf_pool_size) {
1445 			SPDK_ERRLOG("Small buffer pool count is %zu but should be %u\n",
1446 				    spdk_mempool_count(g_bdev_mgr.buf_small_pool),
1447 				    g_bdev_opts.small_buf_pool_size);
1448 			assert(false);
1449 		}
1450 
1451 		spdk_mempool_free(g_bdev_mgr.buf_small_pool);
1452 	}
1453 
1454 	if (g_bdev_mgr.buf_large_pool) {
1455 		if (spdk_mempool_count(g_bdev_mgr.buf_large_pool) != g_bdev_opts.large_buf_pool_size) {
1456 			SPDK_ERRLOG("Large buffer pool count is %zu but should be %u\n",
1457 				    spdk_mempool_count(g_bdev_mgr.buf_large_pool),
1458 				    g_bdev_opts.large_buf_pool_size);
1459 			assert(false);
1460 		}
1461 
1462 		spdk_mempool_free(g_bdev_mgr.buf_large_pool);
1463 	}
1464 
1465 	spdk_free(g_bdev_mgr.zero_buffer);
1466 
1467 	bdev_examine_allowlist_free();
1468 
1469 	cb_fn(g_fini_cb_arg);
1470 	g_fini_cb_fn = NULL;
1471 	g_fini_cb_arg = NULL;
1472 	g_bdev_mgr.init_complete = false;
1473 	g_bdev_mgr.module_init_complete = false;
1474 }
1475 
1476 static void
1477 bdev_module_finish_iter(void *arg)
1478 {
1479 	struct spdk_bdev_module *bdev_module;
1480 
1481 	/* FIXME: Handling initialization failures is broken now,
1482 	 * so we won't even try cleaning up after successfully
1483 	 * initialized modules. if module_init_complete is false,
1484 	 * just call spdk_bdev_mgr_unregister_cb
1485 	 */
1486 	if (!g_bdev_mgr.module_init_complete) {
1487 		bdev_mgr_unregister_cb(NULL);
1488 		return;
1489 	}
1490 
1491 	/* Start iterating from the last touched module */
1492 	if (!g_resume_bdev_module) {
1493 		bdev_module = TAILQ_LAST(&g_bdev_mgr.bdev_modules, bdev_module_list);
1494 	} else {
1495 		bdev_module = TAILQ_PREV(g_resume_bdev_module, bdev_module_list,
1496 					 internal.tailq);
1497 	}
1498 
1499 	while (bdev_module) {
1500 		if (bdev_module->async_fini) {
1501 			/* Save our place so we can resume later. We must
1502 			 * save the variable here, before calling module_fini()
1503 			 * below, because in some cases the module may immediately
1504 			 * call spdk_bdev_module_finish_done() and re-enter
1505 			 * this function to continue iterating. */
1506 			g_resume_bdev_module = bdev_module;
1507 		}
1508 
1509 		if (bdev_module->module_fini) {
1510 			bdev_module->module_fini();
1511 		}
1512 
1513 		if (bdev_module->async_fini) {
1514 			return;
1515 		}
1516 
1517 		bdev_module = TAILQ_PREV(bdev_module, bdev_module_list,
1518 					 internal.tailq);
1519 	}
1520 
1521 	g_resume_bdev_module = NULL;
1522 	spdk_io_device_unregister(&g_bdev_mgr, bdev_mgr_unregister_cb);
1523 }
1524 
1525 void
1526 spdk_bdev_module_finish_done(void)
1527 {
1528 	if (spdk_get_thread() != g_fini_thread) {
1529 		spdk_thread_send_msg(g_fini_thread, bdev_module_finish_iter, NULL);
1530 	} else {
1531 		bdev_module_finish_iter(NULL);
1532 	}
1533 }
1534 
1535 static void
1536 bdev_finish_unregister_bdevs_iter(void *cb_arg, int bdeverrno)
1537 {
1538 	struct spdk_bdev *bdev = cb_arg;
1539 
1540 	if (bdeverrno && bdev) {
1541 		SPDK_WARNLOG("Unable to unregister bdev '%s' during spdk_bdev_finish()\n",
1542 			     bdev->name);
1543 
1544 		/*
1545 		 * Since the call to spdk_bdev_unregister() failed, we have no way to free this
1546 		 *  bdev; try to continue by manually removing this bdev from the list and continue
1547 		 *  with the next bdev in the list.
1548 		 */
1549 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
1550 	}
1551 
1552 	if (TAILQ_EMPTY(&g_bdev_mgr.bdevs)) {
1553 		SPDK_DEBUGLOG(bdev, "Done unregistering bdevs\n");
1554 		/*
1555 		 * Bdev module finish need to be deferred as we might be in the middle of some context
1556 		 * (like bdev part free) that will use this bdev (or private bdev driver ctx data)
1557 		 * after returning.
1558 		 */
1559 		spdk_thread_send_msg(spdk_get_thread(), bdev_module_finish_iter, NULL);
1560 		return;
1561 	}
1562 
1563 	/*
1564 	 * Unregister last unclaimed bdev in the list, to ensure that bdev subsystem
1565 	 * shutdown proceeds top-down. The goal is to give virtual bdevs an opportunity
1566 	 * to detect clean shutdown as opposed to run-time hot removal of the underlying
1567 	 * base bdevs.
1568 	 *
1569 	 * Also, walk the list in the reverse order.
1570 	 */
1571 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1572 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1573 		if (bdev->internal.claim_module != NULL) {
1574 			SPDK_DEBUGLOG(bdev, "Skipping claimed bdev '%s'(<-'%s').\n",
1575 				      bdev->name, bdev->internal.claim_module->name);
1576 			continue;
1577 		}
1578 
1579 		SPDK_DEBUGLOG(bdev, "Unregistering bdev '%s'\n", bdev->name);
1580 		spdk_bdev_unregister(bdev, bdev_finish_unregister_bdevs_iter, bdev);
1581 		return;
1582 	}
1583 
1584 	/*
1585 	 * If any bdev fails to unclaim underlying bdev properly, we may face the
1586 	 * case of bdev list consisting of claimed bdevs only (if claims are managed
1587 	 * correctly, this would mean there's a loop in the claims graph which is
1588 	 * clearly impossible). Warn and unregister last bdev on the list then.
1589 	 */
1590 	for (bdev = TAILQ_LAST(&g_bdev_mgr.bdevs, spdk_bdev_list);
1591 	     bdev; bdev = TAILQ_PREV(bdev, spdk_bdev_list, internal.link)) {
1592 		SPDK_WARNLOG("Unregistering claimed bdev '%s'!\n", bdev->name);
1593 		spdk_bdev_unregister(bdev, bdev_finish_unregister_bdevs_iter, bdev);
1594 		return;
1595 	}
1596 }
1597 
1598 void
1599 spdk_bdev_finish(spdk_bdev_fini_cb cb_fn, void *cb_arg)
1600 {
1601 	struct spdk_bdev_module *m;
1602 
1603 	assert(cb_fn != NULL);
1604 
1605 	g_fini_thread = spdk_get_thread();
1606 
1607 	g_fini_cb_fn = cb_fn;
1608 	g_fini_cb_arg = cb_arg;
1609 
1610 	TAILQ_FOREACH(m, &g_bdev_mgr.bdev_modules, internal.tailq) {
1611 		if (m->fini_start) {
1612 			m->fini_start();
1613 		}
1614 	}
1615 
1616 	bdev_finish_unregister_bdevs_iter(NULL, 0);
1617 }
1618 
1619 struct spdk_bdev_io *
1620 bdev_channel_get_io(struct spdk_bdev_channel *channel)
1621 {
1622 	struct spdk_bdev_mgmt_channel *ch = channel->shared_resource->mgmt_ch;
1623 	struct spdk_bdev_io *bdev_io;
1624 
1625 	if (ch->per_thread_cache_count > 0) {
1626 		bdev_io = STAILQ_FIRST(&ch->per_thread_cache);
1627 		STAILQ_REMOVE_HEAD(&ch->per_thread_cache, internal.buf_link);
1628 		ch->per_thread_cache_count--;
1629 	} else if (spdk_unlikely(!TAILQ_EMPTY(&ch->io_wait_queue))) {
1630 		/*
1631 		 * Don't try to look for bdev_ios in the global pool if there are
1632 		 * waiters on bdev_ios - we don't want this caller to jump the line.
1633 		 */
1634 		bdev_io = NULL;
1635 	} else {
1636 		bdev_io = spdk_mempool_get(g_bdev_mgr.bdev_io_pool);
1637 	}
1638 
1639 	return bdev_io;
1640 }
1641 
1642 void
1643 spdk_bdev_free_io(struct spdk_bdev_io *bdev_io)
1644 {
1645 	struct spdk_bdev_mgmt_channel *ch;
1646 
1647 	assert(bdev_io != NULL);
1648 	assert(bdev_io->internal.status != SPDK_BDEV_IO_STATUS_PENDING);
1649 
1650 	ch = bdev_io->internal.ch->shared_resource->mgmt_ch;
1651 
1652 	if (bdev_io->internal.buf != NULL) {
1653 		bdev_io_put_buf(bdev_io);
1654 	}
1655 
1656 	if (ch->per_thread_cache_count < ch->bdev_io_cache_size) {
1657 		ch->per_thread_cache_count++;
1658 		STAILQ_INSERT_HEAD(&ch->per_thread_cache, bdev_io, internal.buf_link);
1659 		while (ch->per_thread_cache_count > 0 && !TAILQ_EMPTY(&ch->io_wait_queue)) {
1660 			struct spdk_bdev_io_wait_entry *entry;
1661 
1662 			entry = TAILQ_FIRST(&ch->io_wait_queue);
1663 			TAILQ_REMOVE(&ch->io_wait_queue, entry, link);
1664 			entry->cb_fn(entry->cb_arg);
1665 		}
1666 	} else {
1667 		/* We should never have a full cache with entries on the io wait queue. */
1668 		assert(TAILQ_EMPTY(&ch->io_wait_queue));
1669 		spdk_mempool_put(g_bdev_mgr.bdev_io_pool, (void *)bdev_io);
1670 	}
1671 }
1672 
1673 static bool
1674 bdev_qos_is_iops_rate_limit(enum spdk_bdev_qos_rate_limit_type limit)
1675 {
1676 	assert(limit != SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
1677 
1678 	switch (limit) {
1679 	case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
1680 		return true;
1681 	case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
1682 	case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
1683 	case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
1684 		return false;
1685 	case SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES:
1686 	default:
1687 		return false;
1688 	}
1689 }
1690 
1691 static bool
1692 bdev_qos_io_to_limit(struct spdk_bdev_io *bdev_io)
1693 {
1694 	switch (bdev_io->type) {
1695 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1696 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1697 	case SPDK_BDEV_IO_TYPE_READ:
1698 	case SPDK_BDEV_IO_TYPE_WRITE:
1699 		return true;
1700 	case SPDK_BDEV_IO_TYPE_ZCOPY:
1701 		if (bdev_io->u.bdev.zcopy.start) {
1702 			return true;
1703 		} else {
1704 			return false;
1705 		}
1706 	default:
1707 		return false;
1708 	}
1709 }
1710 
1711 static bool
1712 bdev_is_read_io(struct spdk_bdev_io *bdev_io)
1713 {
1714 	switch (bdev_io->type) {
1715 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1716 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1717 		/* Bit 1 (0x2) set for read operation */
1718 		if (bdev_io->u.nvme_passthru.cmd.opc & SPDK_NVME_OPC_READ) {
1719 			return true;
1720 		} else {
1721 			return false;
1722 		}
1723 	case SPDK_BDEV_IO_TYPE_READ:
1724 		return true;
1725 	case SPDK_BDEV_IO_TYPE_ZCOPY:
1726 		/* Populate to read from disk */
1727 		if (bdev_io->u.bdev.zcopy.populate) {
1728 			return true;
1729 		} else {
1730 			return false;
1731 		}
1732 	default:
1733 		return false;
1734 	}
1735 }
1736 
1737 static uint64_t
1738 bdev_get_io_size_in_byte(struct spdk_bdev_io *bdev_io)
1739 {
1740 	struct spdk_bdev	*bdev = bdev_io->bdev;
1741 
1742 	switch (bdev_io->type) {
1743 	case SPDK_BDEV_IO_TYPE_NVME_IO:
1744 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
1745 		return bdev_io->u.nvme_passthru.nbytes;
1746 	case SPDK_BDEV_IO_TYPE_READ:
1747 	case SPDK_BDEV_IO_TYPE_WRITE:
1748 		return bdev_io->u.bdev.num_blocks * bdev->blocklen;
1749 	case SPDK_BDEV_IO_TYPE_ZCOPY:
1750 		/* Track the data in the start phase only */
1751 		if (bdev_io->u.bdev.zcopy.start) {
1752 			return bdev_io->u.bdev.num_blocks * bdev->blocklen;
1753 		} else {
1754 			return 0;
1755 		}
1756 	default:
1757 		return 0;
1758 	}
1759 }
1760 
1761 static bool
1762 bdev_qos_rw_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1763 {
1764 	if (limit->max_per_timeslice > 0 && limit->remaining_this_timeslice <= 0) {
1765 		return true;
1766 	} else {
1767 		return false;
1768 	}
1769 }
1770 
1771 static bool
1772 bdev_qos_r_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1773 {
1774 	if (bdev_is_read_io(io) == false) {
1775 		return false;
1776 	}
1777 
1778 	return bdev_qos_rw_queue_io(limit, io);
1779 }
1780 
1781 static bool
1782 bdev_qos_w_queue_io(const struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1783 {
1784 	if (bdev_is_read_io(io) == true) {
1785 		return false;
1786 	}
1787 
1788 	return bdev_qos_rw_queue_io(limit, io);
1789 }
1790 
1791 static void
1792 bdev_qos_rw_iops_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1793 {
1794 	limit->remaining_this_timeslice--;
1795 }
1796 
1797 static void
1798 bdev_qos_rw_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1799 {
1800 	limit->remaining_this_timeslice -= bdev_get_io_size_in_byte(io);
1801 }
1802 
1803 static void
1804 bdev_qos_r_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1805 {
1806 	if (bdev_is_read_io(io) == false) {
1807 		return;
1808 	}
1809 
1810 	return bdev_qos_rw_bps_update_quota(limit, io);
1811 }
1812 
1813 static void
1814 bdev_qos_w_bps_update_quota(struct spdk_bdev_qos_limit *limit, struct spdk_bdev_io *io)
1815 {
1816 	if (bdev_is_read_io(io) == true) {
1817 		return;
1818 	}
1819 
1820 	return bdev_qos_rw_bps_update_quota(limit, io);
1821 }
1822 
1823 static void
1824 bdev_qos_set_ops(struct spdk_bdev_qos *qos)
1825 {
1826 	int i;
1827 
1828 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1829 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
1830 			qos->rate_limits[i].queue_io = NULL;
1831 			qos->rate_limits[i].update_quota = NULL;
1832 			continue;
1833 		}
1834 
1835 		switch (i) {
1836 		case SPDK_BDEV_QOS_RW_IOPS_RATE_LIMIT:
1837 			qos->rate_limits[i].queue_io = bdev_qos_rw_queue_io;
1838 			qos->rate_limits[i].update_quota = bdev_qos_rw_iops_update_quota;
1839 			break;
1840 		case SPDK_BDEV_QOS_RW_BPS_RATE_LIMIT:
1841 			qos->rate_limits[i].queue_io = bdev_qos_rw_queue_io;
1842 			qos->rate_limits[i].update_quota = bdev_qos_rw_bps_update_quota;
1843 			break;
1844 		case SPDK_BDEV_QOS_R_BPS_RATE_LIMIT:
1845 			qos->rate_limits[i].queue_io = bdev_qos_r_queue_io;
1846 			qos->rate_limits[i].update_quota = bdev_qos_r_bps_update_quota;
1847 			break;
1848 		case SPDK_BDEV_QOS_W_BPS_RATE_LIMIT:
1849 			qos->rate_limits[i].queue_io = bdev_qos_w_queue_io;
1850 			qos->rate_limits[i].update_quota = bdev_qos_w_bps_update_quota;
1851 			break;
1852 		default:
1853 			break;
1854 		}
1855 	}
1856 }
1857 
1858 static void
1859 _bdev_io_complete_in_submit(struct spdk_bdev_channel *bdev_ch,
1860 			    struct spdk_bdev_io *bdev_io,
1861 			    enum spdk_bdev_io_status status)
1862 {
1863 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1864 
1865 	bdev_io->internal.in_submit_request = true;
1866 	bdev_ch->io_outstanding++;
1867 	shared_resource->io_outstanding++;
1868 	spdk_bdev_io_complete(bdev_io, status);
1869 	bdev_io->internal.in_submit_request = false;
1870 }
1871 
1872 static inline void
1873 bdev_io_do_submit(struct spdk_bdev_channel *bdev_ch, struct spdk_bdev_io *bdev_io)
1874 {
1875 	struct spdk_bdev *bdev = bdev_io->bdev;
1876 	struct spdk_io_channel *ch = bdev_ch->channel;
1877 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
1878 
1879 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_ABORT)) {
1880 		struct spdk_bdev_mgmt_channel *mgmt_channel = shared_resource->mgmt_ch;
1881 		struct spdk_bdev_io *bio_to_abort = bdev_io->u.abort.bio_to_abort;
1882 
1883 		if (bdev_abort_queued_io(&shared_resource->nomem_io, bio_to_abort) ||
1884 		    bdev_abort_buf_io(&mgmt_channel->need_buf_small, bio_to_abort) ||
1885 		    bdev_abort_buf_io(&mgmt_channel->need_buf_large, bio_to_abort)) {
1886 			_bdev_io_complete_in_submit(bdev_ch, bdev_io,
1887 						    SPDK_BDEV_IO_STATUS_SUCCESS);
1888 			return;
1889 		}
1890 	}
1891 
1892 	if (spdk_likely(TAILQ_EMPTY(&shared_resource->nomem_io))) {
1893 		bdev_ch->io_outstanding++;
1894 		shared_resource->io_outstanding++;
1895 		bdev_io->internal.in_submit_request = true;
1896 		bdev->fn_table->submit_request(ch, bdev_io);
1897 		bdev_io->internal.in_submit_request = false;
1898 	} else {
1899 		TAILQ_INSERT_TAIL(&shared_resource->nomem_io, bdev_io, internal.link);
1900 	}
1901 }
1902 
1903 static int
1904 bdev_qos_io_submit(struct spdk_bdev_channel *ch, struct spdk_bdev_qos *qos)
1905 {
1906 	struct spdk_bdev_io		*bdev_io = NULL, *tmp = NULL;
1907 	int				i, submitted_ios = 0;
1908 
1909 	TAILQ_FOREACH_SAFE(bdev_io, &qos->queued, internal.link, tmp) {
1910 		if (bdev_qos_io_to_limit(bdev_io) == true) {
1911 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1912 				if (!qos->rate_limits[i].queue_io) {
1913 					continue;
1914 				}
1915 
1916 				if (qos->rate_limits[i].queue_io(&qos->rate_limits[i],
1917 								 bdev_io) == true) {
1918 					return submitted_ios;
1919 				}
1920 			}
1921 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
1922 				if (!qos->rate_limits[i].update_quota) {
1923 					continue;
1924 				}
1925 
1926 				qos->rate_limits[i].update_quota(&qos->rate_limits[i], bdev_io);
1927 			}
1928 		}
1929 
1930 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
1931 		bdev_io_do_submit(ch, bdev_io);
1932 		submitted_ios++;
1933 	}
1934 
1935 	return submitted_ios;
1936 }
1937 
1938 static void
1939 bdev_queue_io_wait_with_cb(struct spdk_bdev_io *bdev_io, spdk_bdev_io_wait_cb cb_fn)
1940 {
1941 	int rc;
1942 
1943 	bdev_io->internal.waitq_entry.bdev = bdev_io->bdev;
1944 	bdev_io->internal.waitq_entry.cb_fn = cb_fn;
1945 	bdev_io->internal.waitq_entry.cb_arg = bdev_io;
1946 	rc = spdk_bdev_queue_io_wait(bdev_io->bdev, spdk_io_channel_from_ctx(bdev_io->internal.ch),
1947 				     &bdev_io->internal.waitq_entry);
1948 	if (rc != 0) {
1949 		SPDK_ERRLOG("Queue IO failed, rc=%d\n", rc);
1950 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
1951 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
1952 	}
1953 }
1954 
1955 static bool
1956 bdev_io_type_can_split(uint8_t type)
1957 {
1958 	assert(type != SPDK_BDEV_IO_TYPE_INVALID);
1959 	assert(type < SPDK_BDEV_NUM_IO_TYPES);
1960 
1961 	/* Only split READ and WRITE I/O.  Theoretically other types of I/O like
1962 	 * UNMAP could be split, but these types of I/O are typically much larger
1963 	 * in size (sometimes the size of the entire block device), and the bdev
1964 	 * module can more efficiently split these types of I/O.  Plus those types
1965 	 * of I/O do not have a payload, which makes the splitting process simpler.
1966 	 */
1967 	if (type == SPDK_BDEV_IO_TYPE_READ || type == SPDK_BDEV_IO_TYPE_WRITE) {
1968 		return true;
1969 	} else {
1970 		return false;
1971 	}
1972 }
1973 
1974 static bool
1975 bdev_io_should_split(struct spdk_bdev_io *bdev_io)
1976 {
1977 	uint32_t io_boundary = bdev_io->bdev->optimal_io_boundary;
1978 	uint32_t max_size = bdev_io->bdev->max_segment_size;
1979 	int max_segs = bdev_io->bdev->max_num_segments;
1980 
1981 	io_boundary = bdev_io->bdev->split_on_optimal_io_boundary ? io_boundary : 0;
1982 
1983 	if (spdk_likely(!io_boundary && !max_segs && !max_size)) {
1984 		return false;
1985 	}
1986 
1987 	if (!bdev_io_type_can_split(bdev_io->type)) {
1988 		return false;
1989 	}
1990 
1991 	if (io_boundary) {
1992 		uint64_t start_stripe, end_stripe;
1993 
1994 		start_stripe = bdev_io->u.bdev.offset_blocks;
1995 		end_stripe = start_stripe + bdev_io->u.bdev.num_blocks - 1;
1996 		/* Avoid expensive div operations if possible.  These spdk_u32 functions are very cheap. */
1997 		if (spdk_likely(spdk_u32_is_pow2(io_boundary))) {
1998 			start_stripe >>= spdk_u32log2(io_boundary);
1999 			end_stripe >>= spdk_u32log2(io_boundary);
2000 		} else {
2001 			start_stripe /= io_boundary;
2002 			end_stripe /= io_boundary;
2003 		}
2004 
2005 		if (start_stripe != end_stripe) {
2006 			return true;
2007 		}
2008 	}
2009 
2010 	if (max_segs) {
2011 		if (bdev_io->u.bdev.iovcnt > max_segs) {
2012 			return true;
2013 		}
2014 	}
2015 
2016 	if (max_size) {
2017 		for (int i = 0; i < bdev_io->u.bdev.iovcnt; i++) {
2018 			if (bdev_io->u.bdev.iovs[i].iov_len > max_size) {
2019 				return true;
2020 			}
2021 		}
2022 	}
2023 
2024 	return false;
2025 }
2026 
2027 static uint32_t
2028 _to_next_boundary(uint64_t offset, uint32_t boundary)
2029 {
2030 	return (boundary - (offset % boundary));
2031 }
2032 
2033 static void
2034 bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
2035 
2036 static void
2037 _bdev_io_split(void *_bdev_io)
2038 {
2039 	struct iovec *parent_iov, *iov;
2040 	struct spdk_bdev_io *bdev_io = _bdev_io;
2041 	struct spdk_bdev *bdev = bdev_io->bdev;
2042 	uint64_t parent_offset, current_offset, remaining;
2043 	uint32_t parent_iov_offset, parent_iovcnt, parent_iovpos, child_iovcnt;
2044 	uint32_t to_next_boundary, to_next_boundary_bytes, to_last_block_bytes;
2045 	uint32_t iovcnt, iov_len, child_iovsize;
2046 	uint32_t blocklen = bdev->blocklen;
2047 	uint32_t io_boundary = bdev->optimal_io_boundary;
2048 	uint32_t max_segment_size = bdev->max_segment_size;
2049 	uint32_t max_child_iovcnt = bdev->max_num_segments;
2050 	void *md_buf = NULL;
2051 	int rc;
2052 
2053 	max_segment_size = max_segment_size ? max_segment_size : UINT32_MAX;
2054 	max_child_iovcnt = max_child_iovcnt ? spdk_min(max_child_iovcnt, BDEV_IO_NUM_CHILD_IOV) :
2055 			   BDEV_IO_NUM_CHILD_IOV;
2056 	io_boundary = bdev->split_on_optimal_io_boundary ? io_boundary : UINT32_MAX;
2057 
2058 	remaining = bdev_io->u.bdev.split_remaining_num_blocks;
2059 	current_offset = bdev_io->u.bdev.split_current_offset_blocks;
2060 	parent_offset = bdev_io->u.bdev.offset_blocks;
2061 	parent_iov_offset = (current_offset - parent_offset) * blocklen;
2062 	parent_iovcnt = bdev_io->u.bdev.iovcnt;
2063 
2064 	for (parent_iovpos = 0; parent_iovpos < parent_iovcnt; parent_iovpos++) {
2065 		parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
2066 		if (parent_iov_offset < parent_iov->iov_len) {
2067 			break;
2068 		}
2069 		parent_iov_offset -= parent_iov->iov_len;
2070 	}
2071 
2072 	child_iovcnt = 0;
2073 	while (remaining > 0 && parent_iovpos < parent_iovcnt && child_iovcnt < BDEV_IO_NUM_CHILD_IOV) {
2074 		to_next_boundary = _to_next_boundary(current_offset, io_boundary);
2075 		to_next_boundary = spdk_min(remaining, to_next_boundary);
2076 		to_next_boundary_bytes = to_next_boundary * blocklen;
2077 
2078 		iov = &bdev_io->child_iov[child_iovcnt];
2079 		iovcnt = 0;
2080 
2081 		if (bdev_io->u.bdev.md_buf) {
2082 			md_buf = (char *)bdev_io->u.bdev.md_buf +
2083 				 (current_offset - parent_offset) * spdk_bdev_get_md_size(bdev);
2084 		}
2085 
2086 		child_iovsize = spdk_min(BDEV_IO_NUM_CHILD_IOV - child_iovcnt, max_child_iovcnt);
2087 		while (to_next_boundary_bytes > 0 && parent_iovpos < parent_iovcnt &&
2088 		       iovcnt < child_iovsize) {
2089 			parent_iov = &bdev_io->u.bdev.iovs[parent_iovpos];
2090 			iov_len = parent_iov->iov_len - parent_iov_offset;
2091 
2092 			iov_len = spdk_min(iov_len, max_segment_size);
2093 			iov_len = spdk_min(iov_len, to_next_boundary_bytes);
2094 			to_next_boundary_bytes -= iov_len;
2095 
2096 			bdev_io->child_iov[child_iovcnt].iov_base = parent_iov->iov_base + parent_iov_offset;
2097 			bdev_io->child_iov[child_iovcnt].iov_len = iov_len;
2098 
2099 			if (iov_len < parent_iov->iov_len - parent_iov_offset) {
2100 				parent_iov_offset += iov_len;
2101 			} else {
2102 				parent_iovpos++;
2103 				parent_iov_offset = 0;
2104 			}
2105 			child_iovcnt++;
2106 			iovcnt++;
2107 		}
2108 
2109 		if (to_next_boundary_bytes > 0) {
2110 			/* We had to stop this child I/O early because we ran out of
2111 			 * child_iov space or were limited by max_num_segments.
2112 			 * Ensure the iovs to be aligned with block size and
2113 			 * then adjust to_next_boundary before starting the
2114 			 * child I/O.
2115 			 */
2116 			assert(child_iovcnt == BDEV_IO_NUM_CHILD_IOV ||
2117 			       iovcnt == child_iovsize);
2118 			to_last_block_bytes = to_next_boundary_bytes % blocklen;
2119 			if (to_last_block_bytes != 0) {
2120 				uint32_t child_iovpos = child_iovcnt - 1;
2121 				/* don't decrease child_iovcnt when it equals to BDEV_IO_NUM_CHILD_IOV
2122 				 * so the loop will naturally end
2123 				 */
2124 
2125 				to_last_block_bytes = blocklen - to_last_block_bytes;
2126 				to_next_boundary_bytes += to_last_block_bytes;
2127 				while (to_last_block_bytes > 0 && iovcnt > 0) {
2128 					iov_len = spdk_min(to_last_block_bytes,
2129 							   bdev_io->child_iov[child_iovpos].iov_len);
2130 					bdev_io->child_iov[child_iovpos].iov_len -= iov_len;
2131 					if (bdev_io->child_iov[child_iovpos].iov_len == 0) {
2132 						child_iovpos--;
2133 						if (--iovcnt == 0) {
2134 							/* If the child IO is less than a block size just return.
2135 							 * If the first child IO of any split round is less than
2136 							 * a block size, an error exit.
2137 							 */
2138 							if (bdev_io->u.bdev.split_outstanding == 0) {
2139 								SPDK_ERRLOG("The first child io was less than a block size\n");
2140 								bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2141 								spdk_trace_record_tsc(spdk_get_ticks(), TRACE_BDEV_IO_DONE, 0, 0,
2142 										      (uintptr_t)bdev_io, 0);
2143 								TAILQ_REMOVE(&bdev_io->internal.ch->io_submitted, bdev_io, internal.ch_link);
2144 								bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
2145 							}
2146 
2147 							return;
2148 						}
2149 					}
2150 
2151 					to_last_block_bytes -= iov_len;
2152 
2153 					if (parent_iov_offset == 0) {
2154 						parent_iovpos--;
2155 						parent_iov_offset = bdev_io->u.bdev.iovs[parent_iovpos].iov_len;
2156 					}
2157 					parent_iov_offset -= iov_len;
2158 				}
2159 
2160 				assert(to_last_block_bytes == 0);
2161 			}
2162 			to_next_boundary -= to_next_boundary_bytes / blocklen;
2163 		}
2164 
2165 		bdev_io->u.bdev.split_outstanding++;
2166 
2167 		if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
2168 			rc = bdev_readv_blocks_with_md(bdev_io->internal.desc,
2169 						       spdk_io_channel_from_ctx(bdev_io->internal.ch),
2170 						       iov, iovcnt, md_buf, current_offset,
2171 						       to_next_boundary,
2172 						       bdev_io_split_done, bdev_io);
2173 		} else {
2174 			rc = bdev_writev_blocks_with_md(bdev_io->internal.desc,
2175 							spdk_io_channel_from_ctx(bdev_io->internal.ch),
2176 							iov, iovcnt, md_buf, current_offset,
2177 							to_next_boundary,
2178 							bdev_io_split_done, bdev_io);
2179 		}
2180 
2181 		if (rc == 0) {
2182 			current_offset += to_next_boundary;
2183 			remaining -= to_next_boundary;
2184 			bdev_io->u.bdev.split_current_offset_blocks = current_offset;
2185 			bdev_io->u.bdev.split_remaining_num_blocks = remaining;
2186 		} else {
2187 			bdev_io->u.bdev.split_outstanding--;
2188 			if (rc == -ENOMEM) {
2189 				if (bdev_io->u.bdev.split_outstanding == 0) {
2190 					/* No I/O is outstanding. Hence we should wait here. */
2191 					bdev_queue_io_wait_with_cb(bdev_io, _bdev_io_split);
2192 				}
2193 			} else {
2194 				bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2195 				if (bdev_io->u.bdev.split_outstanding == 0) {
2196 					spdk_trace_record_tsc(spdk_get_ticks(), TRACE_BDEV_IO_DONE, 0, 0,
2197 							      (uintptr_t)bdev_io, 0);
2198 					TAILQ_REMOVE(&bdev_io->internal.ch->io_submitted, bdev_io, internal.ch_link);
2199 					bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
2200 				}
2201 			}
2202 
2203 			return;
2204 		}
2205 	}
2206 }
2207 
2208 static void
2209 bdev_io_split_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
2210 {
2211 	struct spdk_bdev_io *parent_io = cb_arg;
2212 
2213 	spdk_bdev_free_io(bdev_io);
2214 
2215 	if (!success) {
2216 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
2217 		/* If any child I/O failed, stop further splitting process. */
2218 		parent_io->u.bdev.split_current_offset_blocks += parent_io->u.bdev.split_remaining_num_blocks;
2219 		parent_io->u.bdev.split_remaining_num_blocks = 0;
2220 	}
2221 	parent_io->u.bdev.split_outstanding--;
2222 	if (parent_io->u.bdev.split_outstanding != 0) {
2223 		return;
2224 	}
2225 
2226 	/*
2227 	 * Parent I/O finishes when all blocks are consumed.
2228 	 */
2229 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
2230 		assert(parent_io->internal.cb != bdev_io_split_done);
2231 		spdk_trace_record_tsc(spdk_get_ticks(), TRACE_BDEV_IO_DONE, 0, 0,
2232 				      (uintptr_t)parent_io, 0);
2233 		TAILQ_REMOVE(&parent_io->internal.ch->io_submitted, parent_io, internal.ch_link);
2234 		parent_io->internal.cb(parent_io, parent_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
2235 				       parent_io->internal.caller_ctx);
2236 		return;
2237 	}
2238 
2239 	/*
2240 	 * Continue with the splitting process.  This function will complete the parent I/O if the
2241 	 * splitting is done.
2242 	 */
2243 	_bdev_io_split(parent_io);
2244 }
2245 
2246 static void
2247 bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success);
2248 
2249 static void
2250 bdev_io_split(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io)
2251 {
2252 	assert(bdev_io_type_can_split(bdev_io->type));
2253 
2254 	bdev_io->u.bdev.split_current_offset_blocks = bdev_io->u.bdev.offset_blocks;
2255 	bdev_io->u.bdev.split_remaining_num_blocks = bdev_io->u.bdev.num_blocks;
2256 	bdev_io->u.bdev.split_outstanding = 0;
2257 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
2258 
2259 	if (_is_buf_allocated(bdev_io->u.bdev.iovs)) {
2260 		_bdev_io_split(bdev_io);
2261 	} else {
2262 		assert(bdev_io->type == SPDK_BDEV_IO_TYPE_READ);
2263 		spdk_bdev_io_get_buf(bdev_io, bdev_io_split_get_buf_cb,
2264 				     bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
2265 	}
2266 }
2267 
2268 static void
2269 bdev_io_split_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success)
2270 {
2271 	if (!success) {
2272 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2273 		return;
2274 	}
2275 
2276 	_bdev_io_split(bdev_io);
2277 }
2278 
2279 /* Explicitly mark this inline, since it's used as a function pointer and otherwise won't
2280  *  be inlined, at least on some compilers.
2281  */
2282 static inline void
2283 _bdev_io_submit(void *ctx)
2284 {
2285 	struct spdk_bdev_io *bdev_io = ctx;
2286 	struct spdk_bdev *bdev = bdev_io->bdev;
2287 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
2288 	uint64_t tsc;
2289 
2290 	tsc = spdk_get_ticks();
2291 	bdev_io->internal.submit_tsc = tsc;
2292 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_START, 0, 0, (uintptr_t)bdev_io, bdev_io->type);
2293 
2294 	if (spdk_likely(bdev_ch->flags == 0)) {
2295 		bdev_io_do_submit(bdev_ch, bdev_io);
2296 		return;
2297 	}
2298 
2299 	if (bdev_ch->flags & BDEV_CH_RESET_IN_PROGRESS) {
2300 		_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
2301 	} else if (bdev_ch->flags & BDEV_CH_QOS_ENABLED) {
2302 		if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_ABORT) &&
2303 		    bdev_abort_queued_io(&bdev->internal.qos->queued, bdev_io->u.abort.bio_to_abort)) {
2304 			_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_SUCCESS);
2305 		} else {
2306 			TAILQ_INSERT_TAIL(&bdev->internal.qos->queued, bdev_io, internal.link);
2307 			bdev_qos_io_submit(bdev_ch, bdev->internal.qos);
2308 		}
2309 	} else {
2310 		SPDK_ERRLOG("unknown bdev_ch flag %x found\n", bdev_ch->flags);
2311 		_bdev_io_complete_in_submit(bdev_ch, bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
2312 	}
2313 }
2314 
2315 bool
2316 bdev_lba_range_overlapped(struct lba_range *range1, struct lba_range *range2);
2317 
2318 bool
2319 bdev_lba_range_overlapped(struct lba_range *range1, struct lba_range *range2)
2320 {
2321 	if (range1->length == 0 || range2->length == 0) {
2322 		return false;
2323 	}
2324 
2325 	if (range1->offset + range1->length <= range2->offset) {
2326 		return false;
2327 	}
2328 
2329 	if (range2->offset + range2->length <= range1->offset) {
2330 		return false;
2331 	}
2332 
2333 	return true;
2334 }
2335 
2336 static bool
2337 bdev_io_range_is_locked(struct spdk_bdev_io *bdev_io, struct lba_range *range)
2338 {
2339 	struct spdk_bdev_channel *ch = bdev_io->internal.ch;
2340 	struct lba_range r;
2341 
2342 	switch (bdev_io->type) {
2343 	case SPDK_BDEV_IO_TYPE_NVME_IO:
2344 	case SPDK_BDEV_IO_TYPE_NVME_IO_MD:
2345 		/* Don't try to decode the NVMe command - just assume worst-case and that
2346 		 * it overlaps a locked range.
2347 		 */
2348 		return true;
2349 	case SPDK_BDEV_IO_TYPE_WRITE:
2350 	case SPDK_BDEV_IO_TYPE_UNMAP:
2351 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2352 	case SPDK_BDEV_IO_TYPE_ZCOPY:
2353 		r.offset = bdev_io->u.bdev.offset_blocks;
2354 		r.length = bdev_io->u.bdev.num_blocks;
2355 		if (!bdev_lba_range_overlapped(range, &r)) {
2356 			/* This I/O doesn't overlap the specified LBA range. */
2357 			return false;
2358 		} else if (range->owner_ch == ch && range->locked_ctx == bdev_io->internal.caller_ctx) {
2359 			/* This I/O overlaps, but the I/O is on the same channel that locked this
2360 			 * range, and the caller_ctx is the same as the locked_ctx.  This means
2361 			 * that this I/O is associated with the lock, and is allowed to execute.
2362 			 */
2363 			return false;
2364 		} else {
2365 			return true;
2366 		}
2367 	default:
2368 		return false;
2369 	}
2370 }
2371 
2372 void
2373 bdev_io_submit(struct spdk_bdev_io *bdev_io)
2374 {
2375 	struct spdk_bdev *bdev = bdev_io->bdev;
2376 	struct spdk_thread *thread = spdk_bdev_io_get_thread(bdev_io);
2377 	struct spdk_bdev_channel *ch = bdev_io->internal.ch;
2378 
2379 	assert(thread != NULL);
2380 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
2381 
2382 	if (!TAILQ_EMPTY(&ch->locked_ranges)) {
2383 		struct lba_range *range;
2384 
2385 		TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
2386 			if (bdev_io_range_is_locked(bdev_io, range)) {
2387 				TAILQ_INSERT_TAIL(&ch->io_locked, bdev_io, internal.ch_link);
2388 				return;
2389 			}
2390 		}
2391 	}
2392 
2393 	TAILQ_INSERT_TAIL(&ch->io_submitted, bdev_io, internal.ch_link);
2394 
2395 	if (bdev_io_should_split(bdev_io)) {
2396 		bdev_io->internal.submit_tsc = spdk_get_ticks();
2397 		spdk_trace_record_tsc(bdev_io->internal.submit_tsc, TRACE_BDEV_IO_START, 0, 0,
2398 				      (uintptr_t)bdev_io, bdev_io->type);
2399 		bdev_io_split(NULL, bdev_io);
2400 		return;
2401 	}
2402 
2403 	if (ch->flags & BDEV_CH_QOS_ENABLED) {
2404 		if ((thread == bdev->internal.qos->thread) || !bdev->internal.qos->thread) {
2405 			_bdev_io_submit(bdev_io);
2406 		} else {
2407 			bdev_io->internal.io_submit_ch = ch;
2408 			bdev_io->internal.ch = bdev->internal.qos->ch;
2409 			spdk_thread_send_msg(bdev->internal.qos->thread, _bdev_io_submit, bdev_io);
2410 		}
2411 	} else {
2412 		_bdev_io_submit(bdev_io);
2413 	}
2414 }
2415 
2416 static void
2417 bdev_io_submit_reset(struct spdk_bdev_io *bdev_io)
2418 {
2419 	struct spdk_bdev *bdev = bdev_io->bdev;
2420 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
2421 	struct spdk_io_channel *ch = bdev_ch->channel;
2422 
2423 	assert(bdev_io->internal.status == SPDK_BDEV_IO_STATUS_PENDING);
2424 
2425 	bdev_io->internal.in_submit_request = true;
2426 	bdev->fn_table->submit_request(ch, bdev_io);
2427 	bdev_io->internal.in_submit_request = false;
2428 }
2429 
2430 void
2431 bdev_io_init(struct spdk_bdev_io *bdev_io,
2432 	     struct spdk_bdev *bdev, void *cb_arg,
2433 	     spdk_bdev_io_completion_cb cb)
2434 {
2435 	bdev_io->bdev = bdev;
2436 	bdev_io->internal.caller_ctx = cb_arg;
2437 	bdev_io->internal.cb = cb;
2438 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
2439 	bdev_io->internal.in_submit_request = false;
2440 	bdev_io->internal.buf = NULL;
2441 	bdev_io->internal.io_submit_ch = NULL;
2442 	bdev_io->internal.orig_iovs = NULL;
2443 	bdev_io->internal.orig_iovcnt = 0;
2444 	bdev_io->internal.orig_md_buf = NULL;
2445 	bdev_io->internal.error.nvme.cdw0 = 0;
2446 	bdev_io->num_retries = 0;
2447 	bdev_io->internal.get_buf_cb = NULL;
2448 	bdev_io->internal.get_aux_buf_cb = NULL;
2449 }
2450 
2451 static bool
2452 bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
2453 {
2454 	return bdev->fn_table->io_type_supported(bdev->ctxt, io_type);
2455 }
2456 
2457 bool
2458 spdk_bdev_io_type_supported(struct spdk_bdev *bdev, enum spdk_bdev_io_type io_type)
2459 {
2460 	bool supported;
2461 
2462 	supported = bdev_io_type_supported(bdev, io_type);
2463 
2464 	if (!supported) {
2465 		switch (io_type) {
2466 		case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
2467 			/* The bdev layer will emulate write zeroes as long as write is supported. */
2468 			supported = bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
2469 			break;
2470 		case SPDK_BDEV_IO_TYPE_ZCOPY:
2471 			/* Zero copy can be emulated with regular read and write */
2472 			supported = bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_READ) &&
2473 				    bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE);
2474 			break;
2475 		default:
2476 			break;
2477 		}
2478 	}
2479 
2480 	return supported;
2481 }
2482 
2483 int
2484 spdk_bdev_dump_info_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
2485 {
2486 	if (bdev->fn_table->dump_info_json) {
2487 		return bdev->fn_table->dump_info_json(bdev->ctxt, w);
2488 	}
2489 
2490 	return 0;
2491 }
2492 
2493 static void
2494 bdev_qos_update_max_quota_per_timeslice(struct spdk_bdev_qos *qos)
2495 {
2496 	uint32_t max_per_timeslice = 0;
2497 	int i;
2498 
2499 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2500 		if (qos->rate_limits[i].limit == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
2501 			qos->rate_limits[i].max_per_timeslice = 0;
2502 			continue;
2503 		}
2504 
2505 		max_per_timeslice = qos->rate_limits[i].limit *
2506 				    SPDK_BDEV_QOS_TIMESLICE_IN_USEC / SPDK_SEC_TO_USEC;
2507 
2508 		qos->rate_limits[i].max_per_timeslice = spdk_max(max_per_timeslice,
2509 							qos->rate_limits[i].min_per_timeslice);
2510 
2511 		qos->rate_limits[i].remaining_this_timeslice = qos->rate_limits[i].max_per_timeslice;
2512 	}
2513 
2514 	bdev_qos_set_ops(qos);
2515 }
2516 
2517 static int
2518 bdev_channel_poll_qos(void *arg)
2519 {
2520 	struct spdk_bdev_qos *qos = arg;
2521 	uint64_t now = spdk_get_ticks();
2522 	int i;
2523 
2524 	if (now < (qos->last_timeslice + qos->timeslice_size)) {
2525 		/* We received our callback earlier than expected - return
2526 		 *  immediately and wait to do accounting until at least one
2527 		 *  timeslice has actually expired.  This should never happen
2528 		 *  with a well-behaved timer implementation.
2529 		 */
2530 		return SPDK_POLLER_IDLE;
2531 	}
2532 
2533 	/* Reset for next round of rate limiting */
2534 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2535 		/* We may have allowed the IOs or bytes to slightly overrun in the last
2536 		 * timeslice. remaining_this_timeslice is signed, so if it's negative
2537 		 * here, we'll account for the overrun so that the next timeslice will
2538 		 * be appropriately reduced.
2539 		 */
2540 		if (qos->rate_limits[i].remaining_this_timeslice > 0) {
2541 			qos->rate_limits[i].remaining_this_timeslice = 0;
2542 		}
2543 	}
2544 
2545 	while (now >= (qos->last_timeslice + qos->timeslice_size)) {
2546 		qos->last_timeslice += qos->timeslice_size;
2547 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2548 			qos->rate_limits[i].remaining_this_timeslice +=
2549 				qos->rate_limits[i].max_per_timeslice;
2550 		}
2551 	}
2552 
2553 	return bdev_qos_io_submit(qos->ch, qos);
2554 }
2555 
2556 static void
2557 bdev_channel_destroy_resource(struct spdk_bdev_channel *ch)
2558 {
2559 	struct spdk_bdev_shared_resource *shared_resource;
2560 	struct lba_range *range;
2561 
2562 	while (!TAILQ_EMPTY(&ch->locked_ranges)) {
2563 		range = TAILQ_FIRST(&ch->locked_ranges);
2564 		TAILQ_REMOVE(&ch->locked_ranges, range, tailq);
2565 		free(range);
2566 	}
2567 
2568 	spdk_put_io_channel(ch->channel);
2569 
2570 	shared_resource = ch->shared_resource;
2571 
2572 	assert(TAILQ_EMPTY(&ch->io_locked));
2573 	assert(TAILQ_EMPTY(&ch->io_submitted));
2574 	assert(ch->io_outstanding == 0);
2575 	assert(shared_resource->ref > 0);
2576 	shared_resource->ref--;
2577 	if (shared_resource->ref == 0) {
2578 		assert(shared_resource->io_outstanding == 0);
2579 		TAILQ_REMOVE(&shared_resource->mgmt_ch->shared_resources, shared_resource, link);
2580 		spdk_put_io_channel(spdk_io_channel_from_ctx(shared_resource->mgmt_ch));
2581 		free(shared_resource);
2582 	}
2583 }
2584 
2585 /* Caller must hold bdev->internal.mutex. */
2586 static void
2587 bdev_enable_qos(struct spdk_bdev *bdev, struct spdk_bdev_channel *ch)
2588 {
2589 	struct spdk_bdev_qos	*qos = bdev->internal.qos;
2590 	int			i;
2591 
2592 	/* Rate limiting on this bdev enabled */
2593 	if (qos) {
2594 		if (qos->ch == NULL) {
2595 			struct spdk_io_channel *io_ch;
2596 
2597 			SPDK_DEBUGLOG(bdev, "Selecting channel %p as QoS channel for bdev %s on thread %p\n", ch,
2598 				      bdev->name, spdk_get_thread());
2599 
2600 			/* No qos channel has been selected, so set one up */
2601 
2602 			/* Take another reference to ch */
2603 			io_ch = spdk_get_io_channel(__bdev_to_io_dev(bdev));
2604 			assert(io_ch != NULL);
2605 			qos->ch = ch;
2606 
2607 			qos->thread = spdk_io_channel_get_thread(io_ch);
2608 
2609 			TAILQ_INIT(&qos->queued);
2610 
2611 			for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
2612 				if (bdev_qos_is_iops_rate_limit(i) == true) {
2613 					qos->rate_limits[i].min_per_timeslice =
2614 						SPDK_BDEV_QOS_MIN_IO_PER_TIMESLICE;
2615 				} else {
2616 					qos->rate_limits[i].min_per_timeslice =
2617 						SPDK_BDEV_QOS_MIN_BYTE_PER_TIMESLICE;
2618 				}
2619 
2620 				if (qos->rate_limits[i].limit == 0) {
2621 					qos->rate_limits[i].limit = SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
2622 				}
2623 			}
2624 			bdev_qos_update_max_quota_per_timeslice(qos);
2625 			qos->timeslice_size =
2626 				SPDK_BDEV_QOS_TIMESLICE_IN_USEC * spdk_get_ticks_hz() / SPDK_SEC_TO_USEC;
2627 			qos->last_timeslice = spdk_get_ticks();
2628 			qos->poller = SPDK_POLLER_REGISTER(bdev_channel_poll_qos,
2629 							   qos,
2630 							   SPDK_BDEV_QOS_TIMESLICE_IN_USEC);
2631 		}
2632 
2633 		ch->flags |= BDEV_CH_QOS_ENABLED;
2634 	}
2635 }
2636 
2637 struct poll_timeout_ctx {
2638 	struct spdk_bdev_desc	*desc;
2639 	uint64_t		timeout_in_sec;
2640 	spdk_bdev_io_timeout_cb	cb_fn;
2641 	void			*cb_arg;
2642 };
2643 
2644 static void
2645 bdev_desc_free(struct spdk_bdev_desc *desc)
2646 {
2647 	pthread_mutex_destroy(&desc->mutex);
2648 	free(desc->media_events_buffer);
2649 	free(desc);
2650 }
2651 
2652 static void
2653 bdev_channel_poll_timeout_io_done(struct spdk_io_channel_iter *i, int status)
2654 {
2655 	struct poll_timeout_ctx *ctx  = spdk_io_channel_iter_get_ctx(i);
2656 	struct spdk_bdev_desc *desc = ctx->desc;
2657 
2658 	free(ctx);
2659 
2660 	pthread_mutex_lock(&desc->mutex);
2661 	desc->refs--;
2662 	if (desc->closed == true && desc->refs == 0) {
2663 		pthread_mutex_unlock(&desc->mutex);
2664 		bdev_desc_free(desc);
2665 		return;
2666 	}
2667 	pthread_mutex_unlock(&desc->mutex);
2668 }
2669 
2670 static void
2671 bdev_channel_poll_timeout_io(struct spdk_io_channel_iter *i)
2672 {
2673 	struct poll_timeout_ctx *ctx  = spdk_io_channel_iter_get_ctx(i);
2674 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
2675 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(io_ch);
2676 	struct spdk_bdev_desc *desc = ctx->desc;
2677 	struct spdk_bdev_io *bdev_io;
2678 	uint64_t now;
2679 
2680 	pthread_mutex_lock(&desc->mutex);
2681 	if (desc->closed == true) {
2682 		pthread_mutex_unlock(&desc->mutex);
2683 		spdk_for_each_channel_continue(i, -1);
2684 		return;
2685 	}
2686 	pthread_mutex_unlock(&desc->mutex);
2687 
2688 	now = spdk_get_ticks();
2689 	TAILQ_FOREACH(bdev_io, &bdev_ch->io_submitted, internal.ch_link) {
2690 		/* Exclude any I/O that are generated via splitting. */
2691 		if (bdev_io->internal.cb == bdev_io_split_done) {
2692 			continue;
2693 		}
2694 
2695 		/* Once we find an I/O that has not timed out, we can immediately
2696 		 * exit the loop.
2697 		 */
2698 		if (now < (bdev_io->internal.submit_tsc +
2699 			   ctx->timeout_in_sec * spdk_get_ticks_hz())) {
2700 			goto end;
2701 		}
2702 
2703 		if (bdev_io->internal.desc == desc) {
2704 			ctx->cb_fn(ctx->cb_arg, bdev_io);
2705 		}
2706 	}
2707 
2708 end:
2709 	spdk_for_each_channel_continue(i, 0);
2710 }
2711 
2712 static int
2713 bdev_poll_timeout_io(void *arg)
2714 {
2715 	struct spdk_bdev_desc *desc = arg;
2716 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
2717 	struct poll_timeout_ctx *ctx;
2718 
2719 	ctx = calloc(1, sizeof(struct poll_timeout_ctx));
2720 	if (!ctx) {
2721 		SPDK_ERRLOG("failed to allocate memory\n");
2722 		return SPDK_POLLER_BUSY;
2723 	}
2724 	ctx->desc = desc;
2725 	ctx->cb_arg = desc->cb_arg;
2726 	ctx->cb_fn = desc->cb_fn;
2727 	ctx->timeout_in_sec = desc->timeout_in_sec;
2728 
2729 	/* Take a ref on the descriptor in case it gets closed while we are checking
2730 	 * all of the channels.
2731 	 */
2732 	pthread_mutex_lock(&desc->mutex);
2733 	desc->refs++;
2734 	pthread_mutex_unlock(&desc->mutex);
2735 
2736 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
2737 			      bdev_channel_poll_timeout_io,
2738 			      ctx,
2739 			      bdev_channel_poll_timeout_io_done);
2740 
2741 	return SPDK_POLLER_BUSY;
2742 }
2743 
2744 int
2745 spdk_bdev_set_timeout(struct spdk_bdev_desc *desc, uint64_t timeout_in_sec,
2746 		      spdk_bdev_io_timeout_cb cb_fn, void *cb_arg)
2747 {
2748 	assert(desc->thread == spdk_get_thread());
2749 
2750 	spdk_poller_unregister(&desc->io_timeout_poller);
2751 
2752 	if (timeout_in_sec) {
2753 		assert(cb_fn != NULL);
2754 		desc->io_timeout_poller = SPDK_POLLER_REGISTER(bdev_poll_timeout_io,
2755 					  desc,
2756 					  SPDK_BDEV_IO_POLL_INTERVAL_IN_MSEC * SPDK_SEC_TO_USEC /
2757 					  1000);
2758 		if (desc->io_timeout_poller == NULL) {
2759 			SPDK_ERRLOG("can not register the desc timeout IO poller\n");
2760 			return -1;
2761 		}
2762 	}
2763 
2764 	desc->cb_fn = cb_fn;
2765 	desc->cb_arg = cb_arg;
2766 	desc->timeout_in_sec = timeout_in_sec;
2767 
2768 	return 0;
2769 }
2770 
2771 static int
2772 bdev_channel_create(void *io_device, void *ctx_buf)
2773 {
2774 	struct spdk_bdev		*bdev = __bdev_from_io_dev(io_device);
2775 	struct spdk_bdev_channel	*ch = ctx_buf;
2776 	struct spdk_io_channel		*mgmt_io_ch;
2777 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
2778 	struct spdk_bdev_shared_resource *shared_resource;
2779 	struct lba_range		*range;
2780 
2781 	ch->bdev = bdev;
2782 	ch->channel = bdev->fn_table->get_io_channel(bdev->ctxt);
2783 	if (!ch->channel) {
2784 		return -1;
2785 	}
2786 
2787 	assert(ch->histogram == NULL);
2788 	if (bdev->internal.histogram_enabled) {
2789 		ch->histogram = spdk_histogram_data_alloc();
2790 		if (ch->histogram == NULL) {
2791 			SPDK_ERRLOG("Could not allocate histogram\n");
2792 		}
2793 	}
2794 
2795 	mgmt_io_ch = spdk_get_io_channel(&g_bdev_mgr);
2796 	if (!mgmt_io_ch) {
2797 		spdk_put_io_channel(ch->channel);
2798 		return -1;
2799 	}
2800 
2801 	mgmt_ch = spdk_io_channel_get_ctx(mgmt_io_ch);
2802 	TAILQ_FOREACH(shared_resource, &mgmt_ch->shared_resources, link) {
2803 		if (shared_resource->shared_ch == ch->channel) {
2804 			spdk_put_io_channel(mgmt_io_ch);
2805 			shared_resource->ref++;
2806 			break;
2807 		}
2808 	}
2809 
2810 	if (shared_resource == NULL) {
2811 		shared_resource = calloc(1, sizeof(*shared_resource));
2812 		if (shared_resource == NULL) {
2813 			spdk_put_io_channel(ch->channel);
2814 			spdk_put_io_channel(mgmt_io_ch);
2815 			return -1;
2816 		}
2817 
2818 		shared_resource->mgmt_ch = mgmt_ch;
2819 		shared_resource->io_outstanding = 0;
2820 		TAILQ_INIT(&shared_resource->nomem_io);
2821 		shared_resource->nomem_threshold = 0;
2822 		shared_resource->shared_ch = ch->channel;
2823 		shared_resource->ref = 1;
2824 		TAILQ_INSERT_TAIL(&mgmt_ch->shared_resources, shared_resource, link);
2825 	}
2826 
2827 	memset(&ch->stat, 0, sizeof(ch->stat));
2828 	ch->stat.ticks_rate = spdk_get_ticks_hz();
2829 	ch->io_outstanding = 0;
2830 	TAILQ_INIT(&ch->queued_resets);
2831 	TAILQ_INIT(&ch->locked_ranges);
2832 	ch->flags = 0;
2833 	ch->shared_resource = shared_resource;
2834 
2835 	TAILQ_INIT(&ch->io_submitted);
2836 	TAILQ_INIT(&ch->io_locked);
2837 
2838 #ifdef SPDK_CONFIG_VTUNE
2839 	{
2840 		char *name;
2841 		__itt_init_ittlib(NULL, 0);
2842 		name = spdk_sprintf_alloc("spdk_bdev_%s_%p", ch->bdev->name, ch);
2843 		if (!name) {
2844 			bdev_channel_destroy_resource(ch);
2845 			return -1;
2846 		}
2847 		ch->handle = __itt_string_handle_create(name);
2848 		free(name);
2849 		ch->start_tsc = spdk_get_ticks();
2850 		ch->interval_tsc = spdk_get_ticks_hz() / 100;
2851 		memset(&ch->prev_stat, 0, sizeof(ch->prev_stat));
2852 	}
2853 #endif
2854 
2855 	pthread_mutex_lock(&bdev->internal.mutex);
2856 	bdev_enable_qos(bdev, ch);
2857 
2858 	TAILQ_FOREACH(range, &bdev->internal.locked_ranges, tailq) {
2859 		struct lba_range *new_range;
2860 
2861 		new_range = calloc(1, sizeof(*new_range));
2862 		if (new_range == NULL) {
2863 			pthread_mutex_unlock(&bdev->internal.mutex);
2864 			bdev_channel_destroy_resource(ch);
2865 			return -1;
2866 		}
2867 		new_range->length = range->length;
2868 		new_range->offset = range->offset;
2869 		new_range->locked_ctx = range->locked_ctx;
2870 		TAILQ_INSERT_TAIL(&ch->locked_ranges, new_range, tailq);
2871 	}
2872 
2873 	pthread_mutex_unlock(&bdev->internal.mutex);
2874 
2875 	return 0;
2876 }
2877 
2878 /*
2879  * Abort I/O that are waiting on a data buffer.  These types of I/O are
2880  *  linked using the spdk_bdev_io internal.buf_link TAILQ_ENTRY.
2881  */
2882 static void
2883 bdev_abort_all_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_channel *ch)
2884 {
2885 	bdev_io_stailq_t tmp;
2886 	struct spdk_bdev_io *bdev_io;
2887 
2888 	STAILQ_INIT(&tmp);
2889 
2890 	while (!STAILQ_EMPTY(queue)) {
2891 		bdev_io = STAILQ_FIRST(queue);
2892 		STAILQ_REMOVE_HEAD(queue, internal.buf_link);
2893 		if (bdev_io->internal.ch == ch) {
2894 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
2895 		} else {
2896 			STAILQ_INSERT_TAIL(&tmp, bdev_io, internal.buf_link);
2897 		}
2898 	}
2899 
2900 	STAILQ_SWAP(&tmp, queue, spdk_bdev_io);
2901 }
2902 
2903 /*
2904  * Abort I/O that are queued waiting for submission.  These types of I/O are
2905  *  linked using the spdk_bdev_io link TAILQ_ENTRY.
2906  */
2907 static void
2908 bdev_abort_all_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_channel *ch)
2909 {
2910 	struct spdk_bdev_io *bdev_io, *tmp;
2911 
2912 	TAILQ_FOREACH_SAFE(bdev_io, queue, internal.link, tmp) {
2913 		if (bdev_io->internal.ch == ch) {
2914 			TAILQ_REMOVE(queue, bdev_io, internal.link);
2915 			/*
2916 			 * spdk_bdev_io_complete() assumes that the completed I/O had
2917 			 *  been submitted to the bdev module.  Since in this case it
2918 			 *  hadn't, bump io_outstanding to account for the decrement
2919 			 *  that spdk_bdev_io_complete() will do.
2920 			 */
2921 			if (bdev_io->type != SPDK_BDEV_IO_TYPE_RESET) {
2922 				ch->io_outstanding++;
2923 				ch->shared_resource->io_outstanding++;
2924 			}
2925 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_ABORTED);
2926 		}
2927 	}
2928 }
2929 
2930 static bool
2931 bdev_abort_queued_io(bdev_io_tailq_t *queue, struct spdk_bdev_io *bio_to_abort)
2932 {
2933 	struct spdk_bdev_io *bdev_io;
2934 
2935 	TAILQ_FOREACH(bdev_io, queue, internal.link) {
2936 		if (bdev_io == bio_to_abort) {
2937 			TAILQ_REMOVE(queue, bio_to_abort, internal.link);
2938 			spdk_bdev_io_complete(bio_to_abort, SPDK_BDEV_IO_STATUS_ABORTED);
2939 			return true;
2940 		}
2941 	}
2942 
2943 	return false;
2944 }
2945 
2946 static bool
2947 bdev_abort_buf_io(bdev_io_stailq_t *queue, struct spdk_bdev_io *bio_to_abort)
2948 {
2949 	struct spdk_bdev_io *bdev_io;
2950 
2951 	STAILQ_FOREACH(bdev_io, queue, internal.buf_link) {
2952 		if (bdev_io == bio_to_abort) {
2953 			STAILQ_REMOVE(queue, bio_to_abort, spdk_bdev_io, internal.buf_link);
2954 			spdk_bdev_io_complete(bio_to_abort, SPDK_BDEV_IO_STATUS_ABORTED);
2955 			return true;
2956 		}
2957 	}
2958 
2959 	return false;
2960 }
2961 
2962 static void
2963 bdev_qos_channel_destroy(void *cb_arg)
2964 {
2965 	struct spdk_bdev_qos *qos = cb_arg;
2966 
2967 	spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
2968 	spdk_poller_unregister(&qos->poller);
2969 
2970 	SPDK_DEBUGLOG(bdev, "Free QoS %p.\n", qos);
2971 
2972 	free(qos);
2973 }
2974 
2975 static int
2976 bdev_qos_destroy(struct spdk_bdev *bdev)
2977 {
2978 	int i;
2979 
2980 	/*
2981 	 * Cleanly shutting down the QoS poller is tricky, because
2982 	 * during the asynchronous operation the user could open
2983 	 * a new descriptor and create a new channel, spawning
2984 	 * a new QoS poller.
2985 	 *
2986 	 * The strategy is to create a new QoS structure here and swap it
2987 	 * in. The shutdown path then continues to refer to the old one
2988 	 * until it completes and then releases it.
2989 	 */
2990 	struct spdk_bdev_qos *new_qos, *old_qos;
2991 
2992 	old_qos = bdev->internal.qos;
2993 
2994 	new_qos = calloc(1, sizeof(*new_qos));
2995 	if (!new_qos) {
2996 		SPDK_ERRLOG("Unable to allocate memory to shut down QoS.\n");
2997 		return -ENOMEM;
2998 	}
2999 
3000 	/* Copy the old QoS data into the newly allocated structure */
3001 	memcpy(new_qos, old_qos, sizeof(*new_qos));
3002 
3003 	/* Zero out the key parts of the QoS structure */
3004 	new_qos->ch = NULL;
3005 	new_qos->thread = NULL;
3006 	new_qos->poller = NULL;
3007 	TAILQ_INIT(&new_qos->queued);
3008 	/*
3009 	 * The limit member of spdk_bdev_qos_limit structure is not zeroed.
3010 	 * It will be used later for the new QoS structure.
3011 	 */
3012 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3013 		new_qos->rate_limits[i].remaining_this_timeslice = 0;
3014 		new_qos->rate_limits[i].min_per_timeslice = 0;
3015 		new_qos->rate_limits[i].max_per_timeslice = 0;
3016 	}
3017 
3018 	bdev->internal.qos = new_qos;
3019 
3020 	if (old_qos->thread == NULL) {
3021 		free(old_qos);
3022 	} else {
3023 		spdk_thread_send_msg(old_qos->thread, bdev_qos_channel_destroy, old_qos);
3024 	}
3025 
3026 	/* It is safe to continue with destroying the bdev even though the QoS channel hasn't
3027 	 * been destroyed yet. The destruction path will end up waiting for the final
3028 	 * channel to be put before it releases resources. */
3029 
3030 	return 0;
3031 }
3032 
3033 static void
3034 bdev_io_stat_add(struct spdk_bdev_io_stat *total, struct spdk_bdev_io_stat *add)
3035 {
3036 	total->bytes_read += add->bytes_read;
3037 	total->num_read_ops += add->num_read_ops;
3038 	total->bytes_written += add->bytes_written;
3039 	total->num_write_ops += add->num_write_ops;
3040 	total->bytes_unmapped += add->bytes_unmapped;
3041 	total->num_unmap_ops += add->num_unmap_ops;
3042 	total->read_latency_ticks += add->read_latency_ticks;
3043 	total->write_latency_ticks += add->write_latency_ticks;
3044 	total->unmap_latency_ticks += add->unmap_latency_ticks;
3045 }
3046 
3047 static void
3048 bdev_channel_destroy(void *io_device, void *ctx_buf)
3049 {
3050 	struct spdk_bdev_channel	*ch = ctx_buf;
3051 	struct spdk_bdev_mgmt_channel	*mgmt_ch;
3052 	struct spdk_bdev_shared_resource *shared_resource = ch->shared_resource;
3053 
3054 	SPDK_DEBUGLOG(bdev, "Destroying channel %p for bdev %s on thread %p\n", ch, ch->bdev->name,
3055 		      spdk_get_thread());
3056 
3057 	/* This channel is going away, so add its statistics into the bdev so that they don't get lost. */
3058 	pthread_mutex_lock(&ch->bdev->internal.mutex);
3059 	bdev_io_stat_add(&ch->bdev->internal.stat, &ch->stat);
3060 	pthread_mutex_unlock(&ch->bdev->internal.mutex);
3061 
3062 	mgmt_ch = shared_resource->mgmt_ch;
3063 
3064 	bdev_abort_all_queued_io(&ch->queued_resets, ch);
3065 	bdev_abort_all_queued_io(&shared_resource->nomem_io, ch);
3066 	bdev_abort_all_buf_io(&mgmt_ch->need_buf_small, ch);
3067 	bdev_abort_all_buf_io(&mgmt_ch->need_buf_large, ch);
3068 
3069 	if (ch->histogram) {
3070 		spdk_histogram_data_free(ch->histogram);
3071 	}
3072 
3073 	bdev_channel_destroy_resource(ch);
3074 }
3075 
3076 int
3077 spdk_bdev_alias_add(struct spdk_bdev *bdev, const char *alias)
3078 {
3079 	struct spdk_bdev_alias *tmp;
3080 
3081 	if (alias == NULL) {
3082 		SPDK_ERRLOG("Empty alias passed\n");
3083 		return -EINVAL;
3084 	}
3085 
3086 	if (spdk_bdev_get_by_name(alias)) {
3087 		SPDK_ERRLOG("Bdev name/alias: %s already exists\n", alias);
3088 		return -EEXIST;
3089 	}
3090 
3091 	tmp = calloc(1, sizeof(*tmp));
3092 	if (tmp == NULL) {
3093 		SPDK_ERRLOG("Unable to allocate alias\n");
3094 		return -ENOMEM;
3095 	}
3096 
3097 	tmp->alias = strdup(alias);
3098 	if (tmp->alias == NULL) {
3099 		free(tmp);
3100 		SPDK_ERRLOG("Unable to allocate alias\n");
3101 		return -ENOMEM;
3102 	}
3103 
3104 	TAILQ_INSERT_TAIL(&bdev->aliases, tmp, tailq);
3105 
3106 	return 0;
3107 }
3108 
3109 int
3110 spdk_bdev_alias_del(struct spdk_bdev *bdev, const char *alias)
3111 {
3112 	struct spdk_bdev_alias *tmp;
3113 
3114 	TAILQ_FOREACH(tmp, &bdev->aliases, tailq) {
3115 		if (strcmp(alias, tmp->alias) == 0) {
3116 			TAILQ_REMOVE(&bdev->aliases, tmp, tailq);
3117 			free(tmp->alias);
3118 			free(tmp);
3119 			return 0;
3120 		}
3121 	}
3122 
3123 	SPDK_INFOLOG(bdev, "Alias %s does not exists\n", alias);
3124 
3125 	return -ENOENT;
3126 }
3127 
3128 void
3129 spdk_bdev_alias_del_all(struct spdk_bdev *bdev)
3130 {
3131 	struct spdk_bdev_alias *p, *tmp;
3132 
3133 	TAILQ_FOREACH_SAFE(p, &bdev->aliases, tailq, tmp) {
3134 		TAILQ_REMOVE(&bdev->aliases, p, tailq);
3135 		free(p->alias);
3136 		free(p);
3137 	}
3138 }
3139 
3140 struct spdk_io_channel *
3141 spdk_bdev_get_io_channel(struct spdk_bdev_desc *desc)
3142 {
3143 	return spdk_get_io_channel(__bdev_to_io_dev(spdk_bdev_desc_get_bdev(desc)));
3144 }
3145 
3146 void *
3147 spdk_bdev_get_module_ctx(struct spdk_bdev_desc *desc)
3148 {
3149 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3150 	void *ctx = NULL;
3151 
3152 	if (bdev->fn_table->get_module_ctx) {
3153 		ctx = bdev->fn_table->get_module_ctx(bdev->ctxt);
3154 	}
3155 
3156 	return ctx;
3157 }
3158 
3159 const char *
3160 spdk_bdev_get_module_name(const struct spdk_bdev *bdev)
3161 {
3162 	return bdev->module->name;
3163 }
3164 
3165 const char *
3166 spdk_bdev_get_name(const struct spdk_bdev *bdev)
3167 {
3168 	return bdev->name;
3169 }
3170 
3171 const char *
3172 spdk_bdev_get_product_name(const struct spdk_bdev *bdev)
3173 {
3174 	return bdev->product_name;
3175 }
3176 
3177 const struct spdk_bdev_aliases_list *
3178 spdk_bdev_get_aliases(const struct spdk_bdev *bdev)
3179 {
3180 	return &bdev->aliases;
3181 }
3182 
3183 uint32_t
3184 spdk_bdev_get_block_size(const struct spdk_bdev *bdev)
3185 {
3186 	return bdev->blocklen;
3187 }
3188 
3189 uint32_t
3190 spdk_bdev_get_write_unit_size(const struct spdk_bdev *bdev)
3191 {
3192 	return bdev->write_unit_size;
3193 }
3194 
3195 uint64_t
3196 spdk_bdev_get_num_blocks(const struct spdk_bdev *bdev)
3197 {
3198 	return bdev->blockcnt;
3199 }
3200 
3201 const char *
3202 spdk_bdev_get_qos_rpc_type(enum spdk_bdev_qos_rate_limit_type type)
3203 {
3204 	return qos_rpc_type[type];
3205 }
3206 
3207 void
3208 spdk_bdev_get_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
3209 {
3210 	int i;
3211 
3212 	memset(limits, 0, sizeof(*limits) * SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES);
3213 
3214 	pthread_mutex_lock(&bdev->internal.mutex);
3215 	if (bdev->internal.qos) {
3216 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
3217 			if (bdev->internal.qos->rate_limits[i].limit !=
3218 			    SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
3219 				limits[i] = bdev->internal.qos->rate_limits[i].limit;
3220 				if (bdev_qos_is_iops_rate_limit(i) == false) {
3221 					/* Change from Byte to Megabyte which is user visible. */
3222 					limits[i] = limits[i] / 1024 / 1024;
3223 				}
3224 			}
3225 		}
3226 	}
3227 	pthread_mutex_unlock(&bdev->internal.mutex);
3228 }
3229 
3230 size_t
3231 spdk_bdev_get_buf_align(const struct spdk_bdev *bdev)
3232 {
3233 	return 1 << bdev->required_alignment;
3234 }
3235 
3236 uint32_t
3237 spdk_bdev_get_optimal_io_boundary(const struct spdk_bdev *bdev)
3238 {
3239 	return bdev->optimal_io_boundary;
3240 }
3241 
3242 bool
3243 spdk_bdev_has_write_cache(const struct spdk_bdev *bdev)
3244 {
3245 	return bdev->write_cache;
3246 }
3247 
3248 const struct spdk_uuid *
3249 spdk_bdev_get_uuid(const struct spdk_bdev *bdev)
3250 {
3251 	return &bdev->uuid;
3252 }
3253 
3254 uint16_t
3255 spdk_bdev_get_acwu(const struct spdk_bdev *bdev)
3256 {
3257 	return bdev->acwu;
3258 }
3259 
3260 uint32_t
3261 spdk_bdev_get_md_size(const struct spdk_bdev *bdev)
3262 {
3263 	return bdev->md_len;
3264 }
3265 
3266 bool
3267 spdk_bdev_is_md_interleaved(const struct spdk_bdev *bdev)
3268 {
3269 	return (bdev->md_len != 0) && bdev->md_interleave;
3270 }
3271 
3272 bool
3273 spdk_bdev_is_md_separate(const struct spdk_bdev *bdev)
3274 {
3275 	return (bdev->md_len != 0) && !bdev->md_interleave;
3276 }
3277 
3278 bool
3279 spdk_bdev_is_zoned(const struct spdk_bdev *bdev)
3280 {
3281 	return bdev->zoned;
3282 }
3283 
3284 uint32_t
3285 spdk_bdev_get_data_block_size(const struct spdk_bdev *bdev)
3286 {
3287 	if (spdk_bdev_is_md_interleaved(bdev)) {
3288 		return bdev->blocklen - bdev->md_len;
3289 	} else {
3290 		return bdev->blocklen;
3291 	}
3292 }
3293 
3294 static uint32_t
3295 _bdev_get_block_size_with_md(const struct spdk_bdev *bdev)
3296 {
3297 	if (!spdk_bdev_is_md_interleaved(bdev)) {
3298 		return bdev->blocklen + bdev->md_len;
3299 	} else {
3300 		return bdev->blocklen;
3301 	}
3302 }
3303 
3304 enum spdk_dif_type spdk_bdev_get_dif_type(const struct spdk_bdev *bdev)
3305 {
3306 	if (bdev->md_len != 0) {
3307 		return bdev->dif_type;
3308 	} else {
3309 		return SPDK_DIF_DISABLE;
3310 	}
3311 }
3312 
3313 bool
3314 spdk_bdev_is_dif_head_of_md(const struct spdk_bdev *bdev)
3315 {
3316 	if (spdk_bdev_get_dif_type(bdev) != SPDK_DIF_DISABLE) {
3317 		return bdev->dif_is_head_of_md;
3318 	} else {
3319 		return false;
3320 	}
3321 }
3322 
3323 bool
3324 spdk_bdev_is_dif_check_enabled(const struct spdk_bdev *bdev,
3325 			       enum spdk_dif_check_type check_type)
3326 {
3327 	if (spdk_bdev_get_dif_type(bdev) == SPDK_DIF_DISABLE) {
3328 		return false;
3329 	}
3330 
3331 	switch (check_type) {
3332 	case SPDK_DIF_CHECK_TYPE_REFTAG:
3333 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_REFTAG_CHECK) != 0;
3334 	case SPDK_DIF_CHECK_TYPE_APPTAG:
3335 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_APPTAG_CHECK) != 0;
3336 	case SPDK_DIF_CHECK_TYPE_GUARD:
3337 		return (bdev->dif_check_flags & SPDK_DIF_FLAGS_GUARD_CHECK) != 0;
3338 	default:
3339 		return false;
3340 	}
3341 }
3342 
3343 uint64_t
3344 spdk_bdev_get_qd(const struct spdk_bdev *bdev)
3345 {
3346 	return bdev->internal.measured_queue_depth;
3347 }
3348 
3349 uint64_t
3350 spdk_bdev_get_qd_sampling_period(const struct spdk_bdev *bdev)
3351 {
3352 	return bdev->internal.period;
3353 }
3354 
3355 uint64_t
3356 spdk_bdev_get_weighted_io_time(const struct spdk_bdev *bdev)
3357 {
3358 	return bdev->internal.weighted_io_time;
3359 }
3360 
3361 uint64_t
3362 spdk_bdev_get_io_time(const struct spdk_bdev *bdev)
3363 {
3364 	return bdev->internal.io_time;
3365 }
3366 
3367 static void
3368 _calculate_measured_qd_cpl(struct spdk_io_channel_iter *i, int status)
3369 {
3370 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
3371 
3372 	bdev->internal.measured_queue_depth = bdev->internal.temporary_queue_depth;
3373 
3374 	if (bdev->internal.measured_queue_depth) {
3375 		bdev->internal.io_time += bdev->internal.period;
3376 		bdev->internal.weighted_io_time += bdev->internal.period * bdev->internal.measured_queue_depth;
3377 	}
3378 }
3379 
3380 static void
3381 _calculate_measured_qd(struct spdk_io_channel_iter *i)
3382 {
3383 	struct spdk_bdev *bdev = spdk_io_channel_iter_get_ctx(i);
3384 	struct spdk_io_channel *io_ch = spdk_io_channel_iter_get_channel(i);
3385 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(io_ch);
3386 
3387 	bdev->internal.temporary_queue_depth += ch->io_outstanding;
3388 	spdk_for_each_channel_continue(i, 0);
3389 }
3390 
3391 static int
3392 bdev_calculate_measured_queue_depth(void *ctx)
3393 {
3394 	struct spdk_bdev *bdev = ctx;
3395 	bdev->internal.temporary_queue_depth = 0;
3396 	spdk_for_each_channel(__bdev_to_io_dev(bdev), _calculate_measured_qd, bdev,
3397 			      _calculate_measured_qd_cpl);
3398 	return SPDK_POLLER_BUSY;
3399 }
3400 
3401 void
3402 spdk_bdev_set_qd_sampling_period(struct spdk_bdev *bdev, uint64_t period)
3403 {
3404 	bdev->internal.period = period;
3405 
3406 	if (bdev->internal.qd_poller != NULL) {
3407 		spdk_poller_unregister(&bdev->internal.qd_poller);
3408 		bdev->internal.measured_queue_depth = UINT64_MAX;
3409 	}
3410 
3411 	if (period != 0) {
3412 		bdev->internal.qd_poller = SPDK_POLLER_REGISTER(bdev_calculate_measured_queue_depth, bdev,
3413 					   period);
3414 	}
3415 }
3416 
3417 static void
3418 _resize_notify(void *arg)
3419 {
3420 	struct spdk_bdev_desc *desc = arg;
3421 
3422 	pthread_mutex_lock(&desc->mutex);
3423 	desc->refs--;
3424 	if (!desc->closed) {
3425 		pthread_mutex_unlock(&desc->mutex);
3426 		desc->callback.event_fn(SPDK_BDEV_EVENT_RESIZE,
3427 					desc->bdev,
3428 					desc->callback.ctx);
3429 		return;
3430 	} else if (0 == desc->refs) {
3431 		/* This descriptor was closed after this resize_notify message was sent.
3432 		 * spdk_bdev_close() could not free the descriptor since this message was
3433 		 * in flight, so we free it now using bdev_desc_free().
3434 		 */
3435 		pthread_mutex_unlock(&desc->mutex);
3436 		bdev_desc_free(desc);
3437 		return;
3438 	}
3439 	pthread_mutex_unlock(&desc->mutex);
3440 }
3441 
3442 int
3443 spdk_bdev_notify_blockcnt_change(struct spdk_bdev *bdev, uint64_t size)
3444 {
3445 	struct spdk_bdev_desc *desc;
3446 	int ret;
3447 
3448 	if (size == bdev->blockcnt) {
3449 		return 0;
3450 	}
3451 
3452 	pthread_mutex_lock(&bdev->internal.mutex);
3453 
3454 	/* bdev has open descriptors */
3455 	if (!TAILQ_EMPTY(&bdev->internal.open_descs) &&
3456 	    bdev->blockcnt > size) {
3457 		ret = -EBUSY;
3458 	} else {
3459 		bdev->blockcnt = size;
3460 		TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
3461 			pthread_mutex_lock(&desc->mutex);
3462 			if (!desc->closed) {
3463 				desc->refs++;
3464 				spdk_thread_send_msg(desc->thread, _resize_notify, desc);
3465 			}
3466 			pthread_mutex_unlock(&desc->mutex);
3467 		}
3468 		ret = 0;
3469 	}
3470 
3471 	pthread_mutex_unlock(&bdev->internal.mutex);
3472 
3473 	return ret;
3474 }
3475 
3476 /*
3477  * Convert I/O offset and length from bytes to blocks.
3478  *
3479  * Returns zero on success or non-zero if the byte parameters aren't divisible by the block size.
3480  */
3481 static uint64_t
3482 bdev_bytes_to_blocks(struct spdk_bdev *bdev, uint64_t offset_bytes, uint64_t *offset_blocks,
3483 		     uint64_t num_bytes, uint64_t *num_blocks)
3484 {
3485 	uint32_t block_size = bdev->blocklen;
3486 	uint8_t shift_cnt;
3487 
3488 	/* Avoid expensive div operations if possible. These spdk_u32 functions are very cheap. */
3489 	if (spdk_likely(spdk_u32_is_pow2(block_size))) {
3490 		shift_cnt = spdk_u32log2(block_size);
3491 		*offset_blocks = offset_bytes >> shift_cnt;
3492 		*num_blocks = num_bytes >> shift_cnt;
3493 		return (offset_bytes - (*offset_blocks << shift_cnt)) |
3494 		       (num_bytes - (*num_blocks << shift_cnt));
3495 	} else {
3496 		*offset_blocks = offset_bytes / block_size;
3497 		*num_blocks = num_bytes / block_size;
3498 		return (offset_bytes % block_size) | (num_bytes % block_size);
3499 	}
3500 }
3501 
3502 static bool
3503 bdev_io_valid_blocks(struct spdk_bdev *bdev, uint64_t offset_blocks, uint64_t num_blocks)
3504 {
3505 	/* Return failure if offset_blocks + num_blocks is less than offset_blocks; indicates there
3506 	 * has been an overflow and hence the offset has been wrapped around */
3507 	if (offset_blocks + num_blocks < offset_blocks) {
3508 		return false;
3509 	}
3510 
3511 	/* Return failure if offset_blocks + num_blocks exceeds the size of the bdev */
3512 	if (offset_blocks + num_blocks > bdev->blockcnt) {
3513 		return false;
3514 	}
3515 
3516 	return true;
3517 }
3518 
3519 static bool
3520 _bdev_io_check_md_buf(const struct iovec *iovs, const void *md_buf)
3521 {
3522 	return _is_buf_allocated(iovs) == (md_buf != NULL);
3523 }
3524 
3525 static int
3526 bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch, void *buf,
3527 			 void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
3528 			 spdk_bdev_io_completion_cb cb, void *cb_arg)
3529 {
3530 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3531 	struct spdk_bdev_io *bdev_io;
3532 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3533 
3534 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3535 		return -EINVAL;
3536 	}
3537 
3538 	bdev_io = bdev_channel_get_io(channel);
3539 	if (!bdev_io) {
3540 		return -ENOMEM;
3541 	}
3542 
3543 	bdev_io->internal.ch = channel;
3544 	bdev_io->internal.desc = desc;
3545 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
3546 	bdev_io->u.bdev.iovs = &bdev_io->iov;
3547 	bdev_io->u.bdev.iovs[0].iov_base = buf;
3548 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
3549 	bdev_io->u.bdev.iovcnt = 1;
3550 	bdev_io->u.bdev.md_buf = md_buf;
3551 	bdev_io->u.bdev.num_blocks = num_blocks;
3552 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3553 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3554 
3555 	bdev_io_submit(bdev_io);
3556 	return 0;
3557 }
3558 
3559 int
3560 spdk_bdev_read(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3561 	       void *buf, uint64_t offset, uint64_t nbytes,
3562 	       spdk_bdev_io_completion_cb cb, void *cb_arg)
3563 {
3564 	uint64_t offset_blocks, num_blocks;
3565 
3566 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3567 				 nbytes, &num_blocks) != 0) {
3568 		return -EINVAL;
3569 	}
3570 
3571 	return spdk_bdev_read_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
3572 }
3573 
3574 int
3575 spdk_bdev_read_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3576 		      void *buf, uint64_t offset_blocks, uint64_t num_blocks,
3577 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
3578 {
3579 	return bdev_read_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks, cb, cb_arg);
3580 }
3581 
3582 int
3583 spdk_bdev_read_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3584 			      void *buf, void *md_buf, int64_t offset_blocks, uint64_t num_blocks,
3585 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
3586 {
3587 	struct iovec iov = {
3588 		.iov_base = buf,
3589 	};
3590 
3591 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3592 		return -EINVAL;
3593 	}
3594 
3595 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
3596 		return -EINVAL;
3597 	}
3598 
3599 	return bdev_read_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
3600 					cb, cb_arg);
3601 }
3602 
3603 int
3604 spdk_bdev_readv(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3605 		struct iovec *iov, int iovcnt,
3606 		uint64_t offset, uint64_t nbytes,
3607 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3608 {
3609 	uint64_t offset_blocks, num_blocks;
3610 
3611 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3612 				 nbytes, &num_blocks) != 0) {
3613 		return -EINVAL;
3614 	}
3615 
3616 	return spdk_bdev_readv_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
3617 }
3618 
3619 static int
3620 bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3621 			  struct iovec *iov, int iovcnt, void *md_buf, uint64_t offset_blocks,
3622 			  uint64_t num_blocks, spdk_bdev_io_completion_cb cb, void *cb_arg)
3623 {
3624 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3625 	struct spdk_bdev_io *bdev_io;
3626 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3627 
3628 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3629 		return -EINVAL;
3630 	}
3631 
3632 	bdev_io = bdev_channel_get_io(channel);
3633 	if (!bdev_io) {
3634 		return -ENOMEM;
3635 	}
3636 
3637 	bdev_io->internal.ch = channel;
3638 	bdev_io->internal.desc = desc;
3639 	bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
3640 	bdev_io->u.bdev.iovs = iov;
3641 	bdev_io->u.bdev.iovcnt = iovcnt;
3642 	bdev_io->u.bdev.md_buf = md_buf;
3643 	bdev_io->u.bdev.num_blocks = num_blocks;
3644 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3645 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3646 
3647 	bdev_io_submit(bdev_io);
3648 	return 0;
3649 }
3650 
3651 int spdk_bdev_readv_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3652 			   struct iovec *iov, int iovcnt,
3653 			   uint64_t offset_blocks, uint64_t num_blocks,
3654 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
3655 {
3656 	return bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
3657 					 num_blocks, cb, cb_arg);
3658 }
3659 
3660 int
3661 spdk_bdev_readv_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3662 			       struct iovec *iov, int iovcnt, void *md_buf,
3663 			       uint64_t offset_blocks, uint64_t num_blocks,
3664 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
3665 {
3666 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3667 		return -EINVAL;
3668 	}
3669 
3670 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
3671 		return -EINVAL;
3672 	}
3673 
3674 	return bdev_readv_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
3675 					 num_blocks, cb, cb_arg);
3676 }
3677 
3678 static int
3679 bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3680 			  void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
3681 			  spdk_bdev_io_completion_cb cb, void *cb_arg)
3682 {
3683 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3684 	struct spdk_bdev_io *bdev_io;
3685 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3686 
3687 	if (!desc->write) {
3688 		return -EBADF;
3689 	}
3690 
3691 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3692 		return -EINVAL;
3693 	}
3694 
3695 	bdev_io = bdev_channel_get_io(channel);
3696 	if (!bdev_io) {
3697 		return -ENOMEM;
3698 	}
3699 
3700 	bdev_io->internal.ch = channel;
3701 	bdev_io->internal.desc = desc;
3702 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3703 	bdev_io->u.bdev.iovs = &bdev_io->iov;
3704 	bdev_io->u.bdev.iovs[0].iov_base = buf;
3705 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
3706 	bdev_io->u.bdev.iovcnt = 1;
3707 	bdev_io->u.bdev.md_buf = md_buf;
3708 	bdev_io->u.bdev.num_blocks = num_blocks;
3709 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3710 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3711 
3712 	bdev_io_submit(bdev_io);
3713 	return 0;
3714 }
3715 
3716 int
3717 spdk_bdev_write(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3718 		void *buf, uint64_t offset, uint64_t nbytes,
3719 		spdk_bdev_io_completion_cb cb, void *cb_arg)
3720 {
3721 	uint64_t offset_blocks, num_blocks;
3722 
3723 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3724 				 nbytes, &num_blocks) != 0) {
3725 		return -EINVAL;
3726 	}
3727 
3728 	return spdk_bdev_write_blocks(desc, ch, buf, offset_blocks, num_blocks, cb, cb_arg);
3729 }
3730 
3731 int
3732 spdk_bdev_write_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3733 		       void *buf, uint64_t offset_blocks, uint64_t num_blocks,
3734 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
3735 {
3736 	return bdev_write_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
3737 					 cb, cb_arg);
3738 }
3739 
3740 int
3741 spdk_bdev_write_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3742 			       void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
3743 			       spdk_bdev_io_completion_cb cb, void *cb_arg)
3744 {
3745 	struct iovec iov = {
3746 		.iov_base = buf,
3747 	};
3748 
3749 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3750 		return -EINVAL;
3751 	}
3752 
3753 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
3754 		return -EINVAL;
3755 	}
3756 
3757 	return bdev_write_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
3758 					 cb, cb_arg);
3759 }
3760 
3761 static int
3762 bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3763 			   struct iovec *iov, int iovcnt, void *md_buf,
3764 			   uint64_t offset_blocks, uint64_t num_blocks,
3765 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
3766 {
3767 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3768 	struct spdk_bdev_io *bdev_io;
3769 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3770 
3771 	if (!desc->write) {
3772 		return -EBADF;
3773 	}
3774 
3775 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3776 		return -EINVAL;
3777 	}
3778 
3779 	bdev_io = bdev_channel_get_io(channel);
3780 	if (!bdev_io) {
3781 		return -ENOMEM;
3782 	}
3783 
3784 	bdev_io->internal.ch = channel;
3785 	bdev_io->internal.desc = desc;
3786 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
3787 	bdev_io->u.bdev.iovs = iov;
3788 	bdev_io->u.bdev.iovcnt = iovcnt;
3789 	bdev_io->u.bdev.md_buf = md_buf;
3790 	bdev_io->u.bdev.num_blocks = num_blocks;
3791 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3792 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3793 
3794 	bdev_io_submit(bdev_io);
3795 	return 0;
3796 }
3797 
3798 int
3799 spdk_bdev_writev(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3800 		 struct iovec *iov, int iovcnt,
3801 		 uint64_t offset, uint64_t len,
3802 		 spdk_bdev_io_completion_cb cb, void *cb_arg)
3803 {
3804 	uint64_t offset_blocks, num_blocks;
3805 
3806 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
3807 				 len, &num_blocks) != 0) {
3808 		return -EINVAL;
3809 	}
3810 
3811 	return spdk_bdev_writev_blocks(desc, ch, iov, iovcnt, offset_blocks, num_blocks, cb, cb_arg);
3812 }
3813 
3814 int
3815 spdk_bdev_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3816 			struct iovec *iov, int iovcnt,
3817 			uint64_t offset_blocks, uint64_t num_blocks,
3818 			spdk_bdev_io_completion_cb cb, void *cb_arg)
3819 {
3820 	return bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
3821 					  num_blocks, cb, cb_arg);
3822 }
3823 
3824 int
3825 spdk_bdev_writev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3826 				struct iovec *iov, int iovcnt, void *md_buf,
3827 				uint64_t offset_blocks, uint64_t num_blocks,
3828 				spdk_bdev_io_completion_cb cb, void *cb_arg)
3829 {
3830 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3831 		return -EINVAL;
3832 	}
3833 
3834 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
3835 		return -EINVAL;
3836 	}
3837 
3838 	return bdev_writev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
3839 					  num_blocks, cb, cb_arg);
3840 }
3841 
3842 static void
3843 bdev_compare_do_read_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
3844 {
3845 	struct spdk_bdev_io *parent_io = cb_arg;
3846 	uint8_t *read_buf = bdev_io->u.bdev.iovs[0].iov_base;
3847 	int i, rc = 0;
3848 
3849 	if (!success) {
3850 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
3851 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
3852 		spdk_bdev_free_io(bdev_io);
3853 		return;
3854 	}
3855 
3856 	for (i = 0; i < parent_io->u.bdev.iovcnt; i++) {
3857 		rc = memcmp(read_buf,
3858 			    parent_io->u.bdev.iovs[i].iov_base,
3859 			    parent_io->u.bdev.iovs[i].iov_len);
3860 		if (rc) {
3861 			break;
3862 		}
3863 		read_buf += parent_io->u.bdev.iovs[i].iov_len;
3864 	}
3865 
3866 	spdk_bdev_free_io(bdev_io);
3867 
3868 	if (rc == 0) {
3869 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
3870 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
3871 	} else {
3872 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_MISCOMPARE;
3873 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
3874 	}
3875 }
3876 
3877 static void
3878 bdev_compare_do_read(void *_bdev_io)
3879 {
3880 	struct spdk_bdev_io *bdev_io = _bdev_io;
3881 	int rc;
3882 
3883 	rc = spdk_bdev_read_blocks(bdev_io->internal.desc,
3884 				   spdk_io_channel_from_ctx(bdev_io->internal.ch), NULL,
3885 				   bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
3886 				   bdev_compare_do_read_done, bdev_io);
3887 
3888 	if (rc == -ENOMEM) {
3889 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_do_read);
3890 	} else if (rc != 0) {
3891 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
3892 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
3893 	}
3894 }
3895 
3896 static int
3897 bdev_comparev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3898 			     struct iovec *iov, int iovcnt, void *md_buf,
3899 			     uint64_t offset_blocks, uint64_t num_blocks,
3900 			     spdk_bdev_io_completion_cb cb, void *cb_arg)
3901 {
3902 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3903 	struct spdk_bdev_io *bdev_io;
3904 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3905 
3906 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3907 		return -EINVAL;
3908 	}
3909 
3910 	bdev_io = bdev_channel_get_io(channel);
3911 	if (!bdev_io) {
3912 		return -ENOMEM;
3913 	}
3914 
3915 	bdev_io->internal.ch = channel;
3916 	bdev_io->internal.desc = desc;
3917 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE;
3918 	bdev_io->u.bdev.iovs = iov;
3919 	bdev_io->u.bdev.iovcnt = iovcnt;
3920 	bdev_io->u.bdev.md_buf = md_buf;
3921 	bdev_io->u.bdev.num_blocks = num_blocks;
3922 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3923 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3924 
3925 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE)) {
3926 		bdev_io_submit(bdev_io);
3927 		return 0;
3928 	}
3929 
3930 	bdev_compare_do_read(bdev_io);
3931 
3932 	return 0;
3933 }
3934 
3935 int
3936 spdk_bdev_comparev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3937 			  struct iovec *iov, int iovcnt,
3938 			  uint64_t offset_blocks, uint64_t num_blocks,
3939 			  spdk_bdev_io_completion_cb cb, void *cb_arg)
3940 {
3941 	return bdev_comparev_blocks_with_md(desc, ch, iov, iovcnt, NULL, offset_blocks,
3942 					    num_blocks, cb, cb_arg);
3943 }
3944 
3945 int
3946 spdk_bdev_comparev_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3947 				  struct iovec *iov, int iovcnt, void *md_buf,
3948 				  uint64_t offset_blocks, uint64_t num_blocks,
3949 				  spdk_bdev_io_completion_cb cb, void *cb_arg)
3950 {
3951 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
3952 		return -EINVAL;
3953 	}
3954 
3955 	if (!_bdev_io_check_md_buf(iov, md_buf)) {
3956 		return -EINVAL;
3957 	}
3958 
3959 	return bdev_comparev_blocks_with_md(desc, ch, iov, iovcnt, md_buf, offset_blocks,
3960 					    num_blocks, cb, cb_arg);
3961 }
3962 
3963 static int
3964 bdev_compare_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
3965 			    void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
3966 			    spdk_bdev_io_completion_cb cb, void *cb_arg)
3967 {
3968 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
3969 	struct spdk_bdev_io *bdev_io;
3970 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
3971 
3972 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
3973 		return -EINVAL;
3974 	}
3975 
3976 	bdev_io = bdev_channel_get_io(channel);
3977 	if (!bdev_io) {
3978 		return -ENOMEM;
3979 	}
3980 
3981 	bdev_io->internal.ch = channel;
3982 	bdev_io->internal.desc = desc;
3983 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE;
3984 	bdev_io->u.bdev.iovs = &bdev_io->iov;
3985 	bdev_io->u.bdev.iovs[0].iov_base = buf;
3986 	bdev_io->u.bdev.iovs[0].iov_len = num_blocks * bdev->blocklen;
3987 	bdev_io->u.bdev.iovcnt = 1;
3988 	bdev_io->u.bdev.md_buf = md_buf;
3989 	bdev_io->u.bdev.num_blocks = num_blocks;
3990 	bdev_io->u.bdev.offset_blocks = offset_blocks;
3991 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
3992 
3993 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE)) {
3994 		bdev_io_submit(bdev_io);
3995 		return 0;
3996 	}
3997 
3998 	bdev_compare_do_read(bdev_io);
3999 
4000 	return 0;
4001 }
4002 
4003 int
4004 spdk_bdev_compare_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4005 			 void *buf, uint64_t offset_blocks, uint64_t num_blocks,
4006 			 spdk_bdev_io_completion_cb cb, void *cb_arg)
4007 {
4008 	return bdev_compare_blocks_with_md(desc, ch, buf, NULL, offset_blocks, num_blocks,
4009 					   cb, cb_arg);
4010 }
4011 
4012 int
4013 spdk_bdev_compare_blocks_with_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4014 				 void *buf, void *md_buf, uint64_t offset_blocks, uint64_t num_blocks,
4015 				 spdk_bdev_io_completion_cb cb, void *cb_arg)
4016 {
4017 	struct iovec iov = {
4018 		.iov_base = buf,
4019 	};
4020 
4021 	if (!spdk_bdev_is_md_separate(spdk_bdev_desc_get_bdev(desc))) {
4022 		return -EINVAL;
4023 	}
4024 
4025 	if (!_bdev_io_check_md_buf(&iov, md_buf)) {
4026 		return -EINVAL;
4027 	}
4028 
4029 	return bdev_compare_blocks_with_md(desc, ch, buf, md_buf, offset_blocks, num_blocks,
4030 					   cb, cb_arg);
4031 }
4032 
4033 static void
4034 bdev_comparev_and_writev_blocks_unlocked(void *ctx, int unlock_status)
4035 {
4036 	struct spdk_bdev_io *bdev_io = ctx;
4037 
4038 	if (unlock_status) {
4039 		SPDK_ERRLOG("LBA range unlock failed\n");
4040 	}
4041 
4042 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS ? true :
4043 			     false, bdev_io->internal.caller_ctx);
4044 }
4045 
4046 static void
4047 bdev_comparev_and_writev_blocks_unlock(struct spdk_bdev_io *bdev_io, int status)
4048 {
4049 	bdev_io->internal.status = status;
4050 
4051 	bdev_unlock_lba_range(bdev_io->internal.desc, spdk_io_channel_from_ctx(bdev_io->internal.ch),
4052 			      bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4053 			      bdev_comparev_and_writev_blocks_unlocked, bdev_io);
4054 }
4055 
4056 static void
4057 bdev_compare_and_write_do_write_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4058 {
4059 	struct spdk_bdev_io *parent_io = cb_arg;
4060 
4061 	if (!success) {
4062 		SPDK_ERRLOG("Compare and write operation failed\n");
4063 	}
4064 
4065 	spdk_bdev_free_io(bdev_io);
4066 
4067 	bdev_comparev_and_writev_blocks_unlock(parent_io,
4068 					       success ? SPDK_BDEV_IO_STATUS_SUCCESS : SPDK_BDEV_IO_STATUS_FAILED);
4069 }
4070 
4071 static void
4072 bdev_compare_and_write_do_write(void *_bdev_io)
4073 {
4074 	struct spdk_bdev_io *bdev_io = _bdev_io;
4075 	int rc;
4076 
4077 	rc = spdk_bdev_writev_blocks(bdev_io->internal.desc,
4078 				     spdk_io_channel_from_ctx(bdev_io->internal.ch),
4079 				     bdev_io->u.bdev.fused_iovs, bdev_io->u.bdev.fused_iovcnt,
4080 				     bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4081 				     bdev_compare_and_write_do_write_done, bdev_io);
4082 
4083 
4084 	if (rc == -ENOMEM) {
4085 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_and_write_do_write);
4086 	} else if (rc != 0) {
4087 		bdev_comparev_and_writev_blocks_unlock(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
4088 	}
4089 }
4090 
4091 static void
4092 bdev_compare_and_write_do_compare_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4093 {
4094 	struct spdk_bdev_io *parent_io = cb_arg;
4095 
4096 	spdk_bdev_free_io(bdev_io);
4097 
4098 	if (!success) {
4099 		bdev_comparev_and_writev_blocks_unlock(parent_io, SPDK_BDEV_IO_STATUS_MISCOMPARE);
4100 		return;
4101 	}
4102 
4103 	bdev_compare_and_write_do_write(parent_io);
4104 }
4105 
4106 static void
4107 bdev_compare_and_write_do_compare(void *_bdev_io)
4108 {
4109 	struct spdk_bdev_io *bdev_io = _bdev_io;
4110 	int rc;
4111 
4112 	rc = spdk_bdev_comparev_blocks(bdev_io->internal.desc,
4113 				       spdk_io_channel_from_ctx(bdev_io->internal.ch), bdev_io->u.bdev.iovs,
4114 				       bdev_io->u.bdev.iovcnt, bdev_io->u.bdev.offset_blocks, bdev_io->u.bdev.num_blocks,
4115 				       bdev_compare_and_write_do_compare_done, bdev_io);
4116 
4117 	if (rc == -ENOMEM) {
4118 		bdev_queue_io_wait_with_cb(bdev_io, bdev_compare_and_write_do_compare);
4119 	} else if (rc != 0) {
4120 		bdev_comparev_and_writev_blocks_unlock(bdev_io, SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED);
4121 	}
4122 }
4123 
4124 static void
4125 bdev_comparev_and_writev_blocks_locked(void *ctx, int status)
4126 {
4127 	struct spdk_bdev_io *bdev_io = ctx;
4128 
4129 	if (status) {
4130 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED;
4131 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
4132 		return;
4133 	}
4134 
4135 	bdev_compare_and_write_do_compare(bdev_io);
4136 }
4137 
4138 int
4139 spdk_bdev_comparev_and_writev_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4140 				     struct iovec *compare_iov, int compare_iovcnt,
4141 				     struct iovec *write_iov, int write_iovcnt,
4142 				     uint64_t offset_blocks, uint64_t num_blocks,
4143 				     spdk_bdev_io_completion_cb cb, void *cb_arg)
4144 {
4145 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4146 	struct spdk_bdev_io *bdev_io;
4147 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4148 
4149 	if (!desc->write) {
4150 		return -EBADF;
4151 	}
4152 
4153 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4154 		return -EINVAL;
4155 	}
4156 
4157 	if (num_blocks > bdev->acwu) {
4158 		return -EINVAL;
4159 	}
4160 
4161 	bdev_io = bdev_channel_get_io(channel);
4162 	if (!bdev_io) {
4163 		return -ENOMEM;
4164 	}
4165 
4166 	bdev_io->internal.ch = channel;
4167 	bdev_io->internal.desc = desc;
4168 	bdev_io->type = SPDK_BDEV_IO_TYPE_COMPARE_AND_WRITE;
4169 	bdev_io->u.bdev.iovs = compare_iov;
4170 	bdev_io->u.bdev.iovcnt = compare_iovcnt;
4171 	bdev_io->u.bdev.fused_iovs = write_iov;
4172 	bdev_io->u.bdev.fused_iovcnt = write_iovcnt;
4173 	bdev_io->u.bdev.md_buf = NULL;
4174 	bdev_io->u.bdev.num_blocks = num_blocks;
4175 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4176 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4177 
4178 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_COMPARE_AND_WRITE)) {
4179 		bdev_io_submit(bdev_io);
4180 		return 0;
4181 	}
4182 
4183 	return bdev_lock_lba_range(desc, ch, offset_blocks, num_blocks,
4184 				   bdev_comparev_and_writev_blocks_locked, bdev_io);
4185 }
4186 
4187 static void
4188 bdev_zcopy_get_buf(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io, bool success)
4189 {
4190 	if (!success) {
4191 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
4192 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NOMEM;
4193 		bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
4194 		return;
4195 	}
4196 
4197 	if (bdev_io->u.bdev.zcopy.populate) {
4198 		/* Read the real data into the buffer */
4199 		bdev_io->type = SPDK_BDEV_IO_TYPE_READ;
4200 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
4201 		bdev_io_submit(bdev_io);
4202 		return;
4203 	}
4204 
4205 	/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
4206 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4207 	bdev_io->internal.cb(bdev_io, success, bdev_io->internal.caller_ctx);
4208 }
4209 
4210 int
4211 spdk_bdev_zcopy_start(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4212 		      uint64_t offset_blocks, uint64_t num_blocks,
4213 		      bool populate,
4214 		      spdk_bdev_io_completion_cb cb, void *cb_arg)
4215 {
4216 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4217 	struct spdk_bdev_io *bdev_io;
4218 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4219 
4220 	if (!desc->write) {
4221 		return -EBADF;
4222 	}
4223 
4224 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4225 		return -EINVAL;
4226 	}
4227 
4228 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
4229 		return -ENOTSUP;
4230 	}
4231 
4232 	bdev_io = bdev_channel_get_io(channel);
4233 	if (!bdev_io) {
4234 		return -ENOMEM;
4235 	}
4236 
4237 	bdev_io->internal.ch = channel;
4238 	bdev_io->internal.desc = desc;
4239 	bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
4240 	bdev_io->u.bdev.num_blocks = num_blocks;
4241 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4242 	bdev_io->u.bdev.iovs = NULL;
4243 	bdev_io->u.bdev.iovcnt = 0;
4244 	bdev_io->u.bdev.md_buf = NULL;
4245 	bdev_io->u.bdev.zcopy.populate = populate ? 1 : 0;
4246 	bdev_io->u.bdev.zcopy.commit = 0;
4247 	bdev_io->u.bdev.zcopy.start = 1;
4248 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4249 
4250 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
4251 		bdev_io_submit(bdev_io);
4252 	} else {
4253 		/* Emulate zcopy by allocating a buffer */
4254 		spdk_bdev_io_get_buf(bdev_io, bdev_zcopy_get_buf,
4255 				     bdev_io->u.bdev.num_blocks * bdev->blocklen);
4256 	}
4257 
4258 	return 0;
4259 }
4260 
4261 int
4262 spdk_bdev_zcopy_end(struct spdk_bdev_io *bdev_io, bool commit,
4263 		    spdk_bdev_io_completion_cb cb, void *cb_arg)
4264 {
4265 	struct spdk_bdev *bdev = bdev_io->bdev;
4266 
4267 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
4268 		/* This can happen if the zcopy was emulated in start */
4269 		if (bdev_io->u.bdev.zcopy.start != 1) {
4270 			return -EINVAL;
4271 		}
4272 		bdev_io->type = SPDK_BDEV_IO_TYPE_ZCOPY;
4273 	}
4274 
4275 	if (bdev_io->type != SPDK_BDEV_IO_TYPE_ZCOPY) {
4276 		return -EINVAL;
4277 	}
4278 
4279 	bdev_io->u.bdev.zcopy.commit = commit ? 1 : 0;
4280 	bdev_io->u.bdev.zcopy.start = 0;
4281 	bdev_io->internal.caller_ctx = cb_arg;
4282 	bdev_io->internal.cb = cb;
4283 	bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
4284 
4285 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
4286 		bdev_io_submit(bdev_io);
4287 		return 0;
4288 	}
4289 
4290 	if (!bdev_io->u.bdev.zcopy.commit) {
4291 		/* Don't use spdk_bdev_io_complete here - this bdev_io was never actually submitted. */
4292 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4293 		bdev_io->internal.cb(bdev_io, true, bdev_io->internal.caller_ctx);
4294 		return 0;
4295 	}
4296 
4297 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE;
4298 	bdev_io_submit(bdev_io);
4299 
4300 	return 0;
4301 }
4302 
4303 int
4304 spdk_bdev_write_zeroes(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4305 		       uint64_t offset, uint64_t len,
4306 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4307 {
4308 	uint64_t offset_blocks, num_blocks;
4309 
4310 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4311 				 len, &num_blocks) != 0) {
4312 		return -EINVAL;
4313 	}
4314 
4315 	return spdk_bdev_write_zeroes_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
4316 }
4317 
4318 int
4319 spdk_bdev_write_zeroes_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4320 			      uint64_t offset_blocks, uint64_t num_blocks,
4321 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
4322 {
4323 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4324 	struct spdk_bdev_io *bdev_io;
4325 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4326 
4327 	if (!desc->write) {
4328 		return -EBADF;
4329 	}
4330 
4331 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4332 		return -EINVAL;
4333 	}
4334 
4335 	if (!bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES) &&
4336 	    !bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE)) {
4337 		return -ENOTSUP;
4338 	}
4339 
4340 	bdev_io = bdev_channel_get_io(channel);
4341 
4342 	if (!bdev_io) {
4343 		return -ENOMEM;
4344 	}
4345 
4346 	bdev_io->type = SPDK_BDEV_IO_TYPE_WRITE_ZEROES;
4347 	bdev_io->internal.ch = channel;
4348 	bdev_io->internal.desc = desc;
4349 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4350 	bdev_io->u.bdev.num_blocks = num_blocks;
4351 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4352 
4353 	if (bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE_ZEROES)) {
4354 		bdev_io_submit(bdev_io);
4355 		return 0;
4356 	}
4357 
4358 	assert(bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_WRITE));
4359 	assert(_bdev_get_block_size_with_md(bdev) <= ZERO_BUFFER_SIZE);
4360 	bdev_io->u.bdev.split_remaining_num_blocks = num_blocks;
4361 	bdev_io->u.bdev.split_current_offset_blocks = offset_blocks;
4362 	bdev_write_zero_buffer_next(bdev_io);
4363 
4364 	return 0;
4365 }
4366 
4367 int
4368 spdk_bdev_unmap(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4369 		uint64_t offset, uint64_t nbytes,
4370 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4371 {
4372 	uint64_t offset_blocks, num_blocks;
4373 
4374 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4375 				 nbytes, &num_blocks) != 0) {
4376 		return -EINVAL;
4377 	}
4378 
4379 	return spdk_bdev_unmap_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
4380 }
4381 
4382 int
4383 spdk_bdev_unmap_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4384 		       uint64_t offset_blocks, uint64_t num_blocks,
4385 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4386 {
4387 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4388 	struct spdk_bdev_io *bdev_io;
4389 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4390 
4391 	if (!desc->write) {
4392 		return -EBADF;
4393 	}
4394 
4395 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4396 		return -EINVAL;
4397 	}
4398 
4399 	if (num_blocks == 0) {
4400 		SPDK_ERRLOG("Can't unmap 0 bytes\n");
4401 		return -EINVAL;
4402 	}
4403 
4404 	bdev_io = bdev_channel_get_io(channel);
4405 	if (!bdev_io) {
4406 		return -ENOMEM;
4407 	}
4408 
4409 	bdev_io->internal.ch = channel;
4410 	bdev_io->internal.desc = desc;
4411 	bdev_io->type = SPDK_BDEV_IO_TYPE_UNMAP;
4412 
4413 	bdev_io->u.bdev.iovs = &bdev_io->iov;
4414 	bdev_io->u.bdev.iovs[0].iov_base = NULL;
4415 	bdev_io->u.bdev.iovs[0].iov_len = 0;
4416 	bdev_io->u.bdev.iovcnt = 1;
4417 
4418 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4419 	bdev_io->u.bdev.num_blocks = num_blocks;
4420 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4421 
4422 	bdev_io_submit(bdev_io);
4423 	return 0;
4424 }
4425 
4426 int
4427 spdk_bdev_flush(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4428 		uint64_t offset, uint64_t length,
4429 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4430 {
4431 	uint64_t offset_blocks, num_blocks;
4432 
4433 	if (bdev_bytes_to_blocks(spdk_bdev_desc_get_bdev(desc), offset, &offset_blocks,
4434 				 length, &num_blocks) != 0) {
4435 		return -EINVAL;
4436 	}
4437 
4438 	return spdk_bdev_flush_blocks(desc, ch, offset_blocks, num_blocks, cb, cb_arg);
4439 }
4440 
4441 int
4442 spdk_bdev_flush_blocks(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4443 		       uint64_t offset_blocks, uint64_t num_blocks,
4444 		       spdk_bdev_io_completion_cb cb, void *cb_arg)
4445 {
4446 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4447 	struct spdk_bdev_io *bdev_io;
4448 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4449 
4450 	if (!desc->write) {
4451 		return -EBADF;
4452 	}
4453 
4454 	if (!bdev_io_valid_blocks(bdev, offset_blocks, num_blocks)) {
4455 		return -EINVAL;
4456 	}
4457 
4458 	bdev_io = bdev_channel_get_io(channel);
4459 	if (!bdev_io) {
4460 		return -ENOMEM;
4461 	}
4462 
4463 	bdev_io->internal.ch = channel;
4464 	bdev_io->internal.desc = desc;
4465 	bdev_io->type = SPDK_BDEV_IO_TYPE_FLUSH;
4466 	bdev_io->u.bdev.iovs = NULL;
4467 	bdev_io->u.bdev.iovcnt = 0;
4468 	bdev_io->u.bdev.offset_blocks = offset_blocks;
4469 	bdev_io->u.bdev.num_blocks = num_blocks;
4470 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4471 
4472 	bdev_io_submit(bdev_io);
4473 	return 0;
4474 }
4475 
4476 static void
4477 bdev_reset_dev(struct spdk_io_channel_iter *i, int status)
4478 {
4479 	struct spdk_bdev_channel *ch = spdk_io_channel_iter_get_ctx(i);
4480 	struct spdk_bdev_io *bdev_io;
4481 
4482 	bdev_io = TAILQ_FIRST(&ch->queued_resets);
4483 	TAILQ_REMOVE(&ch->queued_resets, bdev_io, internal.link);
4484 	bdev_io_submit_reset(bdev_io);
4485 }
4486 
4487 static void
4488 bdev_reset_freeze_channel(struct spdk_io_channel_iter *i)
4489 {
4490 	struct spdk_io_channel		*ch;
4491 	struct spdk_bdev_channel	*channel;
4492 	struct spdk_bdev_mgmt_channel	*mgmt_channel;
4493 	struct spdk_bdev_shared_resource *shared_resource;
4494 	bdev_io_tailq_t			tmp_queued;
4495 
4496 	TAILQ_INIT(&tmp_queued);
4497 
4498 	ch = spdk_io_channel_iter_get_channel(i);
4499 	channel = spdk_io_channel_get_ctx(ch);
4500 	shared_resource = channel->shared_resource;
4501 	mgmt_channel = shared_resource->mgmt_ch;
4502 
4503 	channel->flags |= BDEV_CH_RESET_IN_PROGRESS;
4504 
4505 	if ((channel->flags & BDEV_CH_QOS_ENABLED) != 0) {
4506 		/* The QoS object is always valid and readable while
4507 		 * the channel flag is set, so the lock here should not
4508 		 * be necessary. We're not in the fast path though, so
4509 		 * just take it anyway. */
4510 		pthread_mutex_lock(&channel->bdev->internal.mutex);
4511 		if (channel->bdev->internal.qos->ch == channel) {
4512 			TAILQ_SWAP(&channel->bdev->internal.qos->queued, &tmp_queued, spdk_bdev_io, internal.link);
4513 		}
4514 		pthread_mutex_unlock(&channel->bdev->internal.mutex);
4515 	}
4516 
4517 	bdev_abort_all_queued_io(&shared_resource->nomem_io, channel);
4518 	bdev_abort_all_buf_io(&mgmt_channel->need_buf_small, channel);
4519 	bdev_abort_all_buf_io(&mgmt_channel->need_buf_large, channel);
4520 	bdev_abort_all_queued_io(&tmp_queued, channel);
4521 
4522 	spdk_for_each_channel_continue(i, 0);
4523 }
4524 
4525 static void
4526 bdev_start_reset(void *ctx)
4527 {
4528 	struct spdk_bdev_channel *ch = ctx;
4529 
4530 	spdk_for_each_channel(__bdev_to_io_dev(ch->bdev), bdev_reset_freeze_channel,
4531 			      ch, bdev_reset_dev);
4532 }
4533 
4534 static void
4535 bdev_channel_start_reset(struct spdk_bdev_channel *ch)
4536 {
4537 	struct spdk_bdev *bdev = ch->bdev;
4538 
4539 	assert(!TAILQ_EMPTY(&ch->queued_resets));
4540 
4541 	pthread_mutex_lock(&bdev->internal.mutex);
4542 	if (bdev->internal.reset_in_progress == NULL) {
4543 		bdev->internal.reset_in_progress = TAILQ_FIRST(&ch->queued_resets);
4544 		/*
4545 		 * Take a channel reference for the target bdev for the life of this
4546 		 *  reset.  This guards against the channel getting destroyed while
4547 		 *  spdk_for_each_channel() calls related to this reset IO are in
4548 		 *  progress.  We will release the reference when this reset is
4549 		 *  completed.
4550 		 */
4551 		bdev->internal.reset_in_progress->u.reset.ch_ref = spdk_get_io_channel(__bdev_to_io_dev(bdev));
4552 		bdev_start_reset(ch);
4553 	}
4554 	pthread_mutex_unlock(&bdev->internal.mutex);
4555 }
4556 
4557 int
4558 spdk_bdev_reset(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4559 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4560 {
4561 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4562 	struct spdk_bdev_io *bdev_io;
4563 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4564 
4565 	bdev_io = bdev_channel_get_io(channel);
4566 	if (!bdev_io) {
4567 		return -ENOMEM;
4568 	}
4569 
4570 	bdev_io->internal.ch = channel;
4571 	bdev_io->internal.desc = desc;
4572 	bdev_io->internal.submit_tsc = spdk_get_ticks();
4573 	bdev_io->type = SPDK_BDEV_IO_TYPE_RESET;
4574 	bdev_io->u.reset.ch_ref = NULL;
4575 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4576 
4577 	pthread_mutex_lock(&bdev->internal.mutex);
4578 	TAILQ_INSERT_TAIL(&channel->queued_resets, bdev_io, internal.link);
4579 	pthread_mutex_unlock(&bdev->internal.mutex);
4580 
4581 	TAILQ_INSERT_TAIL(&bdev_io->internal.ch->io_submitted, bdev_io,
4582 			  internal.ch_link);
4583 
4584 	bdev_channel_start_reset(channel);
4585 
4586 	return 0;
4587 }
4588 
4589 void
4590 spdk_bdev_get_io_stat(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
4591 		      struct spdk_bdev_io_stat *stat)
4592 {
4593 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4594 
4595 	*stat = channel->stat;
4596 }
4597 
4598 static void
4599 bdev_get_device_stat_done(struct spdk_io_channel_iter *i, int status)
4600 {
4601 	void *io_device = spdk_io_channel_iter_get_io_device(i);
4602 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
4603 
4604 	bdev_iostat_ctx->cb(__bdev_from_io_dev(io_device), bdev_iostat_ctx->stat,
4605 			    bdev_iostat_ctx->cb_arg, 0);
4606 	free(bdev_iostat_ctx);
4607 }
4608 
4609 static void
4610 bdev_get_each_channel_stat(struct spdk_io_channel_iter *i)
4611 {
4612 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx = spdk_io_channel_iter_get_ctx(i);
4613 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
4614 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4615 
4616 	bdev_io_stat_add(bdev_iostat_ctx->stat, &channel->stat);
4617 	spdk_for_each_channel_continue(i, 0);
4618 }
4619 
4620 void
4621 spdk_bdev_get_device_stat(struct spdk_bdev *bdev, struct spdk_bdev_io_stat *stat,
4622 			  spdk_bdev_get_device_stat_cb cb, void *cb_arg)
4623 {
4624 	struct spdk_bdev_iostat_ctx *bdev_iostat_ctx;
4625 
4626 	assert(bdev != NULL);
4627 	assert(stat != NULL);
4628 	assert(cb != NULL);
4629 
4630 	bdev_iostat_ctx = calloc(1, sizeof(struct spdk_bdev_iostat_ctx));
4631 	if (bdev_iostat_ctx == NULL) {
4632 		SPDK_ERRLOG("Unable to allocate memory for spdk_bdev_iostat_ctx\n");
4633 		cb(bdev, stat, cb_arg, -ENOMEM);
4634 		return;
4635 	}
4636 
4637 	bdev_iostat_ctx->stat = stat;
4638 	bdev_iostat_ctx->cb = cb;
4639 	bdev_iostat_ctx->cb_arg = cb_arg;
4640 
4641 	/* Start with the statistics from previously deleted channels. */
4642 	pthread_mutex_lock(&bdev->internal.mutex);
4643 	bdev_io_stat_add(bdev_iostat_ctx->stat, &bdev->internal.stat);
4644 	pthread_mutex_unlock(&bdev->internal.mutex);
4645 
4646 	/* Then iterate and add the statistics from each existing channel. */
4647 	spdk_for_each_channel(__bdev_to_io_dev(bdev),
4648 			      bdev_get_each_channel_stat,
4649 			      bdev_iostat_ctx,
4650 			      bdev_get_device_stat_done);
4651 }
4652 
4653 int
4654 spdk_bdev_nvme_admin_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4655 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
4656 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
4657 {
4658 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4659 	struct spdk_bdev_io *bdev_io;
4660 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4661 
4662 	if (!desc->write) {
4663 		return -EBADF;
4664 	}
4665 
4666 	bdev_io = bdev_channel_get_io(channel);
4667 	if (!bdev_io) {
4668 		return -ENOMEM;
4669 	}
4670 
4671 	bdev_io->internal.ch = channel;
4672 	bdev_io->internal.desc = desc;
4673 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_ADMIN;
4674 	bdev_io->u.nvme_passthru.cmd = *cmd;
4675 	bdev_io->u.nvme_passthru.buf = buf;
4676 	bdev_io->u.nvme_passthru.nbytes = nbytes;
4677 	bdev_io->u.nvme_passthru.md_buf = NULL;
4678 	bdev_io->u.nvme_passthru.md_len = 0;
4679 
4680 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4681 
4682 	bdev_io_submit(bdev_io);
4683 	return 0;
4684 }
4685 
4686 int
4687 spdk_bdev_nvme_io_passthru(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4688 			   const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes,
4689 			   spdk_bdev_io_completion_cb cb, void *cb_arg)
4690 {
4691 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4692 	struct spdk_bdev_io *bdev_io;
4693 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4694 
4695 	if (!desc->write) {
4696 		/*
4697 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
4698 		 *  to easily determine if the command is a read or write, but for now just
4699 		 *  do not allow io_passthru with a read-only descriptor.
4700 		 */
4701 		return -EBADF;
4702 	}
4703 
4704 	bdev_io = bdev_channel_get_io(channel);
4705 	if (!bdev_io) {
4706 		return -ENOMEM;
4707 	}
4708 
4709 	bdev_io->internal.ch = channel;
4710 	bdev_io->internal.desc = desc;
4711 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO;
4712 	bdev_io->u.nvme_passthru.cmd = *cmd;
4713 	bdev_io->u.nvme_passthru.buf = buf;
4714 	bdev_io->u.nvme_passthru.nbytes = nbytes;
4715 	bdev_io->u.nvme_passthru.md_buf = NULL;
4716 	bdev_io->u.nvme_passthru.md_len = 0;
4717 
4718 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4719 
4720 	bdev_io_submit(bdev_io);
4721 	return 0;
4722 }
4723 
4724 int
4725 spdk_bdev_nvme_io_passthru_md(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4726 			      const struct spdk_nvme_cmd *cmd, void *buf, size_t nbytes, void *md_buf, size_t md_len,
4727 			      spdk_bdev_io_completion_cb cb, void *cb_arg)
4728 {
4729 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4730 	struct spdk_bdev_io *bdev_io;
4731 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4732 
4733 	if (!desc->write) {
4734 		/*
4735 		 * Do not try to parse the NVMe command - we could maybe use bits in the opcode
4736 		 *  to easily determine if the command is a read or write, but for now just
4737 		 *  do not allow io_passthru with a read-only descriptor.
4738 		 */
4739 		return -EBADF;
4740 	}
4741 
4742 	bdev_io = bdev_channel_get_io(channel);
4743 	if (!bdev_io) {
4744 		return -ENOMEM;
4745 	}
4746 
4747 	bdev_io->internal.ch = channel;
4748 	bdev_io->internal.desc = desc;
4749 	bdev_io->type = SPDK_BDEV_IO_TYPE_NVME_IO_MD;
4750 	bdev_io->u.nvme_passthru.cmd = *cmd;
4751 	bdev_io->u.nvme_passthru.buf = buf;
4752 	bdev_io->u.nvme_passthru.nbytes = nbytes;
4753 	bdev_io->u.nvme_passthru.md_buf = md_buf;
4754 	bdev_io->u.nvme_passthru.md_len = md_len;
4755 
4756 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4757 
4758 	bdev_io_submit(bdev_io);
4759 	return 0;
4760 }
4761 
4762 static void bdev_abort_retry(void *ctx);
4763 static void bdev_abort(struct spdk_bdev_io *parent_io);
4764 
4765 static void
4766 bdev_abort_io_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
4767 {
4768 	struct spdk_bdev_channel *channel = bdev_io->internal.ch;
4769 	struct spdk_bdev_io *parent_io = cb_arg;
4770 	struct spdk_bdev_io *bio_to_abort, *tmp_io;
4771 
4772 	bio_to_abort = bdev_io->u.abort.bio_to_abort;
4773 
4774 	spdk_bdev_free_io(bdev_io);
4775 
4776 	if (!success) {
4777 		/* Check if the target I/O completed in the meantime. */
4778 		TAILQ_FOREACH(tmp_io, &channel->io_submitted, internal.ch_link) {
4779 			if (tmp_io == bio_to_abort) {
4780 				break;
4781 			}
4782 		}
4783 
4784 		/* If the target I/O still exists, set the parent to failed. */
4785 		if (tmp_io != NULL) {
4786 			parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4787 		}
4788 	}
4789 
4790 	parent_io->u.bdev.split_outstanding--;
4791 	if (parent_io->u.bdev.split_outstanding == 0) {
4792 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
4793 			bdev_abort_retry(parent_io);
4794 		} else {
4795 			bdev_io_complete(parent_io);
4796 		}
4797 	}
4798 }
4799 
4800 static int
4801 bdev_abort_io(struct spdk_bdev_desc *desc, struct spdk_bdev_channel *channel,
4802 	      struct spdk_bdev_io *bio_to_abort,
4803 	      spdk_bdev_io_completion_cb cb, void *cb_arg)
4804 {
4805 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4806 	struct spdk_bdev_io *bdev_io;
4807 
4808 	if (bio_to_abort->type == SPDK_BDEV_IO_TYPE_ABORT ||
4809 	    bio_to_abort->type == SPDK_BDEV_IO_TYPE_RESET) {
4810 		/* TODO: Abort reset or abort request. */
4811 		return -ENOTSUP;
4812 	}
4813 
4814 	bdev_io = bdev_channel_get_io(channel);
4815 	if (bdev_io == NULL) {
4816 		return -ENOMEM;
4817 	}
4818 
4819 	bdev_io->internal.ch = channel;
4820 	bdev_io->internal.desc = desc;
4821 	bdev_io->type = SPDK_BDEV_IO_TYPE_ABORT;
4822 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4823 
4824 	if (bdev->split_on_optimal_io_boundary && bdev_io_should_split(bio_to_abort)) {
4825 		bdev_io->u.bdev.abort.bio_cb_arg = bio_to_abort;
4826 
4827 		/* Parent abort request is not submitted directly, but to manage its
4828 		 * execution add it to the submitted list here.
4829 		 */
4830 		bdev_io->internal.submit_tsc = spdk_get_ticks();
4831 		TAILQ_INSERT_TAIL(&channel->io_submitted, bdev_io, internal.ch_link);
4832 
4833 		bdev_abort(bdev_io);
4834 
4835 		return 0;
4836 	}
4837 
4838 	bdev_io->u.abort.bio_to_abort = bio_to_abort;
4839 
4840 	/* Submit the abort request to the underlying bdev module. */
4841 	bdev_io_submit(bdev_io);
4842 
4843 	return 0;
4844 }
4845 
4846 static uint32_t
4847 _bdev_abort(struct spdk_bdev_io *parent_io)
4848 {
4849 	struct spdk_bdev_desc *desc = parent_io->internal.desc;
4850 	struct spdk_bdev_channel *channel = parent_io->internal.ch;
4851 	void *bio_cb_arg;
4852 	struct spdk_bdev_io *bio_to_abort;
4853 	uint32_t matched_ios;
4854 	int rc;
4855 
4856 	bio_cb_arg = parent_io->u.bdev.abort.bio_cb_arg;
4857 
4858 	/* matched_ios is returned and will be kept by the caller.
4859 	 *
4860 	 * This funcion will be used for two cases, 1) the same cb_arg is used for
4861 	 * multiple I/Os, 2) a single large I/O is split into smaller ones.
4862 	 * Incrementing split_outstanding directly here may confuse readers especially
4863 	 * for the 1st case.
4864 	 *
4865 	 * Completion of I/O abort is processed after stack unwinding. Hence this trick
4866 	 * works as expected.
4867 	 */
4868 	matched_ios = 0;
4869 	parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
4870 
4871 	TAILQ_FOREACH(bio_to_abort, &channel->io_submitted, internal.ch_link) {
4872 		if (bio_to_abort->internal.caller_ctx != bio_cb_arg) {
4873 			continue;
4874 		}
4875 
4876 		if (bio_to_abort->internal.submit_tsc > parent_io->internal.submit_tsc) {
4877 			/* Any I/O which was submitted after this abort command should be excluded. */
4878 			continue;
4879 		}
4880 
4881 		rc = bdev_abort_io(desc, channel, bio_to_abort, bdev_abort_io_done, parent_io);
4882 		if (rc != 0) {
4883 			if (rc == -ENOMEM) {
4884 				parent_io->internal.status = SPDK_BDEV_IO_STATUS_NOMEM;
4885 			} else {
4886 				parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4887 			}
4888 			break;
4889 		}
4890 		matched_ios++;
4891 	}
4892 
4893 	return matched_ios;
4894 }
4895 
4896 static void
4897 bdev_abort_retry(void *ctx)
4898 {
4899 	struct spdk_bdev_io *parent_io = ctx;
4900 	uint32_t matched_ios;
4901 
4902 	matched_ios = _bdev_abort(parent_io);
4903 
4904 	if (matched_ios == 0) {
4905 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
4906 			bdev_queue_io_wait_with_cb(parent_io, bdev_abort_retry);
4907 		} else {
4908 			/* For retry, the case that no target I/O was found is success
4909 			 * because it means target I/Os completed in the meantime.
4910 			 */
4911 			bdev_io_complete(parent_io);
4912 		}
4913 		return;
4914 	}
4915 
4916 	/* Use split_outstanding to manage the progress of aborting I/Os. */
4917 	parent_io->u.bdev.split_outstanding = matched_ios;
4918 }
4919 
4920 static void
4921 bdev_abort(struct spdk_bdev_io *parent_io)
4922 {
4923 	uint32_t matched_ios;
4924 
4925 	matched_ios = _bdev_abort(parent_io);
4926 
4927 	if (matched_ios == 0) {
4928 		if (parent_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
4929 			bdev_queue_io_wait_with_cb(parent_io, bdev_abort_retry);
4930 		} else {
4931 			/* The case the no target I/O was found is failure. */
4932 			parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
4933 			bdev_io_complete(parent_io);
4934 		}
4935 		return;
4936 	}
4937 
4938 	/* Use split_outstanding to manage the progress of aborting I/Os. */
4939 	parent_io->u.bdev.split_outstanding = matched_ios;
4940 }
4941 
4942 int
4943 spdk_bdev_abort(struct spdk_bdev_desc *desc, struct spdk_io_channel *ch,
4944 		void *bio_cb_arg,
4945 		spdk_bdev_io_completion_cb cb, void *cb_arg)
4946 {
4947 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
4948 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4949 	struct spdk_bdev_io *bdev_io;
4950 
4951 	if (bio_cb_arg == NULL) {
4952 		return -EINVAL;
4953 	}
4954 
4955 	if (!spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_ABORT)) {
4956 		return -ENOTSUP;
4957 	}
4958 
4959 	bdev_io = bdev_channel_get_io(channel);
4960 	if (bdev_io == NULL) {
4961 		return -ENOMEM;
4962 	}
4963 
4964 	bdev_io->internal.ch = channel;
4965 	bdev_io->internal.desc = desc;
4966 	bdev_io->internal.submit_tsc = spdk_get_ticks();
4967 	bdev_io->type = SPDK_BDEV_IO_TYPE_ABORT;
4968 	bdev_io_init(bdev_io, bdev, cb_arg, cb);
4969 
4970 	bdev_io->u.bdev.abort.bio_cb_arg = bio_cb_arg;
4971 
4972 	/* Parent abort request is not submitted directly, but to manage its execution,
4973 	 * add it to the submitted list here.
4974 	 */
4975 	TAILQ_INSERT_TAIL(&channel->io_submitted, bdev_io, internal.ch_link);
4976 
4977 	bdev_abort(bdev_io);
4978 
4979 	return 0;
4980 }
4981 
4982 int
4983 spdk_bdev_queue_io_wait(struct spdk_bdev *bdev, struct spdk_io_channel *ch,
4984 			struct spdk_bdev_io_wait_entry *entry)
4985 {
4986 	struct spdk_bdev_channel *channel = spdk_io_channel_get_ctx(ch);
4987 	struct spdk_bdev_mgmt_channel *mgmt_ch = channel->shared_resource->mgmt_ch;
4988 
4989 	if (bdev != entry->bdev) {
4990 		SPDK_ERRLOG("bdevs do not match\n");
4991 		return -EINVAL;
4992 	}
4993 
4994 	if (mgmt_ch->per_thread_cache_count > 0) {
4995 		SPDK_ERRLOG("Cannot queue io_wait if spdk_bdev_io available in per-thread cache\n");
4996 		return -EINVAL;
4997 	}
4998 
4999 	TAILQ_INSERT_TAIL(&mgmt_ch->io_wait_queue, entry, link);
5000 	return 0;
5001 }
5002 
5003 static void
5004 bdev_ch_retry_io(struct spdk_bdev_channel *bdev_ch)
5005 {
5006 	struct spdk_bdev *bdev = bdev_ch->bdev;
5007 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
5008 	struct spdk_bdev_io *bdev_io;
5009 
5010 	if (shared_resource->io_outstanding > shared_resource->nomem_threshold) {
5011 		/*
5012 		 * Allow some more I/O to complete before retrying the nomem_io queue.
5013 		 *  Some drivers (such as nvme) cannot immediately take a new I/O in
5014 		 *  the context of a completion, because the resources for the I/O are
5015 		 *  not released until control returns to the bdev poller.  Also, we
5016 		 *  may require several small I/O to complete before a larger I/O
5017 		 *  (that requires splitting) can be submitted.
5018 		 */
5019 		return;
5020 	}
5021 
5022 	while (!TAILQ_EMPTY(&shared_resource->nomem_io)) {
5023 		bdev_io = TAILQ_FIRST(&shared_resource->nomem_io);
5024 		TAILQ_REMOVE(&shared_resource->nomem_io, bdev_io, internal.link);
5025 		bdev_io->internal.ch->io_outstanding++;
5026 		shared_resource->io_outstanding++;
5027 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_PENDING;
5028 		bdev_io->internal.error.nvme.cdw0 = 0;
5029 		bdev_io->num_retries++;
5030 		bdev->fn_table->submit_request(spdk_bdev_io_get_io_channel(bdev_io), bdev_io);
5031 		if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NOMEM) {
5032 			break;
5033 		}
5034 	}
5035 }
5036 
5037 static inline void
5038 bdev_io_complete(void *ctx)
5039 {
5040 	struct spdk_bdev_io *bdev_io = ctx;
5041 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
5042 	uint64_t tsc, tsc_diff;
5043 
5044 	if (spdk_unlikely(bdev_io->internal.in_submit_request || bdev_io->internal.io_submit_ch)) {
5045 		/*
5046 		 * Send the completion to the thread that originally submitted the I/O,
5047 		 * which may not be the current thread in the case of QoS.
5048 		 */
5049 		if (bdev_io->internal.io_submit_ch) {
5050 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
5051 			bdev_io->internal.io_submit_ch = NULL;
5052 		}
5053 
5054 		/*
5055 		 * Defer completion to avoid potential infinite recursion if the
5056 		 * user's completion callback issues a new I/O.
5057 		 */
5058 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
5059 				     bdev_io_complete, bdev_io);
5060 		return;
5061 	}
5062 
5063 	tsc = spdk_get_ticks();
5064 	tsc_diff = tsc - bdev_io->internal.submit_tsc;
5065 	spdk_trace_record_tsc(tsc, TRACE_BDEV_IO_DONE, 0, 0, (uintptr_t)bdev_io, 0);
5066 
5067 	TAILQ_REMOVE(&bdev_ch->io_submitted, bdev_io, internal.ch_link);
5068 
5069 	if (bdev_io->internal.ch->histogram) {
5070 		spdk_histogram_data_tally(bdev_io->internal.ch->histogram, tsc_diff);
5071 	}
5072 
5073 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5074 		switch (bdev_io->type) {
5075 		case SPDK_BDEV_IO_TYPE_READ:
5076 			bdev_io->internal.ch->stat.bytes_read += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5077 			bdev_io->internal.ch->stat.num_read_ops++;
5078 			bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
5079 			break;
5080 		case SPDK_BDEV_IO_TYPE_WRITE:
5081 			bdev_io->internal.ch->stat.bytes_written += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5082 			bdev_io->internal.ch->stat.num_write_ops++;
5083 			bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
5084 			break;
5085 		case SPDK_BDEV_IO_TYPE_UNMAP:
5086 			bdev_io->internal.ch->stat.bytes_unmapped += bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5087 			bdev_io->internal.ch->stat.num_unmap_ops++;
5088 			bdev_io->internal.ch->stat.unmap_latency_ticks += tsc_diff;
5089 			break;
5090 		case SPDK_BDEV_IO_TYPE_ZCOPY:
5091 			/* Track the data in the start phase only */
5092 			if (bdev_io->u.bdev.zcopy.start) {
5093 				if (bdev_io->u.bdev.zcopy.populate) {
5094 					bdev_io->internal.ch->stat.bytes_read +=
5095 						bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5096 					bdev_io->internal.ch->stat.num_read_ops++;
5097 					bdev_io->internal.ch->stat.read_latency_ticks += tsc_diff;
5098 				} else {
5099 					bdev_io->internal.ch->stat.bytes_written +=
5100 						bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen;
5101 					bdev_io->internal.ch->stat.num_write_ops++;
5102 					bdev_io->internal.ch->stat.write_latency_ticks += tsc_diff;
5103 				}
5104 			}
5105 			break;
5106 		default:
5107 			break;
5108 		}
5109 	}
5110 
5111 #ifdef SPDK_CONFIG_VTUNE
5112 	uint64_t now_tsc = spdk_get_ticks();
5113 	if (now_tsc > (bdev_io->internal.ch->start_tsc + bdev_io->internal.ch->interval_tsc)) {
5114 		uint64_t data[5];
5115 
5116 		data[0] = bdev_io->internal.ch->stat.num_read_ops - bdev_io->internal.ch->prev_stat.num_read_ops;
5117 		data[1] = bdev_io->internal.ch->stat.bytes_read - bdev_io->internal.ch->prev_stat.bytes_read;
5118 		data[2] = bdev_io->internal.ch->stat.num_write_ops - bdev_io->internal.ch->prev_stat.num_write_ops;
5119 		data[3] = bdev_io->internal.ch->stat.bytes_written - bdev_io->internal.ch->prev_stat.bytes_written;
5120 		data[4] = bdev_io->bdev->fn_table->get_spin_time ?
5121 			  bdev_io->bdev->fn_table->get_spin_time(spdk_bdev_io_get_io_channel(bdev_io)) : 0;
5122 
5123 		__itt_metadata_add(g_bdev_mgr.domain, __itt_null, bdev_io->internal.ch->handle,
5124 				   __itt_metadata_u64, 5, data);
5125 
5126 		bdev_io->internal.ch->prev_stat = bdev_io->internal.ch->stat;
5127 		bdev_io->internal.ch->start_tsc = now_tsc;
5128 	}
5129 #endif
5130 
5131 	assert(bdev_io->internal.cb != NULL);
5132 	assert(spdk_get_thread() == spdk_bdev_io_get_thread(bdev_io));
5133 
5134 	bdev_io->internal.cb(bdev_io, bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS,
5135 			     bdev_io->internal.caller_ctx);
5136 }
5137 
5138 static void
5139 bdev_reset_complete(struct spdk_io_channel_iter *i, int status)
5140 {
5141 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
5142 
5143 	if (bdev_io->u.reset.ch_ref != NULL) {
5144 		spdk_put_io_channel(bdev_io->u.reset.ch_ref);
5145 		bdev_io->u.reset.ch_ref = NULL;
5146 	}
5147 
5148 	bdev_io_complete(bdev_io);
5149 }
5150 
5151 static void
5152 bdev_unfreeze_channel(struct spdk_io_channel_iter *i)
5153 {
5154 	struct spdk_bdev_io *bdev_io = spdk_io_channel_iter_get_ctx(i);
5155 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
5156 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
5157 	struct spdk_bdev_io *queued_reset;
5158 
5159 	ch->flags &= ~BDEV_CH_RESET_IN_PROGRESS;
5160 	while (!TAILQ_EMPTY(&ch->queued_resets)) {
5161 		queued_reset = TAILQ_FIRST(&ch->queued_resets);
5162 		TAILQ_REMOVE(&ch->queued_resets, queued_reset, internal.link);
5163 		spdk_bdev_io_complete(queued_reset, bdev_io->internal.status);
5164 	}
5165 
5166 	spdk_for_each_channel_continue(i, 0);
5167 }
5168 
5169 void
5170 spdk_bdev_io_complete(struct spdk_bdev_io *bdev_io, enum spdk_bdev_io_status status)
5171 {
5172 	struct spdk_bdev *bdev = bdev_io->bdev;
5173 	struct spdk_bdev_channel *bdev_ch = bdev_io->internal.ch;
5174 	struct spdk_bdev_shared_resource *shared_resource = bdev_ch->shared_resource;
5175 
5176 	bdev_io->internal.status = status;
5177 
5178 	if (spdk_unlikely(bdev_io->type == SPDK_BDEV_IO_TYPE_RESET)) {
5179 		bool unlock_channels = false;
5180 
5181 		if (status == SPDK_BDEV_IO_STATUS_NOMEM) {
5182 			SPDK_ERRLOG("NOMEM returned for reset\n");
5183 		}
5184 		pthread_mutex_lock(&bdev->internal.mutex);
5185 		if (bdev_io == bdev->internal.reset_in_progress) {
5186 			bdev->internal.reset_in_progress = NULL;
5187 			unlock_channels = true;
5188 		}
5189 		pthread_mutex_unlock(&bdev->internal.mutex);
5190 
5191 		if (unlock_channels) {
5192 			spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_unfreeze_channel,
5193 					      bdev_io, bdev_reset_complete);
5194 			return;
5195 		}
5196 	} else {
5197 		_bdev_io_unset_bounce_buf(bdev_io);
5198 
5199 		assert(bdev_ch->io_outstanding > 0);
5200 		assert(shared_resource->io_outstanding > 0);
5201 		bdev_ch->io_outstanding--;
5202 		shared_resource->io_outstanding--;
5203 
5204 		if (spdk_unlikely(status == SPDK_BDEV_IO_STATUS_NOMEM)) {
5205 			TAILQ_INSERT_HEAD(&shared_resource->nomem_io, bdev_io, internal.link);
5206 			/*
5207 			 * Wait for some of the outstanding I/O to complete before we
5208 			 *  retry any of the nomem_io.  Normally we will wait for
5209 			 *  NOMEM_THRESHOLD_COUNT I/O to complete but for low queue
5210 			 *  depth channels we will instead wait for half to complete.
5211 			 */
5212 			shared_resource->nomem_threshold = spdk_max((int64_t)shared_resource->io_outstanding / 2,
5213 							   (int64_t)shared_resource->io_outstanding - NOMEM_THRESHOLD_COUNT);
5214 			return;
5215 		}
5216 
5217 		if (spdk_unlikely(!TAILQ_EMPTY(&shared_resource->nomem_io))) {
5218 			bdev_ch_retry_io(bdev_ch);
5219 		}
5220 	}
5221 
5222 	bdev_io_complete(bdev_io);
5223 }
5224 
5225 void
5226 spdk_bdev_io_complete_scsi_status(struct spdk_bdev_io *bdev_io, enum spdk_scsi_status sc,
5227 				  enum spdk_scsi_sense sk, uint8_t asc, uint8_t ascq)
5228 {
5229 	if (sc == SPDK_SCSI_STATUS_GOOD) {
5230 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5231 	} else {
5232 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SCSI_ERROR;
5233 		bdev_io->internal.error.scsi.sc = sc;
5234 		bdev_io->internal.error.scsi.sk = sk;
5235 		bdev_io->internal.error.scsi.asc = asc;
5236 		bdev_io->internal.error.scsi.ascq = ascq;
5237 	}
5238 
5239 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5240 }
5241 
5242 void
5243 spdk_bdev_io_get_scsi_status(const struct spdk_bdev_io *bdev_io,
5244 			     int *sc, int *sk, int *asc, int *ascq)
5245 {
5246 	assert(sc != NULL);
5247 	assert(sk != NULL);
5248 	assert(asc != NULL);
5249 	assert(ascq != NULL);
5250 
5251 	switch (bdev_io->internal.status) {
5252 	case SPDK_BDEV_IO_STATUS_SUCCESS:
5253 		*sc = SPDK_SCSI_STATUS_GOOD;
5254 		*sk = SPDK_SCSI_SENSE_NO_SENSE;
5255 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
5256 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
5257 		break;
5258 	case SPDK_BDEV_IO_STATUS_NVME_ERROR:
5259 		spdk_scsi_nvme_translate(bdev_io, sc, sk, asc, ascq);
5260 		break;
5261 	case SPDK_BDEV_IO_STATUS_SCSI_ERROR:
5262 		*sc = bdev_io->internal.error.scsi.sc;
5263 		*sk = bdev_io->internal.error.scsi.sk;
5264 		*asc = bdev_io->internal.error.scsi.asc;
5265 		*ascq = bdev_io->internal.error.scsi.ascq;
5266 		break;
5267 	default:
5268 		*sc = SPDK_SCSI_STATUS_CHECK_CONDITION;
5269 		*sk = SPDK_SCSI_SENSE_ABORTED_COMMAND;
5270 		*asc = SPDK_SCSI_ASC_NO_ADDITIONAL_SENSE;
5271 		*ascq = SPDK_SCSI_ASCQ_CAUSE_NOT_REPORTABLE;
5272 		break;
5273 	}
5274 }
5275 
5276 void
5277 spdk_bdev_io_complete_aio_status(struct spdk_bdev_io *bdev_io, int aio_result)
5278 {
5279 	if (aio_result == 0) {
5280 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5281 	} else {
5282 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_AIO_ERROR;
5283 	}
5284 
5285 	bdev_io->internal.error.aio_result = aio_result;
5286 
5287 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5288 }
5289 
5290 void
5291 spdk_bdev_io_get_aio_status(const struct spdk_bdev_io *bdev_io, int *aio_result)
5292 {
5293 	assert(aio_result != NULL);
5294 
5295 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_AIO_ERROR) {
5296 		*aio_result = bdev_io->internal.error.aio_result;
5297 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5298 		*aio_result = 0;
5299 	} else {
5300 		*aio_result = -EIO;
5301 	}
5302 }
5303 
5304 void
5305 spdk_bdev_io_complete_nvme_status(struct spdk_bdev_io *bdev_io, uint32_t cdw0, int sct, int sc)
5306 {
5307 	if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_SUCCESS) {
5308 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
5309 	} else if (sct == SPDK_NVME_SCT_GENERIC && sc == SPDK_NVME_SC_ABORTED_BY_REQUEST) {
5310 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_ABORTED;
5311 	} else {
5312 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_NVME_ERROR;
5313 	}
5314 
5315 	bdev_io->internal.error.nvme.cdw0 = cdw0;
5316 	bdev_io->internal.error.nvme.sct = sct;
5317 	bdev_io->internal.error.nvme.sc = sc;
5318 
5319 	spdk_bdev_io_complete(bdev_io, bdev_io->internal.status);
5320 }
5321 
5322 void
5323 spdk_bdev_io_get_nvme_status(const struct spdk_bdev_io *bdev_io, uint32_t *cdw0, int *sct, int *sc)
5324 {
5325 	assert(sct != NULL);
5326 	assert(sc != NULL);
5327 	assert(cdw0 != NULL);
5328 
5329 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
5330 		*sct = bdev_io->internal.error.nvme.sct;
5331 		*sc = bdev_io->internal.error.nvme.sc;
5332 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5333 		*sct = SPDK_NVME_SCT_GENERIC;
5334 		*sc = SPDK_NVME_SC_SUCCESS;
5335 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_ABORTED) {
5336 		*sct = SPDK_NVME_SCT_GENERIC;
5337 		*sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
5338 	} else {
5339 		*sct = SPDK_NVME_SCT_GENERIC;
5340 		*sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5341 	}
5342 
5343 	*cdw0 = bdev_io->internal.error.nvme.cdw0;
5344 }
5345 
5346 void
5347 spdk_bdev_io_get_nvme_fused_status(const struct spdk_bdev_io *bdev_io, uint32_t *cdw0,
5348 				   int *first_sct, int *first_sc, int *second_sct, int *second_sc)
5349 {
5350 	assert(first_sct != NULL);
5351 	assert(first_sc != NULL);
5352 	assert(second_sct != NULL);
5353 	assert(second_sc != NULL);
5354 	assert(cdw0 != NULL);
5355 
5356 	if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_NVME_ERROR) {
5357 		if (bdev_io->internal.error.nvme.sct == SPDK_NVME_SCT_MEDIA_ERROR &&
5358 		    bdev_io->internal.error.nvme.sc == SPDK_NVME_SC_COMPARE_FAILURE) {
5359 			*first_sct = bdev_io->internal.error.nvme.sct;
5360 			*first_sc = bdev_io->internal.error.nvme.sc;
5361 			*second_sct = SPDK_NVME_SCT_GENERIC;
5362 			*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5363 		} else {
5364 			*first_sct = SPDK_NVME_SCT_GENERIC;
5365 			*first_sc = SPDK_NVME_SC_SUCCESS;
5366 			*second_sct = bdev_io->internal.error.nvme.sct;
5367 			*second_sc = bdev_io->internal.error.nvme.sc;
5368 		}
5369 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_SUCCESS) {
5370 		*first_sct = SPDK_NVME_SCT_GENERIC;
5371 		*first_sc = SPDK_NVME_SC_SUCCESS;
5372 		*second_sct = SPDK_NVME_SCT_GENERIC;
5373 		*second_sc = SPDK_NVME_SC_SUCCESS;
5374 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_FIRST_FUSED_FAILED) {
5375 		*first_sct = SPDK_NVME_SCT_GENERIC;
5376 		*first_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5377 		*second_sct = SPDK_NVME_SCT_GENERIC;
5378 		*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5379 	} else if (bdev_io->internal.status == SPDK_BDEV_IO_STATUS_MISCOMPARE) {
5380 		*first_sct = SPDK_NVME_SCT_MEDIA_ERROR;
5381 		*first_sc = SPDK_NVME_SC_COMPARE_FAILURE;
5382 		*second_sct = SPDK_NVME_SCT_GENERIC;
5383 		*second_sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
5384 	} else {
5385 		*first_sct = SPDK_NVME_SCT_GENERIC;
5386 		*first_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5387 		*second_sct = SPDK_NVME_SCT_GENERIC;
5388 		*second_sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
5389 	}
5390 
5391 	*cdw0 = bdev_io->internal.error.nvme.cdw0;
5392 }
5393 
5394 struct spdk_thread *
5395 spdk_bdev_io_get_thread(struct spdk_bdev_io *bdev_io)
5396 {
5397 	return spdk_io_channel_get_thread(bdev_io->internal.ch->channel);
5398 }
5399 
5400 struct spdk_io_channel *
5401 spdk_bdev_io_get_io_channel(struct spdk_bdev_io *bdev_io)
5402 {
5403 	return bdev_io->internal.ch->channel;
5404 }
5405 
5406 static int
5407 bdev_init(struct spdk_bdev *bdev)
5408 {
5409 	char *bdev_name;
5410 
5411 	assert(bdev->module != NULL);
5412 
5413 	if (!bdev->name) {
5414 		SPDK_ERRLOG("Bdev name is NULL\n");
5415 		return -EINVAL;
5416 	}
5417 
5418 	if (!strlen(bdev->name)) {
5419 		SPDK_ERRLOG("Bdev name must not be an empty string\n");
5420 		return -EINVAL;
5421 	}
5422 
5423 	if (spdk_bdev_get_by_name(bdev->name)) {
5424 		SPDK_ERRLOG("Bdev name:%s already exists\n", bdev->name);
5425 		return -EEXIST;
5426 	}
5427 
5428 	/* Users often register their own I/O devices using the bdev name. In
5429 	 * order to avoid conflicts, prepend bdev_. */
5430 	bdev_name = spdk_sprintf_alloc("bdev_%s", bdev->name);
5431 	if (!bdev_name) {
5432 		SPDK_ERRLOG("Unable to allocate memory for internal bdev name.\n");
5433 		return -ENOMEM;
5434 	}
5435 
5436 	bdev->internal.status = SPDK_BDEV_STATUS_READY;
5437 	bdev->internal.measured_queue_depth = UINT64_MAX;
5438 	bdev->internal.claim_module = NULL;
5439 	bdev->internal.qd_poller = NULL;
5440 	bdev->internal.qos = NULL;
5441 
5442 	/* If the user didn't specify a uuid, generate one. */
5443 	if (spdk_mem_all_zero(&bdev->uuid, sizeof(bdev->uuid))) {
5444 		spdk_uuid_generate(&bdev->uuid);
5445 	}
5446 
5447 	if (spdk_bdev_get_buf_align(bdev) > 1) {
5448 		if (bdev->split_on_optimal_io_boundary) {
5449 			bdev->optimal_io_boundary = spdk_min(bdev->optimal_io_boundary,
5450 							     SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen);
5451 		} else {
5452 			bdev->split_on_optimal_io_boundary = true;
5453 			bdev->optimal_io_boundary = SPDK_BDEV_LARGE_BUF_MAX_SIZE / bdev->blocklen;
5454 		}
5455 	}
5456 
5457 	/* If the user didn't specify a write unit size, set it to one. */
5458 	if (bdev->write_unit_size == 0) {
5459 		bdev->write_unit_size = 1;
5460 	}
5461 
5462 	/* Set ACWU value to 1 if bdev module did not set it (does not support it natively) */
5463 	if (bdev->acwu == 0) {
5464 		bdev->acwu = 1;
5465 	}
5466 
5467 	TAILQ_INIT(&bdev->internal.open_descs);
5468 	TAILQ_INIT(&bdev->internal.locked_ranges);
5469 	TAILQ_INIT(&bdev->internal.pending_locked_ranges);
5470 
5471 	TAILQ_INIT(&bdev->aliases);
5472 
5473 	bdev->internal.reset_in_progress = NULL;
5474 
5475 	spdk_io_device_register(__bdev_to_io_dev(bdev),
5476 				bdev_channel_create, bdev_channel_destroy,
5477 				sizeof(struct spdk_bdev_channel),
5478 				bdev_name);
5479 
5480 	free(bdev_name);
5481 
5482 	pthread_mutex_init(&bdev->internal.mutex, NULL);
5483 	return 0;
5484 }
5485 
5486 static void
5487 bdev_destroy_cb(void *io_device)
5488 {
5489 	int			rc;
5490 	struct spdk_bdev	*bdev;
5491 	spdk_bdev_unregister_cb	cb_fn;
5492 	void			*cb_arg;
5493 
5494 	bdev = __bdev_from_io_dev(io_device);
5495 	cb_fn = bdev->internal.unregister_cb;
5496 	cb_arg = bdev->internal.unregister_ctx;
5497 
5498 	pthread_mutex_destroy(&bdev->internal.mutex);
5499 	free(bdev->internal.qos);
5500 
5501 	rc = bdev->fn_table->destruct(bdev->ctxt);
5502 	if (rc < 0) {
5503 		SPDK_ERRLOG("destruct failed\n");
5504 	}
5505 	if (rc <= 0 && cb_fn != NULL) {
5506 		cb_fn(cb_arg, rc);
5507 	}
5508 }
5509 
5510 static void
5511 bdev_start_finished(void *arg)
5512 {
5513 	struct spdk_bdev *bdev = arg;
5514 
5515 	spdk_notify_send("bdev_register", spdk_bdev_get_name(bdev));
5516 }
5517 
5518 static void
5519 bdev_start(struct spdk_bdev *bdev)
5520 {
5521 	SPDK_DEBUGLOG(bdev, "Inserting bdev %s into list\n", bdev->name);
5522 	TAILQ_INSERT_TAIL(&g_bdev_mgr.bdevs, bdev, internal.link);
5523 
5524 	/* Examine configuration before initializing I/O */
5525 	bdev_examine(bdev);
5526 
5527 	spdk_bdev_wait_for_examine(bdev_start_finished, bdev);
5528 }
5529 
5530 int
5531 spdk_bdev_register(struct spdk_bdev *bdev)
5532 {
5533 	int rc = bdev_init(bdev);
5534 
5535 	if (rc == 0) {
5536 		bdev_start(bdev);
5537 	}
5538 
5539 	return rc;
5540 }
5541 
5542 void
5543 spdk_bdev_destruct_done(struct spdk_bdev *bdev, int bdeverrno)
5544 {
5545 	if (bdev->internal.unregister_cb != NULL) {
5546 		bdev->internal.unregister_cb(bdev->internal.unregister_ctx, bdeverrno);
5547 	}
5548 }
5549 
5550 static void
5551 _remove_notify(void *arg)
5552 {
5553 	struct spdk_bdev_desc *desc = arg;
5554 
5555 	pthread_mutex_lock(&desc->mutex);
5556 	desc->refs--;
5557 
5558 	if (!desc->closed) {
5559 		pthread_mutex_unlock(&desc->mutex);
5560 		desc->callback.event_fn(SPDK_BDEV_EVENT_REMOVE, desc->bdev, desc->callback.ctx);
5561 		return;
5562 	} else if (0 == desc->refs) {
5563 		/* This descriptor was closed after this remove_notify message was sent.
5564 		 * spdk_bdev_close() could not free the descriptor since this message was
5565 		 * in flight, so we free it now using bdev_desc_free().
5566 		 */
5567 		pthread_mutex_unlock(&desc->mutex);
5568 		bdev_desc_free(desc);
5569 		return;
5570 	}
5571 	pthread_mutex_unlock(&desc->mutex);
5572 }
5573 
5574 /* Must be called while holding bdev->internal.mutex.
5575  * returns: 0 - bdev removed and ready to be destructed.
5576  *          -EBUSY - bdev can't be destructed yet.  */
5577 static int
5578 bdev_unregister_unsafe(struct spdk_bdev *bdev)
5579 {
5580 	struct spdk_bdev_desc	*desc, *tmp;
5581 	int			rc = 0;
5582 
5583 	/* Notify each descriptor about hotremoval */
5584 	TAILQ_FOREACH_SAFE(desc, &bdev->internal.open_descs, link, tmp) {
5585 		rc = -EBUSY;
5586 		pthread_mutex_lock(&desc->mutex);
5587 		/*
5588 		 * Defer invocation of the event_cb to a separate message that will
5589 		 *  run later on its thread.  This ensures this context unwinds and
5590 		 *  we don't recursively unregister this bdev again if the event_cb
5591 		 *  immediately closes its descriptor.
5592 		 */
5593 		desc->refs++;
5594 		spdk_thread_send_msg(desc->thread, _remove_notify, desc);
5595 		pthread_mutex_unlock(&desc->mutex);
5596 	}
5597 
5598 	/* If there are no descriptors, proceed removing the bdev */
5599 	if (rc == 0) {
5600 		TAILQ_REMOVE(&g_bdev_mgr.bdevs, bdev, internal.link);
5601 		SPDK_DEBUGLOG(bdev, "Removing bdev %s from list done\n", bdev->name);
5602 		spdk_notify_send("bdev_unregister", spdk_bdev_get_name(bdev));
5603 	}
5604 
5605 	return rc;
5606 }
5607 
5608 void
5609 spdk_bdev_unregister(struct spdk_bdev *bdev, spdk_bdev_unregister_cb cb_fn, void *cb_arg)
5610 {
5611 	struct spdk_thread	*thread;
5612 	int			rc;
5613 
5614 	SPDK_DEBUGLOG(bdev, "Removing bdev %s from list\n", bdev->name);
5615 
5616 	thread = spdk_get_thread();
5617 	if (!thread) {
5618 		/* The user called this from a non-SPDK thread. */
5619 		if (cb_fn != NULL) {
5620 			cb_fn(cb_arg, -ENOTSUP);
5621 		}
5622 		return;
5623 	}
5624 
5625 	pthread_mutex_lock(&g_bdev_mgr.mutex);
5626 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
5627 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
5628 		if (cb_fn) {
5629 			cb_fn(cb_arg, -EBUSY);
5630 		}
5631 		return;
5632 	}
5633 
5634 	pthread_mutex_lock(&bdev->internal.mutex);
5635 	bdev->internal.status = SPDK_BDEV_STATUS_REMOVING;
5636 	bdev->internal.unregister_cb = cb_fn;
5637 	bdev->internal.unregister_ctx = cb_arg;
5638 
5639 	/* Call under lock. */
5640 	rc = bdev_unregister_unsafe(bdev);
5641 	pthread_mutex_unlock(&bdev->internal.mutex);
5642 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
5643 
5644 	if (rc == 0) {
5645 		spdk_io_device_unregister(__bdev_to_io_dev(bdev), bdev_destroy_cb);
5646 	}
5647 }
5648 
5649 static int
5650 bdev_start_qos(struct spdk_bdev *bdev)
5651 {
5652 	struct set_qos_limit_ctx *ctx;
5653 
5654 	/* Enable QoS */
5655 	if (bdev->internal.qos && bdev->internal.qos->thread == NULL) {
5656 		ctx = calloc(1, sizeof(*ctx));
5657 		if (ctx == NULL) {
5658 			SPDK_ERRLOG("Failed to allocate memory for QoS context\n");
5659 			return -ENOMEM;
5660 		}
5661 		ctx->bdev = bdev;
5662 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
5663 				      bdev_enable_qos_msg, ctx,
5664 				      bdev_enable_qos_done);
5665 	}
5666 
5667 	return 0;
5668 }
5669 
5670 static int
5671 bdev_open(struct spdk_bdev *bdev, bool write, struct spdk_bdev_desc *desc)
5672 {
5673 	struct spdk_thread *thread;
5674 	int rc = 0;
5675 
5676 	thread = spdk_get_thread();
5677 	if (!thread) {
5678 		SPDK_ERRLOG("Cannot open bdev from non-SPDK thread.\n");
5679 		return -ENOTSUP;
5680 	}
5681 
5682 	SPDK_DEBUGLOG(bdev, "Opening descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
5683 		      spdk_get_thread());
5684 
5685 	desc->bdev = bdev;
5686 	desc->thread = thread;
5687 	desc->write = write;
5688 
5689 	pthread_mutex_lock(&bdev->internal.mutex);
5690 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING) {
5691 		pthread_mutex_unlock(&bdev->internal.mutex);
5692 		return -ENODEV;
5693 	}
5694 
5695 	if (write && bdev->internal.claim_module) {
5696 		SPDK_ERRLOG("Could not open %s - %s module already claimed it\n",
5697 			    bdev->name, bdev->internal.claim_module->name);
5698 		pthread_mutex_unlock(&bdev->internal.mutex);
5699 		return -EPERM;
5700 	}
5701 
5702 	rc = bdev_start_qos(bdev);
5703 	if (rc != 0) {
5704 		SPDK_ERRLOG("Failed to start QoS on bdev %s\n", bdev->name);
5705 		pthread_mutex_unlock(&bdev->internal.mutex);
5706 		return rc;
5707 	}
5708 
5709 	TAILQ_INSERT_TAIL(&bdev->internal.open_descs, desc, link);
5710 
5711 	pthread_mutex_unlock(&bdev->internal.mutex);
5712 
5713 	return 0;
5714 }
5715 
5716 int
5717 spdk_bdev_open_ext(const char *bdev_name, bool write, spdk_bdev_event_cb_t event_cb,
5718 		   void *event_ctx, struct spdk_bdev_desc **_desc)
5719 {
5720 	struct spdk_bdev_desc *desc;
5721 	struct spdk_bdev *bdev;
5722 	unsigned int event_id;
5723 	int rc;
5724 
5725 	if (event_cb == NULL) {
5726 		SPDK_ERRLOG("Missing event callback function\n");
5727 		return -EINVAL;
5728 	}
5729 
5730 	pthread_mutex_lock(&g_bdev_mgr.mutex);
5731 
5732 	bdev = spdk_bdev_get_by_name(bdev_name);
5733 
5734 	if (bdev == NULL) {
5735 		SPDK_NOTICELOG("Currently unable to find bdev with name: %s\n", bdev_name);
5736 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
5737 		return -ENODEV;
5738 	}
5739 
5740 	desc = calloc(1, sizeof(*desc));
5741 	if (desc == NULL) {
5742 		SPDK_ERRLOG("Failed to allocate memory for bdev descriptor\n");
5743 		pthread_mutex_unlock(&g_bdev_mgr.mutex);
5744 		return -ENOMEM;
5745 	}
5746 
5747 	TAILQ_INIT(&desc->pending_media_events);
5748 	TAILQ_INIT(&desc->free_media_events);
5749 
5750 	desc->callback.event_fn = event_cb;
5751 	desc->callback.ctx = event_ctx;
5752 	pthread_mutex_init(&desc->mutex, NULL);
5753 
5754 	if (bdev->media_events) {
5755 		desc->media_events_buffer = calloc(MEDIA_EVENT_POOL_SIZE,
5756 						   sizeof(*desc->media_events_buffer));
5757 		if (desc->media_events_buffer == NULL) {
5758 			SPDK_ERRLOG("Failed to initialize media event pool\n");
5759 			bdev_desc_free(desc);
5760 			pthread_mutex_unlock(&g_bdev_mgr.mutex);
5761 			return -ENOMEM;
5762 		}
5763 
5764 		for (event_id = 0; event_id < MEDIA_EVENT_POOL_SIZE; ++event_id) {
5765 			TAILQ_INSERT_TAIL(&desc->free_media_events,
5766 					  &desc->media_events_buffer[event_id], tailq);
5767 		}
5768 	}
5769 
5770 	rc = bdev_open(bdev, write, desc);
5771 	if (rc != 0) {
5772 		bdev_desc_free(desc);
5773 		desc = NULL;
5774 	}
5775 
5776 	*_desc = desc;
5777 
5778 	pthread_mutex_unlock(&g_bdev_mgr.mutex);
5779 
5780 	return rc;
5781 }
5782 
5783 void
5784 spdk_bdev_close(struct spdk_bdev_desc *desc)
5785 {
5786 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
5787 	int rc;
5788 
5789 	SPDK_DEBUGLOG(bdev, "Closing descriptor %p for bdev %s on thread %p\n", desc, bdev->name,
5790 		      spdk_get_thread());
5791 
5792 	assert(desc->thread == spdk_get_thread());
5793 
5794 	spdk_poller_unregister(&desc->io_timeout_poller);
5795 
5796 	pthread_mutex_lock(&bdev->internal.mutex);
5797 	pthread_mutex_lock(&desc->mutex);
5798 
5799 	TAILQ_REMOVE(&bdev->internal.open_descs, desc, link);
5800 
5801 	desc->closed = true;
5802 
5803 	if (0 == desc->refs) {
5804 		pthread_mutex_unlock(&desc->mutex);
5805 		bdev_desc_free(desc);
5806 	} else {
5807 		pthread_mutex_unlock(&desc->mutex);
5808 	}
5809 
5810 	/* If no more descriptors, kill QoS channel */
5811 	if (bdev->internal.qos && TAILQ_EMPTY(&bdev->internal.open_descs)) {
5812 		SPDK_DEBUGLOG(bdev, "Closed last descriptor for bdev %s on thread %p. Stopping QoS.\n",
5813 			      bdev->name, spdk_get_thread());
5814 
5815 		if (bdev_qos_destroy(bdev)) {
5816 			/* There isn't anything we can do to recover here. Just let the
5817 			 * old QoS poller keep running. The QoS handling won't change
5818 			 * cores when the user allocates a new channel, but it won't break. */
5819 			SPDK_ERRLOG("Unable to shut down QoS poller. It will continue running on the current thread.\n");
5820 		}
5821 	}
5822 
5823 	spdk_bdev_set_qd_sampling_period(bdev, 0);
5824 
5825 	if (bdev->internal.status == SPDK_BDEV_STATUS_REMOVING && TAILQ_EMPTY(&bdev->internal.open_descs)) {
5826 		rc = bdev_unregister_unsafe(bdev);
5827 		pthread_mutex_unlock(&bdev->internal.mutex);
5828 
5829 		if (rc == 0) {
5830 			spdk_io_device_unregister(__bdev_to_io_dev(bdev), bdev_destroy_cb);
5831 		}
5832 	} else {
5833 		pthread_mutex_unlock(&bdev->internal.mutex);
5834 	}
5835 }
5836 
5837 int
5838 spdk_bdev_module_claim_bdev(struct spdk_bdev *bdev, struct spdk_bdev_desc *desc,
5839 			    struct spdk_bdev_module *module)
5840 {
5841 	if (bdev->internal.claim_module != NULL) {
5842 		SPDK_ERRLOG("bdev %s already claimed by module %s\n", bdev->name,
5843 			    bdev->internal.claim_module->name);
5844 		return -EPERM;
5845 	}
5846 
5847 	if (desc && !desc->write) {
5848 		desc->write = true;
5849 	}
5850 
5851 	bdev->internal.claim_module = module;
5852 	return 0;
5853 }
5854 
5855 void
5856 spdk_bdev_module_release_bdev(struct spdk_bdev *bdev)
5857 {
5858 	assert(bdev->internal.claim_module != NULL);
5859 	bdev->internal.claim_module = NULL;
5860 }
5861 
5862 struct spdk_bdev *
5863 spdk_bdev_desc_get_bdev(struct spdk_bdev_desc *desc)
5864 {
5865 	assert(desc != NULL);
5866 	return desc->bdev;
5867 }
5868 
5869 void
5870 spdk_bdev_io_get_iovec(struct spdk_bdev_io *bdev_io, struct iovec **iovp, int *iovcntp)
5871 {
5872 	struct iovec *iovs;
5873 	int iovcnt;
5874 
5875 	if (bdev_io == NULL) {
5876 		return;
5877 	}
5878 
5879 	switch (bdev_io->type) {
5880 	case SPDK_BDEV_IO_TYPE_READ:
5881 	case SPDK_BDEV_IO_TYPE_WRITE:
5882 	case SPDK_BDEV_IO_TYPE_ZCOPY:
5883 		iovs = bdev_io->u.bdev.iovs;
5884 		iovcnt = bdev_io->u.bdev.iovcnt;
5885 		break;
5886 	default:
5887 		iovs = NULL;
5888 		iovcnt = 0;
5889 		break;
5890 	}
5891 
5892 	if (iovp) {
5893 		*iovp = iovs;
5894 	}
5895 	if (iovcntp) {
5896 		*iovcntp = iovcnt;
5897 	}
5898 }
5899 
5900 void *
5901 spdk_bdev_io_get_md_buf(struct spdk_bdev_io *bdev_io)
5902 {
5903 	if (bdev_io == NULL) {
5904 		return NULL;
5905 	}
5906 
5907 	if (!spdk_bdev_is_md_separate(bdev_io->bdev)) {
5908 		return NULL;
5909 	}
5910 
5911 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ ||
5912 	    bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
5913 		return bdev_io->u.bdev.md_buf;
5914 	}
5915 
5916 	return NULL;
5917 }
5918 
5919 void *
5920 spdk_bdev_io_get_cb_arg(struct spdk_bdev_io *bdev_io)
5921 {
5922 	if (bdev_io == NULL) {
5923 		assert(false);
5924 		return NULL;
5925 	}
5926 
5927 	return bdev_io->internal.caller_ctx;
5928 }
5929 
5930 void
5931 spdk_bdev_module_list_add(struct spdk_bdev_module *bdev_module)
5932 {
5933 
5934 	if (spdk_bdev_module_list_find(bdev_module->name)) {
5935 		SPDK_ERRLOG("ERROR: module '%s' already registered.\n", bdev_module->name);
5936 		assert(false);
5937 	}
5938 
5939 	/*
5940 	 * Modules with examine callbacks must be initialized first, so they are
5941 	 *  ready to handle examine callbacks from later modules that will
5942 	 *  register physical bdevs.
5943 	 */
5944 	if (bdev_module->examine_config != NULL || bdev_module->examine_disk != NULL) {
5945 		TAILQ_INSERT_HEAD(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
5946 	} else {
5947 		TAILQ_INSERT_TAIL(&g_bdev_mgr.bdev_modules, bdev_module, internal.tailq);
5948 	}
5949 }
5950 
5951 struct spdk_bdev_module *
5952 spdk_bdev_module_list_find(const char *name)
5953 {
5954 	struct spdk_bdev_module *bdev_module;
5955 
5956 	TAILQ_FOREACH(bdev_module, &g_bdev_mgr.bdev_modules, internal.tailq) {
5957 		if (strcmp(name, bdev_module->name) == 0) {
5958 			break;
5959 		}
5960 	}
5961 
5962 	return bdev_module;
5963 }
5964 
5965 static void
5966 bdev_write_zero_buffer_next(void *_bdev_io)
5967 {
5968 	struct spdk_bdev_io *bdev_io = _bdev_io;
5969 	uint64_t num_bytes, num_blocks;
5970 	void *md_buf = NULL;
5971 	int rc;
5972 
5973 	num_bytes = spdk_min(_bdev_get_block_size_with_md(bdev_io->bdev) *
5974 			     bdev_io->u.bdev.split_remaining_num_blocks,
5975 			     ZERO_BUFFER_SIZE);
5976 	num_blocks = num_bytes / _bdev_get_block_size_with_md(bdev_io->bdev);
5977 
5978 	if (spdk_bdev_is_md_separate(bdev_io->bdev)) {
5979 		md_buf = (char *)g_bdev_mgr.zero_buffer +
5980 			 spdk_bdev_get_block_size(bdev_io->bdev) * num_blocks;
5981 	}
5982 
5983 	rc = bdev_write_blocks_with_md(bdev_io->internal.desc,
5984 				       spdk_io_channel_from_ctx(bdev_io->internal.ch),
5985 				       g_bdev_mgr.zero_buffer, md_buf,
5986 				       bdev_io->u.bdev.split_current_offset_blocks, num_blocks,
5987 				       bdev_write_zero_buffer_done, bdev_io);
5988 	if (rc == 0) {
5989 		bdev_io->u.bdev.split_remaining_num_blocks -= num_blocks;
5990 		bdev_io->u.bdev.split_current_offset_blocks += num_blocks;
5991 	} else if (rc == -ENOMEM) {
5992 		bdev_queue_io_wait_with_cb(bdev_io, bdev_write_zero_buffer_next);
5993 	} else {
5994 		bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
5995 		bdev_io->internal.cb(bdev_io, false, bdev_io->internal.caller_ctx);
5996 	}
5997 }
5998 
5999 static void
6000 bdev_write_zero_buffer_done(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
6001 {
6002 	struct spdk_bdev_io *parent_io = cb_arg;
6003 
6004 	spdk_bdev_free_io(bdev_io);
6005 
6006 	if (!success) {
6007 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
6008 		parent_io->internal.cb(parent_io, false, parent_io->internal.caller_ctx);
6009 		return;
6010 	}
6011 
6012 	if (parent_io->u.bdev.split_remaining_num_blocks == 0) {
6013 		parent_io->internal.status = SPDK_BDEV_IO_STATUS_SUCCESS;
6014 		parent_io->internal.cb(parent_io, true, parent_io->internal.caller_ctx);
6015 		return;
6016 	}
6017 
6018 	bdev_write_zero_buffer_next(parent_io);
6019 }
6020 
6021 static void
6022 bdev_set_qos_limit_done(struct set_qos_limit_ctx *ctx, int status)
6023 {
6024 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
6025 	ctx->bdev->internal.qos_mod_in_progress = false;
6026 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
6027 
6028 	if (ctx->cb_fn) {
6029 		ctx->cb_fn(ctx->cb_arg, status);
6030 	}
6031 	free(ctx);
6032 }
6033 
6034 static void
6035 bdev_disable_qos_done(void *cb_arg)
6036 {
6037 	struct set_qos_limit_ctx *ctx = cb_arg;
6038 	struct spdk_bdev *bdev = ctx->bdev;
6039 	struct spdk_bdev_io *bdev_io;
6040 	struct spdk_bdev_qos *qos;
6041 
6042 	pthread_mutex_lock(&bdev->internal.mutex);
6043 	qos = bdev->internal.qos;
6044 	bdev->internal.qos = NULL;
6045 	pthread_mutex_unlock(&bdev->internal.mutex);
6046 
6047 	while (!TAILQ_EMPTY(&qos->queued)) {
6048 		/* Send queued I/O back to their original thread for resubmission. */
6049 		bdev_io = TAILQ_FIRST(&qos->queued);
6050 		TAILQ_REMOVE(&qos->queued, bdev_io, internal.link);
6051 
6052 		if (bdev_io->internal.io_submit_ch) {
6053 			/*
6054 			 * Channel was changed when sending it to the QoS thread - change it back
6055 			 *  before sending it back to the original thread.
6056 			 */
6057 			bdev_io->internal.ch = bdev_io->internal.io_submit_ch;
6058 			bdev_io->internal.io_submit_ch = NULL;
6059 		}
6060 
6061 		spdk_thread_send_msg(spdk_bdev_io_get_thread(bdev_io),
6062 				     _bdev_io_submit, bdev_io);
6063 	}
6064 
6065 	if (qos->thread != NULL) {
6066 		spdk_put_io_channel(spdk_io_channel_from_ctx(qos->ch));
6067 		spdk_poller_unregister(&qos->poller);
6068 	}
6069 
6070 	free(qos);
6071 
6072 	bdev_set_qos_limit_done(ctx, 0);
6073 }
6074 
6075 static void
6076 bdev_disable_qos_msg_done(struct spdk_io_channel_iter *i, int status)
6077 {
6078 	void *io_device = spdk_io_channel_iter_get_io_device(i);
6079 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
6080 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6081 	struct spdk_thread *thread;
6082 
6083 	pthread_mutex_lock(&bdev->internal.mutex);
6084 	thread = bdev->internal.qos->thread;
6085 	pthread_mutex_unlock(&bdev->internal.mutex);
6086 
6087 	if (thread != NULL) {
6088 		spdk_thread_send_msg(thread, bdev_disable_qos_done, ctx);
6089 	} else {
6090 		bdev_disable_qos_done(ctx);
6091 	}
6092 }
6093 
6094 static void
6095 bdev_disable_qos_msg(struct spdk_io_channel_iter *i)
6096 {
6097 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
6098 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
6099 
6100 	bdev_ch->flags &= ~BDEV_CH_QOS_ENABLED;
6101 
6102 	spdk_for_each_channel_continue(i, 0);
6103 }
6104 
6105 static void
6106 bdev_update_qos_rate_limit_msg(void *cb_arg)
6107 {
6108 	struct set_qos_limit_ctx *ctx = cb_arg;
6109 	struct spdk_bdev *bdev = ctx->bdev;
6110 
6111 	pthread_mutex_lock(&bdev->internal.mutex);
6112 	bdev_qos_update_max_quota_per_timeslice(bdev->internal.qos);
6113 	pthread_mutex_unlock(&bdev->internal.mutex);
6114 
6115 	bdev_set_qos_limit_done(ctx, 0);
6116 }
6117 
6118 static void
6119 bdev_enable_qos_msg(struct spdk_io_channel_iter *i)
6120 {
6121 	void *io_device = spdk_io_channel_iter_get_io_device(i);
6122 	struct spdk_bdev *bdev = __bdev_from_io_dev(io_device);
6123 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
6124 	struct spdk_bdev_channel *bdev_ch = spdk_io_channel_get_ctx(ch);
6125 
6126 	pthread_mutex_lock(&bdev->internal.mutex);
6127 	bdev_enable_qos(bdev, bdev_ch);
6128 	pthread_mutex_unlock(&bdev->internal.mutex);
6129 	spdk_for_each_channel_continue(i, 0);
6130 }
6131 
6132 static void
6133 bdev_enable_qos_done(struct spdk_io_channel_iter *i, int status)
6134 {
6135 	struct set_qos_limit_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6136 
6137 	bdev_set_qos_limit_done(ctx, status);
6138 }
6139 
6140 static void
6141 bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits)
6142 {
6143 	int i;
6144 
6145 	assert(bdev->internal.qos != NULL);
6146 
6147 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6148 		if (limits[i] != SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
6149 			bdev->internal.qos->rate_limits[i].limit = limits[i];
6150 
6151 			if (limits[i] == 0) {
6152 				bdev->internal.qos->rate_limits[i].limit =
6153 					SPDK_BDEV_QOS_LIMIT_NOT_DEFINED;
6154 			}
6155 		}
6156 	}
6157 }
6158 
6159 void
6160 spdk_bdev_set_qos_rate_limits(struct spdk_bdev *bdev, uint64_t *limits,
6161 			      void (*cb_fn)(void *cb_arg, int status), void *cb_arg)
6162 {
6163 	struct set_qos_limit_ctx	*ctx;
6164 	uint32_t			limit_set_complement;
6165 	uint64_t			min_limit_per_sec;
6166 	int				i;
6167 	bool				disable_rate_limit = true;
6168 
6169 	for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6170 		if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED) {
6171 			continue;
6172 		}
6173 
6174 		if (limits[i] > 0) {
6175 			disable_rate_limit = false;
6176 		}
6177 
6178 		if (bdev_qos_is_iops_rate_limit(i) == true) {
6179 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_IOS_PER_SEC;
6180 		} else {
6181 			/* Change from megabyte to byte rate limit */
6182 			limits[i] = limits[i] * 1024 * 1024;
6183 			min_limit_per_sec = SPDK_BDEV_QOS_MIN_BYTES_PER_SEC;
6184 		}
6185 
6186 		limit_set_complement = limits[i] % min_limit_per_sec;
6187 		if (limit_set_complement) {
6188 			SPDK_ERRLOG("Requested rate limit %" PRIu64 " is not a multiple of %" PRIu64 "\n",
6189 				    limits[i], min_limit_per_sec);
6190 			limits[i] += min_limit_per_sec - limit_set_complement;
6191 			SPDK_ERRLOG("Round up the rate limit to %" PRIu64 "\n", limits[i]);
6192 		}
6193 	}
6194 
6195 	ctx = calloc(1, sizeof(*ctx));
6196 	if (ctx == NULL) {
6197 		cb_fn(cb_arg, -ENOMEM);
6198 		return;
6199 	}
6200 
6201 	ctx->cb_fn = cb_fn;
6202 	ctx->cb_arg = cb_arg;
6203 	ctx->bdev = bdev;
6204 
6205 	pthread_mutex_lock(&bdev->internal.mutex);
6206 	if (bdev->internal.qos_mod_in_progress) {
6207 		pthread_mutex_unlock(&bdev->internal.mutex);
6208 		free(ctx);
6209 		cb_fn(cb_arg, -EAGAIN);
6210 		return;
6211 	}
6212 	bdev->internal.qos_mod_in_progress = true;
6213 
6214 	if (disable_rate_limit == true && bdev->internal.qos) {
6215 		for (i = 0; i < SPDK_BDEV_QOS_NUM_RATE_LIMIT_TYPES; i++) {
6216 			if (limits[i] == SPDK_BDEV_QOS_LIMIT_NOT_DEFINED &&
6217 			    (bdev->internal.qos->rate_limits[i].limit > 0 &&
6218 			     bdev->internal.qos->rate_limits[i].limit !=
6219 			     SPDK_BDEV_QOS_LIMIT_NOT_DEFINED)) {
6220 				disable_rate_limit = false;
6221 				break;
6222 			}
6223 		}
6224 	}
6225 
6226 	if (disable_rate_limit == false) {
6227 		if (bdev->internal.qos == NULL) {
6228 			bdev->internal.qos = calloc(1, sizeof(*bdev->internal.qos));
6229 			if (!bdev->internal.qos) {
6230 				pthread_mutex_unlock(&bdev->internal.mutex);
6231 				SPDK_ERRLOG("Unable to allocate memory for QoS tracking\n");
6232 				bdev_set_qos_limit_done(ctx, -ENOMEM);
6233 				return;
6234 			}
6235 		}
6236 
6237 		if (bdev->internal.qos->thread == NULL) {
6238 			/* Enabling */
6239 			bdev_set_qos_rate_limits(bdev, limits);
6240 
6241 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
6242 					      bdev_enable_qos_msg, ctx,
6243 					      bdev_enable_qos_done);
6244 		} else {
6245 			/* Updating */
6246 			bdev_set_qos_rate_limits(bdev, limits);
6247 
6248 			spdk_thread_send_msg(bdev->internal.qos->thread,
6249 					     bdev_update_qos_rate_limit_msg, ctx);
6250 		}
6251 	} else {
6252 		if (bdev->internal.qos != NULL) {
6253 			bdev_set_qos_rate_limits(bdev, limits);
6254 
6255 			/* Disabling */
6256 			spdk_for_each_channel(__bdev_to_io_dev(bdev),
6257 					      bdev_disable_qos_msg, ctx,
6258 					      bdev_disable_qos_msg_done);
6259 		} else {
6260 			pthread_mutex_unlock(&bdev->internal.mutex);
6261 			bdev_set_qos_limit_done(ctx, 0);
6262 			return;
6263 		}
6264 	}
6265 
6266 	pthread_mutex_unlock(&bdev->internal.mutex);
6267 }
6268 
6269 struct spdk_bdev_histogram_ctx {
6270 	spdk_bdev_histogram_status_cb cb_fn;
6271 	void *cb_arg;
6272 	struct spdk_bdev *bdev;
6273 	int status;
6274 };
6275 
6276 static void
6277 bdev_histogram_disable_channel_cb(struct spdk_io_channel_iter *i, int status)
6278 {
6279 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6280 
6281 	pthread_mutex_lock(&ctx->bdev->internal.mutex);
6282 	ctx->bdev->internal.histogram_in_progress = false;
6283 	pthread_mutex_unlock(&ctx->bdev->internal.mutex);
6284 	ctx->cb_fn(ctx->cb_arg, ctx->status);
6285 	free(ctx);
6286 }
6287 
6288 static void
6289 bdev_histogram_disable_channel(struct spdk_io_channel_iter *i)
6290 {
6291 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6292 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6293 
6294 	if (ch->histogram != NULL) {
6295 		spdk_histogram_data_free(ch->histogram);
6296 		ch->histogram = NULL;
6297 	}
6298 	spdk_for_each_channel_continue(i, 0);
6299 }
6300 
6301 static void
6302 bdev_histogram_enable_channel_cb(struct spdk_io_channel_iter *i, int status)
6303 {
6304 	struct spdk_bdev_histogram_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6305 
6306 	if (status != 0) {
6307 		ctx->status = status;
6308 		ctx->bdev->internal.histogram_enabled = false;
6309 		spdk_for_each_channel(__bdev_to_io_dev(ctx->bdev), bdev_histogram_disable_channel, ctx,
6310 				      bdev_histogram_disable_channel_cb);
6311 	} else {
6312 		pthread_mutex_lock(&ctx->bdev->internal.mutex);
6313 		ctx->bdev->internal.histogram_in_progress = false;
6314 		pthread_mutex_unlock(&ctx->bdev->internal.mutex);
6315 		ctx->cb_fn(ctx->cb_arg, ctx->status);
6316 		free(ctx);
6317 	}
6318 }
6319 
6320 static void
6321 bdev_histogram_enable_channel(struct spdk_io_channel_iter *i)
6322 {
6323 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6324 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6325 	int status = 0;
6326 
6327 	if (ch->histogram == NULL) {
6328 		ch->histogram = spdk_histogram_data_alloc();
6329 		if (ch->histogram == NULL) {
6330 			status = -ENOMEM;
6331 		}
6332 	}
6333 
6334 	spdk_for_each_channel_continue(i, status);
6335 }
6336 
6337 void
6338 spdk_bdev_histogram_enable(struct spdk_bdev *bdev, spdk_bdev_histogram_status_cb cb_fn,
6339 			   void *cb_arg, bool enable)
6340 {
6341 	struct spdk_bdev_histogram_ctx *ctx;
6342 
6343 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_ctx));
6344 	if (ctx == NULL) {
6345 		cb_fn(cb_arg, -ENOMEM);
6346 		return;
6347 	}
6348 
6349 	ctx->bdev = bdev;
6350 	ctx->status = 0;
6351 	ctx->cb_fn = cb_fn;
6352 	ctx->cb_arg = cb_arg;
6353 
6354 	pthread_mutex_lock(&bdev->internal.mutex);
6355 	if (bdev->internal.histogram_in_progress) {
6356 		pthread_mutex_unlock(&bdev->internal.mutex);
6357 		free(ctx);
6358 		cb_fn(cb_arg, -EAGAIN);
6359 		return;
6360 	}
6361 
6362 	bdev->internal.histogram_in_progress = true;
6363 	pthread_mutex_unlock(&bdev->internal.mutex);
6364 
6365 	bdev->internal.histogram_enabled = enable;
6366 
6367 	if (enable) {
6368 		/* Allocate histogram for each channel */
6369 		spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_enable_channel, ctx,
6370 				      bdev_histogram_enable_channel_cb);
6371 	} else {
6372 		spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_disable_channel, ctx,
6373 				      bdev_histogram_disable_channel_cb);
6374 	}
6375 }
6376 
6377 struct spdk_bdev_histogram_data_ctx {
6378 	spdk_bdev_histogram_data_cb cb_fn;
6379 	void *cb_arg;
6380 	struct spdk_bdev *bdev;
6381 	/** merged histogram data from all channels */
6382 	struct spdk_histogram_data	*histogram;
6383 };
6384 
6385 static void
6386 bdev_histogram_get_channel_cb(struct spdk_io_channel_iter *i, int status)
6387 {
6388 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6389 
6390 	ctx->cb_fn(ctx->cb_arg, status, ctx->histogram);
6391 	free(ctx);
6392 }
6393 
6394 static void
6395 bdev_histogram_get_channel(struct spdk_io_channel_iter *i)
6396 {
6397 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6398 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6399 	struct spdk_bdev_histogram_data_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6400 	int status = 0;
6401 
6402 	if (ch->histogram == NULL) {
6403 		status = -EFAULT;
6404 	} else {
6405 		spdk_histogram_data_merge(ctx->histogram, ch->histogram);
6406 	}
6407 
6408 	spdk_for_each_channel_continue(i, status);
6409 }
6410 
6411 void
6412 spdk_bdev_histogram_get(struct spdk_bdev *bdev, struct spdk_histogram_data *histogram,
6413 			spdk_bdev_histogram_data_cb cb_fn,
6414 			void *cb_arg)
6415 {
6416 	struct spdk_bdev_histogram_data_ctx *ctx;
6417 
6418 	ctx = calloc(1, sizeof(struct spdk_bdev_histogram_data_ctx));
6419 	if (ctx == NULL) {
6420 		cb_fn(cb_arg, -ENOMEM, NULL);
6421 		return;
6422 	}
6423 
6424 	ctx->bdev = bdev;
6425 	ctx->cb_fn = cb_fn;
6426 	ctx->cb_arg = cb_arg;
6427 
6428 	ctx->histogram = histogram;
6429 
6430 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_histogram_get_channel, ctx,
6431 			      bdev_histogram_get_channel_cb);
6432 }
6433 
6434 size_t
6435 spdk_bdev_get_media_events(struct spdk_bdev_desc *desc, struct spdk_bdev_media_event *events,
6436 			   size_t max_events)
6437 {
6438 	struct media_event_entry *entry;
6439 	size_t num_events = 0;
6440 
6441 	for (; num_events < max_events; ++num_events) {
6442 		entry = TAILQ_FIRST(&desc->pending_media_events);
6443 		if (entry == NULL) {
6444 			break;
6445 		}
6446 
6447 		events[num_events] = entry->event;
6448 		TAILQ_REMOVE(&desc->pending_media_events, entry, tailq);
6449 		TAILQ_INSERT_TAIL(&desc->free_media_events, entry, tailq);
6450 	}
6451 
6452 	return num_events;
6453 }
6454 
6455 int
6456 spdk_bdev_push_media_events(struct spdk_bdev *bdev, const struct spdk_bdev_media_event *events,
6457 			    size_t num_events)
6458 {
6459 	struct spdk_bdev_desc *desc;
6460 	struct media_event_entry *entry;
6461 	size_t event_id;
6462 	int rc = 0;
6463 
6464 	assert(bdev->media_events);
6465 
6466 	pthread_mutex_lock(&bdev->internal.mutex);
6467 	TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
6468 		if (desc->write) {
6469 			break;
6470 		}
6471 	}
6472 
6473 	if (desc == NULL || desc->media_events_buffer == NULL) {
6474 		rc = -ENODEV;
6475 		goto out;
6476 	}
6477 
6478 	for (event_id = 0; event_id < num_events; ++event_id) {
6479 		entry = TAILQ_FIRST(&desc->free_media_events);
6480 		if (entry == NULL) {
6481 			break;
6482 		}
6483 
6484 		TAILQ_REMOVE(&desc->free_media_events, entry, tailq);
6485 		TAILQ_INSERT_TAIL(&desc->pending_media_events, entry, tailq);
6486 		entry->event = events[event_id];
6487 	}
6488 
6489 	rc = event_id;
6490 out:
6491 	pthread_mutex_unlock(&bdev->internal.mutex);
6492 	return rc;
6493 }
6494 
6495 void
6496 spdk_bdev_notify_media_management(struct spdk_bdev *bdev)
6497 {
6498 	struct spdk_bdev_desc *desc;
6499 
6500 	pthread_mutex_lock(&bdev->internal.mutex);
6501 	TAILQ_FOREACH(desc, &bdev->internal.open_descs, link) {
6502 		if (!TAILQ_EMPTY(&desc->pending_media_events)) {
6503 			desc->callback.event_fn(SPDK_BDEV_EVENT_MEDIA_MANAGEMENT, bdev,
6504 						desc->callback.ctx);
6505 		}
6506 	}
6507 	pthread_mutex_unlock(&bdev->internal.mutex);
6508 }
6509 
6510 struct locked_lba_range_ctx {
6511 	struct lba_range		range;
6512 	struct spdk_bdev		*bdev;
6513 	struct lba_range		*current_range;
6514 	struct lba_range		*owner_range;
6515 	struct spdk_poller		*poller;
6516 	lock_range_cb			cb_fn;
6517 	void				*cb_arg;
6518 };
6519 
6520 static void
6521 bdev_lock_error_cleanup_cb(struct spdk_io_channel_iter *i, int status)
6522 {
6523 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6524 
6525 	ctx->cb_fn(ctx->cb_arg, -ENOMEM);
6526 	free(ctx);
6527 }
6528 
6529 static void
6530 bdev_unlock_lba_range_get_channel(struct spdk_io_channel_iter *i);
6531 
6532 static void
6533 bdev_lock_lba_range_cb(struct spdk_io_channel_iter *i, int status)
6534 {
6535 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6536 	struct spdk_bdev *bdev = ctx->bdev;
6537 
6538 	if (status == -ENOMEM) {
6539 		/* One of the channels could not allocate a range object.
6540 		 * So we have to go back and clean up any ranges that were
6541 		 * allocated successfully before we return error status to
6542 		 * the caller.  We can reuse the unlock function to do that
6543 		 * clean up.
6544 		 */
6545 		spdk_for_each_channel(__bdev_to_io_dev(bdev),
6546 				      bdev_unlock_lba_range_get_channel, ctx,
6547 				      bdev_lock_error_cleanup_cb);
6548 		return;
6549 	}
6550 
6551 	/* All channels have locked this range and no I/O overlapping the range
6552 	 * are outstanding!  Set the owner_ch for the range object for the
6553 	 * locking channel, so that this channel will know that it is allowed
6554 	 * to write to this range.
6555 	 */
6556 	ctx->owner_range->owner_ch = ctx->range.owner_ch;
6557 	ctx->cb_fn(ctx->cb_arg, status);
6558 
6559 	/* Don't free the ctx here.  Its range is in the bdev's global list of
6560 	 * locked ranges still, and will be removed and freed when this range
6561 	 * is later unlocked.
6562 	 */
6563 }
6564 
6565 static int
6566 bdev_lock_lba_range_check_io(void *_i)
6567 {
6568 	struct spdk_io_channel_iter *i = _i;
6569 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6570 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6571 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6572 	struct lba_range *range = ctx->current_range;
6573 	struct spdk_bdev_io *bdev_io;
6574 
6575 	spdk_poller_unregister(&ctx->poller);
6576 
6577 	/* The range is now in the locked_ranges, so no new IO can be submitted to this
6578 	 * range.  But we need to wait until any outstanding IO overlapping with this range
6579 	 * are completed.
6580 	 */
6581 	TAILQ_FOREACH(bdev_io, &ch->io_submitted, internal.ch_link) {
6582 		if (bdev_io_range_is_locked(bdev_io, range)) {
6583 			ctx->poller = SPDK_POLLER_REGISTER(bdev_lock_lba_range_check_io, i, 100);
6584 			return SPDK_POLLER_BUSY;
6585 		}
6586 	}
6587 
6588 	spdk_for_each_channel_continue(i, 0);
6589 	return SPDK_POLLER_BUSY;
6590 }
6591 
6592 static void
6593 bdev_lock_lba_range_get_channel(struct spdk_io_channel_iter *i)
6594 {
6595 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6596 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6597 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6598 	struct lba_range *range;
6599 
6600 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
6601 		if (range->length == ctx->range.length &&
6602 		    range->offset == ctx->range.offset &&
6603 		    range->locked_ctx == ctx->range.locked_ctx) {
6604 			/* This range already exists on this channel, so don't add
6605 			 * it again.  This can happen when a new channel is created
6606 			 * while the for_each_channel operation is in progress.
6607 			 * Do not check for outstanding I/O in that case, since the
6608 			 * range was locked before any I/O could be submitted to the
6609 			 * new channel.
6610 			 */
6611 			spdk_for_each_channel_continue(i, 0);
6612 			return;
6613 		}
6614 	}
6615 
6616 	range = calloc(1, sizeof(*range));
6617 	if (range == NULL) {
6618 		spdk_for_each_channel_continue(i, -ENOMEM);
6619 		return;
6620 	}
6621 
6622 	range->length = ctx->range.length;
6623 	range->offset = ctx->range.offset;
6624 	range->locked_ctx = ctx->range.locked_ctx;
6625 	ctx->current_range = range;
6626 	if (ctx->range.owner_ch == ch) {
6627 		/* This is the range object for the channel that will hold
6628 		 * the lock.  Store it in the ctx object so that we can easily
6629 		 * set its owner_ch after the lock is finally acquired.
6630 		 */
6631 		ctx->owner_range = range;
6632 	}
6633 	TAILQ_INSERT_TAIL(&ch->locked_ranges, range, tailq);
6634 	bdev_lock_lba_range_check_io(i);
6635 }
6636 
6637 static void
6638 bdev_lock_lba_range_ctx(struct spdk_bdev *bdev, struct locked_lba_range_ctx *ctx)
6639 {
6640 	assert(spdk_get_thread() == ctx->range.owner_ch->channel->thread);
6641 
6642 	/* We will add a copy of this range to each channel now. */
6643 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_lock_lba_range_get_channel, ctx,
6644 			      bdev_lock_lba_range_cb);
6645 }
6646 
6647 static bool
6648 bdev_lba_range_overlaps_tailq(struct lba_range *range, lba_range_tailq_t *tailq)
6649 {
6650 	struct lba_range *r;
6651 
6652 	TAILQ_FOREACH(r, tailq, tailq) {
6653 		if (bdev_lba_range_overlapped(range, r)) {
6654 			return true;
6655 		}
6656 	}
6657 	return false;
6658 }
6659 
6660 static int
6661 bdev_lock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
6662 		    uint64_t offset, uint64_t length,
6663 		    lock_range_cb cb_fn, void *cb_arg)
6664 {
6665 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
6666 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6667 	struct locked_lba_range_ctx *ctx;
6668 
6669 	if (cb_arg == NULL) {
6670 		SPDK_ERRLOG("cb_arg must not be NULL\n");
6671 		return -EINVAL;
6672 	}
6673 
6674 	ctx = calloc(1, sizeof(*ctx));
6675 	if (ctx == NULL) {
6676 		return -ENOMEM;
6677 	}
6678 
6679 	ctx->range.offset = offset;
6680 	ctx->range.length = length;
6681 	ctx->range.owner_ch = ch;
6682 	ctx->range.locked_ctx = cb_arg;
6683 	ctx->bdev = bdev;
6684 	ctx->cb_fn = cb_fn;
6685 	ctx->cb_arg = cb_arg;
6686 
6687 	pthread_mutex_lock(&bdev->internal.mutex);
6688 	if (bdev_lba_range_overlaps_tailq(&ctx->range, &bdev->internal.locked_ranges)) {
6689 		/* There is an active lock overlapping with this range.
6690 		 * Put it on the pending list until this range no
6691 		 * longer overlaps with another.
6692 		 */
6693 		TAILQ_INSERT_TAIL(&bdev->internal.pending_locked_ranges, &ctx->range, tailq);
6694 	} else {
6695 		TAILQ_INSERT_TAIL(&bdev->internal.locked_ranges, &ctx->range, tailq);
6696 		bdev_lock_lba_range_ctx(bdev, ctx);
6697 	}
6698 	pthread_mutex_unlock(&bdev->internal.mutex);
6699 	return 0;
6700 }
6701 
6702 static void
6703 bdev_lock_lba_range_ctx_msg(void *_ctx)
6704 {
6705 	struct locked_lba_range_ctx *ctx = _ctx;
6706 
6707 	bdev_lock_lba_range_ctx(ctx->bdev, ctx);
6708 }
6709 
6710 static void
6711 bdev_unlock_lba_range_cb(struct spdk_io_channel_iter *i, int status)
6712 {
6713 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6714 	struct locked_lba_range_ctx *pending_ctx;
6715 	struct spdk_bdev_channel *ch = ctx->range.owner_ch;
6716 	struct spdk_bdev *bdev = ch->bdev;
6717 	struct lba_range *range, *tmp;
6718 
6719 	pthread_mutex_lock(&bdev->internal.mutex);
6720 	/* Check if there are any pending locked ranges that overlap with this range
6721 	 * that was just unlocked.  If there are, check that it doesn't overlap with any
6722 	 * other locked ranges before calling bdev_lock_lba_range_ctx which will start
6723 	 * the lock process.
6724 	 */
6725 	TAILQ_FOREACH_SAFE(range, &bdev->internal.pending_locked_ranges, tailq, tmp) {
6726 		if (bdev_lba_range_overlapped(range, &ctx->range) &&
6727 		    !bdev_lba_range_overlaps_tailq(range, &bdev->internal.locked_ranges)) {
6728 			TAILQ_REMOVE(&bdev->internal.pending_locked_ranges, range, tailq);
6729 			pending_ctx = SPDK_CONTAINEROF(range, struct locked_lba_range_ctx, range);
6730 			TAILQ_INSERT_TAIL(&bdev->internal.locked_ranges, range, tailq);
6731 			spdk_thread_send_msg(pending_ctx->range.owner_ch->channel->thread,
6732 					     bdev_lock_lba_range_ctx_msg, pending_ctx);
6733 		}
6734 	}
6735 	pthread_mutex_unlock(&bdev->internal.mutex);
6736 
6737 	ctx->cb_fn(ctx->cb_arg, status);
6738 	free(ctx);
6739 }
6740 
6741 static void
6742 bdev_unlock_lba_range_get_channel(struct spdk_io_channel_iter *i)
6743 {
6744 	struct spdk_io_channel *_ch = spdk_io_channel_iter_get_channel(i);
6745 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6746 	struct locked_lba_range_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
6747 	TAILQ_HEAD(, spdk_bdev_io) io_locked;
6748 	struct spdk_bdev_io *bdev_io;
6749 	struct lba_range *range;
6750 
6751 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
6752 		if (ctx->range.offset == range->offset &&
6753 		    ctx->range.length == range->length &&
6754 		    ctx->range.locked_ctx == range->locked_ctx) {
6755 			TAILQ_REMOVE(&ch->locked_ranges, range, tailq);
6756 			free(range);
6757 			break;
6758 		}
6759 	}
6760 
6761 	/* Note: we should almost always be able to assert that the range specified
6762 	 * was found.  But there are some very rare corner cases where a new channel
6763 	 * gets created simultaneously with a range unlock, where this function
6764 	 * would execute on that new channel and wouldn't have the range.
6765 	 * We also use this to clean up range allocations when a later allocation
6766 	 * fails in the locking path.
6767 	 * So we can't actually assert() here.
6768 	 */
6769 
6770 	/* Swap the locked IO into a temporary list, and then try to submit them again.
6771 	 * We could hyper-optimize this to only resubmit locked I/O that overlap
6772 	 * with the range that was just unlocked, but this isn't a performance path so
6773 	 * we go for simplicity here.
6774 	 */
6775 	TAILQ_INIT(&io_locked);
6776 	TAILQ_SWAP(&ch->io_locked, &io_locked, spdk_bdev_io, internal.ch_link);
6777 	while (!TAILQ_EMPTY(&io_locked)) {
6778 		bdev_io = TAILQ_FIRST(&io_locked);
6779 		TAILQ_REMOVE(&io_locked, bdev_io, internal.ch_link);
6780 		bdev_io_submit(bdev_io);
6781 	}
6782 
6783 	spdk_for_each_channel_continue(i, 0);
6784 }
6785 
6786 static int
6787 bdev_unlock_lba_range(struct spdk_bdev_desc *desc, struct spdk_io_channel *_ch,
6788 		      uint64_t offset, uint64_t length,
6789 		      lock_range_cb cb_fn, void *cb_arg)
6790 {
6791 	struct spdk_bdev *bdev = spdk_bdev_desc_get_bdev(desc);
6792 	struct spdk_bdev_channel *ch = spdk_io_channel_get_ctx(_ch);
6793 	struct locked_lba_range_ctx *ctx;
6794 	struct lba_range *range;
6795 	bool range_found = false;
6796 
6797 	/* Let's make sure the specified channel actually has a lock on
6798 	 * the specified range.  Note that the range must match exactly.
6799 	 */
6800 	TAILQ_FOREACH(range, &ch->locked_ranges, tailq) {
6801 		if (range->offset == offset && range->length == length &&
6802 		    range->owner_ch == ch && range->locked_ctx == cb_arg) {
6803 			range_found = true;
6804 			break;
6805 		}
6806 	}
6807 
6808 	if (!range_found) {
6809 		return -EINVAL;
6810 	}
6811 
6812 	pthread_mutex_lock(&bdev->internal.mutex);
6813 	/* We confirmed that this channel has locked the specified range.  To
6814 	 * start the unlock the process, we find the range in the bdev's locked_ranges
6815 	 * and remove it.  This ensures new channels don't inherit the locked range.
6816 	 * Then we will send a message to each channel (including the one specified
6817 	 * here) to remove the range from its per-channel list.
6818 	 */
6819 	TAILQ_FOREACH(range, &bdev->internal.locked_ranges, tailq) {
6820 		if (range->offset == offset && range->length == length &&
6821 		    range->locked_ctx == cb_arg) {
6822 			break;
6823 		}
6824 	}
6825 	if (range == NULL) {
6826 		assert(false);
6827 		pthread_mutex_unlock(&bdev->internal.mutex);
6828 		return -EINVAL;
6829 	}
6830 	TAILQ_REMOVE(&bdev->internal.locked_ranges, range, tailq);
6831 	ctx = SPDK_CONTAINEROF(range, struct locked_lba_range_ctx, range);
6832 	pthread_mutex_unlock(&bdev->internal.mutex);
6833 
6834 	ctx->cb_fn = cb_fn;
6835 	ctx->cb_arg = cb_arg;
6836 
6837 	spdk_for_each_channel(__bdev_to_io_dev(bdev), bdev_unlock_lba_range_get_channel, ctx,
6838 			      bdev_unlock_lba_range_cb);
6839 	return 0;
6840 }
6841 
6842 SPDK_LOG_REGISTER_COMPONENT(bdev)
6843 
6844 SPDK_TRACE_REGISTER_FN(bdev_trace, "bdev", TRACE_GROUP_BDEV)
6845 {
6846 	spdk_trace_register_owner(OWNER_BDEV, 'b');
6847 	spdk_trace_register_object(OBJECT_BDEV_IO, 'i');
6848 	spdk_trace_register_description("BDEV_IO_START", TRACE_BDEV_IO_START, OWNER_BDEV,
6849 					OBJECT_BDEV_IO, 1, 0, "type:   ");
6850 	spdk_trace_register_description("BDEV_IO_DONE", TRACE_BDEV_IO_DONE, OWNER_BDEV,
6851 					OBJECT_BDEV_IO, 0, 0, "");
6852 }
6853