loop: No need to initialize ->queue_lock explicitly before calling blk_cleanup_queue()
[linux-2.6-block.git] / block / blk-core.c
CommitLineData
1da177e4 1/*
1da177e4
LT
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6728cb0e
JA
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7 * - July2000
1da177e4
LT
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9 */
10
11/*
12 * This handles all read/write requests to block devices
13 */
1da177e4
LT
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/backing-dev.h>
17#include <linux/bio.h>
18#include <linux/blkdev.h>
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>
55782138
LZ
30
31#define CREATE_TRACE_POINTS
32#include <trace/events/block.h>
1da177e4 33
8324aa91
JA
34#include "blk.h"
35
d07335e5 36EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
b0da3f0d 37EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
55782138 38EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
0bfc2455 39
165125e1 40static int __make_request(struct request_queue *q, struct bio *bio);
1da177e4
LT
41
42/*
43 * For the allocated request tables
44 */
5ece6c52 45static struct kmem_cache *request_cachep;
1da177e4
LT
46
47/*
48 * For queue allocation
49 */
6728cb0e 50struct kmem_cache *blk_requestq_cachep;
1da177e4 51
1da177e4
LT
52/*
53 * Controlling structure to kblockd
54 */
ff856bad 55static struct workqueue_struct *kblockd_workqueue;
1da177e4 56
26b8256e
JA
57static void drive_stat_acct(struct request *rq, int new_io)
58{
28f13702 59 struct hd_struct *part;
26b8256e 60 int rw = rq_data_dir(rq);
c9959059 61 int cpu;
26b8256e 62
c2553b58 63 if (!blk_do_io_stat(rq))
26b8256e
JA
64 return;
65
074a7aca 66 cpu = part_stat_lock();
c9959059 67
09e099d4
JM
68 if (!new_io) {
69 part = rq->part;
074a7aca 70 part_stat_inc(cpu, part, merges[rw]);
09e099d4
JM
71 } else {
72 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
6c23a968 73 if (!hd_struct_try_get(part)) {
09e099d4
JM
74 /*
75 * The partition is already being removed,
76 * the request will be accounted on the disk only
77 *
78 * We take a reference on disk->part0 although that
79 * partition will never be deleted, so we can treat
80 * it as any other partition.
81 */
82 part = &rq->rq_disk->part0;
6c23a968 83 hd_struct_get(part);
09e099d4 84 }
074a7aca 85 part_round_stats(cpu, part);
316d315b 86 part_inc_in_flight(part, rw);
09e099d4 87 rq->part = part;
26b8256e 88 }
e71bf0d0 89
074a7aca 90 part_stat_unlock();
26b8256e
JA
91}
92
8324aa91 93void blk_queue_congestion_threshold(struct request_queue *q)
1da177e4
LT
94{
95 int nr;
96
97 nr = q->nr_requests - (q->nr_requests / 8) + 1;
98 if (nr > q->nr_requests)
99 nr = q->nr_requests;
100 q->nr_congestion_on = nr;
101
102 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
103 if (nr < 1)
104 nr = 1;
105 q->nr_congestion_off = nr;
106}
107
1da177e4
LT
108/**
109 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
110 * @bdev: device
111 *
112 * Locates the passed device's request queue and returns the address of its
113 * backing_dev_info
114 *
115 * Will return NULL if the request queue cannot be located.
116 */
117struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
118{
119 struct backing_dev_info *ret = NULL;
165125e1 120 struct request_queue *q = bdev_get_queue(bdev);
1da177e4
LT
121
122 if (q)
123 ret = &q->backing_dev_info;
124 return ret;
125}
1da177e4
LT
126EXPORT_SYMBOL(blk_get_backing_dev_info);
127
2a4aa30c 128void blk_rq_init(struct request_queue *q, struct request *rq)
1da177e4 129{
1afb20f3
FT
130 memset(rq, 0, sizeof(*rq));
131
1da177e4 132 INIT_LIST_HEAD(&rq->queuelist);
242f9dcb 133 INIT_LIST_HEAD(&rq->timeout_list);
c7c22e4d 134 rq->cpu = -1;
63a71386 135 rq->q = q;
a2dec7b3 136 rq->__sector = (sector_t) -1;
2e662b65
JA
137 INIT_HLIST_NODE(&rq->hash);
138 RB_CLEAR_NODE(&rq->rb_node);
d7e3c324 139 rq->cmd = rq->__cmd;
e2494e1b 140 rq->cmd_len = BLK_MAX_CDB;
63a71386 141 rq->tag = -1;
1da177e4 142 rq->ref_count = 1;
b243ddcb 143 rq->start_time = jiffies;
9195291e 144 set_start_time_ns(rq);
09e099d4 145 rq->part = NULL;
1da177e4 146}
2a4aa30c 147EXPORT_SYMBOL(blk_rq_init);
1da177e4 148
5bb23a68
N
149static void req_bio_endio(struct request *rq, struct bio *bio,
150 unsigned int nbytes, int error)
1da177e4 151{
143a87f4
TH
152 if (error)
153 clear_bit(BIO_UPTODATE, &bio->bi_flags);
154 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
155 error = -EIO;
156
157 if (unlikely(nbytes > bio->bi_size)) {
158 printk(KERN_ERR "%s: want %u bytes done, %u left\n",
159 __func__, nbytes, bio->bi_size);
160 nbytes = bio->bi_size;
5bb23a68 161 }
143a87f4
TH
162
163 if (unlikely(rq->cmd_flags & REQ_QUIET))
164 set_bit(BIO_QUIET, &bio->bi_flags);
165
166 bio->bi_size -= nbytes;
167 bio->bi_sector += (nbytes >> 9);
168
169 if (bio_integrity(bio))
170 bio_integrity_advance(bio, nbytes);
171
172 /* don't actually finish bio if it's part of flush sequence */
173 if (bio->bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
174 bio_endio(bio, error);
1da177e4 175}
1da177e4 176
1da177e4
LT
177void blk_dump_rq_flags(struct request *rq, char *msg)
178{
179 int bit;
180
6728cb0e 181 printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
4aff5e23
JA
182 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
183 rq->cmd_flags);
1da177e4 184
83096ebf
TH
185 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
186 (unsigned long long)blk_rq_pos(rq),
187 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
731ec497 188 printk(KERN_INFO " bio %p, biotail %p, buffer %p, len %u\n",
2e46e8b2 189 rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
1da177e4 190
33659ebb 191 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
6728cb0e 192 printk(KERN_INFO " cdb: ");
d34c87e4 193 for (bit = 0; bit < BLK_MAX_CDB; bit++)
1da177e4
LT
194 printk("%02x ", rq->cmd[bit]);
195 printk("\n");
196 }
197}
1da177e4
LT
198EXPORT_SYMBOL(blk_dump_rq_flags);
199
1da177e4
LT
200/*
201 * "plug" the device if there are no outstanding requests: this will
202 * force the transfer to start only after we have put all the requests
203 * on the list.
204 *
205 * This is called with interrupts off and no requests on the queue and
206 * with the queue lock held.
207 */
165125e1 208void blk_plug_device(struct request_queue *q)
1da177e4
LT
209{
210 WARN_ON(!irqs_disabled());
211
212 /*
213 * don't plug a stopped queue, it must be paired with blk_start_queue()
214 * which will restart the queueing
215 */
7daac490 216 if (blk_queue_stopped(q))
1da177e4
LT
217 return;
218
e48ec690 219 if (!queue_flag_test_and_set(QUEUE_FLAG_PLUGGED, q)) {
1da177e4 220 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
5f3ea37c 221 trace_block_plug(q);
2056a782 222 }
1da177e4 223}
1da177e4
LT
224EXPORT_SYMBOL(blk_plug_device);
225
6c5e0c4d
JA
226/**
227 * blk_plug_device_unlocked - plug a device without queue lock held
228 * @q: The &struct request_queue to plug
229 *
230 * Description:
231 * Like @blk_plug_device(), but grabs the queue lock and disables
232 * interrupts.
233 **/
234void blk_plug_device_unlocked(struct request_queue *q)
235{
236 unsigned long flags;
237
238 spin_lock_irqsave(q->queue_lock, flags);
239 blk_plug_device(q);
240 spin_unlock_irqrestore(q->queue_lock, flags);
241}
242EXPORT_SYMBOL(blk_plug_device_unlocked);
243
1da177e4
LT
244/*
245 * remove the queue from the plugged list, if present. called with
246 * queue lock held and interrupts disabled.
247 */
165125e1 248int blk_remove_plug(struct request_queue *q)
1da177e4
LT
249{
250 WARN_ON(!irqs_disabled());
251
e48ec690 252 if (!queue_flag_test_and_clear(QUEUE_FLAG_PLUGGED, q))
1da177e4
LT
253 return 0;
254
255 del_timer(&q->unplug_timer);
256 return 1;
257}
1da177e4
LT
258EXPORT_SYMBOL(blk_remove_plug);
259
260/*
261 * remove the plug and let it rip..
262 */
165125e1 263void __generic_unplug_device(struct request_queue *q)
1da177e4 264{
7daac490 265 if (unlikely(blk_queue_stopped(q)))
1da177e4 266 return;
a31a9738 267 if (!blk_remove_plug(q) && !blk_queue_nonrot(q))
1da177e4
LT
268 return;
269
22e2c507 270 q->request_fn(q);
1da177e4 271}
1da177e4
LT
272
273/**
274 * generic_unplug_device - fire a request queue
165125e1 275 * @q: The &struct request_queue in question
1da177e4
LT
276 *
277 * Description:
278 * Linux uses plugging to build bigger requests queues before letting
279 * the device have at them. If a queue is plugged, the I/O scheduler
280 * is still adding and merging requests on the queue. Once the queue
281 * gets unplugged, the request_fn defined for the queue is invoked and
282 * transfers started.
283 **/
165125e1 284void generic_unplug_device(struct request_queue *q)
1da177e4 285{
dbaf2c00
JA
286 if (blk_queue_plugged(q)) {
287 spin_lock_irq(q->queue_lock);
288 __generic_unplug_device(q);
289 spin_unlock_irq(q->queue_lock);
290 }
1da177e4
LT
291}
292EXPORT_SYMBOL(generic_unplug_device);
293
294static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
295 struct page *page)
296{
165125e1 297 struct request_queue *q = bdi->unplug_io_data;
1da177e4 298
2ad8b1ef 299 blk_unplug(q);
1da177e4
LT
300}
301
86db1e29 302void blk_unplug_work(struct work_struct *work)
1da177e4 303{
165125e1
JA
304 struct request_queue *q =
305 container_of(work, struct request_queue, unplug_work);
1da177e4 306
5f3ea37c 307 trace_block_unplug_io(q);
1da177e4
LT
308 q->unplug_fn(q);
309}
310
86db1e29 311void blk_unplug_timeout(unsigned long data)
1da177e4 312{
165125e1 313 struct request_queue *q = (struct request_queue *)data;
1da177e4 314
5f3ea37c 315 trace_block_unplug_timer(q);
18887ad9 316 kblockd_schedule_work(q, &q->unplug_work);
1da177e4
LT
317}
318
2ad8b1ef
AB
319void blk_unplug(struct request_queue *q)
320{
321 /*
322 * devices don't necessarily have an ->unplug_fn defined
323 */
324 if (q->unplug_fn) {
5f3ea37c 325 trace_block_unplug_io(q);
2ad8b1ef
AB
326 q->unplug_fn(q);
327 }
328}
329EXPORT_SYMBOL(blk_unplug);
330
1da177e4
LT
331/**
332 * blk_start_queue - restart a previously stopped queue
165125e1 333 * @q: The &struct request_queue in question
1da177e4
LT
334 *
335 * Description:
336 * blk_start_queue() will clear the stop flag on the queue, and call
337 * the request_fn for the queue if it was in a stopped state when
338 * entered. Also see blk_stop_queue(). Queue lock must be held.
339 **/
165125e1 340void blk_start_queue(struct request_queue *q)
1da177e4 341{
a038e253
PBG
342 WARN_ON(!irqs_disabled());
343
75ad23bc 344 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
a538cd03 345 __blk_run_queue(q);
1da177e4 346}
1da177e4
LT
347EXPORT_SYMBOL(blk_start_queue);
348
349/**
350 * blk_stop_queue - stop a queue
165125e1 351 * @q: The &struct request_queue in question
1da177e4
LT
352 *
353 * Description:
354 * The Linux block layer assumes that a block driver will consume all
355 * entries on the request queue when the request_fn strategy is called.
356 * Often this will not happen, because of hardware limitations (queue
357 * depth settings). If a device driver gets a 'queue full' response,
358 * or if it simply chooses not to queue more I/O at one point, it can
359 * call this function to prevent the request_fn from being called until
360 * the driver has signalled it's ready to go again. This happens by calling
361 * blk_start_queue() to restart queue operations. Queue lock must be held.
362 **/
165125e1 363void blk_stop_queue(struct request_queue *q)
1da177e4
LT
364{
365 blk_remove_plug(q);
75ad23bc 366 queue_flag_set(QUEUE_FLAG_STOPPED, q);
1da177e4
LT
367}
368EXPORT_SYMBOL(blk_stop_queue);
369
370/**
371 * blk_sync_queue - cancel any pending callbacks on a queue
372 * @q: the queue
373 *
374 * Description:
375 * The block layer may perform asynchronous callback activity
376 * on a queue, such as calling the unplug function after a timeout.
377 * A block device may call blk_sync_queue to ensure that any
378 * such activity is cancelled, thus allowing it to release resources
59c51591 379 * that the callbacks might use. The caller must already have made sure
1da177e4
LT
380 * that its ->make_request_fn will not re-add plugging prior to calling
381 * this function.
382 *
383 */
384void blk_sync_queue(struct request_queue *q)
385{
386 del_timer_sync(&q->unplug_timer);
70ed28b9 387 del_timer_sync(&q->timeout);
64d01dc9 388 cancel_work_sync(&q->unplug_work);
e43473b7 389 throtl_shutdown_timer_wq(q);
1da177e4
LT
390}
391EXPORT_SYMBOL(blk_sync_queue);
392
393/**
80a4b58e 394 * __blk_run_queue - run a single device queue
1da177e4 395 * @q: The queue to run
80a4b58e
JA
396 *
397 * Description:
398 * See @blk_run_queue. This variant must be called with the queue lock
399 * held and interrupts disabled.
400 *
1da177e4 401 */
75ad23bc 402void __blk_run_queue(struct request_queue *q)
1da177e4 403{
1da177e4 404 blk_remove_plug(q);
dac07ec1 405
a538cd03
TH
406 if (unlikely(blk_queue_stopped(q)))
407 return;
408
409 if (elv_queue_empty(q))
410 return;
411
dac07ec1
JA
412 /*
413 * Only recurse once to avoid overrunning the stack, let the unplug
414 * handling reinvoke the handler shortly if we already got there.
415 */
a538cd03
TH
416 if (!queue_flag_test_and_set(QUEUE_FLAG_REENTER, q)) {
417 q->request_fn(q);
418 queue_flag_clear(QUEUE_FLAG_REENTER, q);
419 } else {
420 queue_flag_set(QUEUE_FLAG_PLUGGED, q);
421 kblockd_schedule_work(q, &q->unplug_work);
422 }
75ad23bc
NP
423}
424EXPORT_SYMBOL(__blk_run_queue);
dac07ec1 425
75ad23bc
NP
426/**
427 * blk_run_queue - run a single device queue
428 * @q: The queue to run
80a4b58e
JA
429 *
430 * Description:
431 * Invoke request handling on this queue, if it has pending work to do.
a7f55792 432 * May be used to restart queueing when a request has completed.
75ad23bc
NP
433 */
434void blk_run_queue(struct request_queue *q)
435{
436 unsigned long flags;
437
438 spin_lock_irqsave(q->queue_lock, flags);
439 __blk_run_queue(q);
1da177e4
LT
440 spin_unlock_irqrestore(q->queue_lock, flags);
441}
442EXPORT_SYMBOL(blk_run_queue);
443
165125e1 444void blk_put_queue(struct request_queue *q)
483f4afc
AV
445{
446 kobject_put(&q->kobj);
447}
483f4afc 448
c94a96ac
VG
449/*
450 * Note: If a driver supplied the queue lock, it should not zap that lock
451 * unexpectedly as some queue cleanup components like elevator_exit() and
452 * blk_throtl_exit() need queue lock.
453 */
6728cb0e 454void blk_cleanup_queue(struct request_queue *q)
483f4afc 455{
e3335de9
JA
456 /*
457 * We know we have process context here, so we can be a little
458 * cautious and ensure that pending block actions on this device
459 * are done before moving on. Going into this function, we should
460 * not have processes doing IO to this device.
461 */
462 blk_sync_queue(q);
463
31373d09 464 del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
483f4afc 465 mutex_lock(&q->sysfs_lock);
75ad23bc 466 queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);
483f4afc
AV
467 mutex_unlock(&q->sysfs_lock);
468
469 if (q->elevator)
470 elevator_exit(q->elevator);
471
472 blk_put_queue(q);
473}
1da177e4
LT
474EXPORT_SYMBOL(blk_cleanup_queue);
475
165125e1 476static int blk_init_free_list(struct request_queue *q)
1da177e4
LT
477{
478 struct request_list *rl = &q->rq;
479
1abec4fd
MS
480 if (unlikely(rl->rq_pool))
481 return 0;
482
1faa16d2
JA
483 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
484 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
cb98fc8b 485 rl->elvpriv = 0;
1faa16d2
JA
486 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
487 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
1da177e4 488
1946089a
CL
489 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
490 mempool_free_slab, request_cachep, q->node);
1da177e4
LT
491
492 if (!rl->rq_pool)
493 return -ENOMEM;
494
495 return 0;
496}
497
165125e1 498struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
1da177e4 499{
1946089a
CL
500 return blk_alloc_queue_node(gfp_mask, -1);
501}
502EXPORT_SYMBOL(blk_alloc_queue);
1da177e4 503
165125e1 504struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1946089a 505{
165125e1 506 struct request_queue *q;
e0bf68dd 507 int err;
1946089a 508
8324aa91 509 q = kmem_cache_alloc_node(blk_requestq_cachep,
94f6030c 510 gfp_mask | __GFP_ZERO, node_id);
1da177e4
LT
511 if (!q)
512 return NULL;
513
e0bf68dd
PZ
514 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
515 q->backing_dev_info.unplug_io_data = q;
0989a025
JA
516 q->backing_dev_info.ra_pages =
517 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
518 q->backing_dev_info.state = 0;
519 q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
d993831f 520 q->backing_dev_info.name = "block";
0989a025 521
e0bf68dd
PZ
522 err = bdi_init(&q->backing_dev_info);
523 if (err) {
8324aa91 524 kmem_cache_free(blk_requestq_cachep, q);
e0bf68dd
PZ
525 return NULL;
526 }
527
e43473b7
VG
528 if (blk_throtl_init(q)) {
529 kmem_cache_free(blk_requestq_cachep, q);
530 return NULL;
531 }
532
31373d09
MG
533 setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
534 laptop_mode_timer_fn, (unsigned long) q);
1da177e4 535 init_timer(&q->unplug_timer);
242f9dcb
JA
536 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
537 INIT_LIST_HEAD(&q->timeout_list);
ae1b1539
TH
538 INIT_LIST_HEAD(&q->flush_queue[0]);
539 INIT_LIST_HEAD(&q->flush_queue[1]);
540 INIT_LIST_HEAD(&q->flush_data_in_flight);
713ada9b 541 INIT_WORK(&q->unplug_work, blk_unplug_work);
483f4afc 542
8324aa91 543 kobject_init(&q->kobj, &blk_queue_ktype);
1da177e4 544
483f4afc 545 mutex_init(&q->sysfs_lock);
e7e72bf6 546 spin_lock_init(&q->__queue_lock);
483f4afc 547
c94a96ac
VG
548 /*
549 * By default initialize queue_lock to internal lock and driver can
550 * override it later if need be.
551 */
552 q->queue_lock = &q->__queue_lock;
553
1da177e4
LT
554 return q;
555}
1946089a 556EXPORT_SYMBOL(blk_alloc_queue_node);
1da177e4
LT
557
558/**
559 * blk_init_queue - prepare a request queue for use with a block device
560 * @rfn: The function to be called to process requests that have been
561 * placed on the queue.
562 * @lock: Request queue spin lock
563 *
564 * Description:
565 * If a block device wishes to use the standard request handling procedures,
566 * which sorts requests and coalesces adjacent requests, then it must
567 * call blk_init_queue(). The function @rfn will be called when there
568 * are requests on the queue that need to be processed. If the device
569 * supports plugging, then @rfn may not be called immediately when requests
570 * are available on the queue, but may be called at some time later instead.
571 * Plugged queues are generally unplugged when a buffer belonging to one
572 * of the requests on the queue is needed, or due to memory pressure.
573 *
574 * @rfn is not required, or even expected, to remove all requests off the
575 * queue, but only as many as it can handle at a time. If it does leave
576 * requests on the queue, it is responsible for arranging that the requests
577 * get dealt with eventually.
578 *
579 * The queue spin lock must be held while manipulating the requests on the
a038e253
PBG
580 * request queue; this lock will be taken also from interrupt context, so irq
581 * disabling is needed for it.
1da177e4 582 *
710027a4 583 * Function returns a pointer to the initialized request queue, or %NULL if
1da177e4
LT
584 * it didn't succeed.
585 *
586 * Note:
587 * blk_init_queue() must be paired with a blk_cleanup_queue() call
588 * when the block device is deactivated (such as at module unload).
589 **/
1946089a 590
165125e1 591struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1da177e4 592{
1946089a
CL
593 return blk_init_queue_node(rfn, lock, -1);
594}
595EXPORT_SYMBOL(blk_init_queue);
596
165125e1 597struct request_queue *
1946089a
CL
598blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
599{
c86d1b8a 600 struct request_queue *uninit_q, *q;
1da177e4 601
c86d1b8a
MS
602 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
603 if (!uninit_q)
604 return NULL;
605
606 q = blk_init_allocated_queue_node(uninit_q, rfn, lock, node_id);
607 if (!q)
608 blk_cleanup_queue(uninit_q);
609
610 return q;
01effb0d
MS
611}
612EXPORT_SYMBOL(blk_init_queue_node);
613
614struct request_queue *
615blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
616 spinlock_t *lock)
617{
618 return blk_init_allocated_queue_node(q, rfn, lock, -1);
619}
620EXPORT_SYMBOL(blk_init_allocated_queue);
621
622struct request_queue *
623blk_init_allocated_queue_node(struct request_queue *q, request_fn_proc *rfn,
624 spinlock_t *lock, int node_id)
625{
1da177e4
LT
626 if (!q)
627 return NULL;
628
1946089a 629 q->node = node_id;
c86d1b8a 630 if (blk_init_free_list(q))
8669aafd 631 return NULL;
1da177e4
LT
632
633 q->request_fn = rfn;
1da177e4 634 q->prep_rq_fn = NULL;
28018c24 635 q->unprep_rq_fn = NULL;
1da177e4 636 q->unplug_fn = generic_unplug_device;
bc58ba94 637 q->queue_flags = QUEUE_FLAG_DEFAULT;
c94a96ac
VG
638
639 /* Override internal queue lock with supplied lock pointer */
640 if (lock)
641 q->queue_lock = lock;
1da177e4 642
f3b144aa
JA
643 /*
644 * This also sets hw/phys segments, boundary and size
645 */
1da177e4 646 blk_queue_make_request(q, __make_request);
1da177e4 647
44ec9542
AS
648 q->sg_reserved_size = INT_MAX;
649
1da177e4
LT
650 /*
651 * all done
652 */
653 if (!elevator_init(q, NULL)) {
654 blk_queue_congestion_threshold(q);
655 return q;
656 }
657
1da177e4
LT
658 return NULL;
659}
01effb0d 660EXPORT_SYMBOL(blk_init_allocated_queue_node);
1da177e4 661
165125e1 662int blk_get_queue(struct request_queue *q)
1da177e4 663{
fde6ad22 664 if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
483f4afc 665 kobject_get(&q->kobj);
1da177e4
LT
666 return 0;
667 }
668
669 return 1;
670}
1da177e4 671
165125e1 672static inline void blk_free_request(struct request_queue *q, struct request *rq)
1da177e4 673{
4aff5e23 674 if (rq->cmd_flags & REQ_ELVPRIV)
cb98fc8b 675 elv_put_request(q, rq);
1da177e4
LT
676 mempool_free(rq, q->rq.rq_pool);
677}
678
1ea25ecb 679static struct request *
42dad764 680blk_alloc_request(struct request_queue *q, int flags, int priv, gfp_t gfp_mask)
1da177e4
LT
681{
682 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
683
684 if (!rq)
685 return NULL;
686
2a4aa30c 687 blk_rq_init(q, rq);
1afb20f3 688
42dad764 689 rq->cmd_flags = flags | REQ_ALLOCED;
1da177e4 690
cb98fc8b 691 if (priv) {
cb78b285 692 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
cb98fc8b
TH
693 mempool_free(rq, q->rq.rq_pool);
694 return NULL;
695 }
4aff5e23 696 rq->cmd_flags |= REQ_ELVPRIV;
cb98fc8b 697 }
1da177e4 698
cb98fc8b 699 return rq;
1da177e4
LT
700}
701
702/*
703 * ioc_batching returns true if the ioc is a valid batching request and
704 * should be given priority access to a request.
705 */
165125e1 706static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
707{
708 if (!ioc)
709 return 0;
710
711 /*
712 * Make sure the process is able to allocate at least 1 request
713 * even if the batch times out, otherwise we could theoretically
714 * lose wakeups.
715 */
716 return ioc->nr_batch_requests == q->nr_batching ||
717 (ioc->nr_batch_requests > 0
718 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
719}
720
721/*
722 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
723 * will cause the process to be a "batcher" on all queues in the system. This
724 * is the behaviour we want though - once it gets a wakeup it should be given
725 * a nice run.
726 */
165125e1 727static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
728{
729 if (!ioc || ioc_batching(q, ioc))
730 return;
731
732 ioc->nr_batch_requests = q->nr_batching;
733 ioc->last_waited = jiffies;
734}
735
1faa16d2 736static void __freed_request(struct request_queue *q, int sync)
1da177e4
LT
737{
738 struct request_list *rl = &q->rq;
739
1faa16d2
JA
740 if (rl->count[sync] < queue_congestion_off_threshold(q))
741 blk_clear_queue_congested(q, sync);
1da177e4 742
1faa16d2
JA
743 if (rl->count[sync] + 1 <= q->nr_requests) {
744 if (waitqueue_active(&rl->wait[sync]))
745 wake_up(&rl->wait[sync]);
1da177e4 746
1faa16d2 747 blk_clear_queue_full(q, sync);
1da177e4
LT
748 }
749}
750
751/*
752 * A request has just been released. Account for it, update the full and
753 * congestion status, wake up any waiters. Called under q->queue_lock.
754 */
1faa16d2 755static void freed_request(struct request_queue *q, int sync, int priv)
1da177e4
LT
756{
757 struct request_list *rl = &q->rq;
758
1faa16d2 759 rl->count[sync]--;
cb98fc8b
TH
760 if (priv)
761 rl->elvpriv--;
1da177e4 762
1faa16d2 763 __freed_request(q, sync);
1da177e4 764
1faa16d2
JA
765 if (unlikely(rl->starved[sync ^ 1]))
766 __freed_request(q, sync ^ 1);
1da177e4
LT
767}
768
9d5a4e94
MS
769/*
770 * Determine if elevator data should be initialized when allocating the
771 * request associated with @bio.
772 */
773static bool blk_rq_should_init_elevator(struct bio *bio)
774{
775 if (!bio)
776 return true;
777
778 /*
779 * Flush requests do not use the elevator so skip initialization.
780 * This allows a request to share the flush and elevator data.
781 */
782 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
783 return false;
784
785 return true;
786}
787
1da177e4 788/*
d6344532
NP
789 * Get a free request, queue_lock must be held.
790 * Returns NULL on failure, with queue_lock held.
791 * Returns !NULL on success, with queue_lock *not held*.
1da177e4 792 */
165125e1 793static struct request *get_request(struct request_queue *q, int rw_flags,
7749a8d4 794 struct bio *bio, gfp_t gfp_mask)
1da177e4
LT
795{
796 struct request *rq = NULL;
797 struct request_list *rl = &q->rq;
88ee5ef1 798 struct io_context *ioc = NULL;
1faa16d2 799 const bool is_sync = rw_is_sync(rw_flags) != 0;
9d5a4e94 800 int may_queue, priv = 0;
88ee5ef1 801
7749a8d4 802 may_queue = elv_may_queue(q, rw_flags);
88ee5ef1
JA
803 if (may_queue == ELV_MQUEUE_NO)
804 goto rq_starved;
805
1faa16d2
JA
806 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
807 if (rl->count[is_sync]+1 >= q->nr_requests) {
b5deef90 808 ioc = current_io_context(GFP_ATOMIC, q->node);
88ee5ef1
JA
809 /*
810 * The queue will fill after this allocation, so set
811 * it as full, and mark this process as "batching".
812 * This process will be allowed to complete a batch of
813 * requests, others will be blocked.
814 */
1faa16d2 815 if (!blk_queue_full(q, is_sync)) {
88ee5ef1 816 ioc_set_batching(q, ioc);
1faa16d2 817 blk_set_queue_full(q, is_sync);
88ee5ef1
JA
818 } else {
819 if (may_queue != ELV_MQUEUE_MUST
820 && !ioc_batching(q, ioc)) {
821 /*
822 * The queue is full and the allocating
823 * process is not a "batcher", and not
824 * exempted by the IO scheduler
825 */
826 goto out;
827 }
828 }
1da177e4 829 }
1faa16d2 830 blk_set_queue_congested(q, is_sync);
1da177e4
LT
831 }
832
082cf69e
JA
833 /*
834 * Only allow batching queuers to allocate up to 50% over the defined
835 * limit of requests, otherwise we could have thousands of requests
836 * allocated with any setting of ->nr_requests
837 */
1faa16d2 838 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
082cf69e 839 goto out;
fd782a4a 840
1faa16d2
JA
841 rl->count[is_sync]++;
842 rl->starved[is_sync] = 0;
cb98fc8b 843
9d5a4e94
MS
844 if (blk_rq_should_init_elevator(bio)) {
845 priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
846 if (priv)
847 rl->elvpriv++;
848 }
cb98fc8b 849
f253b86b
JA
850 if (blk_queue_io_stat(q))
851 rw_flags |= REQ_IO_STAT;
1da177e4
LT
852 spin_unlock_irq(q->queue_lock);
853
7749a8d4 854 rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
88ee5ef1 855 if (unlikely(!rq)) {
1da177e4
LT
856 /*
857 * Allocation failed presumably due to memory. Undo anything
858 * we might have messed up.
859 *
860 * Allocating task should really be put onto the front of the
861 * wait queue, but this is pretty rare.
862 */
863 spin_lock_irq(q->queue_lock);
1faa16d2 864 freed_request(q, is_sync, priv);
1da177e4
LT
865
866 /*
867 * in the very unlikely event that allocation failed and no
868 * requests for this direction was pending, mark us starved
869 * so that freeing of a request in the other direction will
870 * notice us. another possible fix would be to split the
871 * rq mempool into READ and WRITE
872 */
873rq_starved:
1faa16d2
JA
874 if (unlikely(rl->count[is_sync] == 0))
875 rl->starved[is_sync] = 1;
1da177e4 876
1da177e4
LT
877 goto out;
878 }
879
88ee5ef1
JA
880 /*
881 * ioc may be NULL here, and ioc_batching will be false. That's
882 * OK, if the queue is under the request limit then requests need
883 * not count toward the nr_batch_requests limit. There will always
884 * be some limit enforced by BLK_BATCH_TIME.
885 */
1da177e4
LT
886 if (ioc_batching(q, ioc))
887 ioc->nr_batch_requests--;
6728cb0e 888
1faa16d2 889 trace_block_getrq(q, bio, rw_flags & 1);
1da177e4 890out:
1da177e4
LT
891 return rq;
892}
893
894/*
895 * No available requests for this queue, unplug the device and wait for some
896 * requests to become available.
d6344532
NP
897 *
898 * Called with q->queue_lock held, and returns with it unlocked.
1da177e4 899 */
165125e1 900static struct request *get_request_wait(struct request_queue *q, int rw_flags,
22e2c507 901 struct bio *bio)
1da177e4 902{
1faa16d2 903 const bool is_sync = rw_is_sync(rw_flags) != 0;
1da177e4
LT
904 struct request *rq;
905
7749a8d4 906 rq = get_request(q, rw_flags, bio, GFP_NOIO);
450991bc
NP
907 while (!rq) {
908 DEFINE_WAIT(wait);
05caf8db 909 struct io_context *ioc;
1da177e4
LT
910 struct request_list *rl = &q->rq;
911
1faa16d2 912 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1da177e4
LT
913 TASK_UNINTERRUPTIBLE);
914
1faa16d2 915 trace_block_sleeprq(q, bio, rw_flags & 1);
1da177e4 916
05caf8db
ZY
917 __generic_unplug_device(q);
918 spin_unlock_irq(q->queue_lock);
919 io_schedule();
1da177e4 920
05caf8db
ZY
921 /*
922 * After sleeping, we become a "batching" process and
923 * will be able to allocate at least one request, and
924 * up to a big batch of them for a small period time.
925 * See ioc_batching, ioc_set_batching
926 */
927 ioc = current_io_context(GFP_NOIO, q->node);
928 ioc_set_batching(q, ioc);
d6344532 929
05caf8db 930 spin_lock_irq(q->queue_lock);
1faa16d2 931 finish_wait(&rl->wait[is_sync], &wait);
05caf8db
ZY
932
933 rq = get_request(q, rw_flags, bio, GFP_NOIO);
934 };
1da177e4
LT
935
936 return rq;
937}
938
165125e1 939struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1da177e4
LT
940{
941 struct request *rq;
942
943 BUG_ON(rw != READ && rw != WRITE);
944
d6344532
NP
945 spin_lock_irq(q->queue_lock);
946 if (gfp_mask & __GFP_WAIT) {
22e2c507 947 rq = get_request_wait(q, rw, NULL);
d6344532 948 } else {
22e2c507 949 rq = get_request(q, rw, NULL, gfp_mask);
d6344532
NP
950 if (!rq)
951 spin_unlock_irq(q->queue_lock);
952 }
953 /* q->queue_lock is unlocked at this point */
1da177e4
LT
954
955 return rq;
956}
1da177e4
LT
957EXPORT_SYMBOL(blk_get_request);
958
dc72ef4a 959/**
79eb63e9 960 * blk_make_request - given a bio, allocate a corresponding struct request.
8ebf9756 961 * @q: target request queue
79eb63e9
BH
962 * @bio: The bio describing the memory mappings that will be submitted for IO.
963 * It may be a chained-bio properly constructed by block/bio layer.
8ebf9756 964 * @gfp_mask: gfp flags to be used for memory allocation
dc72ef4a 965 *
79eb63e9
BH
966 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
967 * type commands. Where the struct request needs to be farther initialized by
968 * the caller. It is passed a &struct bio, which describes the memory info of
969 * the I/O transfer.
dc72ef4a 970 *
79eb63e9
BH
971 * The caller of blk_make_request must make sure that bi_io_vec
972 * are set to describe the memory buffers. That bio_data_dir() will return
973 * the needed direction of the request. (And all bio's in the passed bio-chain
974 * are properly set accordingly)
975 *
976 * If called under none-sleepable conditions, mapped bio buffers must not
977 * need bouncing, by calling the appropriate masked or flagged allocator,
978 * suitable for the target device. Otherwise the call to blk_queue_bounce will
979 * BUG.
53674ac5
JA
980 *
981 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
982 * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
983 * anything but the first bio in the chain. Otherwise you risk waiting for IO
984 * completion of a bio that hasn't been submitted yet, thus resulting in a
985 * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
986 * of bio_alloc(), as that avoids the mempool deadlock.
987 * If possible a big IO should be split into smaller parts when allocation
988 * fails. Partial allocation should not be an error, or you risk a live-lock.
dc72ef4a 989 */
79eb63e9
BH
990struct request *blk_make_request(struct request_queue *q, struct bio *bio,
991 gfp_t gfp_mask)
dc72ef4a 992{
79eb63e9
BH
993 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
994
995 if (unlikely(!rq))
996 return ERR_PTR(-ENOMEM);
997
998 for_each_bio(bio) {
999 struct bio *bounce_bio = bio;
1000 int ret;
1001
1002 blk_queue_bounce(q, &bounce_bio);
1003 ret = blk_rq_append_bio(q, rq, bounce_bio);
1004 if (unlikely(ret)) {
1005 blk_put_request(rq);
1006 return ERR_PTR(ret);
1007 }
1008 }
1009
1010 return rq;
dc72ef4a 1011}
79eb63e9 1012EXPORT_SYMBOL(blk_make_request);
dc72ef4a 1013
1da177e4
LT
1014/**
1015 * blk_requeue_request - put a request back on queue
1016 * @q: request queue where request should be inserted
1017 * @rq: request to be inserted
1018 *
1019 * Description:
1020 * Drivers often keep queueing requests until the hardware cannot accept
1021 * more, when that condition happens we need to put the request back
1022 * on the queue. Must be called with queue lock held.
1023 */
165125e1 1024void blk_requeue_request(struct request_queue *q, struct request *rq)
1da177e4 1025{
242f9dcb
JA
1026 blk_delete_timer(rq);
1027 blk_clear_rq_complete(rq);
5f3ea37c 1028 trace_block_rq_requeue(q, rq);
2056a782 1029
1da177e4
LT
1030 if (blk_rq_tagged(rq))
1031 blk_queue_end_tag(q, rq);
1032
ba396a6c
JB
1033 BUG_ON(blk_queued_rq(rq));
1034
1da177e4
LT
1035 elv_requeue_request(q, rq);
1036}
1da177e4
LT
1037EXPORT_SYMBOL(blk_requeue_request);
1038
1039/**
710027a4 1040 * blk_insert_request - insert a special request into a request queue
1da177e4
LT
1041 * @q: request queue where request should be inserted
1042 * @rq: request to be inserted
1043 * @at_head: insert request at head or tail of queue
1044 * @data: private data
1da177e4
LT
1045 *
1046 * Description:
1047 * Many block devices need to execute commands asynchronously, so they don't
1048 * block the whole kernel from preemption during request execution. This is
1049 * accomplished normally by inserting aritficial requests tagged as
710027a4
RD
1050 * REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them
1051 * be scheduled for actual execution by the request queue.
1da177e4
LT
1052 *
1053 * We have the option of inserting the head or the tail of the queue.
1054 * Typically we use the tail for new ioctls and so forth. We use the head
1055 * of the queue for things like a QUEUE_FULL message from a device, or a
1056 * host that is unable to accept a particular command.
1057 */
165125e1 1058void blk_insert_request(struct request_queue *q, struct request *rq,
867d1191 1059 int at_head, void *data)
1da177e4 1060{
867d1191 1061 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
1da177e4
LT
1062 unsigned long flags;
1063
1064 /*
1065 * tell I/O scheduler that this isn't a regular read/write (ie it
1066 * must not attempt merges on this) and that it acts as a soft
1067 * barrier
1068 */
4aff5e23 1069 rq->cmd_type = REQ_TYPE_SPECIAL;
1da177e4
LT
1070
1071 rq->special = data;
1072
1073 spin_lock_irqsave(q->queue_lock, flags);
1074
1075 /*
1076 * If command is tagged, release the tag
1077 */
867d1191
TH
1078 if (blk_rq_tagged(rq))
1079 blk_queue_end_tag(q, rq);
1da177e4 1080
b238b3d4 1081 drive_stat_acct(rq, 1);
867d1191 1082 __elv_add_request(q, rq, where, 0);
a7f55792 1083 __blk_run_queue(q);
1da177e4
LT
1084 spin_unlock_irqrestore(q->queue_lock, flags);
1085}
1da177e4
LT
1086EXPORT_SYMBOL(blk_insert_request);
1087
074a7aca
TH
1088static void part_round_stats_single(int cpu, struct hd_struct *part,
1089 unsigned long now)
1090{
1091 if (now == part->stamp)
1092 return;
1093
316d315b 1094 if (part_in_flight(part)) {
074a7aca 1095 __part_stat_add(cpu, part, time_in_queue,
316d315b 1096 part_in_flight(part) * (now - part->stamp));
074a7aca
TH
1097 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1098 }
1099 part->stamp = now;
1100}
1101
1102/**
496aa8a9
RD
1103 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1104 * @cpu: cpu number for stats access
1105 * @part: target partition
1da177e4
LT
1106 *
1107 * The average IO queue length and utilisation statistics are maintained
1108 * by observing the current state of the queue length and the amount of
1109 * time it has been in this state for.
1110 *
1111 * Normally, that accounting is done on IO completion, but that can result
1112 * in more than a second's worth of IO being accounted for within any one
1113 * second, leading to >100% utilisation. To deal with that, we call this
1114 * function to do a round-off before returning the results when reading
1115 * /proc/diskstats. This accounts immediately for all queue usage up to
1116 * the current jiffies and restarts the counters again.
1117 */
c9959059 1118void part_round_stats(int cpu, struct hd_struct *part)
6f2576af
JM
1119{
1120 unsigned long now = jiffies;
1121
074a7aca
TH
1122 if (part->partno)
1123 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1124 part_round_stats_single(cpu, part, now);
6f2576af 1125}
074a7aca 1126EXPORT_SYMBOL_GPL(part_round_stats);
6f2576af 1127
1da177e4
LT
1128/*
1129 * queue lock must be held
1130 */
165125e1 1131void __blk_put_request(struct request_queue *q, struct request *req)
1da177e4 1132{
1da177e4
LT
1133 if (unlikely(!q))
1134 return;
1135 if (unlikely(--req->ref_count))
1136 return;
1137
8922e16c
TH
1138 elv_completed_request(q, req);
1139
1cd96c24
BH
1140 /* this is a bio leak */
1141 WARN_ON(req->bio != NULL);
1142
1da177e4
LT
1143 /*
1144 * Request may not have originated from ll_rw_blk. if not,
1145 * it didn't come out of our reserved rq pools
1146 */
49171e5c 1147 if (req->cmd_flags & REQ_ALLOCED) {
1faa16d2 1148 int is_sync = rq_is_sync(req) != 0;
4aff5e23 1149 int priv = req->cmd_flags & REQ_ELVPRIV;
1da177e4 1150
1da177e4 1151 BUG_ON(!list_empty(&req->queuelist));
9817064b 1152 BUG_ON(!hlist_unhashed(&req->hash));
1da177e4
LT
1153
1154 blk_free_request(q, req);
1faa16d2 1155 freed_request(q, is_sync, priv);
1da177e4
LT
1156 }
1157}
6e39b69e
MC
1158EXPORT_SYMBOL_GPL(__blk_put_request);
1159
1da177e4
LT
1160void blk_put_request(struct request *req)
1161{
8922e16c 1162 unsigned long flags;
165125e1 1163 struct request_queue *q = req->q;
8922e16c 1164
52a93ba8
FT
1165 spin_lock_irqsave(q->queue_lock, flags);
1166 __blk_put_request(q, req);
1167 spin_unlock_irqrestore(q->queue_lock, flags);
1da177e4 1168}
1da177e4
LT
1169EXPORT_SYMBOL(blk_put_request);
1170
66ac0280
CH
1171/**
1172 * blk_add_request_payload - add a payload to a request
1173 * @rq: request to update
1174 * @page: page backing the payload
1175 * @len: length of the payload.
1176 *
1177 * This allows to later add a payload to an already submitted request by
1178 * a block driver. The driver needs to take care of freeing the payload
1179 * itself.
1180 *
1181 * Note that this is a quite horrible hack and nothing but handling of
1182 * discard requests should ever use it.
1183 */
1184void blk_add_request_payload(struct request *rq, struct page *page,
1185 unsigned int len)
1186{
1187 struct bio *bio = rq->bio;
1188
1189 bio->bi_io_vec->bv_page = page;
1190 bio->bi_io_vec->bv_offset = 0;
1191 bio->bi_io_vec->bv_len = len;
1192
1193 bio->bi_size = len;
1194 bio->bi_vcnt = 1;
1195 bio->bi_phys_segments = 1;
1196
1197 rq->__data_len = rq->resid_len = len;
1198 rq->nr_phys_segments = 1;
1199 rq->buffer = bio_data(bio);
1200}
1201EXPORT_SYMBOL_GPL(blk_add_request_payload);
1202
86db1e29 1203void init_request_from_bio(struct request *req, struct bio *bio)
52d9e675 1204{
c7c22e4d 1205 req->cpu = bio->bi_comp_cpu;
4aff5e23 1206 req->cmd_type = REQ_TYPE_FS;
52d9e675 1207
7b6d91da
CH
1208 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1209 if (bio->bi_rw & REQ_RAHEAD)
a82afdfc 1210 req->cmd_flags |= REQ_FAILFAST_MASK;
b31dc66a 1211
52d9e675 1212 req->errors = 0;
a2dec7b3 1213 req->__sector = bio->bi_sector;
52d9e675 1214 req->ioprio = bio_prio(bio);
bc1c56fd 1215 blk_rq_bio_prep(req->q, req, bio);
52d9e675
TH
1216}
1217
644b2d99
JA
1218/*
1219 * Only disabling plugging for non-rotational devices if it does tagging
1220 * as well, otherwise we do need the proper merging
1221 */
1222static inline bool queue_should_plug(struct request_queue *q)
1223{
79da0644 1224 return !(blk_queue_nonrot(q) && blk_queue_tagged(q));
644b2d99
JA
1225}
1226
165125e1 1227static int __make_request(struct request_queue *q, struct bio *bio)
1da177e4 1228{
450991bc 1229 struct request *req;
2e46e8b2
TH
1230 int el_ret;
1231 unsigned int bytes = bio->bi_size;
51da90fc 1232 const unsigned short prio = bio_prio(bio);
5e00d1b5
JS
1233 const bool sync = !!(bio->bi_rw & REQ_SYNC);
1234 const bool unplug = !!(bio->bi_rw & REQ_UNPLUG);
1235 const unsigned long ff = bio->bi_rw & REQ_FAILFAST_MASK;
28e7d184 1236 int where = ELEVATOR_INSERT_SORT;
7749a8d4 1237 int rw_flags;
1da177e4 1238
1da177e4
LT
1239 /*
1240 * low level driver can indicate that it wants pages above a
1241 * certain limit bounced to low memory (ie for highmem, or even
1242 * ISA dma in theory)
1243 */
1244 blk_queue_bounce(q, &bio);
1245
1da177e4
LT
1246 spin_lock_irq(q->queue_lock);
1247
4fed947c 1248 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
ae1b1539 1249 where = ELEVATOR_INSERT_FLUSH;
28e7d184
TH
1250 goto get_rq;
1251 }
1252
1253 if (elv_queue_empty(q))
1da177e4
LT
1254 goto get_rq;
1255
1256 el_ret = elv_merge(q, &req, bio);
1257 switch (el_ret) {
6728cb0e
JA
1258 case ELEVATOR_BACK_MERGE:
1259 BUG_ON(!rq_mergeable(req));
1da177e4 1260
6728cb0e
JA
1261 if (!ll_back_merge_fn(q, req, bio))
1262 break;
1da177e4 1263
5f3ea37c 1264 trace_block_bio_backmerge(q, bio);
2056a782 1265
80a761fd
TH
1266 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1267 blk_rq_set_mixed_merge(req);
1268
6728cb0e
JA
1269 req->biotail->bi_next = bio;
1270 req->biotail = bio;
a2dec7b3 1271 req->__data_len += bytes;
6728cb0e 1272 req->ioprio = ioprio_best(req->ioprio, prio);
ab780f1e
JA
1273 if (!blk_rq_cpu_valid(req))
1274 req->cpu = bio->bi_comp_cpu;
6728cb0e 1275 drive_stat_acct(req, 0);
812d4026 1276 elv_bio_merged(q, req, bio);
6728cb0e
JA
1277 if (!attempt_back_merge(q, req))
1278 elv_merged_request(q, req, el_ret);
1279 goto out;
1da177e4 1280
6728cb0e
JA
1281 case ELEVATOR_FRONT_MERGE:
1282 BUG_ON(!rq_mergeable(req));
1da177e4 1283
6728cb0e
JA
1284 if (!ll_front_merge_fn(q, req, bio))
1285 break;
1da177e4 1286
5f3ea37c 1287 trace_block_bio_frontmerge(q, bio);
2056a782 1288
80a761fd
TH
1289 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff) {
1290 blk_rq_set_mixed_merge(req);
1291 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1292 req->cmd_flags |= ff;
1293 }
1294
6728cb0e
JA
1295 bio->bi_next = req->bio;
1296 req->bio = bio;
1da177e4 1297
6728cb0e
JA
1298 /*
1299 * may not be valid. if the low level driver said
1300 * it didn't need a bounce buffer then it better
1301 * not touch req->buffer either...
1302 */
1303 req->buffer = bio_data(bio);
a2dec7b3
TH
1304 req->__sector = bio->bi_sector;
1305 req->__data_len += bytes;
6728cb0e 1306 req->ioprio = ioprio_best(req->ioprio, prio);
ab780f1e
JA
1307 if (!blk_rq_cpu_valid(req))
1308 req->cpu = bio->bi_comp_cpu;
6728cb0e 1309 drive_stat_acct(req, 0);
812d4026 1310 elv_bio_merged(q, req, bio);
6728cb0e
JA
1311 if (!attempt_front_merge(q, req))
1312 elv_merged_request(q, req, el_ret);
1313 goto out;
1314
1315 /* ELV_NO_MERGE: elevator says don't/can't merge. */
1316 default:
1317 ;
1da177e4
LT
1318 }
1319
450991bc 1320get_rq:
7749a8d4
JA
1321 /*
1322 * This sync check and mask will be re-done in init_request_from_bio(),
1323 * but we need to set it earlier to expose the sync flag to the
1324 * rq allocator and io schedulers.
1325 */
1326 rw_flags = bio_data_dir(bio);
1327 if (sync)
7b6d91da 1328 rw_flags |= REQ_SYNC;
7749a8d4 1329
1da177e4 1330 /*
450991bc 1331 * Grab a free request. This is might sleep but can not fail.
d6344532 1332 * Returns with the queue unlocked.
450991bc 1333 */
7749a8d4 1334 req = get_request_wait(q, rw_flags, bio);
d6344532 1335
450991bc
NP
1336 /*
1337 * After dropping the lock and possibly sleeping here, our request
1338 * may now be mergeable after it had proven unmergeable (above).
1339 * We don't worry about that case for efficiency. It won't happen
1340 * often, and the elevators are able to handle it.
1da177e4 1341 */
52d9e675 1342 init_request_from_bio(req, bio);
1da177e4 1343
450991bc 1344 spin_lock_irq(q->queue_lock);
c7c22e4d
JA
1345 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags) ||
1346 bio_flagged(bio, BIO_CPU_AFFINE))
1347 req->cpu = blk_cpu_to_group(smp_processor_id());
644b2d99 1348 if (queue_should_plug(q) && elv_queue_empty(q))
450991bc 1349 blk_plug_device(q);
dd831006
TH
1350
1351 /* insert the request into the elevator */
1352 drive_stat_acct(req, 1);
28e7d184 1353 __elv_add_request(q, req, where, 0);
1da177e4 1354out:
644b2d99 1355 if (unplug || !queue_should_plug(q))
1da177e4 1356 __generic_unplug_device(q);
1da177e4
LT
1357 spin_unlock_irq(q->queue_lock);
1358 return 0;
1da177e4
LT
1359}
1360
1361/*
1362 * If bio->bi_dev is a partition, remap the location
1363 */
1364static inline void blk_partition_remap(struct bio *bio)
1365{
1366 struct block_device *bdev = bio->bi_bdev;
1367
bf2de6f5 1368 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1da177e4
LT
1369 struct hd_struct *p = bdev->bd_part;
1370
1da177e4
LT
1371 bio->bi_sector += p->start_sect;
1372 bio->bi_bdev = bdev->bd_contains;
c7149d6b 1373
d07335e5
MS
1374 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1375 bdev->bd_dev,
1376 bio->bi_sector - p->start_sect);
1da177e4
LT
1377 }
1378}
1379
1da177e4
LT
1380static void handle_bad_sector(struct bio *bio)
1381{
1382 char b[BDEVNAME_SIZE];
1383
1384 printk(KERN_INFO "attempt to access beyond end of device\n");
1385 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1386 bdevname(bio->bi_bdev, b),
1387 bio->bi_rw,
1388 (unsigned long long)bio->bi_sector + bio_sectors(bio),
77304d2a 1389 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1da177e4
LT
1390
1391 set_bit(BIO_EOF, &bio->bi_flags);
1392}
1393
c17bb495
AM
1394#ifdef CONFIG_FAIL_MAKE_REQUEST
1395
1396static DECLARE_FAULT_ATTR(fail_make_request);
1397
1398static int __init setup_fail_make_request(char *str)
1399{
1400 return setup_fault_attr(&fail_make_request, str);
1401}
1402__setup("fail_make_request=", setup_fail_make_request);
1403
1404static int should_fail_request(struct bio *bio)
1405{
eddb2e26
TH
1406 struct hd_struct *part = bio->bi_bdev->bd_part;
1407
1408 if (part_to_disk(part)->part0.make_it_fail || part->make_it_fail)
c17bb495
AM
1409 return should_fail(&fail_make_request, bio->bi_size);
1410
1411 return 0;
1412}
1413
1414static int __init fail_make_request_debugfs(void)
1415{
1416 return init_fault_attr_dentries(&fail_make_request,
1417 "fail_make_request");
1418}
1419
1420late_initcall(fail_make_request_debugfs);
1421
1422#else /* CONFIG_FAIL_MAKE_REQUEST */
1423
1424static inline int should_fail_request(struct bio *bio)
1425{
1426 return 0;
1427}
1428
1429#endif /* CONFIG_FAIL_MAKE_REQUEST */
1430
c07e2b41
JA
1431/*
1432 * Check whether this bio extends beyond the end of the device.
1433 */
1434static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1435{
1436 sector_t maxsector;
1437
1438 if (!nr_sectors)
1439 return 0;
1440
1441 /* Test device or partition size, when known. */
77304d2a 1442 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
c07e2b41
JA
1443 if (maxsector) {
1444 sector_t sector = bio->bi_sector;
1445
1446 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1447 /*
1448 * This may well happen - the kernel calls bread()
1449 * without checking the size of the device, e.g., when
1450 * mounting a device.
1451 */
1452 handle_bad_sector(bio);
1453 return 1;
1454 }
1455 }
1456
1457 return 0;
1458}
1459
1da177e4 1460/**
710027a4 1461 * generic_make_request - hand a buffer to its device driver for I/O
1da177e4
LT
1462 * @bio: The bio describing the location in memory and on the device.
1463 *
1464 * generic_make_request() is used to make I/O requests of block
1465 * devices. It is passed a &struct bio, which describes the I/O that needs
1466 * to be done.
1467 *
1468 * generic_make_request() does not return any status. The
1469 * success/failure status of the request, along with notification of
1470 * completion, is delivered asynchronously through the bio->bi_end_io
1471 * function described (one day) else where.
1472 *
1473 * The caller of generic_make_request must make sure that bi_io_vec
1474 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1475 * set to describe the device address, and the
1476 * bi_end_io and optionally bi_private are set to describe how
1477 * completion notification should be signaled.
1478 *
1479 * generic_make_request and the drivers it calls may use bi_next if this
1480 * bio happens to be merged with someone else, and may change bi_dev and
1481 * bi_sector for remaps as it sees fit. So the values of these fields
1482 * should NOT be depended on after the call to generic_make_request.
1483 */
d89d8796 1484static inline void __generic_make_request(struct bio *bio)
1da177e4 1485{
165125e1 1486 struct request_queue *q;
5ddfe969 1487 sector_t old_sector;
1da177e4 1488 int ret, nr_sectors = bio_sectors(bio);
2056a782 1489 dev_t old_dev;
51fd77bd 1490 int err = -EIO;
1da177e4
LT
1491
1492 might_sleep();
1da177e4 1493
c07e2b41
JA
1494 if (bio_check_eod(bio, nr_sectors))
1495 goto end_io;
1da177e4
LT
1496
1497 /*
1498 * Resolve the mapping until finished. (drivers are
1499 * still free to implement/resolve their own stacking
1500 * by explicitly returning 0)
1501 *
1502 * NOTE: we don't repeat the blk_size check for each new device.
1503 * Stacking drivers are expected to know what they are doing.
1504 */
5ddfe969 1505 old_sector = -1;
2056a782 1506 old_dev = 0;
1da177e4
LT
1507 do {
1508 char b[BDEVNAME_SIZE];
1509
1510 q = bdev_get_queue(bio->bi_bdev);
a7384677 1511 if (unlikely(!q)) {
1da177e4
LT
1512 printk(KERN_ERR
1513 "generic_make_request: Trying to access "
1514 "nonexistent block-device %s (%Lu)\n",
1515 bdevname(bio->bi_bdev, b),
1516 (long long) bio->bi_sector);
a7384677 1517 goto end_io;
1da177e4
LT
1518 }
1519
7b6d91da 1520 if (unlikely(!(bio->bi_rw & REQ_DISCARD) &&
67efc925 1521 nr_sectors > queue_max_hw_sectors(q))) {
6728cb0e 1522 printk(KERN_ERR "bio too big device %s (%u > %u)\n",
ae03bf63
MP
1523 bdevname(bio->bi_bdev, b),
1524 bio_sectors(bio),
1525 queue_max_hw_sectors(q));
1da177e4
LT
1526 goto end_io;
1527 }
1528
fde6ad22 1529 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1da177e4
LT
1530 goto end_io;
1531
c17bb495
AM
1532 if (should_fail_request(bio))
1533 goto end_io;
1534
1da177e4
LT
1535 /*
1536 * If this device has partitions, remap block n
1537 * of partition p to block n+start(p) of the disk.
1538 */
1539 blk_partition_remap(bio);
1540
7ba1ba12
MP
1541 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
1542 goto end_io;
1543
5ddfe969 1544 if (old_sector != -1)
d07335e5 1545 trace_block_bio_remap(q, bio, old_dev, old_sector);
2056a782 1546
5ddfe969 1547 old_sector = bio->bi_sector;
2056a782
JA
1548 old_dev = bio->bi_bdev->bd_dev;
1549
c07e2b41
JA
1550 if (bio_check_eod(bio, nr_sectors))
1551 goto end_io;
a7384677 1552
1e87901e
TH
1553 /*
1554 * Filter flush bio's early so that make_request based
1555 * drivers without flush support don't have to worry
1556 * about them.
1557 */
1558 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1559 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1560 if (!nr_sectors) {
1561 err = 0;
1562 goto end_io;
1563 }
1564 }
1565
8d57a98c
AH
1566 if ((bio->bi_rw & REQ_DISCARD) &&
1567 (!blk_queue_discard(q) ||
1568 ((bio->bi_rw & REQ_SECURE) &&
1569 !blk_queue_secdiscard(q)))) {
51fd77bd
JA
1570 err = -EOPNOTSUPP;
1571 goto end_io;
1572 }
5ddfe969 1573
e43473b7
VG
1574 blk_throtl_bio(q, &bio);
1575
1576 /*
1577 * If bio = NULL, bio has been throttled and will be submitted
1578 * later.
1579 */
1580 if (!bio)
1581 break;
1582
01edede4
MK
1583 trace_block_bio_queue(q, bio);
1584
1da177e4
LT
1585 ret = q->make_request_fn(q, bio);
1586 } while (ret);
a7384677
TH
1587
1588 return;
1589
1590end_io:
1591 bio_endio(bio, err);
1da177e4
LT
1592}
1593
d89d8796
NB
1594/*
1595 * We only want one ->make_request_fn to be active at a time,
1596 * else stack usage with stacked devices could be a problem.
bddd87c7 1597 * So use current->bio_list to keep a list of requests
d89d8796 1598 * submited by a make_request_fn function.
bddd87c7 1599 * current->bio_list is also used as a flag to say if
d89d8796
NB
1600 * generic_make_request is currently active in this task or not.
1601 * If it is NULL, then no make_request is active. If it is non-NULL,
1602 * then a make_request is active, and new requests should be added
1603 * at the tail
1604 */
1605void generic_make_request(struct bio *bio)
1606{
bddd87c7
AM
1607 struct bio_list bio_list_on_stack;
1608
1609 if (current->bio_list) {
d89d8796 1610 /* make_request is active */
bddd87c7 1611 bio_list_add(current->bio_list, bio);
d89d8796
NB
1612 return;
1613 }
1614 /* following loop may be a bit non-obvious, and so deserves some
1615 * explanation.
1616 * Before entering the loop, bio->bi_next is NULL (as all callers
1617 * ensure that) so we have a list with a single bio.
1618 * We pretend that we have just taken it off a longer list, so
bddd87c7
AM
1619 * we assign bio_list to a pointer to the bio_list_on_stack,
1620 * thus initialising the bio_list of new bios to be
d89d8796
NB
1621 * added. __generic_make_request may indeed add some more bios
1622 * through a recursive call to generic_make_request. If it
1623 * did, we find a non-NULL value in bio_list and re-enter the loop
1624 * from the top. In this case we really did just take the bio
bddd87c7
AM
1625 * of the top of the list (no pretending) and so remove it from
1626 * bio_list, and call into __generic_make_request again.
d89d8796
NB
1627 *
1628 * The loop was structured like this to make only one call to
1629 * __generic_make_request (which is important as it is large and
1630 * inlined) and to keep the structure simple.
1631 */
1632 BUG_ON(bio->bi_next);
bddd87c7
AM
1633 bio_list_init(&bio_list_on_stack);
1634 current->bio_list = &bio_list_on_stack;
d89d8796 1635 do {
d89d8796 1636 __generic_make_request(bio);
bddd87c7 1637 bio = bio_list_pop(current->bio_list);
d89d8796 1638 } while (bio);
bddd87c7 1639 current->bio_list = NULL; /* deactivate */
d89d8796 1640}
1da177e4
LT
1641EXPORT_SYMBOL(generic_make_request);
1642
1643/**
710027a4 1644 * submit_bio - submit a bio to the block device layer for I/O
1da177e4
LT
1645 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1646 * @bio: The &struct bio which describes the I/O
1647 *
1648 * submit_bio() is very similar in purpose to generic_make_request(), and
1649 * uses that function to do most of the work. Both are fairly rough
710027a4 1650 * interfaces; @bio must be presetup and ready for I/O.
1da177e4
LT
1651 *
1652 */
1653void submit_bio(int rw, struct bio *bio)
1654{
1655 int count = bio_sectors(bio);
1656
22e2c507 1657 bio->bi_rw |= rw;
1da177e4 1658
bf2de6f5
JA
1659 /*
1660 * If it's a regular read/write or a barrier with data attached,
1661 * go through the normal accounting stuff before submission.
1662 */
3ffb52e7 1663 if (bio_has_data(bio) && !(rw & REQ_DISCARD)) {
bf2de6f5
JA
1664 if (rw & WRITE) {
1665 count_vm_events(PGPGOUT, count);
1666 } else {
1667 task_io_account_read(bio->bi_size);
1668 count_vm_events(PGPGIN, count);
1669 }
1670
1671 if (unlikely(block_dump)) {
1672 char b[BDEVNAME_SIZE];
8dcbdc74 1673 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
ba25f9dc 1674 current->comm, task_pid_nr(current),
bf2de6f5
JA
1675 (rw & WRITE) ? "WRITE" : "READ",
1676 (unsigned long long)bio->bi_sector,
8dcbdc74
SM
1677 bdevname(bio->bi_bdev, b),
1678 count);
bf2de6f5 1679 }
1da177e4
LT
1680 }
1681
1682 generic_make_request(bio);
1683}
1da177e4
LT
1684EXPORT_SYMBOL(submit_bio);
1685
82124d60
KU
1686/**
1687 * blk_rq_check_limits - Helper function to check a request for the queue limit
1688 * @q: the queue
1689 * @rq: the request being checked
1690 *
1691 * Description:
1692 * @rq may have been made based on weaker limitations of upper-level queues
1693 * in request stacking drivers, and it may violate the limitation of @q.
1694 * Since the block layer and the underlying device driver trust @rq
1695 * after it is inserted to @q, it should be checked against @q before
1696 * the insertion using this generic function.
1697 *
1698 * This function should also be useful for request stacking drivers
eef35c2d 1699 * in some cases below, so export this function.
82124d60
KU
1700 * Request stacking drivers like request-based dm may change the queue
1701 * limits while requests are in the queue (e.g. dm's table swapping).
1702 * Such request stacking drivers should check those requests agaist
1703 * the new queue limits again when they dispatch those requests,
1704 * although such checkings are also done against the old queue limits
1705 * when submitting requests.
1706 */
1707int blk_rq_check_limits(struct request_queue *q, struct request *rq)
1708{
3383977f
S
1709 if (rq->cmd_flags & REQ_DISCARD)
1710 return 0;
1711
ae03bf63
MP
1712 if (blk_rq_sectors(rq) > queue_max_sectors(q) ||
1713 blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {
82124d60
KU
1714 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1715 return -EIO;
1716 }
1717
1718 /*
1719 * queue's settings related to segment counting like q->bounce_pfn
1720 * may differ from that of other stacking queues.
1721 * Recalculate it to check the request correctly on this queue's
1722 * limitation.
1723 */
1724 blk_recalc_rq_segments(rq);
8a78362c 1725 if (rq->nr_phys_segments > queue_max_segments(q)) {
82124d60
KU
1726 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1727 return -EIO;
1728 }
1729
1730 return 0;
1731}
1732EXPORT_SYMBOL_GPL(blk_rq_check_limits);
1733
1734/**
1735 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1736 * @q: the queue to submit the request
1737 * @rq: the request being queued
1738 */
1739int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1740{
1741 unsigned long flags;
1742
1743 if (blk_rq_check_limits(q, rq))
1744 return -EIO;
1745
1746#ifdef CONFIG_FAIL_MAKE_REQUEST
1747 if (rq->rq_disk && rq->rq_disk->part0.make_it_fail &&
1748 should_fail(&fail_make_request, blk_rq_bytes(rq)))
1749 return -EIO;
1750#endif
1751
1752 spin_lock_irqsave(q->queue_lock, flags);
1753
1754 /*
1755 * Submitting request must be dequeued before calling this function
1756 * because it will be linked to another request_queue
1757 */
1758 BUG_ON(blk_queued_rq(rq));
1759
1760 drive_stat_acct(rq, 1);
1761 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
1762
1763 spin_unlock_irqrestore(q->queue_lock, flags);
1764
1765 return 0;
1766}
1767EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1768
80a761fd
TH
1769/**
1770 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1771 * @rq: request to examine
1772 *
1773 * Description:
1774 * A request could be merge of IOs which require different failure
1775 * handling. This function determines the number of bytes which
1776 * can be failed from the beginning of the request without
1777 * crossing into area which need to be retried further.
1778 *
1779 * Return:
1780 * The number of bytes to fail.
1781 *
1782 * Context:
1783 * queue_lock must be held.
1784 */
1785unsigned int blk_rq_err_bytes(const struct request *rq)
1786{
1787 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
1788 unsigned int bytes = 0;
1789 struct bio *bio;
1790
1791 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
1792 return blk_rq_bytes(rq);
1793
1794 /*
1795 * Currently the only 'mixing' which can happen is between
1796 * different fastfail types. We can safely fail portions
1797 * which have all the failfast bits that the first one has -
1798 * the ones which are at least as eager to fail as the first
1799 * one.
1800 */
1801 for (bio = rq->bio; bio; bio = bio->bi_next) {
1802 if ((bio->bi_rw & ff) != ff)
1803 break;
1804 bytes += bio->bi_size;
1805 }
1806
1807 /* this could lead to infinite loop */
1808 BUG_ON(blk_rq_bytes(rq) && !bytes);
1809 return bytes;
1810}
1811EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
1812
bc58ba94
JA
1813static void blk_account_io_completion(struct request *req, unsigned int bytes)
1814{
c2553b58 1815 if (blk_do_io_stat(req)) {
bc58ba94
JA
1816 const int rw = rq_data_dir(req);
1817 struct hd_struct *part;
1818 int cpu;
1819
1820 cpu = part_stat_lock();
09e099d4 1821 part = req->part;
bc58ba94
JA
1822 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
1823 part_stat_unlock();
1824 }
1825}
1826
1827static void blk_account_io_done(struct request *req)
1828{
bc58ba94 1829 /*
dd4c133f
TH
1830 * Account IO completion. flush_rq isn't accounted as a
1831 * normal IO on queueing nor completion. Accounting the
1832 * containing request is enough.
bc58ba94 1833 */
414b4ff5 1834 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
bc58ba94
JA
1835 unsigned long duration = jiffies - req->start_time;
1836 const int rw = rq_data_dir(req);
1837 struct hd_struct *part;
1838 int cpu;
1839
1840 cpu = part_stat_lock();
09e099d4 1841 part = req->part;
bc58ba94
JA
1842
1843 part_stat_inc(cpu, part, ios[rw]);
1844 part_stat_add(cpu, part, ticks[rw], duration);
1845 part_round_stats(cpu, part);
316d315b 1846 part_dec_in_flight(part, rw);
bc58ba94 1847
6c23a968 1848 hd_struct_put(part);
bc58ba94
JA
1849 part_stat_unlock();
1850 }
1851}
1852
3bcddeac 1853/**
9934c8c0
TH
1854 * blk_peek_request - peek at the top of a request queue
1855 * @q: request queue to peek at
1856 *
1857 * Description:
1858 * Return the request at the top of @q. The returned request
1859 * should be started using blk_start_request() before LLD starts
1860 * processing it.
1861 *
1862 * Return:
1863 * Pointer to the request at the top of @q if available. Null
1864 * otherwise.
1865 *
1866 * Context:
1867 * queue_lock must be held.
1868 */
1869struct request *blk_peek_request(struct request_queue *q)
158dbda0
TH
1870{
1871 struct request *rq;
1872 int ret;
1873
1874 while ((rq = __elv_next_request(q)) != NULL) {
1875 if (!(rq->cmd_flags & REQ_STARTED)) {
1876 /*
1877 * This is the first time the device driver
1878 * sees this request (possibly after
1879 * requeueing). Notify IO scheduler.
1880 */
33659ebb 1881 if (rq->cmd_flags & REQ_SORTED)
158dbda0
TH
1882 elv_activate_rq(q, rq);
1883
1884 /*
1885 * just mark as started even if we don't start
1886 * it, a request that has been delayed should
1887 * not be passed by new incoming requests
1888 */
1889 rq->cmd_flags |= REQ_STARTED;
1890 trace_block_rq_issue(q, rq);
1891 }
1892
1893 if (!q->boundary_rq || q->boundary_rq == rq) {
1894 q->end_sector = rq_end_sector(rq);
1895 q->boundary_rq = NULL;
1896 }
1897
1898 if (rq->cmd_flags & REQ_DONTPREP)
1899 break;
1900
2e46e8b2 1901 if (q->dma_drain_size && blk_rq_bytes(rq)) {
158dbda0
TH
1902 /*
1903 * make sure space for the drain appears we
1904 * know we can do this because max_hw_segments
1905 * has been adjusted to be one fewer than the
1906 * device can handle
1907 */
1908 rq->nr_phys_segments++;
1909 }
1910
1911 if (!q->prep_rq_fn)
1912 break;
1913
1914 ret = q->prep_rq_fn(q, rq);
1915 if (ret == BLKPREP_OK) {
1916 break;
1917 } else if (ret == BLKPREP_DEFER) {
1918 /*
1919 * the request may have been (partially) prepped.
1920 * we need to keep this request in the front to
1921 * avoid resource deadlock. REQ_STARTED will
1922 * prevent other fs requests from passing this one.
1923 */
2e46e8b2 1924 if (q->dma_drain_size && blk_rq_bytes(rq) &&
158dbda0
TH
1925 !(rq->cmd_flags & REQ_DONTPREP)) {
1926 /*
1927 * remove the space for the drain we added
1928 * so that we don't add it again
1929 */
1930 --rq->nr_phys_segments;
1931 }
1932
1933 rq = NULL;
1934 break;
1935 } else if (ret == BLKPREP_KILL) {
1936 rq->cmd_flags |= REQ_QUIET;
c143dc90
JB
1937 /*
1938 * Mark this request as started so we don't trigger
1939 * any debug logic in the end I/O path.
1940 */
1941 blk_start_request(rq);
40cbbb78 1942 __blk_end_request_all(rq, -EIO);
158dbda0
TH
1943 } else {
1944 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
1945 break;
1946 }
1947 }
1948
1949 return rq;
1950}
9934c8c0 1951EXPORT_SYMBOL(blk_peek_request);
158dbda0 1952
9934c8c0 1953void blk_dequeue_request(struct request *rq)
158dbda0 1954{
9934c8c0
TH
1955 struct request_queue *q = rq->q;
1956
158dbda0
TH
1957 BUG_ON(list_empty(&rq->queuelist));
1958 BUG_ON(ELV_ON_HASH(rq));
1959
1960 list_del_init(&rq->queuelist);
1961
1962 /*
1963 * the time frame between a request being removed from the lists
1964 * and to it is freed is accounted as io that is in progress at
1965 * the driver side.
1966 */
9195291e 1967 if (blk_account_rq(rq)) {
0a7ae2ff 1968 q->in_flight[rq_is_sync(rq)]++;
9195291e
DS
1969 set_io_start_time_ns(rq);
1970 }
158dbda0
TH
1971}
1972
9934c8c0
TH
1973/**
1974 * blk_start_request - start request processing on the driver
1975 * @req: request to dequeue
1976 *
1977 * Description:
1978 * Dequeue @req and start timeout timer on it. This hands off the
1979 * request to the driver.
1980 *
1981 * Block internal functions which don't want to start timer should
1982 * call blk_dequeue_request().
1983 *
1984 * Context:
1985 * queue_lock must be held.
1986 */
1987void blk_start_request(struct request *req)
1988{
1989 blk_dequeue_request(req);
1990
1991 /*
5f49f631
TH
1992 * We are now handing the request to the hardware, initialize
1993 * resid_len to full count and add the timeout handler.
9934c8c0 1994 */
5f49f631 1995 req->resid_len = blk_rq_bytes(req);
dbb66c4b
FT
1996 if (unlikely(blk_bidi_rq(req)))
1997 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
1998
9934c8c0
TH
1999 blk_add_timer(req);
2000}
2001EXPORT_SYMBOL(blk_start_request);
2002
2003/**
2004 * blk_fetch_request - fetch a request from a request queue
2005 * @q: request queue to fetch a request from
2006 *
2007 * Description:
2008 * Return the request at the top of @q. The request is started on
2009 * return and LLD can start processing it immediately.
2010 *
2011 * Return:
2012 * Pointer to the request at the top of @q if available. Null
2013 * otherwise.
2014 *
2015 * Context:
2016 * queue_lock must be held.
2017 */
2018struct request *blk_fetch_request(struct request_queue *q)
2019{
2020 struct request *rq;
2021
2022 rq = blk_peek_request(q);
2023 if (rq)
2024 blk_start_request(rq);
2025 return rq;
2026}
2027EXPORT_SYMBOL(blk_fetch_request);
2028
3bcddeac 2029/**
2e60e022 2030 * blk_update_request - Special helper function for request stacking drivers
8ebf9756 2031 * @req: the request being processed
710027a4 2032 * @error: %0 for success, < %0 for error
8ebf9756 2033 * @nr_bytes: number of bytes to complete @req
3bcddeac
KU
2034 *
2035 * Description:
8ebf9756
RD
2036 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2037 * the request structure even if @req doesn't have leftover.
2038 * If @req has leftover, sets it up for the next range of segments.
2e60e022
TH
2039 *
2040 * This special helper function is only for request stacking drivers
2041 * (e.g. request-based dm) so that they can handle partial completion.
2042 * Actual device drivers should use blk_end_request instead.
2043 *
2044 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2045 * %false return from this function.
3bcddeac
KU
2046 *
2047 * Return:
2e60e022
TH
2048 * %false - this request doesn't have any more data
2049 * %true - this request has more data
3bcddeac 2050 **/
2e60e022 2051bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
1da177e4 2052{
5450d3e1 2053 int total_bytes, bio_nbytes, next_idx = 0;
1da177e4
LT
2054 struct bio *bio;
2055
2e60e022
TH
2056 if (!req->bio)
2057 return false;
2058
5f3ea37c 2059 trace_block_rq_complete(req->q, req);
2056a782 2060
1da177e4 2061 /*
6f41469c
TH
2062 * For fs requests, rq is just carrier of independent bio's
2063 * and each partial completion should be handled separately.
2064 * Reset per-request error on each partial completion.
2065 *
2066 * TODO: tj: This is too subtle. It would be better to let
2067 * low level drivers do what they see fit.
1da177e4 2068 */
33659ebb 2069 if (req->cmd_type == REQ_TYPE_FS)
1da177e4
LT
2070 req->errors = 0;
2071
33659ebb
CH
2072 if (error && req->cmd_type == REQ_TYPE_FS &&
2073 !(req->cmd_flags & REQ_QUIET)) {
6728cb0e 2074 printk(KERN_ERR "end_request: I/O error, dev %s, sector %llu\n",
1da177e4 2075 req->rq_disk ? req->rq_disk->disk_name : "?",
83096ebf 2076 (unsigned long long)blk_rq_pos(req));
1da177e4
LT
2077 }
2078
bc58ba94 2079 blk_account_io_completion(req, nr_bytes);
d72d904a 2080
1da177e4
LT
2081 total_bytes = bio_nbytes = 0;
2082 while ((bio = req->bio) != NULL) {
2083 int nbytes;
2084
2085 if (nr_bytes >= bio->bi_size) {
2086 req->bio = bio->bi_next;
2087 nbytes = bio->bi_size;
5bb23a68 2088 req_bio_endio(req, bio, nbytes, error);
1da177e4
LT
2089 next_idx = 0;
2090 bio_nbytes = 0;
2091 } else {
2092 int idx = bio->bi_idx + next_idx;
2093
af498d7f 2094 if (unlikely(idx >= bio->bi_vcnt)) {
1da177e4 2095 blk_dump_rq_flags(req, "__end_that");
6728cb0e 2096 printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
af498d7f 2097 __func__, idx, bio->bi_vcnt);
1da177e4
LT
2098 break;
2099 }
2100
2101 nbytes = bio_iovec_idx(bio, idx)->bv_len;
2102 BIO_BUG_ON(nbytes > bio->bi_size);
2103
2104 /*
2105 * not a complete bvec done
2106 */
2107 if (unlikely(nbytes > nr_bytes)) {
2108 bio_nbytes += nr_bytes;
2109 total_bytes += nr_bytes;
2110 break;
2111 }
2112
2113 /*
2114 * advance to the next vector
2115 */
2116 next_idx++;
2117 bio_nbytes += nbytes;
2118 }
2119
2120 total_bytes += nbytes;
2121 nr_bytes -= nbytes;
2122
6728cb0e
JA
2123 bio = req->bio;
2124 if (bio) {
1da177e4
LT
2125 /*
2126 * end more in this run, or just return 'not-done'
2127 */
2128 if (unlikely(nr_bytes <= 0))
2129 break;
2130 }
2131 }
2132
2133 /*
2134 * completely done
2135 */
2e60e022
TH
2136 if (!req->bio) {
2137 /*
2138 * Reset counters so that the request stacking driver
2139 * can find how many bytes remain in the request
2140 * later.
2141 */
a2dec7b3 2142 req->__data_len = 0;
2e60e022
TH
2143 return false;
2144 }
1da177e4
LT
2145
2146 /*
2147 * if the request wasn't completed, update state
2148 */
2149 if (bio_nbytes) {
5bb23a68 2150 req_bio_endio(req, bio, bio_nbytes, error);
1da177e4
LT
2151 bio->bi_idx += next_idx;
2152 bio_iovec(bio)->bv_offset += nr_bytes;
2153 bio_iovec(bio)->bv_len -= nr_bytes;
2154 }
2155
a2dec7b3 2156 req->__data_len -= total_bytes;
2e46e8b2
TH
2157 req->buffer = bio_data(req->bio);
2158
2159 /* update sector only for requests with clear definition of sector */
33659ebb 2160 if (req->cmd_type == REQ_TYPE_FS || (req->cmd_flags & REQ_DISCARD))
a2dec7b3 2161 req->__sector += total_bytes >> 9;
2e46e8b2 2162
80a761fd
TH
2163 /* mixed attributes always follow the first bio */
2164 if (req->cmd_flags & REQ_MIXED_MERGE) {
2165 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2166 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2167 }
2168
2e46e8b2
TH
2169 /*
2170 * If total number of sectors is less than the first segment
2171 * size, something has gone terribly wrong.
2172 */
2173 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2174 printk(KERN_ERR "blk: request botched\n");
a2dec7b3 2175 req->__data_len = blk_rq_cur_bytes(req);
2e46e8b2
TH
2176 }
2177
2178 /* recalculate the number of segments */
1da177e4 2179 blk_recalc_rq_segments(req);
2e46e8b2 2180
2e60e022 2181 return true;
1da177e4 2182}
2e60e022 2183EXPORT_SYMBOL_GPL(blk_update_request);
1da177e4 2184
2e60e022
TH
2185static bool blk_update_bidi_request(struct request *rq, int error,
2186 unsigned int nr_bytes,
2187 unsigned int bidi_bytes)
5efccd17 2188{
2e60e022
TH
2189 if (blk_update_request(rq, error, nr_bytes))
2190 return true;
5efccd17 2191
2e60e022
TH
2192 /* Bidi request must be completed as a whole */
2193 if (unlikely(blk_bidi_rq(rq)) &&
2194 blk_update_request(rq->next_rq, error, bidi_bytes))
2195 return true;
5efccd17 2196
e2e1a148
JA
2197 if (blk_queue_add_random(rq->q))
2198 add_disk_randomness(rq->rq_disk);
2e60e022
TH
2199
2200 return false;
1da177e4
LT
2201}
2202
28018c24
JB
2203/**
2204 * blk_unprep_request - unprepare a request
2205 * @req: the request
2206 *
2207 * This function makes a request ready for complete resubmission (or
2208 * completion). It happens only after all error handling is complete,
2209 * so represents the appropriate moment to deallocate any resources
2210 * that were allocated to the request in the prep_rq_fn. The queue
2211 * lock is held when calling this.
2212 */
2213void blk_unprep_request(struct request *req)
2214{
2215 struct request_queue *q = req->q;
2216
2217 req->cmd_flags &= ~REQ_DONTPREP;
2218 if (q->unprep_rq_fn)
2219 q->unprep_rq_fn(q, req);
2220}
2221EXPORT_SYMBOL_GPL(blk_unprep_request);
2222
1da177e4
LT
2223/*
2224 * queue lock must be held
2225 */
2e60e022 2226static void blk_finish_request(struct request *req, int error)
1da177e4 2227{
b8286239
KU
2228 if (blk_rq_tagged(req))
2229 blk_queue_end_tag(req->q, req);
2230
ba396a6c 2231 BUG_ON(blk_queued_rq(req));
1da177e4 2232
33659ebb 2233 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
31373d09 2234 laptop_io_completion(&req->q->backing_dev_info);
1da177e4 2235
e78042e5
MA
2236 blk_delete_timer(req);
2237
28018c24
JB
2238 if (req->cmd_flags & REQ_DONTPREP)
2239 blk_unprep_request(req);
2240
2241
bc58ba94 2242 blk_account_io_done(req);
b8286239 2243
1da177e4 2244 if (req->end_io)
8ffdc655 2245 req->end_io(req, error);
b8286239
KU
2246 else {
2247 if (blk_bidi_rq(req))
2248 __blk_put_request(req->next_rq->q, req->next_rq);
2249
1da177e4 2250 __blk_put_request(req->q, req);
b8286239 2251 }
1da177e4
LT
2252}
2253
3b11313a 2254/**
2e60e022
TH
2255 * blk_end_bidi_request - Complete a bidi request
2256 * @rq: the request to complete
2257 * @error: %0 for success, < %0 for error
2258 * @nr_bytes: number of bytes to complete @rq
2259 * @bidi_bytes: number of bytes to complete @rq->next_rq
a0cd1285
JA
2260 *
2261 * Description:
e3a04fe3 2262 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2e60e022
TH
2263 * Drivers that supports bidi can safely call this member for any
2264 * type of request, bidi or uni. In the later case @bidi_bytes is
2265 * just ignored.
336cdb40
KU
2266 *
2267 * Return:
2e60e022
TH
2268 * %false - we are done with this request
2269 * %true - still buffers pending for this request
a0cd1285 2270 **/
b1f74493 2271static bool blk_end_bidi_request(struct request *rq, int error,
32fab448
KU
2272 unsigned int nr_bytes, unsigned int bidi_bytes)
2273{
336cdb40 2274 struct request_queue *q = rq->q;
2e60e022 2275 unsigned long flags;
32fab448 2276
2e60e022
TH
2277 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2278 return true;
32fab448 2279
336cdb40 2280 spin_lock_irqsave(q->queue_lock, flags);
2e60e022 2281 blk_finish_request(rq, error);
336cdb40
KU
2282 spin_unlock_irqrestore(q->queue_lock, flags);
2283
2e60e022 2284 return false;
32fab448
KU
2285}
2286
336cdb40 2287/**
2e60e022
TH
2288 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2289 * @rq: the request to complete
710027a4 2290 * @error: %0 for success, < %0 for error
e3a04fe3
KU
2291 * @nr_bytes: number of bytes to complete @rq
2292 * @bidi_bytes: number of bytes to complete @rq->next_rq
336cdb40
KU
2293 *
2294 * Description:
2e60e022
TH
2295 * Identical to blk_end_bidi_request() except that queue lock is
2296 * assumed to be locked on entry and remains so on return.
336cdb40
KU
2297 *
2298 * Return:
2e60e022
TH
2299 * %false - we are done with this request
2300 * %true - still buffers pending for this request
336cdb40 2301 **/
b1f74493
FT
2302static bool __blk_end_bidi_request(struct request *rq, int error,
2303 unsigned int nr_bytes, unsigned int bidi_bytes)
336cdb40 2304{
2e60e022
TH
2305 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2306 return true;
336cdb40 2307
2e60e022 2308 blk_finish_request(rq, error);
336cdb40 2309
2e60e022 2310 return false;
336cdb40 2311}
e19a3ab0
KU
2312
2313/**
2314 * blk_end_request - Helper function for drivers to complete the request.
2315 * @rq: the request being processed
710027a4 2316 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2317 * @nr_bytes: number of bytes to complete
2318 *
2319 * Description:
2320 * Ends I/O on a number of bytes attached to @rq.
2321 * If @rq has leftover, sets it up for the next range of segments.
2322 *
2323 * Return:
b1f74493
FT
2324 * %false - we are done with this request
2325 * %true - still buffers pending for this request
e19a3ab0 2326 **/
b1f74493 2327bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e19a3ab0 2328{
b1f74493 2329 return blk_end_bidi_request(rq, error, nr_bytes, 0);
e19a3ab0 2330}
56ad1740 2331EXPORT_SYMBOL(blk_end_request);
336cdb40
KU
2332
2333/**
b1f74493
FT
2334 * blk_end_request_all - Helper function for drives to finish the request.
2335 * @rq: the request to finish
8ebf9756 2336 * @error: %0 for success, < %0 for error
336cdb40
KU
2337 *
2338 * Description:
b1f74493
FT
2339 * Completely finish @rq.
2340 */
2341void blk_end_request_all(struct request *rq, int error)
336cdb40 2342{
b1f74493
FT
2343 bool pending;
2344 unsigned int bidi_bytes = 0;
336cdb40 2345
b1f74493
FT
2346 if (unlikely(blk_bidi_rq(rq)))
2347 bidi_bytes = blk_rq_bytes(rq->next_rq);
336cdb40 2348
b1f74493
FT
2349 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2350 BUG_ON(pending);
2351}
56ad1740 2352EXPORT_SYMBOL(blk_end_request_all);
336cdb40 2353
b1f74493
FT
2354/**
2355 * blk_end_request_cur - Helper function to finish the current request chunk.
2356 * @rq: the request to finish the current chunk for
8ebf9756 2357 * @error: %0 for success, < %0 for error
b1f74493
FT
2358 *
2359 * Description:
2360 * Complete the current consecutively mapped chunk from @rq.
2361 *
2362 * Return:
2363 * %false - we are done with this request
2364 * %true - still buffers pending for this request
2365 */
2366bool blk_end_request_cur(struct request *rq, int error)
2367{
2368 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
336cdb40 2369}
56ad1740 2370EXPORT_SYMBOL(blk_end_request_cur);
336cdb40 2371
80a761fd
TH
2372/**
2373 * blk_end_request_err - Finish a request till the next failure boundary.
2374 * @rq: the request to finish till the next failure boundary for
2375 * @error: must be negative errno
2376 *
2377 * Description:
2378 * Complete @rq till the next failure boundary.
2379 *
2380 * Return:
2381 * %false - we are done with this request
2382 * %true - still buffers pending for this request
2383 */
2384bool blk_end_request_err(struct request *rq, int error)
2385{
2386 WARN_ON(error >= 0);
2387 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2388}
2389EXPORT_SYMBOL_GPL(blk_end_request_err);
2390
e3a04fe3 2391/**
b1f74493
FT
2392 * __blk_end_request - Helper function for drivers to complete the request.
2393 * @rq: the request being processed
2394 * @error: %0 for success, < %0 for error
2395 * @nr_bytes: number of bytes to complete
e3a04fe3
KU
2396 *
2397 * Description:
b1f74493 2398 * Must be called with queue lock held unlike blk_end_request().
e3a04fe3
KU
2399 *
2400 * Return:
b1f74493
FT
2401 * %false - we are done with this request
2402 * %true - still buffers pending for this request
e3a04fe3 2403 **/
b1f74493 2404bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e3a04fe3 2405{
b1f74493 2406 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
e3a04fe3 2407}
56ad1740 2408EXPORT_SYMBOL(__blk_end_request);
e3a04fe3 2409
32fab448 2410/**
b1f74493
FT
2411 * __blk_end_request_all - Helper function for drives to finish the request.
2412 * @rq: the request to finish
8ebf9756 2413 * @error: %0 for success, < %0 for error
32fab448
KU
2414 *
2415 * Description:
b1f74493 2416 * Completely finish @rq. Must be called with queue lock held.
32fab448 2417 */
b1f74493 2418void __blk_end_request_all(struct request *rq, int error)
32fab448 2419{
b1f74493
FT
2420 bool pending;
2421 unsigned int bidi_bytes = 0;
2422
2423 if (unlikely(blk_bidi_rq(rq)))
2424 bidi_bytes = blk_rq_bytes(rq->next_rq);
2425
2426 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2427 BUG_ON(pending);
32fab448 2428}
56ad1740 2429EXPORT_SYMBOL(__blk_end_request_all);
32fab448 2430
e19a3ab0 2431/**
b1f74493
FT
2432 * __blk_end_request_cur - Helper function to finish the current request chunk.
2433 * @rq: the request to finish the current chunk for
8ebf9756 2434 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2435 *
2436 * Description:
b1f74493
FT
2437 * Complete the current consecutively mapped chunk from @rq. Must
2438 * be called with queue lock held.
e19a3ab0
KU
2439 *
2440 * Return:
b1f74493
FT
2441 * %false - we are done with this request
2442 * %true - still buffers pending for this request
2443 */
2444bool __blk_end_request_cur(struct request *rq, int error)
e19a3ab0 2445{
b1f74493 2446 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
e19a3ab0 2447}
56ad1740 2448EXPORT_SYMBOL(__blk_end_request_cur);
e19a3ab0 2449
80a761fd
TH
2450/**
2451 * __blk_end_request_err - Finish a request till the next failure boundary.
2452 * @rq: the request to finish till the next failure boundary for
2453 * @error: must be negative errno
2454 *
2455 * Description:
2456 * Complete @rq till the next failure boundary. Must be called
2457 * with queue lock held.
2458 *
2459 * Return:
2460 * %false - we are done with this request
2461 * %true - still buffers pending for this request
2462 */
2463bool __blk_end_request_err(struct request *rq, int error)
2464{
2465 WARN_ON(error >= 0);
2466 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2467}
2468EXPORT_SYMBOL_GPL(__blk_end_request_err);
2469
86db1e29
JA
2470void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2471 struct bio *bio)
1da177e4 2472{
a82afdfc 2473 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
7b6d91da 2474 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
1da177e4 2475
fb2dce86
DW
2476 if (bio_has_data(bio)) {
2477 rq->nr_phys_segments = bio_phys_segments(q, bio);
fb2dce86
DW
2478 rq->buffer = bio_data(bio);
2479 }
a2dec7b3 2480 rq->__data_len = bio->bi_size;
1da177e4 2481 rq->bio = rq->biotail = bio;
1da177e4 2482
66846572
N
2483 if (bio->bi_bdev)
2484 rq->rq_disk = bio->bi_bdev->bd_disk;
2485}
1da177e4 2486
2d4dc890
IL
2487#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2488/**
2489 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2490 * @rq: the request to be flushed
2491 *
2492 * Description:
2493 * Flush all pages in @rq.
2494 */
2495void rq_flush_dcache_pages(struct request *rq)
2496{
2497 struct req_iterator iter;
2498 struct bio_vec *bvec;
2499
2500 rq_for_each_segment(bvec, rq, iter)
2501 flush_dcache_page(bvec->bv_page);
2502}
2503EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2504#endif
2505
ef9e3fac
KU
2506/**
2507 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2508 * @q : the queue of the device being checked
2509 *
2510 * Description:
2511 * Check if underlying low-level drivers of a device are busy.
2512 * If the drivers want to export their busy state, they must set own
2513 * exporting function using blk_queue_lld_busy() first.
2514 *
2515 * Basically, this function is used only by request stacking drivers
2516 * to stop dispatching requests to underlying devices when underlying
2517 * devices are busy. This behavior helps more I/O merging on the queue
2518 * of the request stacking driver and prevents I/O throughput regression
2519 * on burst I/O load.
2520 *
2521 * Return:
2522 * 0 - Not busy (The request stacking driver should dispatch request)
2523 * 1 - Busy (The request stacking driver should stop dispatching request)
2524 */
2525int blk_lld_busy(struct request_queue *q)
2526{
2527 if (q->lld_busy_fn)
2528 return q->lld_busy_fn(q);
2529
2530 return 0;
2531}
2532EXPORT_SYMBOL_GPL(blk_lld_busy);
2533
b0fd271d
KU
2534/**
2535 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2536 * @rq: the clone request to be cleaned up
2537 *
2538 * Description:
2539 * Free all bios in @rq for a cloned request.
2540 */
2541void blk_rq_unprep_clone(struct request *rq)
2542{
2543 struct bio *bio;
2544
2545 while ((bio = rq->bio) != NULL) {
2546 rq->bio = bio->bi_next;
2547
2548 bio_put(bio);
2549 }
2550}
2551EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2552
2553/*
2554 * Copy attributes of the original request to the clone request.
2555 * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2556 */
2557static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2558{
2559 dst->cpu = src->cpu;
3a2edd0d 2560 dst->cmd_flags = (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
b0fd271d
KU
2561 dst->cmd_type = src->cmd_type;
2562 dst->__sector = blk_rq_pos(src);
2563 dst->__data_len = blk_rq_bytes(src);
2564 dst->nr_phys_segments = src->nr_phys_segments;
2565 dst->ioprio = src->ioprio;
2566 dst->extra_len = src->extra_len;
2567}
2568
2569/**
2570 * blk_rq_prep_clone - Helper function to setup clone request
2571 * @rq: the request to be setup
2572 * @rq_src: original request to be cloned
2573 * @bs: bio_set that bios for clone are allocated from
2574 * @gfp_mask: memory allocation mask for bio
2575 * @bio_ctr: setup function to be called for each clone bio.
2576 * Returns %0 for success, non %0 for failure.
2577 * @data: private data to be passed to @bio_ctr
2578 *
2579 * Description:
2580 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2581 * The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2582 * are not copied, and copying such parts is the caller's responsibility.
2583 * Also, pages which the original bios are pointing to are not copied
2584 * and the cloned bios just point same pages.
2585 * So cloned bios must be completed before original bios, which means
2586 * the caller must complete @rq before @rq_src.
2587 */
2588int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2589 struct bio_set *bs, gfp_t gfp_mask,
2590 int (*bio_ctr)(struct bio *, struct bio *, void *),
2591 void *data)
2592{
2593 struct bio *bio, *bio_src;
2594
2595 if (!bs)
2596 bs = fs_bio_set;
2597
2598 blk_rq_init(NULL, rq);
2599
2600 __rq_for_each_bio(bio_src, rq_src) {
2601 bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);
2602 if (!bio)
2603 goto free_and_out;
2604
2605 __bio_clone(bio, bio_src);
2606
2607 if (bio_integrity(bio_src) &&
7878cba9 2608 bio_integrity_clone(bio, bio_src, gfp_mask, bs))
b0fd271d
KU
2609 goto free_and_out;
2610
2611 if (bio_ctr && bio_ctr(bio, bio_src, data))
2612 goto free_and_out;
2613
2614 if (rq->bio) {
2615 rq->biotail->bi_next = bio;
2616 rq->biotail = bio;
2617 } else
2618 rq->bio = rq->biotail = bio;
2619 }
2620
2621 __blk_rq_prep_clone(rq, rq_src);
2622
2623 return 0;
2624
2625free_and_out:
2626 if (bio)
2627 bio_free(bio, bs);
2628 blk_rq_unprep_clone(rq);
2629
2630 return -ENOMEM;
2631}
2632EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
2633
18887ad9 2634int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
1da177e4
LT
2635{
2636 return queue_work(kblockd_workqueue, work);
2637}
1da177e4
LT
2638EXPORT_SYMBOL(kblockd_schedule_work);
2639
e43473b7
VG
2640int kblockd_schedule_delayed_work(struct request_queue *q,
2641 struct delayed_work *dwork, unsigned long delay)
2642{
2643 return queue_delayed_work(kblockd_workqueue, dwork, delay);
2644}
2645EXPORT_SYMBOL(kblockd_schedule_delayed_work);
2646
1da177e4
LT
2647int __init blk_dev_init(void)
2648{
9eb55b03
NK
2649 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
2650 sizeof(((struct request *)0)->cmd_flags));
2651
89b90be2
TH
2652 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
2653 kblockd_workqueue = alloc_workqueue("kblockd",
2654 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1da177e4
LT
2655 if (!kblockd_workqueue)
2656 panic("Failed to create kblockd\n");
2657
2658 request_cachep = kmem_cache_create("blkdev_requests",
20c2df83 2659 sizeof(struct request), 0, SLAB_PANIC, NULL);
1da177e4 2660
8324aa91 2661 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
165125e1 2662 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1da177e4 2663
d38ecf93 2664 return 0;
1da177e4 2665}