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