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