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