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