xref: /linux/block/blk-core.c (revision 5b0764a53235d3c77e1ed674e836e1b3fe1a4b1f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 1991, 1992 Linus Torvalds
4  * Copyright (C) 1994,      Karl Keyte: Added support for disk statistics
5  * Elevator latency, (C) 2000  Andrea Arcangeli <andrea@suse.de> SuSE
6  * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
7  * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
8  *	-  July2000
9  * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
10  */
11 
12 /*
13  * This handles all read/write requests to block devices
14  */
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-pm.h>
20 #include <linux/blk-integrity.h>
21 #include <linux/highmem.h>
22 #include <linux/mm.h>
23 #include <linux/pagemap.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/string.h>
26 #include <linux/init.h>
27 #include <linux/completion.h>
28 #include <linux/slab.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/task_io_accounting_ops.h>
32 #include <linux/fault-inject.h>
33 #include <linux/list_sort.h>
34 #include <linux/delay.h>
35 #include <linux/ratelimit.h>
36 #include <linux/pm_runtime.h>
37 #include <linux/t10-pi.h>
38 #include <linux/debugfs.h>
39 #include <linux/bpf.h>
40 #include <linux/part_stat.h>
41 #include <linux/sched/sysctl.h>
42 #include <linux/blk-crypto.h>
43 #include <linux/error-injection.h>
44 
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/block.h>
47 
48 #include "blk.h"
49 #include "blk-mq-sched.h"
50 #include "blk-pm.h"
51 #include "blk-cgroup.h"
52 #include "blk-throttle.h"
53 #include "blk-ioprio.h"
54 #include "error-injection.h"
55 
56 struct dentry *blk_debugfs_root;
57 
58 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
59 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
60 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
61 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
62 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
63 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_insert);
64 
65 static DEFINE_IDA(blk_queue_ida);
66 
67 /*
68  * For queue allocation
69  */
70 static struct kmem_cache *blk_requestq_cachep;
71 
72 /*
73  * Controlling structure to kblockd
74  */
75 static struct workqueue_struct *kblockd_workqueue;
76 
77 /**
78  * blk_queue_flag_set - atomically set a queue flag
79  * @flag: flag to be set
80  * @q: request queue
81  */
82 void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
83 {
84 	set_bit(flag, &q->queue_flags);
85 }
86 EXPORT_SYMBOL(blk_queue_flag_set);
87 
88 /**
89  * blk_queue_flag_clear - atomically clear a queue flag
90  * @flag: flag to be cleared
91  * @q: request queue
92  */
93 void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
94 {
95 	clear_bit(flag, &q->queue_flags);
96 }
97 EXPORT_SYMBOL(blk_queue_flag_clear);
98 
99 #define REQ_OP_NAME(name) [REQ_OP_##name] = #name
100 static const char *const blk_op_name[] = {
101 	REQ_OP_NAME(READ),
102 	REQ_OP_NAME(WRITE),
103 	REQ_OP_NAME(FLUSH),
104 	REQ_OP_NAME(DISCARD),
105 	REQ_OP_NAME(SECURE_ERASE),
106 	REQ_OP_NAME(ZONE_RESET),
107 	REQ_OP_NAME(ZONE_RESET_ALL),
108 	REQ_OP_NAME(ZONE_OPEN),
109 	REQ_OP_NAME(ZONE_CLOSE),
110 	REQ_OP_NAME(ZONE_FINISH),
111 	REQ_OP_NAME(ZONE_APPEND),
112 	REQ_OP_NAME(WRITE_ZEROES),
113 	REQ_OP_NAME(DRV_IN),
114 	REQ_OP_NAME(DRV_OUT),
115 };
116 #undef REQ_OP_NAME
117 
118 /**
119  * blk_op_str - Return the string "name" for an operation REQ_OP_name.
120  * @op: a request operation.
121  *
122  * Convert a request operation REQ_OP_name into the string "name". Useful for
123  * debugging and tracing BIOs and requests. For an invalid request operation
124  * code, the string "UNKNOWN" is returned.
125  */
126 inline const char *blk_op_str(enum req_op op)
127 {
128 	const char *op_str = "UNKNOWN";
129 
130 	if (op < ARRAY_SIZE(blk_op_name) && blk_op_name[op])
131 		op_str = blk_op_name[op];
132 
133 	return op_str;
134 }
135 EXPORT_SYMBOL_GPL(blk_op_str);
136 
137 enum req_op str_to_blk_op(const char *op)
138 {
139 	int i;
140 
141 	for (i = 0; i < ARRAY_SIZE(blk_op_name); i++)
142 		if (blk_op_name[i] && !strcmp(blk_op_name[i], op))
143 			return (enum req_op)i;
144 	return REQ_OP_LAST;
145 }
146 
147 #define ENT(_tag, _errno, _desc)	\
148 [BLK_STS_##_tag] = {				\
149 	.errno		= _errno,		\
150 	.tag		= __stringify(_tag),	\
151 	.name		= _desc,		\
152 }
153 static const struct {
154 	int		errno;
155 	const char	*tag;
156 	const char	*name;
157 } blk_errors[] = {
158 	ENT(OK,			0,		""),
159 	ENT(NOTSUPP,		-EOPNOTSUPP,	"operation not supported"),
160 	ENT(TIMEOUT,		-ETIMEDOUT,	"timeout"),
161 	ENT(NOSPC,		-ENOSPC,	"critical space allocation"),
162 	ENT(TRANSPORT,		-ENOLINK,	"recoverable transport"),
163 	ENT(TARGET,		-EREMOTEIO,	"critical target"),
164 	ENT(RESV_CONFLICT,	-EBADE,		"reservation conflict"),
165 	ENT(MEDIUM,		-ENODATA,	"critical medium"),
166 	ENT(PROTECTION,		-EILSEQ,	"protection"),
167 	ENT(RESOURCE,		-ENOMEM,	"kernel resource"),
168 	ENT(DEV_RESOURCE,	-EBUSY,		"device resource"),
169 	ENT(AGAIN,		-EAGAIN,	"nonblocking retry"),
170 	ENT(OFFLINE,		-ENODEV,	"device offline"),
171 
172 	/* device mapper special case, should not leak out: */
173 	ENT(DM_REQUEUE,		-EREMCHG,	"dm internal retry"),
174 
175 	/* zone device specific errors */
176 	ENT(ZONE_OPEN_RESOURCE, -ETOOMANYREFS,	"open zones exceeded"),
177 	ENT(ZONE_ACTIVE_RESOURCE, -EOVERFLOW,	"active zones exceeded"),
178 
179 	/* Command duration limit device-side timeout */
180 	ENT(DURATION_LIMIT,	-ETIME,		"duration limit exceeded"),
181 	ENT(INVAL,		-EINVAL,	"invalid"),
182 
183 	/* everything else not covered above: */
184 	ENT(IOERR,		-EIO,		"I/O"),
185 };
186 #undef ENT
187 
188 blk_status_t errno_to_blk_status(int errno)
189 {
190 	int i;
191 
192 	for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
193 		if (blk_errors[i].errno == errno)
194 			return (__force blk_status_t)i;
195 	}
196 
197 	return BLK_STS_IOERR;
198 }
199 EXPORT_SYMBOL_GPL(errno_to_blk_status);
200 
201 int blk_status_to_errno(blk_status_t status)
202 {
203 	int idx = (__force int)status;
204 
205 	if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
206 		return -EIO;
207 	return blk_errors[idx].errno;
208 }
209 EXPORT_SYMBOL_GPL(blk_status_to_errno);
210 
211 const char *blk_status_to_str(blk_status_t status)
212 {
213 	int idx = (__force int)status;
214 
215 	if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
216 		return "<null>";
217 	return blk_errors[idx].name;
218 }
219 
220 const char *blk_status_to_tag(blk_status_t status)
221 {
222 	int idx = (__force int)status;
223 
224 	if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors) || !blk_errors[idx].tag))
225 		return "<null>";
226 	return blk_errors[idx].tag;
227 }
228 
229 blk_status_t tag_to_blk_status(const char *tag)
230 {
231 	int i;
232 
233 	for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
234 		if (blk_errors[i].tag &&
235 		    !strcmp(blk_errors[i].tag, tag))
236 			return (__force blk_status_t)i;
237 	}
238 
239 	/*
240 	 * Return BLK_STS_OK for mismatches as this function is intended to
241 	 * parse error status values.
242 	 */
243 	return BLK_STS_OK;
244 }
245 
246 /**
247  * blk_sync_queue - cancel any pending callbacks on a queue
248  * @q: the queue
249  *
250  * Description:
251  *     The block layer may perform asynchronous callback activity
252  *     on a queue, such as calling the unplug function after a timeout.
253  *     A block device may call blk_sync_queue to ensure that any
254  *     such activity is cancelled, thus allowing it to release resources
255  *     that the callbacks might use. The caller must already have made sure
256  *     that its ->submit_bio will not re-add plugging prior to calling
257  *     this function.
258  *
259  *     This function does not cancel any asynchronous activity arising
260  *     out of elevator or throttling code. That would require elevator_exit()
261  *     and blkcg_exit_queue() to be called with queue lock initialized.
262  *
263  */
264 void blk_sync_queue(struct request_queue *q)
265 {
266 	timer_delete_sync(&q->timeout);
267 	cancel_work_sync(&q->timeout_work);
268 }
269 EXPORT_SYMBOL(blk_sync_queue);
270 
271 /**
272  * blk_set_pm_only - increment pm_only counter
273  * @q: request queue pointer
274  */
275 void blk_set_pm_only(struct request_queue *q)
276 {
277 	atomic_inc(&q->pm_only);
278 }
279 EXPORT_SYMBOL_GPL(blk_set_pm_only);
280 
281 void blk_clear_pm_only(struct request_queue *q)
282 {
283 	int pm_only;
284 
285 	pm_only = atomic_dec_return(&q->pm_only);
286 	WARN_ON_ONCE(pm_only < 0);
287 	if (pm_only == 0)
288 		wake_up_all(&q->mq_freeze_wq);
289 }
290 EXPORT_SYMBOL_GPL(blk_clear_pm_only);
291 
292 static void blk_free_queue_rcu(struct rcu_head *rcu_head)
293 {
294 	struct request_queue *q = container_of(rcu_head,
295 			struct request_queue, rcu_head);
296 
297 	percpu_ref_exit(&q->q_usage_counter);
298 	kmem_cache_free(blk_requestq_cachep, q);
299 }
300 
301 static void blk_free_queue(struct request_queue *q)
302 {
303 	blk_free_queue_stats(q->stats);
304 	if (queue_is_mq(q))
305 		blk_mq_release(q);
306 
307 	ida_free(&blk_queue_ida, q->id);
308 	lockdep_unregister_key(&q->io_lock_cls_key);
309 	lockdep_unregister_key(&q->q_lock_cls_key);
310 	call_rcu(&q->rcu_head, blk_free_queue_rcu);
311 }
312 
313 /**
314  * blk_put_queue - decrement the request_queue refcount
315  * @q: the request_queue structure to decrement the refcount for
316  *
317  * Decrements the refcount of the request_queue and free it when the refcount
318  * reaches 0.
319  */
320 void blk_put_queue(struct request_queue *q)
321 {
322 	if (refcount_dec_and_test(&q->refs))
323 		blk_free_queue(q);
324 }
325 EXPORT_SYMBOL(blk_put_queue);
326 
327 bool blk_queue_start_drain(struct request_queue *q)
328 {
329 	/*
330 	 * When queue DYING flag is set, we need to block new req
331 	 * entering queue, so we call blk_freeze_queue_start() to
332 	 * prevent I/O from crossing blk_queue_enter().
333 	 */
334 	bool freeze = __blk_freeze_queue_start(q, current);
335 	if (queue_is_mq(q))
336 		blk_mq_wake_waiters(q);
337 	/* Make blk_queue_enter() reexamine the DYING flag. */
338 	wake_up_all(&q->mq_freeze_wq);
339 
340 	return freeze;
341 }
342 
343 /**
344  * blk_queue_enter() - try to increase q->q_usage_counter
345  * @q: request queue pointer
346  * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
347  */
348 int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
349 {
350 	const bool pm = flags & BLK_MQ_REQ_PM;
351 
352 	while (!blk_try_enter_queue(q, pm)) {
353 		if (flags & BLK_MQ_REQ_NOWAIT)
354 			return -EAGAIN;
355 
356 		/*
357 		 * read pair of barrier in blk_freeze_queue_start(), we need to
358 		 * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
359 		 * reading .mq_freeze_depth or queue dying flag, otherwise the
360 		 * following wait may never return if the two reads are
361 		 * reordered.
362 		 */
363 		smp_rmb();
364 		wait_event(q->mq_freeze_wq,
365 			   (!q->mq_freeze_depth &&
366 			    blk_pm_resume_queue(pm, q)) ||
367 			   blk_queue_dying(q));
368 		if (blk_queue_dying(q))
369 			return -ENODEV;
370 	}
371 
372 	rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
373 	rwsem_release(&q->q_lockdep_map, _RET_IP_);
374 	return 0;
375 }
376 
377 int __bio_queue_enter(struct request_queue *q, struct bio *bio)
378 {
379 	while (!blk_try_enter_queue(q, false)) {
380 		struct gendisk *disk = bio->bi_bdev->bd_disk;
381 
382 		if (bio->bi_opf & REQ_NOWAIT) {
383 			if (test_bit(GD_DEAD, &disk->state))
384 				goto dead;
385 			bio_wouldblock_error(bio);
386 			return -EAGAIN;
387 		}
388 
389 		/*
390 		 * read pair of barrier in blk_freeze_queue_start(), we need to
391 		 * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
392 		 * reading .mq_freeze_depth or queue dying flag, otherwise the
393 		 * following wait may never return if the two reads are
394 		 * reordered.
395 		 */
396 		smp_rmb();
397 		wait_event(q->mq_freeze_wq,
398 			   (!q->mq_freeze_depth &&
399 			    blk_pm_resume_queue(false, q)) ||
400 			   test_bit(GD_DEAD, &disk->state));
401 		if (test_bit(GD_DEAD, &disk->state))
402 			goto dead;
403 	}
404 
405 	rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
406 	rwsem_release(&q->io_lockdep_map, _RET_IP_);
407 	return 0;
408 dead:
409 	bio_io_error(bio);
410 	return -ENODEV;
411 }
412 
413 void blk_queue_exit(struct request_queue *q)
414 {
415 	percpu_ref_put(&q->q_usage_counter);
416 }
417 
418 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
419 {
420 	struct request_queue *q =
421 		container_of(ref, struct request_queue, q_usage_counter);
422 
423 	wake_up_all(&q->mq_freeze_wq);
424 }
425 
426 static void blk_rq_timed_out_timer(struct timer_list *t)
427 {
428 	struct request_queue *q = timer_container_of(q, t, timeout);
429 
430 	kblockd_schedule_work(&q->timeout_work);
431 }
432 
433 static void blk_timeout_work(struct work_struct *work)
434 {
435 }
436 
437 struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
438 {
439 	struct request_queue *q;
440 	int error;
441 
442 	q = kmem_cache_alloc_node(blk_requestq_cachep, GFP_KERNEL | __GFP_ZERO,
443 				  node_id);
444 	if (!q)
445 		return ERR_PTR(-ENOMEM);
446 
447 	q->last_merge = NULL;
448 
449 	q->id = ida_alloc(&blk_queue_ida, GFP_KERNEL);
450 	if (q->id < 0) {
451 		error = q->id;
452 		goto fail_q;
453 	}
454 
455 	q->stats = blk_alloc_queue_stats();
456 	if (!q->stats) {
457 		error = -ENOMEM;
458 		goto fail_id;
459 	}
460 
461 	error = blk_set_default_limits(lim);
462 	if (error)
463 		goto fail_stats;
464 	q->limits = *lim;
465 
466 	q->node = node_id;
467 
468 	atomic_set(&q->nr_active_requests_shared_tags, 0);
469 
470 	timer_setup(&q->timeout, blk_rq_timed_out_timer, 0);
471 	INIT_WORK(&q->timeout_work, blk_timeout_work);
472 	INIT_LIST_HEAD(&q->icq_list);
473 
474 	refcount_set(&q->refs, 1);
475 	mutex_init(&q->debugfs_mutex);
476 	mutex_init(&q->elevator_lock);
477 	mutex_init(&q->sysfs_lock);
478 	mutex_init(&q->limits_lock);
479 	mutex_init(&q->rq_qos_mutex);
480 	spin_lock_init(&q->queue_lock);
481 
482 	init_waitqueue_head(&q->mq_freeze_wq);
483 	mutex_init(&q->mq_freeze_lock);
484 
485 	blkg_init_queue(q);
486 
487 	/*
488 	 * Init percpu_ref in atomic mode so that it's faster to shutdown.
489 	 * See blk_register_queue() for details.
490 	 */
491 	error = percpu_ref_init(&q->q_usage_counter,
492 				blk_queue_usage_counter_release,
493 				PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
494 	if (error)
495 		goto fail_stats;
496 	lockdep_register_key(&q->io_lock_cls_key);
497 	lockdep_register_key(&q->q_lock_cls_key);
498 	lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
499 			 &q->io_lock_cls_key, 0);
500 	lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
501 			 &q->q_lock_cls_key, 0);
502 
503 	/* Teach lockdep about lock ordering (reclaim WRT queue freeze lock). */
504 	fs_reclaim_acquire(GFP_KERNEL);
505 	rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
506 	rwsem_release(&q->io_lockdep_map, _RET_IP_);
507 	fs_reclaim_release(GFP_KERNEL);
508 
509 	q->nr_requests = BLKDEV_DEFAULT_RQ;
510 	q->async_depth = BLKDEV_DEFAULT_RQ;
511 
512 	return q;
513 
514 fail_stats:
515 	blk_free_queue_stats(q->stats);
516 fail_id:
517 	ida_free(&blk_queue_ida, q->id);
518 fail_q:
519 	kmem_cache_free(blk_requestq_cachep, q);
520 	return ERR_PTR(error);
521 }
522 
523 /**
524  * blk_get_queue - increment the request_queue refcount
525  * @q: the request_queue structure to increment the refcount for
526  *
527  * Increment the refcount of the request_queue kobject.
528  *
529  * Context: Any context.
530  */
531 bool blk_get_queue(struct request_queue *q)
532 {
533 	if (unlikely(blk_queue_dying(q)))
534 		return false;
535 	refcount_inc(&q->refs);
536 	return true;
537 }
538 EXPORT_SYMBOL(blk_get_queue);
539 
540 #ifdef CONFIG_FAIL_MAKE_REQUEST
541 
542 static DECLARE_FAULT_ATTR(fail_make_request);
543 
544 static int __init setup_fail_make_request(char *str)
545 {
546 	return setup_fault_attr(&fail_make_request, str);
547 }
548 __setup("fail_make_request=", setup_fail_make_request);
549 
550 bool should_fail_request(struct block_device *part, unsigned int bytes)
551 {
552 	return bdev_test_flag(part, BD_MAKE_IT_FAIL) &&
553 	       should_fail(&fail_make_request, bytes);
554 }
555 
556 static int __init fail_make_request_debugfs(void)
557 {
558 	struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
559 						NULL, &fail_make_request);
560 
561 	return PTR_ERR_OR_ZERO(dir);
562 }
563 
564 late_initcall(fail_make_request_debugfs);
565 #endif /* CONFIG_FAIL_MAKE_REQUEST */
566 
567 static inline void bio_check_ro(struct bio *bio)
568 {
569 	if (op_is_write(bio_op(bio)) && bdev_read_only(bio->bi_bdev)) {
570 		if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
571 			return;
572 
573 		if (bdev_test_flag(bio->bi_bdev, BD_RO_WARNED))
574 			return;
575 
576 		bdev_set_flag(bio->bi_bdev, BD_RO_WARNED);
577 
578 		/*
579 		 * Use ioctl to set underlying disk of raid/dm to read-only
580 		 * will trigger this.
581 		 */
582 		pr_warn("Trying to write to read-only block-device %pg\n",
583 			bio->bi_bdev);
584 	}
585 }
586 
587 int should_fail_bio(struct bio *bio)
588 {
589 	if (should_fail_request(bdev_whole(bio->bi_bdev), bio->bi_iter.bi_size))
590 		return -EIO;
591 	return 0;
592 }
593 ALLOW_ERROR_INJECTION(should_fail_bio, ERRNO);
594 
595 /*
596  * Check whether this bio extends beyond the end of the device or partition.
597  * This may well happen - the kernel calls bread() without checking the size of
598  * the device, e.g., when mounting a file system.
599  */
600 static inline int bio_check_eod(struct bio *bio)
601 {
602 	sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
603 	unsigned int nr_sectors = bio_sectors(bio);
604 
605 	if (nr_sectors &&
606 	    (nr_sectors > maxsector ||
607 	     bio->bi_iter.bi_sector > maxsector - nr_sectors)) {
608 		if (!maxsector)
609 			return -EIO;
610 		pr_info_ratelimited("%s: attempt to access beyond end of device\n"
611 				    "%pg: rw=%d, sector=%llu, nr_sectors = %u limit=%llu\n",
612 				    current->comm, bio->bi_bdev, bio->bi_opf,
613 				    bio->bi_iter.bi_sector, nr_sectors, maxsector);
614 		return -EIO;
615 	}
616 	return 0;
617 }
618 
619 /*
620  * Remap block n of partition p to block n+start(p) of the disk.
621  */
622 static int blk_partition_remap(struct bio *bio)
623 {
624 	struct block_device *p = bio->bi_bdev;
625 
626 	if (unlikely(should_fail_request(p, bio->bi_iter.bi_size)))
627 		return -EIO;
628 	if (bio_sectors(bio)) {
629 		bio->bi_iter.bi_sector += p->bd_start_sect;
630 		trace_block_bio_remap(bio, p->bd_dev,
631 				      bio->bi_iter.bi_sector -
632 				      p->bd_start_sect);
633 	}
634 	bio_set_flag(bio, BIO_REMAPPED);
635 	return 0;
636 }
637 
638 /*
639  * Check write append to a zoned block device.
640  */
641 static inline blk_status_t blk_check_zone_append(struct request_queue *q,
642 						 struct bio *bio)
643 {
644 	int nr_sectors = bio_sectors(bio);
645 
646 	/* Only applicable to zoned block devices */
647 	if (!bdev_is_zoned(bio->bi_bdev))
648 		return BLK_STS_NOTSUPP;
649 
650 	/* The bio sector must point to the start of a sequential zone */
651 	if (!bdev_is_zone_start(bio->bi_bdev, bio->bi_iter.bi_sector))
652 		return BLK_STS_IOERR;
653 
654 	/*
655 	 * Not allowed to cross zone boundaries. Otherwise, the BIO will be
656 	 * split and could result in non-contiguous sectors being written in
657 	 * different zones.
658 	 */
659 	if (nr_sectors > q->limits.chunk_sectors)
660 		return BLK_STS_IOERR;
661 
662 	/* Make sure the BIO is small enough and will not get split */
663 	if (nr_sectors > q->limits.max_zone_append_sectors)
664 		return BLK_STS_IOERR;
665 
666 	bio->bi_opf |= REQ_NOMERGE;
667 
668 	return BLK_STS_OK;
669 }
670 
671 static void __submit_bio(struct bio *bio)
672 {
673 	if (!bdev_test_flag(bio->bi_bdev, BD_HAS_SUBMIT_BIO)) {
674 		blk_mq_submit_bio(bio);
675 	} else if (likely(bio_queue_enter(bio) == 0)) {
676 		struct gendisk *disk = bio->bi_bdev->bd_disk;
677 
678 		if ((bio->bi_opf & REQ_POLLED) &&
679 		    !(disk->queue->limits.features & BLK_FEAT_POLL))
680 			bio_endio_status(bio, BLK_STS_NOTSUPP);
681 		else
682 			disk->fops->submit_bio(bio);
683 		blk_queue_exit(disk->queue);
684 	}
685 }
686 
687 /*
688  * The loop in this function may be a bit non-obvious, and so deserves some
689  * explanation:
690  *
691  *  - Before entering the loop, bio->bi_next is NULL (as all callers ensure
692  *    that), so we have a list with a single bio.
693  *  - We pretend that we have just taken it off a longer list, so we assign
694  *    bio_list to a pointer to the bio_list_on_stack, thus initialising the
695  *    bio_list of new bios to be added.  ->submit_bio() may indeed add some more
696  *    bios through a recursive call to submit_bio_noacct.  If it did, we find a
697  *    non-NULL value in bio_list and re-enter the loop from the top.
698  *  - In this case we really did just take the bio off the top of the list (no
699  *    pretending) and so remove it from bio_list, and call into ->submit_bio()
700  *    again.
701  *
702  * bio_list_on_stack[0] contains bios submitted by the current ->submit_bio.
703  * bio_list_on_stack[1] contains bios that were submitted before the current
704  *	->submit_bio(), but that haven't been processed yet.
705  */
706 static void __submit_bio_noacct(struct bio *bio)
707 {
708 	struct bio_list bio_list_on_stack[2];
709 
710 	BUG_ON(bio->bi_next);
711 
712 	bio_list_init(&bio_list_on_stack[0]);
713 	current->bio_list = bio_list_on_stack;
714 
715 	do {
716 		struct request_queue *q = bdev_get_queue(bio->bi_bdev);
717 		struct bio_list lower, same;
718 
719 		/*
720 		 * Create a fresh bio_list for all subordinate requests.
721 		 */
722 		bio_list_on_stack[1] = bio_list_on_stack[0];
723 		bio_list_init(&bio_list_on_stack[0]);
724 
725 		__submit_bio(bio);
726 
727 		/*
728 		 * Sort new bios into those for a lower level and those for the
729 		 * same level.
730 		 */
731 		bio_list_init(&lower);
732 		bio_list_init(&same);
733 		while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
734 			if (q == bdev_get_queue(bio->bi_bdev))
735 				bio_list_add(&same, bio);
736 			else
737 				bio_list_add(&lower, bio);
738 
739 		/*
740 		 * Now assemble so we handle the lowest level first.
741 		 */
742 		bio_list_merge(&bio_list_on_stack[0], &lower);
743 		bio_list_merge(&bio_list_on_stack[0], &same);
744 		bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
745 	} while ((bio = bio_list_pop(&bio_list_on_stack[0])));
746 
747 	current->bio_list = NULL;
748 }
749 
750 static void __submit_bio_noacct_mq(struct bio *bio)
751 {
752 	struct bio_list bio_list[2] = { };
753 
754 	current->bio_list = bio_list;
755 
756 	do {
757 		__submit_bio(bio);
758 	} while ((bio = bio_list_pop(&bio_list[0])));
759 
760 	current->bio_list = NULL;
761 }
762 
763 void submit_bio_noacct_nocheck(struct bio *bio, bool split)
764 {
765 	if (unlikely(blk_error_inject(bio)))
766 		return;
767 
768 	blk_cgroup_bio_start(bio);
769 
770 	if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
771 		trace_block_bio_queue(bio);
772 		/*
773 		 * Now that enqueuing has been traced, we need to trace
774 		 * completion as well.
775 		 */
776 		bio_set_flag(bio, BIO_TRACE_COMPLETION);
777 	}
778 
779 	/*
780 	 * We only want one ->submit_bio to be active at a time, else stack
781 	 * usage with stacked devices could be a problem.  Use current->bio_list
782 	 * to collect a list of requests submitted by a ->submit_bio method
783 	 * while it is active, and then process them after it returned.
784 	 */
785 	if (current->bio_list) {
786 		if (split)
787 			bio_list_add_head(&current->bio_list[0], bio);
788 		else
789 			bio_list_add(&current->bio_list[0], bio);
790 	} else if (!bdev_test_flag(bio->bi_bdev, BD_HAS_SUBMIT_BIO)) {
791 		__submit_bio_noacct_mq(bio);
792 	} else {
793 		__submit_bio_noacct(bio);
794 	}
795 }
796 
797 static blk_status_t blk_validate_atomic_write_op_size(struct request_queue *q,
798 						 struct bio *bio)
799 {
800 	if (bio->bi_iter.bi_size > queue_atomic_write_unit_max_bytes(q))
801 		return BLK_STS_INVAL;
802 
803 	if (bio->bi_iter.bi_size % queue_atomic_write_unit_min_bytes(q))
804 		return BLK_STS_INVAL;
805 
806 	return BLK_STS_OK;
807 }
808 
809 /**
810  * submit_bio_noacct - re-submit a bio to the block device layer for I/O
811  * @bio:  The bio describing the location in memory and on the device.
812  *
813  * This is a version of submit_bio() that shall only be used for I/O that is
814  * resubmitted to lower level drivers by stacking block drivers.  All file
815  * systems and other upper level users of the block layer should use
816  * submit_bio() instead.
817  */
818 void submit_bio_noacct(struct bio *bio)
819 {
820 	struct block_device *bdev = bio->bi_bdev;
821 	struct request_queue *q = bdev_get_queue(bdev);
822 	blk_status_t status = BLK_STS_IOERR;
823 
824 	might_sleep();
825 
826 	/*
827 	 * For a REQ_NOWAIT based request, return -EOPNOTSUPP
828 	 * if queue does not support NOWAIT.
829 	 */
830 	if ((bio->bi_opf & REQ_NOWAIT) && !bdev_nowait(bdev))
831 		goto not_supported;
832 
833 	if (bio_has_crypt_ctx(bio)) {
834 		if (WARN_ON_ONCE(!bio_has_data(bio)))
835 			goto end_io;
836 		if (!blk_crypto_supported(bio))
837 			goto not_supported;
838 	}
839 
840 	if (should_fail_bio(bio))
841 		goto end_io;
842 	bio_check_ro(bio);
843 	if (!bio_flagged(bio, BIO_REMAPPED)) {
844 		if (unlikely(bio_check_eod(bio)))
845 			goto end_io;
846 		if (bdev_is_partition(bdev) &&
847 		    unlikely(blk_partition_remap(bio)))
848 			goto end_io;
849 	}
850 
851 	/*
852 	 * Filter flush bio's early so that bio based drivers without flush
853 	 * support don't have to worry about them.
854 	 */
855 	if (op_is_flush(bio->bi_opf)) {
856 		if (WARN_ON_ONCE(bio_op(bio) != REQ_OP_WRITE &&
857 				 bio_op(bio) != REQ_OP_ZONE_APPEND))
858 			goto end_io;
859 		if (!bdev_write_cache(bdev)) {
860 			bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
861 			if (!bio_sectors(bio)) {
862 				status = BLK_STS_OK;
863 				goto end_io;
864 			}
865 		}
866 	}
867 
868 	switch (bio_op(bio)) {
869 	case REQ_OP_READ:
870 		break;
871 	case REQ_OP_WRITE:
872 		if (bio->bi_opf & REQ_ATOMIC) {
873 			status = blk_validate_atomic_write_op_size(q, bio);
874 			if (status != BLK_STS_OK)
875 				goto end_io;
876 		}
877 		break;
878 	case REQ_OP_FLUSH:
879 		/*
880 		 * REQ_OP_FLUSH can't be submitted through bios, it is only
881 		 * synthetized in struct request by the flush state machine.
882 		 */
883 		goto not_supported;
884 	case REQ_OP_DISCARD:
885 		if (!bdev_max_discard_sectors(bdev))
886 			goto not_supported;
887 		break;
888 	case REQ_OP_SECURE_ERASE:
889 		if (!bdev_max_secure_erase_sectors(bdev))
890 			goto not_supported;
891 		break;
892 	case REQ_OP_ZONE_APPEND:
893 		status = blk_check_zone_append(q, bio);
894 		if (status != BLK_STS_OK)
895 			goto end_io;
896 		break;
897 	case REQ_OP_WRITE_ZEROES:
898 		if (!q->limits.max_write_zeroes_sectors)
899 			goto not_supported;
900 		break;
901 	case REQ_OP_ZONE_OPEN:
902 	case REQ_OP_ZONE_CLOSE:
903 	case REQ_OP_ZONE_RESET:
904 	case REQ_OP_ZONE_FINISH:
905 		/* Zone management operations require sequential zones. */
906 		if (!bdev_zone_is_seq(bio->bi_bdev, bio->bi_iter.bi_sector))
907 			goto end_io;
908 		break;
909 	case REQ_OP_ZONE_RESET_ALL:
910 		if (!bdev_is_zoned(bio->bi_bdev))
911 			goto not_supported;
912 		break;
913 	case REQ_OP_DRV_IN:
914 	case REQ_OP_DRV_OUT:
915 		/*
916 		 * Driver private operations are only used with passthrough
917 		 * requests.
918 		 */
919 		fallthrough;
920 	default:
921 		goto not_supported;
922 	}
923 
924 	if (blk_throtl_bio(bio))
925 		return;
926 	submit_bio_noacct_nocheck(bio, false);
927 	return;
928 
929 not_supported:
930 	status = BLK_STS_NOTSUPP;
931 end_io:
932 	bio_endio_status(bio, status);
933 }
934 EXPORT_SYMBOL(submit_bio_noacct);
935 
936 static void bio_set_ioprio(struct bio *bio)
937 {
938 	/* Nobody set ioprio so far? Initialize it based on task's nice value */
939 	if (IOPRIO_PRIO_CLASS(bio->bi_ioprio) == IOPRIO_CLASS_NONE)
940 		bio->bi_ioprio = get_current_ioprio();
941 	blkcg_set_ioprio(bio);
942 }
943 
944 /**
945  * submit_bio - submit a bio to the block device layer for I/O
946  * @bio: The &struct bio which describes the I/O
947  *
948  * submit_bio() is used to submit I/O requests to block devices.  It is passed a
949  * fully set up &struct bio that describes the I/O that needs to be done.  The
950  * bio will be sent to the device described by the bi_bdev field.
951  *
952  * The success/failure status of the request, along with notification of
953  * completion, is delivered asynchronously through the ->bi_end_io() callback
954  * in @bio.  The bio must NOT be touched by the caller until ->bi_end_io() has
955  * been called.
956  */
957 void submit_bio(struct bio *bio)
958 {
959 	if (bio_op(bio) == REQ_OP_READ) {
960 		task_io_account_read(bio->bi_iter.bi_size);
961 		count_vm_events(PGPGIN, bio_sectors(bio));
962 	} else if (bio_op(bio) == REQ_OP_WRITE) {
963 		count_vm_events(PGPGOUT, bio_sectors(bio));
964 	}
965 
966 	bio_set_ioprio(bio);
967 	submit_bio_noacct(bio);
968 }
969 EXPORT_SYMBOL(submit_bio);
970 
971 /**
972  * bio_poll - poll for BIO completions
973  * @bio: bio to poll for
974  * @iob: batches of IO
975  * @flags: BLK_POLL_* flags that control the behavior
976  *
977  * Poll for completions on queue associated with the bio. Returns number of
978  * completed entries found.
979  *
980  * Note: the caller must either be the context that submitted @bio, or
981  * be in a RCU critical section to prevent freeing of @bio.
982  */
983 int bio_poll(struct bio *bio, struct io_comp_batch *iob, unsigned int flags)
984 {
985 	blk_qc_t cookie = READ_ONCE(bio->bi_cookie);
986 	struct block_device *bdev;
987 	struct request_queue *q;
988 	int ret = 0;
989 
990 	bdev = READ_ONCE(bio->bi_bdev);
991 	if (!bdev)
992 		return 0;
993 
994 	q = bdev_get_queue(bdev);
995 	if (cookie == BLK_QC_T_NONE)
996 		return 0;
997 
998 	blk_flush_plug(current->plug, false);
999 
1000 	/*
1001 	 * We need to be able to enter a frozen queue, similar to how
1002 	 * timeouts also need to do that. If that is blocked, then we can
1003 	 * have pending IO when a queue freeze is started, and then the
1004 	 * wait for the freeze to finish will wait for polled requests to
1005 	 * timeout as the poller is preventer from entering the queue and
1006 	 * completing them. As long as we prevent new IO from being queued,
1007 	 * that should be all that matters.
1008 	 */
1009 	if (!percpu_ref_tryget(&q->q_usage_counter))
1010 		return 0;
1011 	if (queue_is_mq(q)) {
1012 		ret = blk_mq_poll(q, cookie, iob, flags);
1013 	} else {
1014 		struct gendisk *disk = q->disk;
1015 
1016 		if ((q->limits.features & BLK_FEAT_POLL) && disk &&
1017 		    disk->fops->poll_bio)
1018 			ret = disk->fops->poll_bio(bio, iob, flags);
1019 	}
1020 	blk_queue_exit(q);
1021 	return ret;
1022 }
1023 EXPORT_SYMBOL_GPL(bio_poll);
1024 
1025 /*
1026  * Helper to implement file_operations.iopoll.  Requires the bio to be stored
1027  * in iocb->private, and cleared before freeing the bio.
1028  */
1029 int iocb_bio_iopoll(struct kiocb *kiocb, struct io_comp_batch *iob,
1030 		    unsigned int flags)
1031 {
1032 	struct bio *bio;
1033 	int ret = 0;
1034 
1035 	/*
1036 	 * Note: the bio cache only uses SLAB_TYPESAFE_BY_RCU, so bio can
1037 	 * point to a freshly allocated bio at this point.  If that happens
1038 	 * we have a few cases to consider:
1039 	 *
1040 	 *  1) the bio is being initialized and bi_bdev is NULL.  We can just
1041 	 *     simply nothing in this case
1042 	 *  2) the bio points to a not poll enabled device.  bio_poll will catch
1043 	 *     this and return 0
1044 	 *  3) the bio points to a poll capable device, including but not
1045 	 *     limited to the one that the original bio pointed to.  In this
1046 	 *     case we will call into the actual poll method and poll for I/O,
1047 	 *     even if we don't need to, but it won't cause harm either.
1048 	 *
1049 	 * For cases 2) and 3) above the RCU grace period ensures that bi_bdev
1050 	 * is still allocated. Because partitions hold a reference to the whole
1051 	 * device bdev and thus disk, the disk is also still valid.  Grabbing
1052 	 * a reference to the queue in bio_poll() ensures the hctxs and requests
1053 	 * are still valid as well.
1054 	 */
1055 	rcu_read_lock();
1056 	bio = READ_ONCE(kiocb->private);
1057 	if (bio)
1058 		ret = bio_poll(bio, iob, flags);
1059 	rcu_read_unlock();
1060 
1061 	return ret;
1062 }
1063 EXPORT_SYMBOL_GPL(iocb_bio_iopoll);
1064 
1065 void update_io_ticks(struct block_device *part, unsigned long now, bool end)
1066 {
1067 	unsigned long stamp;
1068 again:
1069 	stamp = READ_ONCE(part->bd_stamp);
1070 	if (unlikely(time_after(now, stamp)) &&
1071 	    likely(try_cmpxchg(&part->bd_stamp, &stamp, now)) &&
1072 	    (end || bdev_count_inflight(part)))
1073 		__part_stat_add(part, io_ticks, now - stamp);
1074 
1075 	if (bdev_is_partition(part)) {
1076 		part = bdev_whole(part);
1077 		goto again;
1078 	}
1079 }
1080 
1081 unsigned long bdev_start_io_acct(struct block_device *bdev, enum req_op op,
1082 				 unsigned long start_time)
1083 {
1084 	part_stat_lock();
1085 	update_io_ticks(bdev, start_time, false);
1086 	bdev_inc_in_flight(bdev, op);
1087 	part_stat_unlock();
1088 
1089 	return start_time;
1090 }
1091 EXPORT_SYMBOL(bdev_start_io_acct);
1092 
1093 /**
1094  * bio_start_io_acct - start I/O accounting for bio based drivers
1095  * @bio:	bio to start account for
1096  *
1097  * Returns the start time that should be passed back to bio_end_io_acct().
1098  */
1099 unsigned long bio_start_io_acct(struct bio *bio)
1100 {
1101 	return bdev_start_io_acct(bio->bi_bdev, bio_op(bio), jiffies);
1102 }
1103 EXPORT_SYMBOL_GPL(bio_start_io_acct);
1104 
1105 void bdev_end_io_acct(struct block_device *bdev, enum req_op op,
1106 		      unsigned int sectors, unsigned long start_time)
1107 {
1108 	const int sgrp = op_stat_group(op);
1109 	unsigned long now = READ_ONCE(jiffies);
1110 	unsigned long duration = now - start_time;
1111 
1112 	part_stat_lock();
1113 	update_io_ticks(bdev, now, true);
1114 	part_stat_inc(bdev, ios[sgrp]);
1115 	part_stat_add(bdev, sectors[sgrp], sectors);
1116 	part_stat_add(bdev, nsecs[sgrp], jiffies_to_nsecs(duration));
1117 	bdev_dec_in_flight(bdev, op);
1118 	part_stat_unlock();
1119 }
1120 EXPORT_SYMBOL(bdev_end_io_acct);
1121 
1122 void bio_end_io_acct_remapped(struct bio *bio, unsigned long start_time,
1123 			      struct block_device *orig_bdev)
1124 {
1125 	bdev_end_io_acct(orig_bdev, bio_op(bio), bio_sectors(bio), start_time);
1126 }
1127 EXPORT_SYMBOL_GPL(bio_end_io_acct_remapped);
1128 
1129 /**
1130  * blk_lld_busy - Check if underlying low-level drivers of a device are busy
1131  * @q : the queue of the device being checked
1132  *
1133  * Description:
1134  *    Check if underlying low-level drivers of a device are busy.
1135  *    If the drivers want to export their busy state, they must set own
1136  *    exporting function using blk_queue_lld_busy() first.
1137  *
1138  *    Basically, this function is used only by request stacking drivers
1139  *    to stop dispatching requests to underlying devices when underlying
1140  *    devices are busy.  This behavior helps more I/O merging on the queue
1141  *    of the request stacking driver and prevents I/O throughput regression
1142  *    on burst I/O load.
1143  *
1144  * Return:
1145  *    0 - Not busy (The request stacking driver should dispatch request)
1146  *    1 - Busy (The request stacking driver should stop dispatching request)
1147  */
1148 int blk_lld_busy(struct request_queue *q)
1149 {
1150 	if (queue_is_mq(q) && q->mq_ops->busy)
1151 		return q->mq_ops->busy(q);
1152 
1153 	return 0;
1154 }
1155 EXPORT_SYMBOL_GPL(blk_lld_busy);
1156 
1157 int kblockd_schedule_work(struct work_struct *work)
1158 {
1159 	return queue_work(kblockd_workqueue, work);
1160 }
1161 EXPORT_SYMBOL(kblockd_schedule_work);
1162 
1163 int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
1164 				unsigned long delay)
1165 {
1166 	return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
1167 }
1168 EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
1169 
1170 void blk_start_plug_nr_ios(struct blk_plug *plug, unsigned short nr_ios)
1171 {
1172 	struct task_struct *tsk = current;
1173 
1174 	/*
1175 	 * If this is a nested plug, don't actually assign it.
1176 	 */
1177 	if (tsk->plug)
1178 		return;
1179 
1180 	plug->cur_ktime = 0;
1181 	rq_list_init(&plug->mq_list);
1182 	rq_list_init(&plug->cached_rqs);
1183 	plug->nr_ios = min_t(unsigned short, nr_ios, BLK_MAX_REQUEST_COUNT);
1184 	plug->rq_count = 0;
1185 	plug->multiple_queues = false;
1186 	plug->has_elevator = false;
1187 	INIT_LIST_HEAD(&plug->cb_list);
1188 
1189 	/*
1190 	 * Store ordering should not be needed here, since a potential
1191 	 * preempt will imply a full memory barrier
1192 	 */
1193 	tsk->plug = plug;
1194 }
1195 
1196 /**
1197  * blk_start_plug - initialize blk_plug and track it inside the task_struct
1198  * @plug:	The &struct blk_plug that needs to be initialized
1199  *
1200  * Description:
1201  *   blk_start_plug() indicates to the block layer an intent by the caller
1202  *   to submit multiple I/O requests in a batch.  The block layer may use
1203  *   this hint to defer submitting I/Os from the caller until blk_finish_plug()
1204  *   is called.  However, the block layer may choose to submit requests
1205  *   before a call to blk_finish_plug() if the number of queued I/Os
1206  *   exceeds %BLK_MAX_REQUEST_COUNT, or if the size of the I/O is larger than
1207  *   %BLK_PLUG_FLUSH_SIZE.  The queued I/Os may also be submitted early if
1208  *   the task schedules (see below).
1209  *
1210  *   Tracking blk_plug inside the task_struct will help with auto-flushing the
1211  *   pending I/O should the task end up blocking between blk_start_plug() and
1212  *   blk_finish_plug(). This is important from a performance perspective, but
1213  *   also ensures that we don't deadlock. For instance, if the task is blocking
1214  *   for a memory allocation, memory reclaim could end up wanting to free a
1215  *   page belonging to that request that is currently residing in our private
1216  *   plug. By flushing the pending I/O when the process goes to sleep, we avoid
1217  *   this kind of deadlock.
1218  */
1219 void blk_start_plug(struct blk_plug *plug)
1220 {
1221 	blk_start_plug_nr_ios(plug, 1);
1222 }
1223 EXPORT_SYMBOL(blk_start_plug);
1224 
1225 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
1226 {
1227 	LIST_HEAD(callbacks);
1228 
1229 	while (!list_empty(&plug->cb_list)) {
1230 		list_splice_init(&plug->cb_list, &callbacks);
1231 
1232 		while (!list_empty(&callbacks)) {
1233 			struct blk_plug_cb *cb = list_first_entry(&callbacks,
1234 							  struct blk_plug_cb,
1235 							  list);
1236 			list_del(&cb->list);
1237 			cb->callback(cb, from_schedule);
1238 		}
1239 	}
1240 }
1241 
1242 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
1243 				      int size)
1244 {
1245 	struct blk_plug *plug = current->plug;
1246 	struct blk_plug_cb *cb;
1247 
1248 	if (!plug)
1249 		return NULL;
1250 
1251 	list_for_each_entry(cb, &plug->cb_list, list)
1252 		if (cb->callback == unplug && cb->data == data)
1253 			return cb;
1254 
1255 	/* Not currently on the callback list */
1256 	BUG_ON(size < sizeof(*cb));
1257 	cb = kzalloc(size, GFP_ATOMIC);
1258 	if (cb) {
1259 		cb->data = data;
1260 		cb->callback = unplug;
1261 		list_add(&cb->list, &plug->cb_list);
1262 	}
1263 	return cb;
1264 }
1265 EXPORT_SYMBOL(blk_check_plugged);
1266 
1267 void __blk_flush_plug(struct blk_plug *plug, bool from_schedule)
1268 {
1269 	if (!list_empty(&plug->cb_list))
1270 		flush_plug_callbacks(plug, from_schedule);
1271 	blk_mq_flush_plug_list(plug, from_schedule);
1272 	/*
1273 	 * Unconditionally flush out cached requests, even if the unplug
1274 	 * event came from schedule. Since we know hold references to the
1275 	 * queue for cached requests, we don't want a blocked task holding
1276 	 * up a queue freeze/quiesce event.
1277 	 */
1278 	if (unlikely(!rq_list_empty(&plug->cached_rqs)))
1279 		blk_mq_free_plug_rqs(plug);
1280 
1281 	plug->cur_ktime = 0;
1282 	current->flags &= ~PF_BLOCK_TS;
1283 }
1284 
1285 /**
1286  * blk_finish_plug - mark the end of a batch of submitted I/O
1287  * @plug:	The &struct blk_plug passed to blk_start_plug()
1288  *
1289  * Description:
1290  * Indicate that a batch of I/O submissions is complete.  This function
1291  * must be paired with an initial call to blk_start_plug().  The intent
1292  * is to allow the block layer to optimize I/O submission.  See the
1293  * documentation for blk_start_plug() for more information.
1294  */
1295 void blk_finish_plug(struct blk_plug *plug)
1296 {
1297 	if (plug == current->plug) {
1298 		__blk_flush_plug(plug, false);
1299 		current->plug = NULL;
1300 	}
1301 }
1302 EXPORT_SYMBOL(blk_finish_plug);
1303 
1304 void blk_io_schedule(void)
1305 {
1306 	/* Prevent hang_check timer from firing at us during very long I/O */
1307 	unsigned long timeout = sysctl_hung_task_timeout_secs * HZ / 2;
1308 
1309 	if (timeout)
1310 		io_schedule_timeout(timeout);
1311 	else
1312 		io_schedule();
1313 }
1314 
1315 int __init blk_dev_init(void)
1316 {
1317 	BUILD_BUG_ON((__force u32)REQ_OP_LAST >= (1 << REQ_OP_BITS));
1318 	BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
1319 			sizeof_field(struct request, cmd_flags));
1320 	BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
1321 			sizeof_field(struct bio, bi_opf));
1322 
1323 	/* used for unplugging and affects IO latency/throughput - HIGHPRI */
1324 	kblockd_workqueue = alloc_workqueue("kblockd",
1325 					    WQ_MEM_RECLAIM | WQ_HIGHPRI | WQ_PERCPU, 0);
1326 	if (!kblockd_workqueue)
1327 		panic("Failed to create kblockd\n");
1328 
1329 	blk_requestq_cachep = KMEM_CACHE(request_queue, SLAB_PANIC);
1330 
1331 	blk_debugfs_root = debugfs_create_dir("block", NULL);
1332 
1333 	return 0;
1334 }
1335