]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - block/blk-core.c
blktrace: make do_blk_trace_setup() static
[mirror_ubuntu-bionic-kernel.git] / block / blk-core.c
CommitLineData
1da177e4 1/*
1da177e4
LT
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6728cb0e
JA
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7 * - July2000
1da177e4
LT
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9 */
10
11/*
12 * This handles all read/write requests to block devices
13 */
1da177e4
LT
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/backing-dev.h>
17#include <linux/bio.h>
18#include <linux/blkdev.h>
320ae51f 19#include <linux/blk-mq.h>
1da177e4
LT
20#include <linux/highmem.h>
21#include <linux/mm.h>
22#include <linux/kernel_stat.h>
23#include <linux/string.h>
24#include <linux/init.h>
1da177e4
LT
25#include <linux/completion.h>
26#include <linux/slab.h>
27#include <linux/swap.h>
28#include <linux/writeback.h>
faccbd4b 29#include <linux/task_io_accounting_ops.h>
c17bb495 30#include <linux/fault-inject.h>
73c10101 31#include <linux/list_sort.h>
e3c78ca5 32#include <linux/delay.h>
aaf7c680 33#include <linux/ratelimit.h>
6c954667 34#include <linux/pm_runtime.h>
eea8f41c 35#include <linux/blk-cgroup.h>
55782138
LZ
36
37#define CREATE_TRACE_POINTS
38#include <trace/events/block.h>
1da177e4 39
8324aa91 40#include "blk.h"
43a5e4e2 41#include "blk-mq.h"
bd166ef1 42#include "blk-mq-sched.h"
87760e5e 43#include "blk-wbt.h"
8324aa91 44
d07335e5 45EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
b0da3f0d 46EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
0a82a8d1 47EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
3291fa57 48EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
cbae8d45 49EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
0bfc2455 50
a73f730d
TH
51DEFINE_IDA(blk_queue_ida);
52
1da177e4
LT
53/*
54 * For the allocated request tables
55 */
d674d414 56struct kmem_cache *request_cachep;
1da177e4
LT
57
58/*
59 * For queue allocation
60 */
6728cb0e 61struct kmem_cache *blk_requestq_cachep;
1da177e4 62
1da177e4
LT
63/*
64 * Controlling structure to kblockd
65 */
ff856bad 66static struct workqueue_struct *kblockd_workqueue;
1da177e4 67
d40f75a0
TH
68static void blk_clear_congested(struct request_list *rl, int sync)
69{
d40f75a0
TH
70#ifdef CONFIG_CGROUP_WRITEBACK
71 clear_wb_congested(rl->blkg->wb_congested, sync);
72#else
482cf79c
TH
73 /*
74 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
75 * flip its congestion state for events on other blkcgs.
76 */
77 if (rl == &rl->q->root_rl)
dc3b17cc 78 clear_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
d40f75a0
TH
79#endif
80}
81
82static void blk_set_congested(struct request_list *rl, int sync)
83{
d40f75a0
TH
84#ifdef CONFIG_CGROUP_WRITEBACK
85 set_wb_congested(rl->blkg->wb_congested, sync);
86#else
482cf79c
TH
87 /* see blk_clear_congested() */
88 if (rl == &rl->q->root_rl)
dc3b17cc 89 set_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
d40f75a0
TH
90#endif
91}
92
8324aa91 93void blk_queue_congestion_threshold(struct request_queue *q)
1da177e4
LT
94{
95 int nr;
96
97 nr = q->nr_requests - (q->nr_requests / 8) + 1;
98 if (nr > q->nr_requests)
99 nr = q->nr_requests;
100 q->nr_congestion_on = nr;
101
102 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
103 if (nr < 1)
104 nr = 1;
105 q->nr_congestion_off = nr;
106}
107
2a4aa30c 108void blk_rq_init(struct request_queue *q, struct request *rq)
1da177e4 109{
1afb20f3
FT
110 memset(rq, 0, sizeof(*rq));
111
1da177e4 112 INIT_LIST_HEAD(&rq->queuelist);
242f9dcb 113 INIT_LIST_HEAD(&rq->timeout_list);
c7c22e4d 114 rq->cpu = -1;
63a71386 115 rq->q = q;
a2dec7b3 116 rq->__sector = (sector_t) -1;
2e662b65
JA
117 INIT_HLIST_NODE(&rq->hash);
118 RB_CLEAR_NODE(&rq->rb_node);
63a71386 119 rq->tag = -1;
bd166ef1 120 rq->internal_tag = -1;
b243ddcb 121 rq->start_time = jiffies;
9195291e 122 set_start_time_ns(rq);
09e099d4 123 rq->part = NULL;
1da177e4 124}
2a4aa30c 125EXPORT_SYMBOL(blk_rq_init);
1da177e4 126
5bb23a68
N
127static void req_bio_endio(struct request *rq, struct bio *bio,
128 unsigned int nbytes, int error)
1da177e4 129{
78d8e58a 130 if (error)
4246a0b6 131 bio->bi_error = error;
797e7dbb 132
e8064021 133 if (unlikely(rq->rq_flags & RQF_QUIET))
b7c44ed9 134 bio_set_flag(bio, BIO_QUIET);
08bafc03 135
f79ea416 136 bio_advance(bio, nbytes);
7ba1ba12 137
143a87f4 138 /* don't actually finish bio if it's part of flush sequence */
e8064021 139 if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
4246a0b6 140 bio_endio(bio);
1da177e4 141}
1da177e4 142
1da177e4
LT
143void blk_dump_rq_flags(struct request *rq, char *msg)
144{
aebf526b
CH
145 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
146 rq->rq_disk ? rq->rq_disk->disk_name : "?",
5953316d 147 (unsigned long long) rq->cmd_flags);
1da177e4 148
83096ebf
TH
149 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
150 (unsigned long long)blk_rq_pos(rq),
151 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
b4f42e28
JA
152 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
153 rq->bio, rq->biotail, blk_rq_bytes(rq));
1da177e4 154}
1da177e4
LT
155EXPORT_SYMBOL(blk_dump_rq_flags);
156
3cca6dc1 157static void blk_delay_work(struct work_struct *work)
1da177e4 158{
3cca6dc1 159 struct request_queue *q;
1da177e4 160
3cca6dc1
JA
161 q = container_of(work, struct request_queue, delay_work.work);
162 spin_lock_irq(q->queue_lock);
24ecfbe2 163 __blk_run_queue(q);
3cca6dc1 164 spin_unlock_irq(q->queue_lock);
1da177e4 165}
1da177e4
LT
166
167/**
3cca6dc1
JA
168 * blk_delay_queue - restart queueing after defined interval
169 * @q: The &struct request_queue in question
170 * @msecs: Delay in msecs
1da177e4
LT
171 *
172 * Description:
3cca6dc1
JA
173 * Sometimes queueing needs to be postponed for a little while, to allow
174 * resources to come back. This function will make sure that queueing is
70460571 175 * restarted around the specified time. Queue lock must be held.
3cca6dc1
JA
176 */
177void blk_delay_queue(struct request_queue *q, unsigned long msecs)
2ad8b1ef 178{
70460571
BVA
179 if (likely(!blk_queue_dead(q)))
180 queue_delayed_work(kblockd_workqueue, &q->delay_work,
181 msecs_to_jiffies(msecs));
2ad8b1ef 182}
3cca6dc1 183EXPORT_SYMBOL(blk_delay_queue);
2ad8b1ef 184
21491412
JA
185/**
186 * blk_start_queue_async - asynchronously restart a previously stopped queue
187 * @q: The &struct request_queue in question
188 *
189 * Description:
190 * blk_start_queue_async() will clear the stop flag on the queue, and
191 * ensure that the request_fn for the queue is run from an async
192 * context.
193 **/
194void blk_start_queue_async(struct request_queue *q)
195{
196 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
197 blk_run_queue_async(q);
198}
199EXPORT_SYMBOL(blk_start_queue_async);
200
1da177e4
LT
201/**
202 * blk_start_queue - restart a previously stopped queue
165125e1 203 * @q: The &struct request_queue in question
1da177e4
LT
204 *
205 * Description:
206 * blk_start_queue() will clear the stop flag on the queue, and call
207 * the request_fn for the queue if it was in a stopped state when
208 * entered. Also see blk_stop_queue(). Queue lock must be held.
209 **/
165125e1 210void blk_start_queue(struct request_queue *q)
1da177e4 211{
a038e253
PBG
212 WARN_ON(!irqs_disabled());
213
75ad23bc 214 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
24ecfbe2 215 __blk_run_queue(q);
1da177e4 216}
1da177e4
LT
217EXPORT_SYMBOL(blk_start_queue);
218
219/**
220 * blk_stop_queue - stop a queue
165125e1 221 * @q: The &struct request_queue in question
1da177e4
LT
222 *
223 * Description:
224 * The Linux block layer assumes that a block driver will consume all
225 * entries on the request queue when the request_fn strategy is called.
226 * Often this will not happen, because of hardware limitations (queue
227 * depth settings). If a device driver gets a 'queue full' response,
228 * or if it simply chooses not to queue more I/O at one point, it can
229 * call this function to prevent the request_fn from being called until
230 * the driver has signalled it's ready to go again. This happens by calling
231 * blk_start_queue() to restart queue operations. Queue lock must be held.
232 **/
165125e1 233void blk_stop_queue(struct request_queue *q)
1da177e4 234{
136b5721 235 cancel_delayed_work(&q->delay_work);
75ad23bc 236 queue_flag_set(QUEUE_FLAG_STOPPED, q);
1da177e4
LT
237}
238EXPORT_SYMBOL(blk_stop_queue);
239
240/**
241 * blk_sync_queue - cancel any pending callbacks on a queue
242 * @q: the queue
243 *
244 * Description:
245 * The block layer may perform asynchronous callback activity
246 * on a queue, such as calling the unplug function after a timeout.
247 * A block device may call blk_sync_queue to ensure that any
248 * such activity is cancelled, thus allowing it to release resources
59c51591 249 * that the callbacks might use. The caller must already have made sure
1da177e4
LT
250 * that its ->make_request_fn will not re-add plugging prior to calling
251 * this function.
252 *
da527770 253 * This function does not cancel any asynchronous activity arising
da3dae54 254 * out of elevator or throttling code. That would require elevator_exit()
5efd6113 255 * and blkcg_exit_queue() to be called with queue lock initialized.
da527770 256 *
1da177e4
LT
257 */
258void blk_sync_queue(struct request_queue *q)
259{
70ed28b9 260 del_timer_sync(&q->timeout);
f04c1fe7
ML
261
262 if (q->mq_ops) {
263 struct blk_mq_hw_ctx *hctx;
264 int i;
265
70f4db63 266 queue_for_each_hw_ctx(q, hctx, i) {
27489a3c 267 cancel_work_sync(&hctx->run_work);
70f4db63
CH
268 cancel_delayed_work_sync(&hctx->delay_work);
269 }
f04c1fe7
ML
270 } else {
271 cancel_delayed_work_sync(&q->delay_work);
272 }
1da177e4
LT
273}
274EXPORT_SYMBOL(blk_sync_queue);
275
c246e80d
BVA
276/**
277 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
278 * @q: The queue to run
279 *
280 * Description:
281 * Invoke request handling on a queue if there are any pending requests.
282 * May be used to restart request handling after a request has completed.
283 * This variant runs the queue whether or not the queue has been
284 * stopped. Must be called with the queue lock held and interrupts
285 * disabled. See also @blk_run_queue.
286 */
287inline void __blk_run_queue_uncond(struct request_queue *q)
288{
289 if (unlikely(blk_queue_dead(q)))
290 return;
291
24faf6f6
BVA
292 /*
293 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
294 * the queue lock internally. As a result multiple threads may be
295 * running such a request function concurrently. Keep track of the
296 * number of active request_fn invocations such that blk_drain_queue()
297 * can wait until all these request_fn calls have finished.
298 */
299 q->request_fn_active++;
c246e80d 300 q->request_fn(q);
24faf6f6 301 q->request_fn_active--;
c246e80d 302}
a7928c15 303EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
c246e80d 304
1da177e4 305/**
80a4b58e 306 * __blk_run_queue - run a single device queue
1da177e4 307 * @q: The queue to run
80a4b58e
JA
308 *
309 * Description:
310 * See @blk_run_queue. This variant must be called with the queue lock
24ecfbe2 311 * held and interrupts disabled.
1da177e4 312 */
24ecfbe2 313void __blk_run_queue(struct request_queue *q)
1da177e4 314{
a538cd03
TH
315 if (unlikely(blk_queue_stopped(q)))
316 return;
317
c246e80d 318 __blk_run_queue_uncond(q);
75ad23bc
NP
319}
320EXPORT_SYMBOL(__blk_run_queue);
dac07ec1 321
24ecfbe2
CH
322/**
323 * blk_run_queue_async - run a single device queue in workqueue context
324 * @q: The queue to run
325 *
326 * Description:
327 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
70460571 328 * of us. The caller must hold the queue lock.
24ecfbe2
CH
329 */
330void blk_run_queue_async(struct request_queue *q)
331{
70460571 332 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
e7c2f967 333 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
24ecfbe2 334}
c21e6beb 335EXPORT_SYMBOL(blk_run_queue_async);
24ecfbe2 336
75ad23bc
NP
337/**
338 * blk_run_queue - run a single device queue
339 * @q: The queue to run
80a4b58e
JA
340 *
341 * Description:
342 * Invoke request handling on this queue, if it has pending work to do.
a7f55792 343 * May be used to restart queueing when a request has completed.
75ad23bc
NP
344 */
345void blk_run_queue(struct request_queue *q)
346{
347 unsigned long flags;
348
349 spin_lock_irqsave(q->queue_lock, flags);
24ecfbe2 350 __blk_run_queue(q);
1da177e4
LT
351 spin_unlock_irqrestore(q->queue_lock, flags);
352}
353EXPORT_SYMBOL(blk_run_queue);
354
165125e1 355void blk_put_queue(struct request_queue *q)
483f4afc
AV
356{
357 kobject_put(&q->kobj);
358}
d86e0e83 359EXPORT_SYMBOL(blk_put_queue);
483f4afc 360
e3c78ca5 361/**
807592a4 362 * __blk_drain_queue - drain requests from request_queue
e3c78ca5 363 * @q: queue to drain
c9a929dd 364 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
e3c78ca5 365 *
c9a929dd
TH
366 * Drain requests from @q. If @drain_all is set, all requests are drained.
367 * If not, only ELVPRIV requests are drained. The caller is responsible
368 * for ensuring that no new requests which need to be drained are queued.
e3c78ca5 369 */
807592a4
BVA
370static void __blk_drain_queue(struct request_queue *q, bool drain_all)
371 __releases(q->queue_lock)
372 __acquires(q->queue_lock)
e3c78ca5 373{
458f27a9
AH
374 int i;
375
807592a4
BVA
376 lockdep_assert_held(q->queue_lock);
377
e3c78ca5 378 while (true) {
481a7d64 379 bool drain = false;
e3c78ca5 380
b855b04a
TH
381 /*
382 * The caller might be trying to drain @q before its
383 * elevator is initialized.
384 */
385 if (q->elevator)
386 elv_drain_elevator(q);
387
5efd6113 388 blkcg_drain_queue(q);
e3c78ca5 389
4eabc941
TH
390 /*
391 * This function might be called on a queue which failed
b855b04a
TH
392 * driver init after queue creation or is not yet fully
393 * active yet. Some drivers (e.g. fd and loop) get unhappy
394 * in such cases. Kick queue iff dispatch queue has
395 * something on it and @q has request_fn set.
4eabc941 396 */
b855b04a 397 if (!list_empty(&q->queue_head) && q->request_fn)
4eabc941 398 __blk_run_queue(q);
c9a929dd 399
8a5ecdd4 400 drain |= q->nr_rqs_elvpriv;
24faf6f6 401 drain |= q->request_fn_active;
481a7d64
TH
402
403 /*
404 * Unfortunately, requests are queued at and tracked from
405 * multiple places and there's no single counter which can
406 * be drained. Check all the queues and counters.
407 */
408 if (drain_all) {
e97c293c 409 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
481a7d64
TH
410 drain |= !list_empty(&q->queue_head);
411 for (i = 0; i < 2; i++) {
8a5ecdd4 412 drain |= q->nr_rqs[i];
481a7d64 413 drain |= q->in_flight[i];
7c94e1c1
ML
414 if (fq)
415 drain |= !list_empty(&fq->flush_queue[i]);
481a7d64
TH
416 }
417 }
e3c78ca5 418
481a7d64 419 if (!drain)
e3c78ca5 420 break;
807592a4
BVA
421
422 spin_unlock_irq(q->queue_lock);
423
e3c78ca5 424 msleep(10);
807592a4
BVA
425
426 spin_lock_irq(q->queue_lock);
e3c78ca5 427 }
458f27a9
AH
428
429 /*
430 * With queue marked dead, any woken up waiter will fail the
431 * allocation path, so the wakeup chaining is lost and we're
432 * left with hung waiters. We need to wake up those waiters.
433 */
434 if (q->request_fn) {
a051661c
TH
435 struct request_list *rl;
436
a051661c
TH
437 blk_queue_for_each_rl(rl, q)
438 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
439 wake_up_all(&rl->wait[i]);
458f27a9 440 }
e3c78ca5
TH
441}
442
d732580b
TH
443/**
444 * blk_queue_bypass_start - enter queue bypass mode
445 * @q: queue of interest
446 *
447 * In bypass mode, only the dispatch FIFO queue of @q is used. This
448 * function makes @q enter bypass mode and drains all requests which were
6ecf23af 449 * throttled or issued before. On return, it's guaranteed that no request
80fd9979
TH
450 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
451 * inside queue or RCU read lock.
d732580b
TH
452 */
453void blk_queue_bypass_start(struct request_queue *q)
454{
455 spin_lock_irq(q->queue_lock);
776687bc 456 q->bypass_depth++;
d732580b
TH
457 queue_flag_set(QUEUE_FLAG_BYPASS, q);
458 spin_unlock_irq(q->queue_lock);
459
776687bc
TH
460 /*
461 * Queues start drained. Skip actual draining till init is
462 * complete. This avoids lenghty delays during queue init which
463 * can happen many times during boot.
464 */
465 if (blk_queue_init_done(q)) {
807592a4
BVA
466 spin_lock_irq(q->queue_lock);
467 __blk_drain_queue(q, false);
468 spin_unlock_irq(q->queue_lock);
469
b82d4b19
TH
470 /* ensure blk_queue_bypass() is %true inside RCU read lock */
471 synchronize_rcu();
472 }
d732580b
TH
473}
474EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
475
476/**
477 * blk_queue_bypass_end - leave queue bypass mode
478 * @q: queue of interest
479 *
480 * Leave bypass mode and restore the normal queueing behavior.
481 */
482void blk_queue_bypass_end(struct request_queue *q)
483{
484 spin_lock_irq(q->queue_lock);
485 if (!--q->bypass_depth)
486 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
487 WARN_ON_ONCE(q->bypass_depth < 0);
488 spin_unlock_irq(q->queue_lock);
489}
490EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
491
aed3ea94
JA
492void blk_set_queue_dying(struct request_queue *q)
493{
1b856086
BVA
494 spin_lock_irq(q->queue_lock);
495 queue_flag_set(QUEUE_FLAG_DYING, q);
496 spin_unlock_irq(q->queue_lock);
aed3ea94
JA
497
498 if (q->mq_ops)
499 blk_mq_wake_waiters(q);
500 else {
501 struct request_list *rl;
502
503 blk_queue_for_each_rl(rl, q) {
504 if (rl->rq_pool) {
505 wake_up(&rl->wait[BLK_RW_SYNC]);
506 wake_up(&rl->wait[BLK_RW_ASYNC]);
507 }
508 }
509 }
510}
511EXPORT_SYMBOL_GPL(blk_set_queue_dying);
512
c9a929dd
TH
513/**
514 * blk_cleanup_queue - shutdown a request queue
515 * @q: request queue to shutdown
516 *
c246e80d
BVA
517 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
518 * put it. All future requests will be failed immediately with -ENODEV.
c94a96ac 519 */
6728cb0e 520void blk_cleanup_queue(struct request_queue *q)
483f4afc 521{
c9a929dd 522 spinlock_t *lock = q->queue_lock;
e3335de9 523
3f3299d5 524 /* mark @q DYING, no new request or merges will be allowed afterwards */
483f4afc 525 mutex_lock(&q->sysfs_lock);
aed3ea94 526 blk_set_queue_dying(q);
c9a929dd 527 spin_lock_irq(lock);
6ecf23af 528
80fd9979 529 /*
3f3299d5 530 * A dying queue is permanently in bypass mode till released. Note
80fd9979
TH
531 * that, unlike blk_queue_bypass_start(), we aren't performing
532 * synchronize_rcu() after entering bypass mode to avoid the delay
533 * as some drivers create and destroy a lot of queues while
534 * probing. This is still safe because blk_release_queue() will be
535 * called only after the queue refcnt drops to zero and nothing,
536 * RCU or not, would be traversing the queue by then.
537 */
6ecf23af
TH
538 q->bypass_depth++;
539 queue_flag_set(QUEUE_FLAG_BYPASS, q);
540
c9a929dd
TH
541 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
542 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
3f3299d5 543 queue_flag_set(QUEUE_FLAG_DYING, q);
c9a929dd
TH
544 spin_unlock_irq(lock);
545 mutex_unlock(&q->sysfs_lock);
546
c246e80d
BVA
547 /*
548 * Drain all requests queued before DYING marking. Set DEAD flag to
549 * prevent that q->request_fn() gets invoked after draining finished.
550 */
3ef28e83
DW
551 blk_freeze_queue(q);
552 spin_lock_irq(lock);
553 if (!q->mq_ops)
43a5e4e2 554 __blk_drain_queue(q, true);
c246e80d 555 queue_flag_set(QUEUE_FLAG_DEAD, q);
807592a4 556 spin_unlock_irq(lock);
c9a929dd 557
5a48fc14
DW
558 /* for synchronous bio-based driver finish in-flight integrity i/o */
559 blk_flush_integrity();
560
c9a929dd 561 /* @q won't process any more request, flush async actions */
dc3b17cc 562 del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
c9a929dd
TH
563 blk_sync_queue(q);
564
45a9c9d9
BVA
565 if (q->mq_ops)
566 blk_mq_free_queue(q);
3ef28e83 567 percpu_ref_exit(&q->q_usage_counter);
45a9c9d9 568
5e5cfac0
AH
569 spin_lock_irq(lock);
570 if (q->queue_lock != &q->__queue_lock)
571 q->queue_lock = &q->__queue_lock;
572 spin_unlock_irq(lock);
573
dc3b17cc 574 bdi_unregister(q->backing_dev_info);
0dba1314 575 put_disk_devt(q->disk_devt);
6cd18e71 576
c9a929dd 577 /* @q is and will stay empty, shutdown and put */
483f4afc
AV
578 blk_put_queue(q);
579}
1da177e4
LT
580EXPORT_SYMBOL(blk_cleanup_queue);
581
271508db 582/* Allocate memory local to the request queue */
6d247d7f 583static void *alloc_request_simple(gfp_t gfp_mask, void *data)
271508db 584{
6d247d7f
CH
585 struct request_queue *q = data;
586
587 return kmem_cache_alloc_node(request_cachep, gfp_mask, q->node);
271508db
DR
588}
589
6d247d7f 590static void free_request_simple(void *element, void *data)
271508db
DR
591{
592 kmem_cache_free(request_cachep, element);
593}
594
6d247d7f
CH
595static void *alloc_request_size(gfp_t gfp_mask, void *data)
596{
597 struct request_queue *q = data;
598 struct request *rq;
599
600 rq = kmalloc_node(sizeof(struct request) + q->cmd_size, gfp_mask,
601 q->node);
602 if (rq && q->init_rq_fn && q->init_rq_fn(q, rq, gfp_mask) < 0) {
603 kfree(rq);
604 rq = NULL;
605 }
606 return rq;
607}
608
609static void free_request_size(void *element, void *data)
610{
611 struct request_queue *q = data;
612
613 if (q->exit_rq_fn)
614 q->exit_rq_fn(q, element);
615 kfree(element);
616}
617
5b788ce3
TH
618int blk_init_rl(struct request_list *rl, struct request_queue *q,
619 gfp_t gfp_mask)
1da177e4 620{
1abec4fd
MS
621 if (unlikely(rl->rq_pool))
622 return 0;
623
5b788ce3 624 rl->q = q;
1faa16d2
JA
625 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
626 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
1faa16d2
JA
627 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
628 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
1da177e4 629
6d247d7f
CH
630 if (q->cmd_size) {
631 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
632 alloc_request_size, free_request_size,
633 q, gfp_mask, q->node);
634 } else {
635 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
636 alloc_request_simple, free_request_simple,
637 q, gfp_mask, q->node);
638 }
1da177e4
LT
639 if (!rl->rq_pool)
640 return -ENOMEM;
641
642 return 0;
643}
644
5b788ce3
TH
645void blk_exit_rl(struct request_list *rl)
646{
647 if (rl->rq_pool)
648 mempool_destroy(rl->rq_pool);
649}
650
165125e1 651struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
1da177e4 652{
c304a51b 653 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
1946089a
CL
654}
655EXPORT_SYMBOL(blk_alloc_queue);
1da177e4 656
6f3b0e8b 657int blk_queue_enter(struct request_queue *q, bool nowait)
3ef28e83
DW
658{
659 while (true) {
660 int ret;
661
662 if (percpu_ref_tryget_live(&q->q_usage_counter))
663 return 0;
664
6f3b0e8b 665 if (nowait)
3ef28e83
DW
666 return -EBUSY;
667
668 ret = wait_event_interruptible(q->mq_freeze_wq,
669 !atomic_read(&q->mq_freeze_depth) ||
670 blk_queue_dying(q));
671 if (blk_queue_dying(q))
672 return -ENODEV;
673 if (ret)
674 return ret;
675 }
676}
677
678void blk_queue_exit(struct request_queue *q)
679{
680 percpu_ref_put(&q->q_usage_counter);
681}
682
683static void blk_queue_usage_counter_release(struct percpu_ref *ref)
684{
685 struct request_queue *q =
686 container_of(ref, struct request_queue, q_usage_counter);
687
688 wake_up_all(&q->mq_freeze_wq);
689}
690
287922eb
CH
691static void blk_rq_timed_out_timer(unsigned long data)
692{
693 struct request_queue *q = (struct request_queue *)data;
694
695 kblockd_schedule_work(&q->timeout_work);
696}
697
165125e1 698struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1946089a 699{
165125e1 700 struct request_queue *q;
1946089a 701
8324aa91 702 q = kmem_cache_alloc_node(blk_requestq_cachep,
94f6030c 703 gfp_mask | __GFP_ZERO, node_id);
1da177e4
LT
704 if (!q)
705 return NULL;
706
00380a40 707 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
a73f730d 708 if (q->id < 0)
3d2936f4 709 goto fail_q;
a73f730d 710
54efd50b
KO
711 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
712 if (!q->bio_split)
713 goto fail_id;
714
d03f6cdc
JK
715 q->backing_dev_info = bdi_alloc_node(gfp_mask, node_id);
716 if (!q->backing_dev_info)
717 goto fail_split;
718
dc3b17cc 719 q->backing_dev_info->ra_pages =
09cbfeaf 720 (VM_MAX_READAHEAD * 1024) / PAGE_SIZE;
dc3b17cc
JK
721 q->backing_dev_info->capabilities = BDI_CAP_CGROUP_WRITEBACK;
722 q->backing_dev_info->name = "block";
5151412d 723 q->node = node_id;
0989a025 724
dc3b17cc 725 setup_timer(&q->backing_dev_info->laptop_mode_wb_timer,
31373d09 726 laptop_mode_timer_fn, (unsigned long) q);
242f9dcb 727 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
b855b04a 728 INIT_LIST_HEAD(&q->queue_head);
242f9dcb 729 INIT_LIST_HEAD(&q->timeout_list);
a612fddf 730 INIT_LIST_HEAD(&q->icq_list);
4eef3049 731#ifdef CONFIG_BLK_CGROUP
e8989fae 732 INIT_LIST_HEAD(&q->blkg_list);
4eef3049 733#endif
3cca6dc1 734 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
483f4afc 735
8324aa91 736 kobject_init(&q->kobj, &blk_queue_ktype);
1da177e4 737
483f4afc 738 mutex_init(&q->sysfs_lock);
e7e72bf6 739 spin_lock_init(&q->__queue_lock);
483f4afc 740
c94a96ac
VG
741 /*
742 * By default initialize queue_lock to internal lock and driver can
743 * override it later if need be.
744 */
745 q->queue_lock = &q->__queue_lock;
746
b82d4b19
TH
747 /*
748 * A queue starts its life with bypass turned on to avoid
749 * unnecessary bypass on/off overhead and nasty surprises during
749fefe6
TH
750 * init. The initial bypass will be finished when the queue is
751 * registered by blk_register_queue().
b82d4b19
TH
752 */
753 q->bypass_depth = 1;
754 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
755
320ae51f
JA
756 init_waitqueue_head(&q->mq_freeze_wq);
757
3ef28e83
DW
758 /*
759 * Init percpu_ref in atomic mode so that it's faster to shutdown.
760 * See blk_register_queue() for details.
761 */
762 if (percpu_ref_init(&q->q_usage_counter,
763 blk_queue_usage_counter_release,
764 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
fff4996b 765 goto fail_bdi;
f51b802c 766
3ef28e83
DW
767 if (blkcg_init_queue(q))
768 goto fail_ref;
769
1da177e4 770 return q;
a73f730d 771
3ef28e83
DW
772fail_ref:
773 percpu_ref_exit(&q->q_usage_counter);
fff4996b 774fail_bdi:
d03f6cdc 775 bdi_put(q->backing_dev_info);
54efd50b
KO
776fail_split:
777 bioset_free(q->bio_split);
a73f730d
TH
778fail_id:
779 ida_simple_remove(&blk_queue_ida, q->id);
780fail_q:
781 kmem_cache_free(blk_requestq_cachep, q);
782 return NULL;
1da177e4 783}
1946089a 784EXPORT_SYMBOL(blk_alloc_queue_node);
1da177e4
LT
785
786/**
787 * blk_init_queue - prepare a request queue for use with a block device
788 * @rfn: The function to be called to process requests that have been
789 * placed on the queue.
790 * @lock: Request queue spin lock
791 *
792 * Description:
793 * If a block device wishes to use the standard request handling procedures,
794 * which sorts requests and coalesces adjacent requests, then it must
795 * call blk_init_queue(). The function @rfn will be called when there
796 * are requests on the queue that need to be processed. If the device
797 * supports plugging, then @rfn may not be called immediately when requests
798 * are available on the queue, but may be called at some time later instead.
799 * Plugged queues are generally unplugged when a buffer belonging to one
800 * of the requests on the queue is needed, or due to memory pressure.
801 *
802 * @rfn is not required, or even expected, to remove all requests off the
803 * queue, but only as many as it can handle at a time. If it does leave
804 * requests on the queue, it is responsible for arranging that the requests
805 * get dealt with eventually.
806 *
807 * The queue spin lock must be held while manipulating the requests on the
a038e253
PBG
808 * request queue; this lock will be taken also from interrupt context, so irq
809 * disabling is needed for it.
1da177e4 810 *
710027a4 811 * Function returns a pointer to the initialized request queue, or %NULL if
1da177e4
LT
812 * it didn't succeed.
813 *
814 * Note:
815 * blk_init_queue() must be paired with a blk_cleanup_queue() call
816 * when the block device is deactivated (such as at module unload).
817 **/
1946089a 818
165125e1 819struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1da177e4 820{
c304a51b 821 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
1946089a
CL
822}
823EXPORT_SYMBOL(blk_init_queue);
824
165125e1 825struct request_queue *
1946089a
CL
826blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
827{
5ea708d1 828 struct request_queue *q;
1da177e4 829
5ea708d1
CH
830 q = blk_alloc_queue_node(GFP_KERNEL, node_id);
831 if (!q)
c86d1b8a
MS
832 return NULL;
833
5ea708d1
CH
834 q->request_fn = rfn;
835 if (lock)
836 q->queue_lock = lock;
837 if (blk_init_allocated_queue(q) < 0) {
838 blk_cleanup_queue(q);
839 return NULL;
840 }
18741986 841
7982e90c 842 return q;
01effb0d
MS
843}
844EXPORT_SYMBOL(blk_init_queue_node);
845
dece1635 846static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
336b7e1f 847
1da177e4 848
5ea708d1
CH
849int blk_init_allocated_queue(struct request_queue *q)
850{
6d247d7f 851 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
ba483388 852 if (!q->fq)
5ea708d1 853 return -ENOMEM;
7982e90c 854
6d247d7f
CH
855 if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
856 goto out_free_flush_queue;
857
a051661c 858 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
6d247d7f 859 goto out_exit_flush_rq;
1da177e4 860
287922eb 861 INIT_WORK(&q->timeout_work, blk_timeout_work);
60ea8226 862 q->queue_flags |= QUEUE_FLAG_DEFAULT;
c94a96ac 863
f3b144aa
JA
864 /*
865 * This also sets hw/phys segments, boundary and size
866 */
c20e8de2 867 blk_queue_make_request(q, blk_queue_bio);
1da177e4 868
44ec9542
AS
869 q->sg_reserved_size = INT_MAX;
870
eb1c160b
TS
871 /* Protect q->elevator from elevator_change */
872 mutex_lock(&q->sysfs_lock);
873
b82d4b19 874 /* init elevator */
eb1c160b
TS
875 if (elevator_init(q, NULL)) {
876 mutex_unlock(&q->sysfs_lock);
6d247d7f 877 goto out_exit_flush_rq;
eb1c160b
TS
878 }
879
880 mutex_unlock(&q->sysfs_lock);
5ea708d1 881 return 0;
708f04d2 882
6d247d7f
CH
883out_exit_flush_rq:
884 if (q->exit_rq_fn)
885 q->exit_rq_fn(q, q->fq->flush_rq);
886out_free_flush_queue:
ba483388 887 blk_free_flush_queue(q->fq);
87760e5e 888 wbt_exit(q);
5ea708d1 889 return -ENOMEM;
1da177e4 890}
5151412d 891EXPORT_SYMBOL(blk_init_allocated_queue);
1da177e4 892
09ac46c4 893bool blk_get_queue(struct request_queue *q)
1da177e4 894{
3f3299d5 895 if (likely(!blk_queue_dying(q))) {
09ac46c4
TH
896 __blk_get_queue(q);
897 return true;
1da177e4
LT
898 }
899
09ac46c4 900 return false;
1da177e4 901}
d86e0e83 902EXPORT_SYMBOL(blk_get_queue);
1da177e4 903
5b788ce3 904static inline void blk_free_request(struct request_list *rl, struct request *rq)
1da177e4 905{
e8064021 906 if (rq->rq_flags & RQF_ELVPRIV) {
5b788ce3 907 elv_put_request(rl->q, rq);
f1f8cc94 908 if (rq->elv.icq)
11a3122f 909 put_io_context(rq->elv.icq->ioc);
f1f8cc94
TH
910 }
911
5b788ce3 912 mempool_free(rq, rl->rq_pool);
1da177e4
LT
913}
914
1da177e4
LT
915/*
916 * ioc_batching returns true if the ioc is a valid batching request and
917 * should be given priority access to a request.
918 */
165125e1 919static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
920{
921 if (!ioc)
922 return 0;
923
924 /*
925 * Make sure the process is able to allocate at least 1 request
926 * even if the batch times out, otherwise we could theoretically
927 * lose wakeups.
928 */
929 return ioc->nr_batch_requests == q->nr_batching ||
930 (ioc->nr_batch_requests > 0
931 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
932}
933
934/*
935 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
936 * will cause the process to be a "batcher" on all queues in the system. This
937 * is the behaviour we want though - once it gets a wakeup it should be given
938 * a nice run.
939 */
165125e1 940static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
941{
942 if (!ioc || ioc_batching(q, ioc))
943 return;
944
945 ioc->nr_batch_requests = q->nr_batching;
946 ioc->last_waited = jiffies;
947}
948
5b788ce3 949static void __freed_request(struct request_list *rl, int sync)
1da177e4 950{
5b788ce3 951 struct request_queue *q = rl->q;
1da177e4 952
d40f75a0
TH
953 if (rl->count[sync] < queue_congestion_off_threshold(q))
954 blk_clear_congested(rl, sync);
1da177e4 955
1faa16d2
JA
956 if (rl->count[sync] + 1 <= q->nr_requests) {
957 if (waitqueue_active(&rl->wait[sync]))
958 wake_up(&rl->wait[sync]);
1da177e4 959
5b788ce3 960 blk_clear_rl_full(rl, sync);
1da177e4
LT
961 }
962}
963
964/*
965 * A request has just been released. Account for it, update the full and
966 * congestion status, wake up any waiters. Called under q->queue_lock.
967 */
e8064021
CH
968static void freed_request(struct request_list *rl, bool sync,
969 req_flags_t rq_flags)
1da177e4 970{
5b788ce3 971 struct request_queue *q = rl->q;
1da177e4 972
8a5ecdd4 973 q->nr_rqs[sync]--;
1faa16d2 974 rl->count[sync]--;
e8064021 975 if (rq_flags & RQF_ELVPRIV)
8a5ecdd4 976 q->nr_rqs_elvpriv--;
1da177e4 977
5b788ce3 978 __freed_request(rl, sync);
1da177e4 979
1faa16d2 980 if (unlikely(rl->starved[sync ^ 1]))
5b788ce3 981 __freed_request(rl, sync ^ 1);
1da177e4
LT
982}
983
e3a2b3f9
JA
984int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
985{
986 struct request_list *rl;
d40f75a0 987 int on_thresh, off_thresh;
e3a2b3f9
JA
988
989 spin_lock_irq(q->queue_lock);
990 q->nr_requests = nr;
991 blk_queue_congestion_threshold(q);
d40f75a0
TH
992 on_thresh = queue_congestion_on_threshold(q);
993 off_thresh = queue_congestion_off_threshold(q);
e3a2b3f9 994
d40f75a0
TH
995 blk_queue_for_each_rl(rl, q) {
996 if (rl->count[BLK_RW_SYNC] >= on_thresh)
997 blk_set_congested(rl, BLK_RW_SYNC);
998 else if (rl->count[BLK_RW_SYNC] < off_thresh)
999 blk_clear_congested(rl, BLK_RW_SYNC);
e3a2b3f9 1000
d40f75a0
TH
1001 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
1002 blk_set_congested(rl, BLK_RW_ASYNC);
1003 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
1004 blk_clear_congested(rl, BLK_RW_ASYNC);
e3a2b3f9 1005
e3a2b3f9
JA
1006 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
1007 blk_set_rl_full(rl, BLK_RW_SYNC);
1008 } else {
1009 blk_clear_rl_full(rl, BLK_RW_SYNC);
1010 wake_up(&rl->wait[BLK_RW_SYNC]);
1011 }
1012
1013 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1014 blk_set_rl_full(rl, BLK_RW_ASYNC);
1015 } else {
1016 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1017 wake_up(&rl->wait[BLK_RW_ASYNC]);
1018 }
1019 }
1020
1021 spin_unlock_irq(q->queue_lock);
1022 return 0;
1023}
1024
da8303c6 1025/**
a06e05e6 1026 * __get_request - get a free request
5b788ce3 1027 * @rl: request list to allocate from
ef295ecf 1028 * @op: operation and flags
da8303c6
TH
1029 * @bio: bio to allocate request for (can be %NULL)
1030 * @gfp_mask: allocation mask
1031 *
1032 * Get a free request from @q. This function may fail under memory
1033 * pressure or if @q is dead.
1034 *
da3dae54 1035 * Must be called with @q->queue_lock held and,
a492f075
JL
1036 * Returns ERR_PTR on failure, with @q->queue_lock held.
1037 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1038 */
ef295ecf
CH
1039static struct request *__get_request(struct request_list *rl, unsigned int op,
1040 struct bio *bio, gfp_t gfp_mask)
1da177e4 1041{
5b788ce3 1042 struct request_queue *q = rl->q;
b679281a 1043 struct request *rq;
7f4b35d1
TH
1044 struct elevator_type *et = q->elevator->type;
1045 struct io_context *ioc = rq_ioc(bio);
f1f8cc94 1046 struct io_cq *icq = NULL;
ef295ecf 1047 const bool is_sync = op_is_sync(op);
75eb6c37 1048 int may_queue;
e8064021 1049 req_flags_t rq_flags = RQF_ALLOCED;
88ee5ef1 1050
3f3299d5 1051 if (unlikely(blk_queue_dying(q)))
a492f075 1052 return ERR_PTR(-ENODEV);
da8303c6 1053
ef295ecf 1054 may_queue = elv_may_queue(q, op);
88ee5ef1
JA
1055 if (may_queue == ELV_MQUEUE_NO)
1056 goto rq_starved;
1057
1faa16d2
JA
1058 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1059 if (rl->count[is_sync]+1 >= q->nr_requests) {
88ee5ef1
JA
1060 /*
1061 * The queue will fill after this allocation, so set
1062 * it as full, and mark this process as "batching".
1063 * This process will be allowed to complete a batch of
1064 * requests, others will be blocked.
1065 */
5b788ce3 1066 if (!blk_rl_full(rl, is_sync)) {
88ee5ef1 1067 ioc_set_batching(q, ioc);
5b788ce3 1068 blk_set_rl_full(rl, is_sync);
88ee5ef1
JA
1069 } else {
1070 if (may_queue != ELV_MQUEUE_MUST
1071 && !ioc_batching(q, ioc)) {
1072 /*
1073 * The queue is full and the allocating
1074 * process is not a "batcher", and not
1075 * exempted by the IO scheduler
1076 */
a492f075 1077 return ERR_PTR(-ENOMEM);
88ee5ef1
JA
1078 }
1079 }
1da177e4 1080 }
d40f75a0 1081 blk_set_congested(rl, is_sync);
1da177e4
LT
1082 }
1083
082cf69e
JA
1084 /*
1085 * Only allow batching queuers to allocate up to 50% over the defined
1086 * limit of requests, otherwise we could have thousands of requests
1087 * allocated with any setting of ->nr_requests
1088 */
1faa16d2 1089 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
a492f075 1090 return ERR_PTR(-ENOMEM);
fd782a4a 1091
8a5ecdd4 1092 q->nr_rqs[is_sync]++;
1faa16d2
JA
1093 rl->count[is_sync]++;
1094 rl->starved[is_sync] = 0;
cb98fc8b 1095
f1f8cc94
TH
1096 /*
1097 * Decide whether the new request will be managed by elevator. If
e8064021 1098 * so, mark @rq_flags and increment elvpriv. Non-zero elvpriv will
f1f8cc94
TH
1099 * prevent the current elevator from being destroyed until the new
1100 * request is freed. This guarantees icq's won't be destroyed and
1101 * makes creating new ones safe.
1102 *
e6f7f93d
CH
1103 * Flush requests do not use the elevator so skip initialization.
1104 * This allows a request to share the flush and elevator data.
1105 *
f1f8cc94
TH
1106 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1107 * it will be created after releasing queue_lock.
1108 */
e6f7f93d 1109 if (!op_is_flush(op) && !blk_queue_bypass(q)) {
e8064021 1110 rq_flags |= RQF_ELVPRIV;
8a5ecdd4 1111 q->nr_rqs_elvpriv++;
f1f8cc94
TH
1112 if (et->icq_cache && ioc)
1113 icq = ioc_lookup_icq(ioc, q);
9d5a4e94 1114 }
cb98fc8b 1115
f253b86b 1116 if (blk_queue_io_stat(q))
e8064021 1117 rq_flags |= RQF_IO_STAT;
1da177e4
LT
1118 spin_unlock_irq(q->queue_lock);
1119
29e2b09a 1120 /* allocate and init request */
5b788ce3 1121 rq = mempool_alloc(rl->rq_pool, gfp_mask);
29e2b09a 1122 if (!rq)
b679281a 1123 goto fail_alloc;
1da177e4 1124
29e2b09a 1125 blk_rq_init(q, rq);
a051661c 1126 blk_rq_set_rl(rq, rl);
5dc8b362 1127 blk_rq_set_prio(rq, ioc);
ef295ecf 1128 rq->cmd_flags = op;
e8064021 1129 rq->rq_flags = rq_flags;
29e2b09a 1130
aaf7c680 1131 /* init elvpriv */
e8064021 1132 if (rq_flags & RQF_ELVPRIV) {
aaf7c680 1133 if (unlikely(et->icq_cache && !icq)) {
7f4b35d1
TH
1134 if (ioc)
1135 icq = ioc_create_icq(ioc, q, gfp_mask);
aaf7c680
TH
1136 if (!icq)
1137 goto fail_elvpriv;
29e2b09a 1138 }
aaf7c680
TH
1139
1140 rq->elv.icq = icq;
1141 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1142 goto fail_elvpriv;
1143
1144 /* @rq->elv.icq holds io_context until @rq is freed */
29e2b09a
TH
1145 if (icq)
1146 get_io_context(icq->ioc);
1147 }
aaf7c680 1148out:
88ee5ef1
JA
1149 /*
1150 * ioc may be NULL here, and ioc_batching will be false. That's
1151 * OK, if the queue is under the request limit then requests need
1152 * not count toward the nr_batch_requests limit. There will always
1153 * be some limit enforced by BLK_BATCH_TIME.
1154 */
1da177e4
LT
1155 if (ioc_batching(q, ioc))
1156 ioc->nr_batch_requests--;
6728cb0e 1157
e6a40b09 1158 trace_block_getrq(q, bio, op);
1da177e4 1159 return rq;
b679281a 1160
aaf7c680
TH
1161fail_elvpriv:
1162 /*
1163 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1164 * and may fail indefinitely under memory pressure and thus
1165 * shouldn't stall IO. Treat this request as !elvpriv. This will
1166 * disturb iosched and blkcg but weird is bettern than dead.
1167 */
7b2b10e0 1168 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
dc3b17cc 1169 __func__, dev_name(q->backing_dev_info->dev));
aaf7c680 1170
e8064021 1171 rq->rq_flags &= ~RQF_ELVPRIV;
aaf7c680
TH
1172 rq->elv.icq = NULL;
1173
1174 spin_lock_irq(q->queue_lock);
8a5ecdd4 1175 q->nr_rqs_elvpriv--;
aaf7c680
TH
1176 spin_unlock_irq(q->queue_lock);
1177 goto out;
1178
b679281a
TH
1179fail_alloc:
1180 /*
1181 * Allocation failed presumably due to memory. Undo anything we
1182 * might have messed up.
1183 *
1184 * Allocating task should really be put onto the front of the wait
1185 * queue, but this is pretty rare.
1186 */
1187 spin_lock_irq(q->queue_lock);
e8064021 1188 freed_request(rl, is_sync, rq_flags);
b679281a
TH
1189
1190 /*
1191 * in the very unlikely event that allocation failed and no
1192 * requests for this direction was pending, mark us starved so that
1193 * freeing of a request in the other direction will notice
1194 * us. another possible fix would be to split the rq mempool into
1195 * READ and WRITE
1196 */
1197rq_starved:
1198 if (unlikely(rl->count[is_sync] == 0))
1199 rl->starved[is_sync] = 1;
a492f075 1200 return ERR_PTR(-ENOMEM);
1da177e4
LT
1201}
1202
da8303c6 1203/**
a06e05e6 1204 * get_request - get a free request
da8303c6 1205 * @q: request_queue to allocate request from
ef295ecf 1206 * @op: operation and flags
da8303c6 1207 * @bio: bio to allocate request for (can be %NULL)
a06e05e6 1208 * @gfp_mask: allocation mask
da8303c6 1209 *
d0164adc
MG
1210 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1211 * this function keeps retrying under memory pressure and fails iff @q is dead.
d6344532 1212 *
da3dae54 1213 * Must be called with @q->queue_lock held and,
a492f075
JL
1214 * Returns ERR_PTR on failure, with @q->queue_lock held.
1215 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1216 */
ef295ecf
CH
1217static struct request *get_request(struct request_queue *q, unsigned int op,
1218 struct bio *bio, gfp_t gfp_mask)
1da177e4 1219{
ef295ecf 1220 const bool is_sync = op_is_sync(op);
a06e05e6 1221 DEFINE_WAIT(wait);
a051661c 1222 struct request_list *rl;
1da177e4 1223 struct request *rq;
a051661c
TH
1224
1225 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
a06e05e6 1226retry:
ef295ecf 1227 rq = __get_request(rl, op, bio, gfp_mask);
a492f075 1228 if (!IS_ERR(rq))
a06e05e6 1229 return rq;
1da177e4 1230
d0164adc 1231 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
a051661c 1232 blk_put_rl(rl);
a492f075 1233 return rq;
a051661c 1234 }
1da177e4 1235
a06e05e6
TH
1236 /* wait on @rl and retry */
1237 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1238 TASK_UNINTERRUPTIBLE);
1da177e4 1239
e6a40b09 1240 trace_block_sleeprq(q, bio, op);
1da177e4 1241
a06e05e6
TH
1242 spin_unlock_irq(q->queue_lock);
1243 io_schedule();
d6344532 1244
a06e05e6
TH
1245 /*
1246 * After sleeping, we become a "batching" process and will be able
1247 * to allocate at least one request, and up to a big batch of them
1248 * for a small period time. See ioc_batching, ioc_set_batching
1249 */
a06e05e6 1250 ioc_set_batching(q, current->io_context);
05caf8db 1251
a06e05e6
TH
1252 spin_lock_irq(q->queue_lock);
1253 finish_wait(&rl->wait[is_sync], &wait);
1da177e4 1254
a06e05e6 1255 goto retry;
1da177e4
LT
1256}
1257
320ae51f
JA
1258static struct request *blk_old_get_request(struct request_queue *q, int rw,
1259 gfp_t gfp_mask)
1da177e4
LT
1260{
1261 struct request *rq;
1262
7f4b35d1
TH
1263 /* create ioc upfront */
1264 create_io_context(gfp_mask, q->node);
1265
d6344532 1266 spin_lock_irq(q->queue_lock);
ef295ecf 1267 rq = get_request(q, rw, NULL, gfp_mask);
0c4de0f3 1268 if (IS_ERR(rq)) {
da8303c6 1269 spin_unlock_irq(q->queue_lock);
0c4de0f3
CH
1270 return rq;
1271 }
1da177e4 1272
0c4de0f3
CH
1273 /* q->queue_lock is unlocked at this point */
1274 rq->__data_len = 0;
1275 rq->__sector = (sector_t) -1;
1276 rq->bio = rq->biotail = NULL;
1da177e4
LT
1277 return rq;
1278}
320ae51f
JA
1279
1280struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1281{
1282 if (q->mq_ops)
6f3b0e8b
CH
1283 return blk_mq_alloc_request(q, rw,
1284 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1285 0 : BLK_MQ_REQ_NOWAIT);
320ae51f
JA
1286 else
1287 return blk_old_get_request(q, rw, gfp_mask);
1288}
1da177e4
LT
1289EXPORT_SYMBOL(blk_get_request);
1290
1291/**
1292 * blk_requeue_request - put a request back on queue
1293 * @q: request queue where request should be inserted
1294 * @rq: request to be inserted
1295 *
1296 * Description:
1297 * Drivers often keep queueing requests until the hardware cannot accept
1298 * more, when that condition happens we need to put the request back
1299 * on the queue. Must be called with queue lock held.
1300 */
165125e1 1301void blk_requeue_request(struct request_queue *q, struct request *rq)
1da177e4 1302{
242f9dcb
JA
1303 blk_delete_timer(rq);
1304 blk_clear_rq_complete(rq);
5f3ea37c 1305 trace_block_rq_requeue(q, rq);
87760e5e 1306 wbt_requeue(q->rq_wb, &rq->issue_stat);
2056a782 1307
e8064021 1308 if (rq->rq_flags & RQF_QUEUED)
1da177e4
LT
1309 blk_queue_end_tag(q, rq);
1310
ba396a6c
JB
1311 BUG_ON(blk_queued_rq(rq));
1312
1da177e4
LT
1313 elv_requeue_request(q, rq);
1314}
1da177e4
LT
1315EXPORT_SYMBOL(blk_requeue_request);
1316
73c10101
JA
1317static void add_acct_request(struct request_queue *q, struct request *rq,
1318 int where)
1319{
320ae51f 1320 blk_account_io_start(rq, true);
7eaceacc 1321 __elv_add_request(q, rq, where);
73c10101
JA
1322}
1323
074a7aca
TH
1324static void part_round_stats_single(int cpu, struct hd_struct *part,
1325 unsigned long now)
1326{
7276d02e
JA
1327 int inflight;
1328
074a7aca
TH
1329 if (now == part->stamp)
1330 return;
1331
7276d02e
JA
1332 inflight = part_in_flight(part);
1333 if (inflight) {
074a7aca 1334 __part_stat_add(cpu, part, time_in_queue,
7276d02e 1335 inflight * (now - part->stamp));
074a7aca
TH
1336 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1337 }
1338 part->stamp = now;
1339}
1340
1341/**
496aa8a9
RD
1342 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1343 * @cpu: cpu number for stats access
1344 * @part: target partition
1da177e4
LT
1345 *
1346 * The average IO queue length and utilisation statistics are maintained
1347 * by observing the current state of the queue length and the amount of
1348 * time it has been in this state for.
1349 *
1350 * Normally, that accounting is done on IO completion, but that can result
1351 * in more than a second's worth of IO being accounted for within any one
1352 * second, leading to >100% utilisation. To deal with that, we call this
1353 * function to do a round-off before returning the results when reading
1354 * /proc/diskstats. This accounts immediately for all queue usage up to
1355 * the current jiffies and restarts the counters again.
1356 */
c9959059 1357void part_round_stats(int cpu, struct hd_struct *part)
6f2576af
JM
1358{
1359 unsigned long now = jiffies;
1360
074a7aca
TH
1361 if (part->partno)
1362 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1363 part_round_stats_single(cpu, part, now);
6f2576af 1364}
074a7aca 1365EXPORT_SYMBOL_GPL(part_round_stats);
6f2576af 1366
47fafbc7 1367#ifdef CONFIG_PM
c8158819
LM
1368static void blk_pm_put_request(struct request *rq)
1369{
e8064021 1370 if (rq->q->dev && !(rq->rq_flags & RQF_PM) && !--rq->q->nr_pending)
c8158819
LM
1371 pm_runtime_mark_last_busy(rq->q->dev);
1372}
1373#else
1374static inline void blk_pm_put_request(struct request *rq) {}
1375#endif
1376
1da177e4
LT
1377/*
1378 * queue lock must be held
1379 */
165125e1 1380void __blk_put_request(struct request_queue *q, struct request *req)
1da177e4 1381{
e8064021
CH
1382 req_flags_t rq_flags = req->rq_flags;
1383
1da177e4
LT
1384 if (unlikely(!q))
1385 return;
1da177e4 1386
6f5ba581
CH
1387 if (q->mq_ops) {
1388 blk_mq_free_request(req);
1389 return;
1390 }
1391
c8158819
LM
1392 blk_pm_put_request(req);
1393
8922e16c
TH
1394 elv_completed_request(q, req);
1395
1cd96c24
BH
1396 /* this is a bio leak */
1397 WARN_ON(req->bio != NULL);
1398
87760e5e
JA
1399 wbt_done(q->rq_wb, &req->issue_stat);
1400
1da177e4
LT
1401 /*
1402 * Request may not have originated from ll_rw_blk. if not,
1403 * it didn't come out of our reserved rq pools
1404 */
e8064021 1405 if (rq_flags & RQF_ALLOCED) {
a051661c 1406 struct request_list *rl = blk_rq_rl(req);
ef295ecf 1407 bool sync = op_is_sync(req->cmd_flags);
1da177e4 1408
1da177e4 1409 BUG_ON(!list_empty(&req->queuelist));
360f92c2 1410 BUG_ON(ELV_ON_HASH(req));
1da177e4 1411
a051661c 1412 blk_free_request(rl, req);
e8064021 1413 freed_request(rl, sync, rq_flags);
a051661c 1414 blk_put_rl(rl);
1da177e4
LT
1415 }
1416}
6e39b69e
MC
1417EXPORT_SYMBOL_GPL(__blk_put_request);
1418
1da177e4
LT
1419void blk_put_request(struct request *req)
1420{
165125e1 1421 struct request_queue *q = req->q;
8922e16c 1422
320ae51f
JA
1423 if (q->mq_ops)
1424 blk_mq_free_request(req);
1425 else {
1426 unsigned long flags;
1427
1428 spin_lock_irqsave(q->queue_lock, flags);
1429 __blk_put_request(q, req);
1430 spin_unlock_irqrestore(q->queue_lock, flags);
1431 }
1da177e4 1432}
1da177e4
LT
1433EXPORT_SYMBOL(blk_put_request);
1434
320ae51f
JA
1435bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1436 struct bio *bio)
73c10101 1437{
1eff9d32 1438 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
73c10101 1439
73c10101
JA
1440 if (!ll_back_merge_fn(q, req, bio))
1441 return false;
1442
8c1cf6bb 1443 trace_block_bio_backmerge(q, req, bio);
73c10101
JA
1444
1445 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1446 blk_rq_set_mixed_merge(req);
1447
1448 req->biotail->bi_next = bio;
1449 req->biotail = bio;
4f024f37 1450 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1451 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1452
320ae51f 1453 blk_account_io_start(req, false);
73c10101
JA
1454 return true;
1455}
1456
320ae51f
JA
1457bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1458 struct bio *bio)
73c10101 1459{
1eff9d32 1460 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
73c10101 1461
73c10101
JA
1462 if (!ll_front_merge_fn(q, req, bio))
1463 return false;
1464
8c1cf6bb 1465 trace_block_bio_frontmerge(q, req, bio);
73c10101
JA
1466
1467 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1468 blk_rq_set_mixed_merge(req);
1469
73c10101
JA
1470 bio->bi_next = req->bio;
1471 req->bio = bio;
1472
4f024f37
KO
1473 req->__sector = bio->bi_iter.bi_sector;
1474 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1475 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1476
320ae51f 1477 blk_account_io_start(req, false);
73c10101
JA
1478 return true;
1479}
1480
bd87b589 1481/**
320ae51f 1482 * blk_attempt_plug_merge - try to merge with %current's plugged list
bd87b589
TH
1483 * @q: request_queue new bio is being queued at
1484 * @bio: new bio being queued
1485 * @request_count: out parameter for number of traversed plugged requests
ccc2600b
RD
1486 * @same_queue_rq: pointer to &struct request that gets filled in when
1487 * another request associated with @q is found on the plug list
1488 * (optional, may be %NULL)
bd87b589
TH
1489 *
1490 * Determine whether @bio being queued on @q can be merged with a request
1491 * on %current's plugged list. Returns %true if merge was successful,
1492 * otherwise %false.
1493 *
07c2bd37
TH
1494 * Plugging coalesces IOs from the same issuer for the same purpose without
1495 * going through @q->queue_lock. As such it's more of an issuing mechanism
1496 * than scheduling, and the request, while may have elvpriv data, is not
1497 * added on the elevator at this point. In addition, we don't have
1498 * reliable access to the elevator outside queue lock. Only check basic
1499 * merging parameters without querying the elevator.
da41a589
RE
1500 *
1501 * Caller must ensure !blk_queue_nomerges(q) beforehand.
73c10101 1502 */
320ae51f 1503bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
5b3f341f
SL
1504 unsigned int *request_count,
1505 struct request **same_queue_rq)
73c10101
JA
1506{
1507 struct blk_plug *plug;
1508 struct request *rq;
1509 bool ret = false;
92f399c7 1510 struct list_head *plug_list;
73c10101 1511
bd87b589 1512 plug = current->plug;
73c10101
JA
1513 if (!plug)
1514 goto out;
56ebdaf2 1515 *request_count = 0;
73c10101 1516
92f399c7
SL
1517 if (q->mq_ops)
1518 plug_list = &plug->mq_list;
1519 else
1520 plug_list = &plug->list;
1521
1522 list_for_each_entry_reverse(rq, plug_list, queuelist) {
73c10101
JA
1523 int el_ret;
1524
5b3f341f 1525 if (rq->q == q) {
1b2e19f1 1526 (*request_count)++;
5b3f341f
SL
1527 /*
1528 * Only blk-mq multiple hardware queues case checks the
1529 * rq in the same queue, there should be only one such
1530 * rq in a queue
1531 **/
1532 if (same_queue_rq)
1533 *same_queue_rq = rq;
1534 }
56ebdaf2 1535
07c2bd37 1536 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
73c10101
JA
1537 continue;
1538
050c8ea8 1539 el_ret = blk_try_merge(rq, bio);
73c10101
JA
1540 if (el_ret == ELEVATOR_BACK_MERGE) {
1541 ret = bio_attempt_back_merge(q, rq, bio);
1542 if (ret)
1543 break;
1544 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1545 ret = bio_attempt_front_merge(q, rq, bio);
1546 if (ret)
1547 break;
1548 }
1549 }
1550out:
1551 return ret;
1552}
1553
0809e3ac
JM
1554unsigned int blk_plug_queued_count(struct request_queue *q)
1555{
1556 struct blk_plug *plug;
1557 struct request *rq;
1558 struct list_head *plug_list;
1559 unsigned int ret = 0;
1560
1561 plug = current->plug;
1562 if (!plug)
1563 goto out;
1564
1565 if (q->mq_ops)
1566 plug_list = &plug->mq_list;
1567 else
1568 plug_list = &plug->list;
1569
1570 list_for_each_entry(rq, plug_list, queuelist) {
1571 if (rq->q == q)
1572 ret++;
1573 }
1574out:
1575 return ret;
1576}
1577
86db1e29 1578void init_request_from_bio(struct request *req, struct bio *bio)
52d9e675 1579{
1eff9d32 1580 if (bio->bi_opf & REQ_RAHEAD)
a82afdfc 1581 req->cmd_flags |= REQ_FAILFAST_MASK;
b31dc66a 1582
52d9e675 1583 req->errors = 0;
4f024f37 1584 req->__sector = bio->bi_iter.bi_sector;
5dc8b362
AM
1585 if (ioprio_valid(bio_prio(bio)))
1586 req->ioprio = bio_prio(bio);
bc1c56fd 1587 blk_rq_bio_prep(req->q, req, bio);
52d9e675
TH
1588}
1589
dece1635 1590static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1da177e4 1591{
73c10101 1592 struct blk_plug *plug;
ef295ecf 1593 int el_ret, where = ELEVATOR_INSERT_SORT;
73c10101 1594 struct request *req;
56ebdaf2 1595 unsigned int request_count = 0;
87760e5e 1596 unsigned int wb_acct;
1da177e4 1597
1da177e4
LT
1598 /*
1599 * low level driver can indicate that it wants pages above a
1600 * certain limit bounced to low memory (ie for highmem, or even
1601 * ISA dma in theory)
1602 */
1603 blk_queue_bounce(q, &bio);
1604
23688bf4
JN
1605 blk_queue_split(q, &bio, q->bio_split);
1606
ffecfd1a 1607 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
4246a0b6
CH
1608 bio->bi_error = -EIO;
1609 bio_endio(bio);
dece1635 1610 return BLK_QC_T_NONE;
ffecfd1a
DW
1611 }
1612
f73f44eb 1613 if (op_is_flush(bio->bi_opf)) {
73c10101 1614 spin_lock_irq(q->queue_lock);
ae1b1539 1615 where = ELEVATOR_INSERT_FLUSH;
28e7d184
TH
1616 goto get_rq;
1617 }
1618
73c10101
JA
1619 /*
1620 * Check if we can merge with the plugged list before grabbing
1621 * any locks.
1622 */
0809e3ac
JM
1623 if (!blk_queue_nomerges(q)) {
1624 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
dece1635 1625 return BLK_QC_T_NONE;
0809e3ac
JM
1626 } else
1627 request_count = blk_plug_queued_count(q);
1da177e4 1628
73c10101 1629 spin_lock_irq(q->queue_lock);
2056a782 1630
73c10101
JA
1631 el_ret = elv_merge(q, &req, bio);
1632 if (el_ret == ELEVATOR_BACK_MERGE) {
73c10101 1633 if (bio_attempt_back_merge(q, req, bio)) {
07c2bd37 1634 elv_bio_merged(q, req, bio);
73c10101
JA
1635 if (!attempt_back_merge(q, req))
1636 elv_merged_request(q, req, el_ret);
1637 goto out_unlock;
1638 }
1639 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
73c10101 1640 if (bio_attempt_front_merge(q, req, bio)) {
07c2bd37 1641 elv_bio_merged(q, req, bio);
73c10101
JA
1642 if (!attempt_front_merge(q, req))
1643 elv_merged_request(q, req, el_ret);
1644 goto out_unlock;
80a761fd 1645 }
1da177e4
LT
1646 }
1647
450991bc 1648get_rq:
87760e5e
JA
1649 wb_acct = wbt_wait(q->rq_wb, bio, q->queue_lock);
1650
1da177e4 1651 /*
450991bc 1652 * Grab a free request. This is might sleep but can not fail.
d6344532 1653 * Returns with the queue unlocked.
450991bc 1654 */
ef295ecf 1655 req = get_request(q, bio->bi_opf, bio, GFP_NOIO);
a492f075 1656 if (IS_ERR(req)) {
87760e5e 1657 __wbt_done(q->rq_wb, wb_acct);
4246a0b6
CH
1658 bio->bi_error = PTR_ERR(req);
1659 bio_endio(bio);
da8303c6
TH
1660 goto out_unlock;
1661 }
d6344532 1662
87760e5e
JA
1663 wbt_track(&req->issue_stat, wb_acct);
1664
450991bc
NP
1665 /*
1666 * After dropping the lock and possibly sleeping here, our request
1667 * may now be mergeable after it had proven unmergeable (above).
1668 * We don't worry about that case for efficiency. It won't happen
1669 * often, and the elevators are able to handle it.
1da177e4 1670 */
52d9e675 1671 init_request_from_bio(req, bio);
1da177e4 1672
9562ad9a 1673 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
11ccf116 1674 req->cpu = raw_smp_processor_id();
73c10101
JA
1675
1676 plug = current->plug;
721a9602 1677 if (plug) {
dc6d36c9
JA
1678 /*
1679 * If this is the first request added after a plug, fire
7aef2e78 1680 * of a plug trace.
0a6219a9
ML
1681 *
1682 * @request_count may become stale because of schedule
1683 * out, so check plug list again.
dc6d36c9 1684 */
0a6219a9 1685 if (!request_count || list_empty(&plug->list))
dc6d36c9 1686 trace_block_plug(q);
3540d5e8 1687 else {
50d24c34
SL
1688 struct request *last = list_entry_rq(plug->list.prev);
1689 if (request_count >= BLK_MAX_REQUEST_COUNT ||
1690 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE) {
3540d5e8 1691 blk_flush_plug_list(plug, false);
019ceb7d
SL
1692 trace_block_plug(q);
1693 }
73c10101 1694 }
73c10101 1695 list_add_tail(&req->queuelist, &plug->list);
320ae51f 1696 blk_account_io_start(req, true);
73c10101
JA
1697 } else {
1698 spin_lock_irq(q->queue_lock);
1699 add_acct_request(q, req, where);
24ecfbe2 1700 __blk_run_queue(q);
73c10101
JA
1701out_unlock:
1702 spin_unlock_irq(q->queue_lock);
1703 }
dece1635
JA
1704
1705 return BLK_QC_T_NONE;
1da177e4
LT
1706}
1707
1708/*
1709 * If bio->bi_dev is a partition, remap the location
1710 */
1711static inline void blk_partition_remap(struct bio *bio)
1712{
1713 struct block_device *bdev = bio->bi_bdev;
1714
778889d8
ST
1715 /*
1716 * Zone reset does not include bi_size so bio_sectors() is always 0.
1717 * Include a test for the reset op code and perform the remap if needed.
1718 */
1719 if (bdev != bdev->bd_contains &&
1720 (bio_sectors(bio) || bio_op(bio) == REQ_OP_ZONE_RESET)) {
1da177e4
LT
1721 struct hd_struct *p = bdev->bd_part;
1722
4f024f37 1723 bio->bi_iter.bi_sector += p->start_sect;
1da177e4 1724 bio->bi_bdev = bdev->bd_contains;
c7149d6b 1725
d07335e5
MS
1726 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1727 bdev->bd_dev,
4f024f37 1728 bio->bi_iter.bi_sector - p->start_sect);
1da177e4
LT
1729 }
1730}
1731
1da177e4
LT
1732static void handle_bad_sector(struct bio *bio)
1733{
1734 char b[BDEVNAME_SIZE];
1735
1736 printk(KERN_INFO "attempt to access beyond end of device\n");
6296b960 1737 printk(KERN_INFO "%s: rw=%d, want=%Lu, limit=%Lu\n",
1da177e4 1738 bdevname(bio->bi_bdev, b),
1eff9d32 1739 bio->bi_opf,
f73a1c7d 1740 (unsigned long long)bio_end_sector(bio),
77304d2a 1741 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1da177e4
LT
1742}
1743
c17bb495
AM
1744#ifdef CONFIG_FAIL_MAKE_REQUEST
1745
1746static DECLARE_FAULT_ATTR(fail_make_request);
1747
1748static int __init setup_fail_make_request(char *str)
1749{
1750 return setup_fault_attr(&fail_make_request, str);
1751}
1752__setup("fail_make_request=", setup_fail_make_request);
1753
b2c9cd37 1754static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
c17bb495 1755{
b2c9cd37 1756 return part->make_it_fail && should_fail(&fail_make_request, bytes);
c17bb495
AM
1757}
1758
1759static int __init fail_make_request_debugfs(void)
1760{
dd48c085
AM
1761 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1762 NULL, &fail_make_request);
1763
21f9fcd8 1764 return PTR_ERR_OR_ZERO(dir);
c17bb495
AM
1765}
1766
1767late_initcall(fail_make_request_debugfs);
1768
1769#else /* CONFIG_FAIL_MAKE_REQUEST */
1770
b2c9cd37
AM
1771static inline bool should_fail_request(struct hd_struct *part,
1772 unsigned int bytes)
c17bb495 1773{
b2c9cd37 1774 return false;
c17bb495
AM
1775}
1776
1777#endif /* CONFIG_FAIL_MAKE_REQUEST */
1778
c07e2b41
JA
1779/*
1780 * Check whether this bio extends beyond the end of the device.
1781 */
1782static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1783{
1784 sector_t maxsector;
1785
1786 if (!nr_sectors)
1787 return 0;
1788
1789 /* Test device or partition size, when known. */
77304d2a 1790 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
c07e2b41 1791 if (maxsector) {
4f024f37 1792 sector_t sector = bio->bi_iter.bi_sector;
c07e2b41
JA
1793
1794 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1795 /*
1796 * This may well happen - the kernel calls bread()
1797 * without checking the size of the device, e.g., when
1798 * mounting a device.
1799 */
1800 handle_bad_sector(bio);
1801 return 1;
1802 }
1803 }
1804
1805 return 0;
1806}
1807
27a84d54
CH
1808static noinline_for_stack bool
1809generic_make_request_checks(struct bio *bio)
1da177e4 1810{
165125e1 1811 struct request_queue *q;
5a7bbad2 1812 int nr_sectors = bio_sectors(bio);
51fd77bd 1813 int err = -EIO;
5a7bbad2
CH
1814 char b[BDEVNAME_SIZE];
1815 struct hd_struct *part;
1da177e4
LT
1816
1817 might_sleep();
1da177e4 1818
c07e2b41
JA
1819 if (bio_check_eod(bio, nr_sectors))
1820 goto end_io;
1da177e4 1821
5a7bbad2
CH
1822 q = bdev_get_queue(bio->bi_bdev);
1823 if (unlikely(!q)) {
1824 printk(KERN_ERR
1825 "generic_make_request: Trying to access "
1826 "nonexistent block-device %s (%Lu)\n",
1827 bdevname(bio->bi_bdev, b),
4f024f37 1828 (long long) bio->bi_iter.bi_sector);
5a7bbad2
CH
1829 goto end_io;
1830 }
c17bb495 1831
5a7bbad2 1832 part = bio->bi_bdev->bd_part;
4f024f37 1833 if (should_fail_request(part, bio->bi_iter.bi_size) ||
5a7bbad2 1834 should_fail_request(&part_to_disk(part)->part0,
4f024f37 1835 bio->bi_iter.bi_size))
5a7bbad2 1836 goto end_io;
2056a782 1837
5a7bbad2
CH
1838 /*
1839 * If this device has partitions, remap block n
1840 * of partition p to block n+start(p) of the disk.
1841 */
1842 blk_partition_remap(bio);
2056a782 1843
5a7bbad2
CH
1844 if (bio_check_eod(bio, nr_sectors))
1845 goto end_io;
1e87901e 1846
5a7bbad2
CH
1847 /*
1848 * Filter flush bio's early so that make_request based
1849 * drivers without flush support don't have to worry
1850 * about them.
1851 */
f3a8ab7d 1852 if (op_is_flush(bio->bi_opf) &&
c888a8f9 1853 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
1eff9d32 1854 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
5a7bbad2
CH
1855 if (!nr_sectors) {
1856 err = 0;
51fd77bd
JA
1857 goto end_io;
1858 }
5a7bbad2 1859 }
5ddfe969 1860
288dab8a
CH
1861 switch (bio_op(bio)) {
1862 case REQ_OP_DISCARD:
1863 if (!blk_queue_discard(q))
1864 goto not_supported;
1865 break;
1866 case REQ_OP_SECURE_ERASE:
1867 if (!blk_queue_secure_erase(q))
1868 goto not_supported;
1869 break;
1870 case REQ_OP_WRITE_SAME:
1871 if (!bdev_write_same(bio->bi_bdev))
1872 goto not_supported;
58886785 1873 break;
2d253440
ST
1874 case REQ_OP_ZONE_REPORT:
1875 case REQ_OP_ZONE_RESET:
1876 if (!bdev_is_zoned(bio->bi_bdev))
1877 goto not_supported;
288dab8a 1878 break;
a6f0788e
CK
1879 case REQ_OP_WRITE_ZEROES:
1880 if (!bdev_write_zeroes_sectors(bio->bi_bdev))
1881 goto not_supported;
1882 break;
288dab8a
CH
1883 default:
1884 break;
5a7bbad2 1885 }
01edede4 1886
7f4b35d1
TH
1887 /*
1888 * Various block parts want %current->io_context and lazy ioc
1889 * allocation ends up trading a lot of pain for a small amount of
1890 * memory. Just allocate it upfront. This may fail and block
1891 * layer knows how to live with it.
1892 */
1893 create_io_context(GFP_ATOMIC, q->node);
1894
ae118896
TH
1895 if (!blkcg_bio_issue_check(q, bio))
1896 return false;
27a84d54 1897
5a7bbad2 1898 trace_block_bio_queue(q, bio);
27a84d54 1899 return true;
a7384677 1900
288dab8a
CH
1901not_supported:
1902 err = -EOPNOTSUPP;
a7384677 1903end_io:
4246a0b6
CH
1904 bio->bi_error = err;
1905 bio_endio(bio);
27a84d54 1906 return false;
1da177e4
LT
1907}
1908
27a84d54
CH
1909/**
1910 * generic_make_request - hand a buffer to its device driver for I/O
1911 * @bio: The bio describing the location in memory and on the device.
1912 *
1913 * generic_make_request() is used to make I/O requests of block
1914 * devices. It is passed a &struct bio, which describes the I/O that needs
1915 * to be done.
1916 *
1917 * generic_make_request() does not return any status. The
1918 * success/failure status of the request, along with notification of
1919 * completion, is delivered asynchronously through the bio->bi_end_io
1920 * function described (one day) else where.
1921 *
1922 * The caller of generic_make_request must make sure that bi_io_vec
1923 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1924 * set to describe the device address, and the
1925 * bi_end_io and optionally bi_private are set to describe how
1926 * completion notification should be signaled.
1927 *
1928 * generic_make_request and the drivers it calls may use bi_next if this
1929 * bio happens to be merged with someone else, and may resubmit the bio to
1930 * a lower device by calling into generic_make_request recursively, which
1931 * means the bio should NOT be touched after the call to ->make_request_fn.
d89d8796 1932 */
dece1635 1933blk_qc_t generic_make_request(struct bio *bio)
d89d8796 1934{
bddd87c7 1935 struct bio_list bio_list_on_stack;
dece1635 1936 blk_qc_t ret = BLK_QC_T_NONE;
bddd87c7 1937
27a84d54 1938 if (!generic_make_request_checks(bio))
dece1635 1939 goto out;
27a84d54
CH
1940
1941 /*
1942 * We only want one ->make_request_fn to be active at a time, else
1943 * stack usage with stacked devices could be a problem. So use
1944 * current->bio_list to keep a list of requests submited by a
1945 * make_request_fn function. current->bio_list is also used as a
1946 * flag to say if generic_make_request is currently active in this
1947 * task or not. If it is NULL, then no make_request is active. If
1948 * it is non-NULL, then a make_request is active, and new requests
1949 * should be added at the tail
1950 */
bddd87c7 1951 if (current->bio_list) {
bddd87c7 1952 bio_list_add(current->bio_list, bio);
dece1635 1953 goto out;
d89d8796 1954 }
27a84d54 1955
d89d8796
NB
1956 /* following loop may be a bit non-obvious, and so deserves some
1957 * explanation.
1958 * Before entering the loop, bio->bi_next is NULL (as all callers
1959 * ensure that) so we have a list with a single bio.
1960 * We pretend that we have just taken it off a longer list, so
bddd87c7
AM
1961 * we assign bio_list to a pointer to the bio_list_on_stack,
1962 * thus initialising the bio_list of new bios to be
27a84d54 1963 * added. ->make_request() may indeed add some more bios
d89d8796
NB
1964 * through a recursive call to generic_make_request. If it
1965 * did, we find a non-NULL value in bio_list and re-enter the loop
1966 * from the top. In this case we really did just take the bio
bddd87c7 1967 * of the top of the list (no pretending) and so remove it from
27a84d54 1968 * bio_list, and call into ->make_request() again.
d89d8796
NB
1969 */
1970 BUG_ON(bio->bi_next);
bddd87c7
AM
1971 bio_list_init(&bio_list_on_stack);
1972 current->bio_list = &bio_list_on_stack;
d89d8796 1973 do {
27a84d54
CH
1974 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
1975
6f3b0e8b 1976 if (likely(blk_queue_enter(q, false) == 0)) {
dece1635 1977 ret = q->make_request_fn(q, bio);
3ef28e83
DW
1978
1979 blk_queue_exit(q);
27a84d54 1980
3ef28e83
DW
1981 bio = bio_list_pop(current->bio_list);
1982 } else {
1983 struct bio *bio_next = bio_list_pop(current->bio_list);
1984
1985 bio_io_error(bio);
1986 bio = bio_next;
1987 }
d89d8796 1988 } while (bio);
bddd87c7 1989 current->bio_list = NULL; /* deactivate */
dece1635
JA
1990
1991out:
1992 return ret;
d89d8796 1993}
1da177e4
LT
1994EXPORT_SYMBOL(generic_make_request);
1995
1996/**
710027a4 1997 * submit_bio - submit a bio to the block device layer for I/O
1da177e4
LT
1998 * @bio: The &struct bio which describes the I/O
1999 *
2000 * submit_bio() is very similar in purpose to generic_make_request(), and
2001 * uses that function to do most of the work. Both are fairly rough
710027a4 2002 * interfaces; @bio must be presetup and ready for I/O.
1da177e4
LT
2003 *
2004 */
4e49ea4a 2005blk_qc_t submit_bio(struct bio *bio)
1da177e4 2006{
bf2de6f5
JA
2007 /*
2008 * If it's a regular read/write or a barrier with data attached,
2009 * go through the normal accounting stuff before submission.
2010 */
e2a60da7 2011 if (bio_has_data(bio)) {
4363ac7c
MP
2012 unsigned int count;
2013
95fe6c1a 2014 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
4363ac7c
MP
2015 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2016 else
2017 count = bio_sectors(bio);
2018
a8ebb056 2019 if (op_is_write(bio_op(bio))) {
bf2de6f5
JA
2020 count_vm_events(PGPGOUT, count);
2021 } else {
4f024f37 2022 task_io_account_read(bio->bi_iter.bi_size);
bf2de6f5
JA
2023 count_vm_events(PGPGIN, count);
2024 }
2025
2026 if (unlikely(block_dump)) {
2027 char b[BDEVNAME_SIZE];
8dcbdc74 2028 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
ba25f9dc 2029 current->comm, task_pid_nr(current),
a8ebb056 2030 op_is_write(bio_op(bio)) ? "WRITE" : "READ",
4f024f37 2031 (unsigned long long)bio->bi_iter.bi_sector,
8dcbdc74
SM
2032 bdevname(bio->bi_bdev, b),
2033 count);
bf2de6f5 2034 }
1da177e4
LT
2035 }
2036
dece1635 2037 return generic_make_request(bio);
1da177e4 2038}
1da177e4
LT
2039EXPORT_SYMBOL(submit_bio);
2040
82124d60 2041/**
bf4e6b4e
HR
2042 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2043 * for new the queue limits
82124d60
KU
2044 * @q: the queue
2045 * @rq: the request being checked
2046 *
2047 * Description:
2048 * @rq may have been made based on weaker limitations of upper-level queues
2049 * in request stacking drivers, and it may violate the limitation of @q.
2050 * Since the block layer and the underlying device driver trust @rq
2051 * after it is inserted to @q, it should be checked against @q before
2052 * the insertion using this generic function.
2053 *
82124d60 2054 * Request stacking drivers like request-based dm may change the queue
bf4e6b4e
HR
2055 * limits when retrying requests on other queues. Those requests need
2056 * to be checked against the new queue limits again during dispatch.
82124d60 2057 */
bf4e6b4e
HR
2058static int blk_cloned_rq_check_limits(struct request_queue *q,
2059 struct request *rq)
82124d60 2060{
8fe0d473 2061 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) {
82124d60
KU
2062 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2063 return -EIO;
2064 }
2065
2066 /*
2067 * queue's settings related to segment counting like q->bounce_pfn
2068 * may differ from that of other stacking queues.
2069 * Recalculate it to check the request correctly on this queue's
2070 * limitation.
2071 */
2072 blk_recalc_rq_segments(rq);
8a78362c 2073 if (rq->nr_phys_segments > queue_max_segments(q)) {
82124d60
KU
2074 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2075 return -EIO;
2076 }
2077
2078 return 0;
2079}
82124d60
KU
2080
2081/**
2082 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2083 * @q: the queue to submit the request
2084 * @rq: the request being queued
2085 */
2086int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2087{
2088 unsigned long flags;
4853abaa 2089 int where = ELEVATOR_INSERT_BACK;
82124d60 2090
bf4e6b4e 2091 if (blk_cloned_rq_check_limits(q, rq))
82124d60
KU
2092 return -EIO;
2093
b2c9cd37
AM
2094 if (rq->rq_disk &&
2095 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
82124d60 2096 return -EIO;
82124d60 2097
7fb4898e
KB
2098 if (q->mq_ops) {
2099 if (blk_queue_io_stat(q))
2100 blk_account_io_start(rq, true);
bd6737f1 2101 blk_mq_sched_insert_request(rq, false, true, false, false);
7fb4898e
KB
2102 return 0;
2103 }
2104
82124d60 2105 spin_lock_irqsave(q->queue_lock, flags);
3f3299d5 2106 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
2107 spin_unlock_irqrestore(q->queue_lock, flags);
2108 return -ENODEV;
2109 }
82124d60
KU
2110
2111 /*
2112 * Submitting request must be dequeued before calling this function
2113 * because it will be linked to another request_queue
2114 */
2115 BUG_ON(blk_queued_rq(rq));
2116
f73f44eb 2117 if (op_is_flush(rq->cmd_flags))
4853abaa
JM
2118 where = ELEVATOR_INSERT_FLUSH;
2119
2120 add_acct_request(q, rq, where);
e67b77c7
JM
2121 if (where == ELEVATOR_INSERT_FLUSH)
2122 __blk_run_queue(q);
82124d60
KU
2123 spin_unlock_irqrestore(q->queue_lock, flags);
2124
2125 return 0;
2126}
2127EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2128
80a761fd
TH
2129/**
2130 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2131 * @rq: request to examine
2132 *
2133 * Description:
2134 * A request could be merge of IOs which require different failure
2135 * handling. This function determines the number of bytes which
2136 * can be failed from the beginning of the request without
2137 * crossing into area which need to be retried further.
2138 *
2139 * Return:
2140 * The number of bytes to fail.
2141 *
2142 * Context:
2143 * queue_lock must be held.
2144 */
2145unsigned int blk_rq_err_bytes(const struct request *rq)
2146{
2147 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2148 unsigned int bytes = 0;
2149 struct bio *bio;
2150
e8064021 2151 if (!(rq->rq_flags & RQF_MIXED_MERGE))
80a761fd
TH
2152 return blk_rq_bytes(rq);
2153
2154 /*
2155 * Currently the only 'mixing' which can happen is between
2156 * different fastfail types. We can safely fail portions
2157 * which have all the failfast bits that the first one has -
2158 * the ones which are at least as eager to fail as the first
2159 * one.
2160 */
2161 for (bio = rq->bio; bio; bio = bio->bi_next) {
1eff9d32 2162 if ((bio->bi_opf & ff) != ff)
80a761fd 2163 break;
4f024f37 2164 bytes += bio->bi_iter.bi_size;
80a761fd
TH
2165 }
2166
2167 /* this could lead to infinite loop */
2168 BUG_ON(blk_rq_bytes(rq) && !bytes);
2169 return bytes;
2170}
2171EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2172
320ae51f 2173void blk_account_io_completion(struct request *req, unsigned int bytes)
bc58ba94 2174{
c2553b58 2175 if (blk_do_io_stat(req)) {
bc58ba94
JA
2176 const int rw = rq_data_dir(req);
2177 struct hd_struct *part;
2178 int cpu;
2179
2180 cpu = part_stat_lock();
09e099d4 2181 part = req->part;
bc58ba94
JA
2182 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2183 part_stat_unlock();
2184 }
2185}
2186
320ae51f 2187void blk_account_io_done(struct request *req)
bc58ba94 2188{
bc58ba94 2189 /*
dd4c133f
TH
2190 * Account IO completion. flush_rq isn't accounted as a
2191 * normal IO on queueing nor completion. Accounting the
2192 * containing request is enough.
bc58ba94 2193 */
e8064021 2194 if (blk_do_io_stat(req) && !(req->rq_flags & RQF_FLUSH_SEQ)) {
bc58ba94
JA
2195 unsigned long duration = jiffies - req->start_time;
2196 const int rw = rq_data_dir(req);
2197 struct hd_struct *part;
2198 int cpu;
2199
2200 cpu = part_stat_lock();
09e099d4 2201 part = req->part;
bc58ba94
JA
2202
2203 part_stat_inc(cpu, part, ios[rw]);
2204 part_stat_add(cpu, part, ticks[rw], duration);
2205 part_round_stats(cpu, part);
316d315b 2206 part_dec_in_flight(part, rw);
bc58ba94 2207
6c23a968 2208 hd_struct_put(part);
bc58ba94
JA
2209 part_stat_unlock();
2210 }
2211}
2212
47fafbc7 2213#ifdef CONFIG_PM
c8158819
LM
2214/*
2215 * Don't process normal requests when queue is suspended
2216 * or in the process of suspending/resuming
2217 */
2218static struct request *blk_pm_peek_request(struct request_queue *q,
2219 struct request *rq)
2220{
2221 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
e8064021 2222 (q->rpm_status != RPM_ACTIVE && !(rq->rq_flags & RQF_PM))))
c8158819
LM
2223 return NULL;
2224 else
2225 return rq;
2226}
2227#else
2228static inline struct request *blk_pm_peek_request(struct request_queue *q,
2229 struct request *rq)
2230{
2231 return rq;
2232}
2233#endif
2234
320ae51f
JA
2235void blk_account_io_start(struct request *rq, bool new_io)
2236{
2237 struct hd_struct *part;
2238 int rw = rq_data_dir(rq);
2239 int cpu;
2240
2241 if (!blk_do_io_stat(rq))
2242 return;
2243
2244 cpu = part_stat_lock();
2245
2246 if (!new_io) {
2247 part = rq->part;
2248 part_stat_inc(cpu, part, merges[rw]);
2249 } else {
2250 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2251 if (!hd_struct_try_get(part)) {
2252 /*
2253 * The partition is already being removed,
2254 * the request will be accounted on the disk only
2255 *
2256 * We take a reference on disk->part0 although that
2257 * partition will never be deleted, so we can treat
2258 * it as any other partition.
2259 */
2260 part = &rq->rq_disk->part0;
2261 hd_struct_get(part);
2262 }
2263 part_round_stats(cpu, part);
2264 part_inc_in_flight(part, rw);
2265 rq->part = part;
2266 }
2267
2268 part_stat_unlock();
2269}
2270
3bcddeac 2271/**
9934c8c0
TH
2272 * blk_peek_request - peek at the top of a request queue
2273 * @q: request queue to peek at
2274 *
2275 * Description:
2276 * Return the request at the top of @q. The returned request
2277 * should be started using blk_start_request() before LLD starts
2278 * processing it.
2279 *
2280 * Return:
2281 * Pointer to the request at the top of @q if available. Null
2282 * otherwise.
2283 *
2284 * Context:
2285 * queue_lock must be held.
2286 */
2287struct request *blk_peek_request(struct request_queue *q)
158dbda0
TH
2288{
2289 struct request *rq;
2290 int ret;
2291
2292 while ((rq = __elv_next_request(q)) != NULL) {
c8158819
LM
2293
2294 rq = blk_pm_peek_request(q, rq);
2295 if (!rq)
2296 break;
2297
e8064021 2298 if (!(rq->rq_flags & RQF_STARTED)) {
158dbda0
TH
2299 /*
2300 * This is the first time the device driver
2301 * sees this request (possibly after
2302 * requeueing). Notify IO scheduler.
2303 */
e8064021 2304 if (rq->rq_flags & RQF_SORTED)
158dbda0
TH
2305 elv_activate_rq(q, rq);
2306
2307 /*
2308 * just mark as started even if we don't start
2309 * it, a request that has been delayed should
2310 * not be passed by new incoming requests
2311 */
e8064021 2312 rq->rq_flags |= RQF_STARTED;
158dbda0
TH
2313 trace_block_rq_issue(q, rq);
2314 }
2315
2316 if (!q->boundary_rq || q->boundary_rq == rq) {
2317 q->end_sector = rq_end_sector(rq);
2318 q->boundary_rq = NULL;
2319 }
2320
e8064021 2321 if (rq->rq_flags & RQF_DONTPREP)
158dbda0
TH
2322 break;
2323
2e46e8b2 2324 if (q->dma_drain_size && blk_rq_bytes(rq)) {
158dbda0
TH
2325 /*
2326 * make sure space for the drain appears we
2327 * know we can do this because max_hw_segments
2328 * has been adjusted to be one fewer than the
2329 * device can handle
2330 */
2331 rq->nr_phys_segments++;
2332 }
2333
2334 if (!q->prep_rq_fn)
2335 break;
2336
2337 ret = q->prep_rq_fn(q, rq);
2338 if (ret == BLKPREP_OK) {
2339 break;
2340 } else if (ret == BLKPREP_DEFER) {
2341 /*
2342 * the request may have been (partially) prepped.
2343 * we need to keep this request in the front to
e8064021 2344 * avoid resource deadlock. RQF_STARTED will
158dbda0
TH
2345 * prevent other fs requests from passing this one.
2346 */
2e46e8b2 2347 if (q->dma_drain_size && blk_rq_bytes(rq) &&
e8064021 2348 !(rq->rq_flags & RQF_DONTPREP)) {
158dbda0
TH
2349 /*
2350 * remove the space for the drain we added
2351 * so that we don't add it again
2352 */
2353 --rq->nr_phys_segments;
2354 }
2355
2356 rq = NULL;
2357 break;
0fb5b1fb
MP
2358 } else if (ret == BLKPREP_KILL || ret == BLKPREP_INVALID) {
2359 int err = (ret == BLKPREP_INVALID) ? -EREMOTEIO : -EIO;
2360
e8064021 2361 rq->rq_flags |= RQF_QUIET;
c143dc90
JB
2362 /*
2363 * Mark this request as started so we don't trigger
2364 * any debug logic in the end I/O path.
2365 */
2366 blk_start_request(rq);
0fb5b1fb 2367 __blk_end_request_all(rq, err);
158dbda0
TH
2368 } else {
2369 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2370 break;
2371 }
2372 }
2373
2374 return rq;
2375}
9934c8c0 2376EXPORT_SYMBOL(blk_peek_request);
158dbda0 2377
9934c8c0 2378void blk_dequeue_request(struct request *rq)
158dbda0 2379{
9934c8c0
TH
2380 struct request_queue *q = rq->q;
2381
158dbda0
TH
2382 BUG_ON(list_empty(&rq->queuelist));
2383 BUG_ON(ELV_ON_HASH(rq));
2384
2385 list_del_init(&rq->queuelist);
2386
2387 /*
2388 * the time frame between a request being removed from the lists
2389 * and to it is freed is accounted as io that is in progress at
2390 * the driver side.
2391 */
9195291e 2392 if (blk_account_rq(rq)) {
0a7ae2ff 2393 q->in_flight[rq_is_sync(rq)]++;
9195291e
DS
2394 set_io_start_time_ns(rq);
2395 }
158dbda0
TH
2396}
2397
9934c8c0
TH
2398/**
2399 * blk_start_request - start request processing on the driver
2400 * @req: request to dequeue
2401 *
2402 * Description:
2403 * Dequeue @req and start timeout timer on it. This hands off the
2404 * request to the driver.
2405 *
2406 * Block internal functions which don't want to start timer should
2407 * call blk_dequeue_request().
2408 *
2409 * Context:
2410 * queue_lock must be held.
2411 */
2412void blk_start_request(struct request *req)
2413{
2414 blk_dequeue_request(req);
2415
cf43e6be
JA
2416 if (test_bit(QUEUE_FLAG_STATS, &req->q->queue_flags)) {
2417 blk_stat_set_issue_time(&req->issue_stat);
2418 req->rq_flags |= RQF_STATS;
87760e5e 2419 wbt_issue(req->q->rq_wb, &req->issue_stat);
cf43e6be
JA
2420 }
2421
4912aa6c 2422 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
9934c8c0
TH
2423 blk_add_timer(req);
2424}
2425EXPORT_SYMBOL(blk_start_request);
2426
2427/**
2428 * blk_fetch_request - fetch a request from a request queue
2429 * @q: request queue to fetch a request from
2430 *
2431 * Description:
2432 * Return the request at the top of @q. The request is started on
2433 * return and LLD can start processing it immediately.
2434 *
2435 * Return:
2436 * Pointer to the request at the top of @q if available. Null
2437 * otherwise.
2438 *
2439 * Context:
2440 * queue_lock must be held.
2441 */
2442struct request *blk_fetch_request(struct request_queue *q)
2443{
2444 struct request *rq;
2445
2446 rq = blk_peek_request(q);
2447 if (rq)
2448 blk_start_request(rq);
2449 return rq;
2450}
2451EXPORT_SYMBOL(blk_fetch_request);
2452
3bcddeac 2453/**
2e60e022 2454 * blk_update_request - Special helper function for request stacking drivers
8ebf9756 2455 * @req: the request being processed
710027a4 2456 * @error: %0 for success, < %0 for error
8ebf9756 2457 * @nr_bytes: number of bytes to complete @req
3bcddeac
KU
2458 *
2459 * Description:
8ebf9756
RD
2460 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2461 * the request structure even if @req doesn't have leftover.
2462 * If @req has leftover, sets it up for the next range of segments.
2e60e022
TH
2463 *
2464 * This special helper function is only for request stacking drivers
2465 * (e.g. request-based dm) so that they can handle partial completion.
2466 * Actual device drivers should use blk_end_request instead.
2467 *
2468 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2469 * %false return from this function.
3bcddeac
KU
2470 *
2471 * Return:
2e60e022
TH
2472 * %false - this request doesn't have any more data
2473 * %true - this request has more data
3bcddeac 2474 **/
2e60e022 2475bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
1da177e4 2476{
f79ea416 2477 int total_bytes;
1da177e4 2478
4a0efdc9
HR
2479 trace_block_rq_complete(req->q, req, nr_bytes);
2480
2e60e022
TH
2481 if (!req->bio)
2482 return false;
2483
1da177e4 2484 /*
6f41469c
TH
2485 * For fs requests, rq is just carrier of independent bio's
2486 * and each partial completion should be handled separately.
2487 * Reset per-request error on each partial completion.
2488 *
2489 * TODO: tj: This is too subtle. It would be better to let
2490 * low level drivers do what they see fit.
1da177e4 2491 */
57292b58 2492 if (!blk_rq_is_passthrough(req))
1da177e4
LT
2493 req->errors = 0;
2494
57292b58 2495 if (error && !blk_rq_is_passthrough(req) &&
e8064021 2496 !(req->rq_flags & RQF_QUIET)) {
79775567
HR
2497 char *error_type;
2498
2499 switch (error) {
2500 case -ENOLINK:
2501 error_type = "recoverable transport";
2502 break;
2503 case -EREMOTEIO:
2504 error_type = "critical target";
2505 break;
2506 case -EBADE:
2507 error_type = "critical nexus";
2508 break;
d1ffc1f8
HR
2509 case -ETIMEDOUT:
2510 error_type = "timeout";
2511 break;
a9d6ceb8
HR
2512 case -ENOSPC:
2513 error_type = "critical space allocation";
2514 break;
7e782af5
HR
2515 case -ENODATA:
2516 error_type = "critical medium";
2517 break;
79775567
HR
2518 case -EIO:
2519 default:
2520 error_type = "I/O";
2521 break;
2522 }
ef3ecb66
RE
2523 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2524 __func__, error_type, req->rq_disk ?
37d7b34f
YZ
2525 req->rq_disk->disk_name : "?",
2526 (unsigned long long)blk_rq_pos(req));
2527
1da177e4
LT
2528 }
2529
bc58ba94 2530 blk_account_io_completion(req, nr_bytes);
d72d904a 2531
f79ea416
KO
2532 total_bytes = 0;
2533 while (req->bio) {
2534 struct bio *bio = req->bio;
4f024f37 2535 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
1da177e4 2536
4f024f37 2537 if (bio_bytes == bio->bi_iter.bi_size)
1da177e4 2538 req->bio = bio->bi_next;
1da177e4 2539
f79ea416 2540 req_bio_endio(req, bio, bio_bytes, error);
1da177e4 2541
f79ea416
KO
2542 total_bytes += bio_bytes;
2543 nr_bytes -= bio_bytes;
1da177e4 2544
f79ea416
KO
2545 if (!nr_bytes)
2546 break;
1da177e4
LT
2547 }
2548
2549 /*
2550 * completely done
2551 */
2e60e022
TH
2552 if (!req->bio) {
2553 /*
2554 * Reset counters so that the request stacking driver
2555 * can find how many bytes remain in the request
2556 * later.
2557 */
a2dec7b3 2558 req->__data_len = 0;
2e60e022
TH
2559 return false;
2560 }
1da177e4 2561
f9d03f96
CH
2562 WARN_ON_ONCE(req->rq_flags & RQF_SPECIAL_PAYLOAD);
2563
a2dec7b3 2564 req->__data_len -= total_bytes;
2e46e8b2
TH
2565
2566 /* update sector only for requests with clear definition of sector */
57292b58 2567 if (!blk_rq_is_passthrough(req))
a2dec7b3 2568 req->__sector += total_bytes >> 9;
2e46e8b2 2569
80a761fd 2570 /* mixed attributes always follow the first bio */
e8064021 2571 if (req->rq_flags & RQF_MIXED_MERGE) {
80a761fd 2572 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1eff9d32 2573 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
80a761fd
TH
2574 }
2575
2e46e8b2
TH
2576 /*
2577 * If total number of sectors is less than the first segment
2578 * size, something has gone terribly wrong.
2579 */
2580 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
8182924b 2581 blk_dump_rq_flags(req, "request botched");
a2dec7b3 2582 req->__data_len = blk_rq_cur_bytes(req);
2e46e8b2
TH
2583 }
2584
2585 /* recalculate the number of segments */
1da177e4 2586 blk_recalc_rq_segments(req);
2e46e8b2 2587
2e60e022 2588 return true;
1da177e4 2589}
2e60e022 2590EXPORT_SYMBOL_GPL(blk_update_request);
1da177e4 2591
2e60e022
TH
2592static bool blk_update_bidi_request(struct request *rq, int error,
2593 unsigned int nr_bytes,
2594 unsigned int bidi_bytes)
5efccd17 2595{
2e60e022
TH
2596 if (blk_update_request(rq, error, nr_bytes))
2597 return true;
5efccd17 2598
2e60e022
TH
2599 /* Bidi request must be completed as a whole */
2600 if (unlikely(blk_bidi_rq(rq)) &&
2601 blk_update_request(rq->next_rq, error, bidi_bytes))
2602 return true;
5efccd17 2603
e2e1a148
JA
2604 if (blk_queue_add_random(rq->q))
2605 add_disk_randomness(rq->rq_disk);
2e60e022
TH
2606
2607 return false;
1da177e4
LT
2608}
2609
28018c24
JB
2610/**
2611 * blk_unprep_request - unprepare a request
2612 * @req: the request
2613 *
2614 * This function makes a request ready for complete resubmission (or
2615 * completion). It happens only after all error handling is complete,
2616 * so represents the appropriate moment to deallocate any resources
2617 * that were allocated to the request in the prep_rq_fn. The queue
2618 * lock is held when calling this.
2619 */
2620void blk_unprep_request(struct request *req)
2621{
2622 struct request_queue *q = req->q;
2623
e8064021 2624 req->rq_flags &= ~RQF_DONTPREP;
28018c24
JB
2625 if (q->unprep_rq_fn)
2626 q->unprep_rq_fn(q, req);
2627}
2628EXPORT_SYMBOL_GPL(blk_unprep_request);
2629
1da177e4
LT
2630/*
2631 * queue lock must be held
2632 */
12120077 2633void blk_finish_request(struct request *req, int error)
1da177e4 2634{
cf43e6be
JA
2635 struct request_queue *q = req->q;
2636
2637 if (req->rq_flags & RQF_STATS)
2638 blk_stat_add(&q->rq_stats[rq_data_dir(req)], req);
2639
e8064021 2640 if (req->rq_flags & RQF_QUEUED)
cf43e6be 2641 blk_queue_end_tag(q, req);
b8286239 2642
ba396a6c 2643 BUG_ON(blk_queued_rq(req));
1da177e4 2644
57292b58 2645 if (unlikely(laptop_mode) && !blk_rq_is_passthrough(req))
dc3b17cc 2646 laptop_io_completion(req->q->backing_dev_info);
1da177e4 2647
e78042e5
MA
2648 blk_delete_timer(req);
2649
e8064021 2650 if (req->rq_flags & RQF_DONTPREP)
28018c24
JB
2651 blk_unprep_request(req);
2652
bc58ba94 2653 blk_account_io_done(req);
b8286239 2654
87760e5e
JA
2655 if (req->end_io) {
2656 wbt_done(req->q->rq_wb, &req->issue_stat);
8ffdc655 2657 req->end_io(req, error);
87760e5e 2658 } else {
b8286239
KU
2659 if (blk_bidi_rq(req))
2660 __blk_put_request(req->next_rq->q, req->next_rq);
2661
cf43e6be 2662 __blk_put_request(q, req);
b8286239 2663 }
1da177e4 2664}
12120077 2665EXPORT_SYMBOL(blk_finish_request);
1da177e4 2666
3b11313a 2667/**
2e60e022
TH
2668 * blk_end_bidi_request - Complete a bidi request
2669 * @rq: the request to complete
2670 * @error: %0 for success, < %0 for error
2671 * @nr_bytes: number of bytes to complete @rq
2672 * @bidi_bytes: number of bytes to complete @rq->next_rq
a0cd1285
JA
2673 *
2674 * Description:
e3a04fe3 2675 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2e60e022
TH
2676 * Drivers that supports bidi can safely call this member for any
2677 * type of request, bidi or uni. In the later case @bidi_bytes is
2678 * just ignored.
336cdb40
KU
2679 *
2680 * Return:
2e60e022
TH
2681 * %false - we are done with this request
2682 * %true - still buffers pending for this request
a0cd1285 2683 **/
b1f74493 2684static bool blk_end_bidi_request(struct request *rq, int error,
32fab448
KU
2685 unsigned int nr_bytes, unsigned int bidi_bytes)
2686{
336cdb40 2687 struct request_queue *q = rq->q;
2e60e022 2688 unsigned long flags;
32fab448 2689
2e60e022
TH
2690 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2691 return true;
32fab448 2692
336cdb40 2693 spin_lock_irqsave(q->queue_lock, flags);
2e60e022 2694 blk_finish_request(rq, error);
336cdb40
KU
2695 spin_unlock_irqrestore(q->queue_lock, flags);
2696
2e60e022 2697 return false;
32fab448
KU
2698}
2699
336cdb40 2700/**
2e60e022
TH
2701 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2702 * @rq: the request to complete
710027a4 2703 * @error: %0 for success, < %0 for error
e3a04fe3
KU
2704 * @nr_bytes: number of bytes to complete @rq
2705 * @bidi_bytes: number of bytes to complete @rq->next_rq
336cdb40
KU
2706 *
2707 * Description:
2e60e022
TH
2708 * Identical to blk_end_bidi_request() except that queue lock is
2709 * assumed to be locked on entry and remains so on return.
336cdb40
KU
2710 *
2711 * Return:
2e60e022
TH
2712 * %false - we are done with this request
2713 * %true - still buffers pending for this request
336cdb40 2714 **/
4853abaa 2715bool __blk_end_bidi_request(struct request *rq, int error,
b1f74493 2716 unsigned int nr_bytes, unsigned int bidi_bytes)
336cdb40 2717{
2e60e022
TH
2718 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2719 return true;
336cdb40 2720
2e60e022 2721 blk_finish_request(rq, error);
336cdb40 2722
2e60e022 2723 return false;
336cdb40 2724}
e19a3ab0
KU
2725
2726/**
2727 * blk_end_request - Helper function for drivers to complete the request.
2728 * @rq: the request being processed
710027a4 2729 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2730 * @nr_bytes: number of bytes to complete
2731 *
2732 * Description:
2733 * Ends I/O on a number of bytes attached to @rq.
2734 * If @rq has leftover, sets it up for the next range of segments.
2735 *
2736 * Return:
b1f74493
FT
2737 * %false - we are done with this request
2738 * %true - still buffers pending for this request
e19a3ab0 2739 **/
b1f74493 2740bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e19a3ab0 2741{
b1f74493 2742 return blk_end_bidi_request(rq, error, nr_bytes, 0);
e19a3ab0 2743}
56ad1740 2744EXPORT_SYMBOL(blk_end_request);
336cdb40
KU
2745
2746/**
b1f74493
FT
2747 * blk_end_request_all - Helper function for drives to finish the request.
2748 * @rq: the request to finish
8ebf9756 2749 * @error: %0 for success, < %0 for error
336cdb40
KU
2750 *
2751 * Description:
b1f74493
FT
2752 * Completely finish @rq.
2753 */
2754void blk_end_request_all(struct request *rq, int error)
336cdb40 2755{
b1f74493
FT
2756 bool pending;
2757 unsigned int bidi_bytes = 0;
336cdb40 2758
b1f74493
FT
2759 if (unlikely(blk_bidi_rq(rq)))
2760 bidi_bytes = blk_rq_bytes(rq->next_rq);
336cdb40 2761
b1f74493
FT
2762 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2763 BUG_ON(pending);
2764}
56ad1740 2765EXPORT_SYMBOL(blk_end_request_all);
336cdb40 2766
b1f74493
FT
2767/**
2768 * blk_end_request_cur - Helper function to finish the current request chunk.
2769 * @rq: the request to finish the current chunk for
8ebf9756 2770 * @error: %0 for success, < %0 for error
b1f74493
FT
2771 *
2772 * Description:
2773 * Complete the current consecutively mapped chunk from @rq.
2774 *
2775 * Return:
2776 * %false - we are done with this request
2777 * %true - still buffers pending for this request
2778 */
2779bool blk_end_request_cur(struct request *rq, int error)
2780{
2781 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
336cdb40 2782}
56ad1740 2783EXPORT_SYMBOL(blk_end_request_cur);
336cdb40 2784
80a761fd
TH
2785/**
2786 * blk_end_request_err - Finish a request till the next failure boundary.
2787 * @rq: the request to finish till the next failure boundary for
2788 * @error: must be negative errno
2789 *
2790 * Description:
2791 * Complete @rq till the next failure boundary.
2792 *
2793 * Return:
2794 * %false - we are done with this request
2795 * %true - still buffers pending for this request
2796 */
2797bool blk_end_request_err(struct request *rq, int error)
2798{
2799 WARN_ON(error >= 0);
2800 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2801}
2802EXPORT_SYMBOL_GPL(blk_end_request_err);
2803
e3a04fe3 2804/**
b1f74493
FT
2805 * __blk_end_request - Helper function for drivers to complete the request.
2806 * @rq: the request being processed
2807 * @error: %0 for success, < %0 for error
2808 * @nr_bytes: number of bytes to complete
e3a04fe3
KU
2809 *
2810 * Description:
b1f74493 2811 * Must be called with queue lock held unlike blk_end_request().
e3a04fe3
KU
2812 *
2813 * Return:
b1f74493
FT
2814 * %false - we are done with this request
2815 * %true - still buffers pending for this request
e3a04fe3 2816 **/
b1f74493 2817bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e3a04fe3 2818{
b1f74493 2819 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
e3a04fe3 2820}
56ad1740 2821EXPORT_SYMBOL(__blk_end_request);
e3a04fe3 2822
32fab448 2823/**
b1f74493
FT
2824 * __blk_end_request_all - Helper function for drives to finish the request.
2825 * @rq: the request to finish
8ebf9756 2826 * @error: %0 for success, < %0 for error
32fab448
KU
2827 *
2828 * Description:
b1f74493 2829 * Completely finish @rq. Must be called with queue lock held.
32fab448 2830 */
b1f74493 2831void __blk_end_request_all(struct request *rq, int error)
32fab448 2832{
b1f74493
FT
2833 bool pending;
2834 unsigned int bidi_bytes = 0;
2835
2836 if (unlikely(blk_bidi_rq(rq)))
2837 bidi_bytes = blk_rq_bytes(rq->next_rq);
2838
2839 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2840 BUG_ON(pending);
32fab448 2841}
56ad1740 2842EXPORT_SYMBOL(__blk_end_request_all);
32fab448 2843
e19a3ab0 2844/**
b1f74493
FT
2845 * __blk_end_request_cur - Helper function to finish the current request chunk.
2846 * @rq: the request to finish the current chunk for
8ebf9756 2847 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2848 *
2849 * Description:
b1f74493
FT
2850 * Complete the current consecutively mapped chunk from @rq. Must
2851 * be called with queue lock held.
e19a3ab0
KU
2852 *
2853 * Return:
b1f74493
FT
2854 * %false - we are done with this request
2855 * %true - still buffers pending for this request
2856 */
2857bool __blk_end_request_cur(struct request *rq, int error)
e19a3ab0 2858{
b1f74493 2859 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
e19a3ab0 2860}
56ad1740 2861EXPORT_SYMBOL(__blk_end_request_cur);
e19a3ab0 2862
80a761fd
TH
2863/**
2864 * __blk_end_request_err - Finish a request till the next failure boundary.
2865 * @rq: the request to finish till the next failure boundary for
2866 * @error: must be negative errno
2867 *
2868 * Description:
2869 * Complete @rq till the next failure boundary. Must be called
2870 * with queue lock held.
2871 *
2872 * Return:
2873 * %false - we are done with this request
2874 * %true - still buffers pending for this request
2875 */
2876bool __blk_end_request_err(struct request *rq, int error)
2877{
2878 WARN_ON(error >= 0);
2879 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2880}
2881EXPORT_SYMBOL_GPL(__blk_end_request_err);
2882
86db1e29
JA
2883void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2884 struct bio *bio)
1da177e4 2885{
b4f42e28 2886 if (bio_has_data(bio))
fb2dce86 2887 rq->nr_phys_segments = bio_phys_segments(q, bio);
b4f42e28 2888
4f024f37 2889 rq->__data_len = bio->bi_iter.bi_size;
1da177e4 2890 rq->bio = rq->biotail = bio;
1da177e4 2891
66846572
N
2892 if (bio->bi_bdev)
2893 rq->rq_disk = bio->bi_bdev->bd_disk;
2894}
1da177e4 2895
2d4dc890
IL
2896#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2897/**
2898 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2899 * @rq: the request to be flushed
2900 *
2901 * Description:
2902 * Flush all pages in @rq.
2903 */
2904void rq_flush_dcache_pages(struct request *rq)
2905{
2906 struct req_iterator iter;
7988613b 2907 struct bio_vec bvec;
2d4dc890
IL
2908
2909 rq_for_each_segment(bvec, rq, iter)
7988613b 2910 flush_dcache_page(bvec.bv_page);
2d4dc890
IL
2911}
2912EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2913#endif
2914
ef9e3fac
KU
2915/**
2916 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2917 * @q : the queue of the device being checked
2918 *
2919 * Description:
2920 * Check if underlying low-level drivers of a device are busy.
2921 * If the drivers want to export their busy state, they must set own
2922 * exporting function using blk_queue_lld_busy() first.
2923 *
2924 * Basically, this function is used only by request stacking drivers
2925 * to stop dispatching requests to underlying devices when underlying
2926 * devices are busy. This behavior helps more I/O merging on the queue
2927 * of the request stacking driver and prevents I/O throughput regression
2928 * on burst I/O load.
2929 *
2930 * Return:
2931 * 0 - Not busy (The request stacking driver should dispatch request)
2932 * 1 - Busy (The request stacking driver should stop dispatching request)
2933 */
2934int blk_lld_busy(struct request_queue *q)
2935{
2936 if (q->lld_busy_fn)
2937 return q->lld_busy_fn(q);
2938
2939 return 0;
2940}
2941EXPORT_SYMBOL_GPL(blk_lld_busy);
2942
78d8e58a
MS
2943/**
2944 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2945 * @rq: the clone request to be cleaned up
2946 *
2947 * Description:
2948 * Free all bios in @rq for a cloned request.
2949 */
2950void blk_rq_unprep_clone(struct request *rq)
2951{
2952 struct bio *bio;
2953
2954 while ((bio = rq->bio) != NULL) {
2955 rq->bio = bio->bi_next;
2956
2957 bio_put(bio);
2958 }
2959}
2960EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2961
2962/*
2963 * Copy attributes of the original request to the clone request.
2964 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
2965 */
2966static void __blk_rq_prep_clone(struct request *dst, struct request *src)
b0fd271d
KU
2967{
2968 dst->cpu = src->cpu;
b0fd271d
KU
2969 dst->__sector = blk_rq_pos(src);
2970 dst->__data_len = blk_rq_bytes(src);
2971 dst->nr_phys_segments = src->nr_phys_segments;
2972 dst->ioprio = src->ioprio;
2973 dst->extra_len = src->extra_len;
78d8e58a
MS
2974}
2975
2976/**
2977 * blk_rq_prep_clone - Helper function to setup clone request
2978 * @rq: the request to be setup
2979 * @rq_src: original request to be cloned
2980 * @bs: bio_set that bios for clone are allocated from
2981 * @gfp_mask: memory allocation mask for bio
2982 * @bio_ctr: setup function to be called for each clone bio.
2983 * Returns %0 for success, non %0 for failure.
2984 * @data: private data to be passed to @bio_ctr
2985 *
2986 * Description:
2987 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2988 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
2989 * are not copied, and copying such parts is the caller's responsibility.
2990 * Also, pages which the original bios are pointing to are not copied
2991 * and the cloned bios just point same pages.
2992 * So cloned bios must be completed before original bios, which means
2993 * the caller must complete @rq before @rq_src.
2994 */
2995int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2996 struct bio_set *bs, gfp_t gfp_mask,
2997 int (*bio_ctr)(struct bio *, struct bio *, void *),
2998 void *data)
2999{
3000 struct bio *bio, *bio_src;
3001
3002 if (!bs)
3003 bs = fs_bio_set;
3004
3005 __rq_for_each_bio(bio_src, rq_src) {
3006 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3007 if (!bio)
3008 goto free_and_out;
3009
3010 if (bio_ctr && bio_ctr(bio, bio_src, data))
3011 goto free_and_out;
3012
3013 if (rq->bio) {
3014 rq->biotail->bi_next = bio;
3015 rq->biotail = bio;
3016 } else
3017 rq->bio = rq->biotail = bio;
3018 }
3019
3020 __blk_rq_prep_clone(rq, rq_src);
3021
3022 return 0;
3023
3024free_and_out:
3025 if (bio)
3026 bio_put(bio);
3027 blk_rq_unprep_clone(rq);
3028
3029 return -ENOMEM;
b0fd271d
KU
3030}
3031EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3032
59c3d45e 3033int kblockd_schedule_work(struct work_struct *work)
1da177e4
LT
3034{
3035 return queue_work(kblockd_workqueue, work);
3036}
1da177e4
LT
3037EXPORT_SYMBOL(kblockd_schedule_work);
3038
ee63cfa7
JA
3039int kblockd_schedule_work_on(int cpu, struct work_struct *work)
3040{
3041 return queue_work_on(cpu, kblockd_workqueue, work);
3042}
3043EXPORT_SYMBOL(kblockd_schedule_work_on);
3044
59c3d45e
JA
3045int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3046 unsigned long delay)
e43473b7
VG
3047{
3048 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3049}
3050EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3051
8ab14595
JA
3052int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3053 unsigned long delay)
3054{
3055 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3056}
3057EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3058
75df7136
SJ
3059/**
3060 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3061 * @plug: The &struct blk_plug that needs to be initialized
3062 *
3063 * Description:
3064 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3065 * pending I/O should the task end up blocking between blk_start_plug() and
3066 * blk_finish_plug(). This is important from a performance perspective, but
3067 * also ensures that we don't deadlock. For instance, if the task is blocking
3068 * for a memory allocation, memory reclaim could end up wanting to free a
3069 * page belonging to that request that is currently residing in our private
3070 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3071 * this kind of deadlock.
3072 */
73c10101
JA
3073void blk_start_plug(struct blk_plug *plug)
3074{
3075 struct task_struct *tsk = current;
3076
dd6cf3e1
SL
3077 /*
3078 * If this is a nested plug, don't actually assign it.
3079 */
3080 if (tsk->plug)
3081 return;
3082
73c10101 3083 INIT_LIST_HEAD(&plug->list);
320ae51f 3084 INIT_LIST_HEAD(&plug->mq_list);
048c9374 3085 INIT_LIST_HEAD(&plug->cb_list);
73c10101 3086 /*
dd6cf3e1
SL
3087 * Store ordering should not be needed here, since a potential
3088 * preempt will imply a full memory barrier
73c10101 3089 */
dd6cf3e1 3090 tsk->plug = plug;
73c10101
JA
3091}
3092EXPORT_SYMBOL(blk_start_plug);
3093
3094static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3095{
3096 struct request *rqa = container_of(a, struct request, queuelist);
3097 struct request *rqb = container_of(b, struct request, queuelist);
3098
975927b9
JM
3099 return !(rqa->q < rqb->q ||
3100 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
73c10101
JA
3101}
3102
49cac01e
JA
3103/*
3104 * If 'from_schedule' is true, then postpone the dispatch of requests
3105 * until a safe kblockd context. We due this to avoid accidental big
3106 * additional stack usage in driver dispatch, in places where the originally
3107 * plugger did not intend it.
3108 */
f6603783 3109static void queue_unplugged(struct request_queue *q, unsigned int depth,
49cac01e 3110 bool from_schedule)
99e22598 3111 __releases(q->queue_lock)
94b5eb28 3112{
49cac01e 3113 trace_block_unplug(q, depth, !from_schedule);
99e22598 3114
70460571 3115 if (from_schedule)
24ecfbe2 3116 blk_run_queue_async(q);
70460571 3117 else
24ecfbe2 3118 __blk_run_queue(q);
70460571 3119 spin_unlock(q->queue_lock);
94b5eb28
JA
3120}
3121
74018dc3 3122static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
048c9374
N
3123{
3124 LIST_HEAD(callbacks);
3125
2a7d5559
SL
3126 while (!list_empty(&plug->cb_list)) {
3127 list_splice_init(&plug->cb_list, &callbacks);
048c9374 3128
2a7d5559
SL
3129 while (!list_empty(&callbacks)) {
3130 struct blk_plug_cb *cb = list_first_entry(&callbacks,
048c9374
N
3131 struct blk_plug_cb,
3132 list);
2a7d5559 3133 list_del(&cb->list);
74018dc3 3134 cb->callback(cb, from_schedule);
2a7d5559 3135 }
048c9374
N
3136 }
3137}
3138
9cbb1750
N
3139struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3140 int size)
3141{
3142 struct blk_plug *plug = current->plug;
3143 struct blk_plug_cb *cb;
3144
3145 if (!plug)
3146 return NULL;
3147
3148 list_for_each_entry(cb, &plug->cb_list, list)
3149 if (cb->callback == unplug && cb->data == data)
3150 return cb;
3151
3152 /* Not currently on the callback list */
3153 BUG_ON(size < sizeof(*cb));
3154 cb = kzalloc(size, GFP_ATOMIC);
3155 if (cb) {
3156 cb->data = data;
3157 cb->callback = unplug;
3158 list_add(&cb->list, &plug->cb_list);
3159 }
3160 return cb;
3161}
3162EXPORT_SYMBOL(blk_check_plugged);
3163
49cac01e 3164void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
73c10101
JA
3165{
3166 struct request_queue *q;
3167 unsigned long flags;
3168 struct request *rq;
109b8129 3169 LIST_HEAD(list);
94b5eb28 3170 unsigned int depth;
73c10101 3171
74018dc3 3172 flush_plug_callbacks(plug, from_schedule);
320ae51f
JA
3173
3174 if (!list_empty(&plug->mq_list))
3175 blk_mq_flush_plug_list(plug, from_schedule);
3176
73c10101
JA
3177 if (list_empty(&plug->list))
3178 return;
3179
109b8129
N
3180 list_splice_init(&plug->list, &list);
3181
422765c2 3182 list_sort(NULL, &list, plug_rq_cmp);
73c10101
JA
3183
3184 q = NULL;
94b5eb28 3185 depth = 0;
18811272
JA
3186
3187 /*
3188 * Save and disable interrupts here, to avoid doing it for every
3189 * queue lock we have to take.
3190 */
73c10101 3191 local_irq_save(flags);
109b8129
N
3192 while (!list_empty(&list)) {
3193 rq = list_entry_rq(list.next);
73c10101 3194 list_del_init(&rq->queuelist);
73c10101
JA
3195 BUG_ON(!rq->q);
3196 if (rq->q != q) {
99e22598
JA
3197 /*
3198 * This drops the queue lock
3199 */
3200 if (q)
49cac01e 3201 queue_unplugged(q, depth, from_schedule);
73c10101 3202 q = rq->q;
94b5eb28 3203 depth = 0;
73c10101
JA
3204 spin_lock(q->queue_lock);
3205 }
8ba61435
TH
3206
3207 /*
3208 * Short-circuit if @q is dead
3209 */
3f3299d5 3210 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
3211 __blk_end_request_all(rq, -ENODEV);
3212 continue;
3213 }
3214
73c10101
JA
3215 /*
3216 * rq is already accounted, so use raw insert
3217 */
f73f44eb 3218 if (op_is_flush(rq->cmd_flags))
401a18e9
JA
3219 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3220 else
3221 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
94b5eb28
JA
3222
3223 depth++;
73c10101
JA
3224 }
3225
99e22598
JA
3226 /*
3227 * This drops the queue lock
3228 */
3229 if (q)
49cac01e 3230 queue_unplugged(q, depth, from_schedule);
73c10101 3231
73c10101
JA
3232 local_irq_restore(flags);
3233}
73c10101
JA
3234
3235void blk_finish_plug(struct blk_plug *plug)
3236{
dd6cf3e1
SL
3237 if (plug != current->plug)
3238 return;
f6603783 3239 blk_flush_plug_list(plug, false);
73c10101 3240
dd6cf3e1 3241 current->plug = NULL;
73c10101 3242}
88b996cd 3243EXPORT_SYMBOL(blk_finish_plug);
73c10101 3244
47fafbc7 3245#ifdef CONFIG_PM
6c954667
LM
3246/**
3247 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3248 * @q: the queue of the device
3249 * @dev: the device the queue belongs to
3250 *
3251 * Description:
3252 * Initialize runtime-PM-related fields for @q and start auto suspend for
3253 * @dev. Drivers that want to take advantage of request-based runtime PM
3254 * should call this function after @dev has been initialized, and its
3255 * request queue @q has been allocated, and runtime PM for it can not happen
3256 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3257 * cases, driver should call this function before any I/O has taken place.
3258 *
3259 * This function takes care of setting up using auto suspend for the device,
3260 * the autosuspend delay is set to -1 to make runtime suspend impossible
3261 * until an updated value is either set by user or by driver. Drivers do
3262 * not need to touch other autosuspend settings.
3263 *
3264 * The block layer runtime PM is request based, so only works for drivers
3265 * that use request as their IO unit instead of those directly use bio's.
3266 */
3267void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3268{
3269 q->dev = dev;
3270 q->rpm_status = RPM_ACTIVE;
3271 pm_runtime_set_autosuspend_delay(q->dev, -1);
3272 pm_runtime_use_autosuspend(q->dev);
3273}
3274EXPORT_SYMBOL(blk_pm_runtime_init);
3275
3276/**
3277 * blk_pre_runtime_suspend - Pre runtime suspend check
3278 * @q: the queue of the device
3279 *
3280 * Description:
3281 * This function will check if runtime suspend is allowed for the device
3282 * by examining if there are any requests pending in the queue. If there
3283 * are requests pending, the device can not be runtime suspended; otherwise,
3284 * the queue's status will be updated to SUSPENDING and the driver can
3285 * proceed to suspend the device.
3286 *
3287 * For the not allowed case, we mark last busy for the device so that
3288 * runtime PM core will try to autosuspend it some time later.
3289 *
3290 * This function should be called near the start of the device's
3291 * runtime_suspend callback.
3292 *
3293 * Return:
3294 * 0 - OK to runtime suspend the device
3295 * -EBUSY - Device should not be runtime suspended
3296 */
3297int blk_pre_runtime_suspend(struct request_queue *q)
3298{
3299 int ret = 0;
3300
4fd41a85
KX
3301 if (!q->dev)
3302 return ret;
3303
6c954667
LM
3304 spin_lock_irq(q->queue_lock);
3305 if (q->nr_pending) {
3306 ret = -EBUSY;
3307 pm_runtime_mark_last_busy(q->dev);
3308 } else {
3309 q->rpm_status = RPM_SUSPENDING;
3310 }
3311 spin_unlock_irq(q->queue_lock);
3312 return ret;
3313}
3314EXPORT_SYMBOL(blk_pre_runtime_suspend);
3315
3316/**
3317 * blk_post_runtime_suspend - Post runtime suspend processing
3318 * @q: the queue of the device
3319 * @err: return value of the device's runtime_suspend function
3320 *
3321 * Description:
3322 * Update the queue's runtime status according to the return value of the
3323 * device's runtime suspend function and mark last busy for the device so
3324 * that PM core will try to auto suspend the device at a later time.
3325 *
3326 * This function should be called near the end of the device's
3327 * runtime_suspend callback.
3328 */
3329void blk_post_runtime_suspend(struct request_queue *q, int err)
3330{
4fd41a85
KX
3331 if (!q->dev)
3332 return;
3333
6c954667
LM
3334 spin_lock_irq(q->queue_lock);
3335 if (!err) {
3336 q->rpm_status = RPM_SUSPENDED;
3337 } else {
3338 q->rpm_status = RPM_ACTIVE;
3339 pm_runtime_mark_last_busy(q->dev);
3340 }
3341 spin_unlock_irq(q->queue_lock);
3342}
3343EXPORT_SYMBOL(blk_post_runtime_suspend);
3344
3345/**
3346 * blk_pre_runtime_resume - Pre runtime resume processing
3347 * @q: the queue of the device
3348 *
3349 * Description:
3350 * Update the queue's runtime status to RESUMING in preparation for the
3351 * runtime resume of the device.
3352 *
3353 * This function should be called near the start of the device's
3354 * runtime_resume callback.
3355 */
3356void blk_pre_runtime_resume(struct request_queue *q)
3357{
4fd41a85
KX
3358 if (!q->dev)
3359 return;
3360
6c954667
LM
3361 spin_lock_irq(q->queue_lock);
3362 q->rpm_status = RPM_RESUMING;
3363 spin_unlock_irq(q->queue_lock);
3364}
3365EXPORT_SYMBOL(blk_pre_runtime_resume);
3366
3367/**
3368 * blk_post_runtime_resume - Post runtime resume processing
3369 * @q: the queue of the device
3370 * @err: return value of the device's runtime_resume function
3371 *
3372 * Description:
3373 * Update the queue's runtime status according to the return value of the
3374 * device's runtime_resume function. If it is successfully resumed, process
3375 * the requests that are queued into the device's queue when it is resuming
3376 * and then mark last busy and initiate autosuspend for it.
3377 *
3378 * This function should be called near the end of the device's
3379 * runtime_resume callback.
3380 */
3381void blk_post_runtime_resume(struct request_queue *q, int err)
3382{
4fd41a85
KX
3383 if (!q->dev)
3384 return;
3385
6c954667
LM
3386 spin_lock_irq(q->queue_lock);
3387 if (!err) {
3388 q->rpm_status = RPM_ACTIVE;
3389 __blk_run_queue(q);
3390 pm_runtime_mark_last_busy(q->dev);
c60855cd 3391 pm_request_autosuspend(q->dev);
6c954667
LM
3392 } else {
3393 q->rpm_status = RPM_SUSPENDED;
3394 }
3395 spin_unlock_irq(q->queue_lock);
3396}
3397EXPORT_SYMBOL(blk_post_runtime_resume);
d07ab6d1
MW
3398
3399/**
3400 * blk_set_runtime_active - Force runtime status of the queue to be active
3401 * @q: the queue of the device
3402 *
3403 * If the device is left runtime suspended during system suspend the resume
3404 * hook typically resumes the device and corrects runtime status
3405 * accordingly. However, that does not affect the queue runtime PM status
3406 * which is still "suspended". This prevents processing requests from the
3407 * queue.
3408 *
3409 * This function can be used in driver's resume hook to correct queue
3410 * runtime PM status and re-enable peeking requests from the queue. It
3411 * should be called before first request is added to the queue.
3412 */
3413void blk_set_runtime_active(struct request_queue *q)
3414{
3415 spin_lock_irq(q->queue_lock);
3416 q->rpm_status = RPM_ACTIVE;
3417 pm_runtime_mark_last_busy(q->dev);
3418 pm_request_autosuspend(q->dev);
3419 spin_unlock_irq(q->queue_lock);
3420}
3421EXPORT_SYMBOL(blk_set_runtime_active);
6c954667
LM
3422#endif
3423
1da177e4
LT
3424int __init blk_dev_init(void)
3425{
ef295ecf
CH
3426 BUILD_BUG_ON(REQ_OP_LAST >= (1 << REQ_OP_BITS));
3427 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
0762b23d 3428 FIELD_SIZEOF(struct request, cmd_flags));
ef295ecf
CH
3429 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
3430 FIELD_SIZEOF(struct bio, bi_opf));
9eb55b03 3431
89b90be2
TH
3432 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3433 kblockd_workqueue = alloc_workqueue("kblockd",
28747fcd 3434 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1da177e4
LT
3435 if (!kblockd_workqueue)
3436 panic("Failed to create kblockd\n");
3437
3438 request_cachep = kmem_cache_create("blkdev_requests",
20c2df83 3439 sizeof(struct request), 0, SLAB_PANIC, NULL);
1da177e4 3440
c2789bd4 3441 blk_requestq_cachep = kmem_cache_create("request_queue",
165125e1 3442 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1da177e4 3443
d38ecf93 3444 return 0;
1da177e4 3445}