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