block: fixup rq_init() a bit
[safe/jmp/linux-2.6] / block / blk-core.c
1 /*
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>
6  * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7  *      -  July2000
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  */
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>
24 #include <linux/completion.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/task_io_accounting_ops.h>
29 #include <linux/interrupt.h>
30 #include <linux/cpu.h>
31 #include <linux/blktrace_api.h>
32 #include <linux/fault-inject.h>
33
34 #include "blk.h"
35
36 static int __make_request(struct request_queue *q, struct bio *bio);
37
38 /*
39  * For the allocated request tables
40  */
41 struct kmem_cache *request_cachep;
42
43 /*
44  * For queue allocation
45  */
46 struct kmem_cache *blk_requestq_cachep;
47
48 /*
49  * Controlling structure to kblockd
50  */
51 static struct workqueue_struct *kblockd_workqueue;
52
53 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
54
55 static void drive_stat_acct(struct request *rq, int new_io)
56 {
57         int rw = rq_data_dir(rq);
58
59         if (!blk_fs_request(rq) || !rq->rq_disk)
60                 return;
61
62         if (!new_io) {
63                 __disk_stat_inc(rq->rq_disk, merges[rw]);
64         } else {
65                 disk_round_stats(rq->rq_disk);
66                 rq->rq_disk->in_flight++;
67         }
68 }
69
70 void blk_queue_congestion_threshold(struct request_queue *q)
71 {
72         int nr;
73
74         nr = q->nr_requests - (q->nr_requests / 8) + 1;
75         if (nr > q->nr_requests)
76                 nr = q->nr_requests;
77         q->nr_congestion_on = nr;
78
79         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
80         if (nr < 1)
81                 nr = 1;
82         q->nr_congestion_off = nr;
83 }
84
85 /**
86  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
87  * @bdev:       device
88  *
89  * Locates the passed device's request queue and returns the address of its
90  * backing_dev_info
91  *
92  * Will return NULL if the request queue cannot be located.
93  */
94 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
95 {
96         struct backing_dev_info *ret = NULL;
97         struct request_queue *q = bdev_get_queue(bdev);
98
99         if (q)
100                 ret = &q->backing_dev_info;
101         return ret;
102 }
103 EXPORT_SYMBOL(blk_get_backing_dev_info);
104
105 /*
106  * We can't just memset() the structure, since the allocation path
107  * already stored some information in the request.
108  */
109 void rq_init(struct request_queue *q, struct request *rq)
110 {
111         INIT_LIST_HEAD(&rq->queuelist);
112         INIT_LIST_HEAD(&rq->donelist);
113         rq->q = q;
114         rq->sector = rq->hard_sector = (sector_t) -1;
115         rq->nr_sectors = rq->hard_nr_sectors = 0;
116         rq->current_nr_sectors = rq->hard_cur_sectors = 0;
117         rq->bio = rq->biotail = NULL;
118         INIT_HLIST_NODE(&rq->hash);
119         RB_CLEAR_NODE(&rq->rb_node);
120         rq->rq_disk = NULL;
121         rq->nr_phys_segments = 0;
122         rq->nr_hw_segments = 0;
123         rq->ioprio = 0;
124         rq->special = NULL;
125         rq->buffer = NULL;
126         rq->tag = -1;
127         rq->errors = 0;
128         rq->ref_count = 1;
129         rq->cmd_len = 0;
130         memset(rq->cmd, 0, sizeof(rq->cmd));
131         rq->data_len = 0;
132         rq->sense_len = 0;
133         rq->data = NULL;
134         rq->sense = NULL;
135         rq->end_io = NULL;
136         rq->end_io_data = NULL;
137         rq->next_rq = NULL;
138 }
139
140 static void req_bio_endio(struct request *rq, struct bio *bio,
141                           unsigned int nbytes, int error)
142 {
143         struct request_queue *q = rq->q;
144
145         if (&q->bar_rq != rq) {
146                 if (error)
147                         clear_bit(BIO_UPTODATE, &bio->bi_flags);
148                 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
149                         error = -EIO;
150
151                 if (unlikely(nbytes > bio->bi_size)) {
152                         printk(KERN_ERR "%s: want %u bytes done, %u left\n",
153                                __FUNCTION__, nbytes, bio->bi_size);
154                         nbytes = bio->bi_size;
155                 }
156
157                 bio->bi_size -= nbytes;
158                 bio->bi_sector += (nbytes >> 9);
159                 if (bio->bi_size == 0)
160                         bio_endio(bio, error);
161         } else {
162
163                 /*
164                  * Okay, this is the barrier request in progress, just
165                  * record the error;
166                  */
167                 if (error && !q->orderr)
168                         q->orderr = error;
169         }
170 }
171
172 void blk_dump_rq_flags(struct request *rq, char *msg)
173 {
174         int bit;
175
176         printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
177                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
178                 rq->cmd_flags);
179
180         printk(KERN_INFO "  sector %llu, nr/cnr %lu/%u\n",
181                                                 (unsigned long long)rq->sector,
182                                                 rq->nr_sectors,
183                                                 rq->current_nr_sectors);
184         printk(KERN_INFO "  bio %p, biotail %p, buffer %p, data %p, len %u\n",
185                                                 rq->bio, rq->biotail,
186                                                 rq->buffer, rq->data,
187                                                 rq->data_len);
188
189         if (blk_pc_request(rq)) {
190                 printk(KERN_INFO "  cdb: ");
191                 for (bit = 0; bit < sizeof(rq->cmd); bit++)
192                         printk("%02x ", rq->cmd[bit]);
193                 printk("\n");
194         }
195 }
196 EXPORT_SYMBOL(blk_dump_rq_flags);
197
198 /*
199  * "plug" the device if there are no outstanding requests: this will
200  * force the transfer to start only after we have put all the requests
201  * on the list.
202  *
203  * This is called with interrupts off and no requests on the queue and
204  * with the queue lock held.
205  */
206 void blk_plug_device(struct request_queue *q)
207 {
208         WARN_ON(!irqs_disabled());
209
210         /*
211          * don't plug a stopped queue, it must be paired with blk_start_queue()
212          * which will restart the queueing
213          */
214         if (blk_queue_stopped(q))
215                 return;
216
217         if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
218                 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
219                 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
220         }
221 }
222 EXPORT_SYMBOL(blk_plug_device);
223
224 /*
225  * remove the queue from the plugged list, if present. called with
226  * queue lock held and interrupts disabled.
227  */
228 int blk_remove_plug(struct request_queue *q)
229 {
230         WARN_ON(!irqs_disabled());
231
232         if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
233                 return 0;
234
235         del_timer(&q->unplug_timer);
236         return 1;
237 }
238 EXPORT_SYMBOL(blk_remove_plug);
239
240 /*
241  * remove the plug and let it rip..
242  */
243 void __generic_unplug_device(struct request_queue *q)
244 {
245         if (unlikely(blk_queue_stopped(q)))
246                 return;
247
248         if (!blk_remove_plug(q))
249                 return;
250
251         q->request_fn(q);
252 }
253 EXPORT_SYMBOL(__generic_unplug_device);
254
255 /**
256  * generic_unplug_device - fire a request queue
257  * @q:    The &struct request_queue in question
258  *
259  * Description:
260  *   Linux uses plugging to build bigger requests queues before letting
261  *   the device have at them. If a queue is plugged, the I/O scheduler
262  *   is still adding and merging requests on the queue. Once the queue
263  *   gets unplugged, the request_fn defined for the queue is invoked and
264  *   transfers started.
265  **/
266 void generic_unplug_device(struct request_queue *q)
267 {
268         spin_lock_irq(q->queue_lock);
269         __generic_unplug_device(q);
270         spin_unlock_irq(q->queue_lock);
271 }
272 EXPORT_SYMBOL(generic_unplug_device);
273
274 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
275                                    struct page *page)
276 {
277         struct request_queue *q = bdi->unplug_io_data;
278
279         blk_unplug(q);
280 }
281
282 void blk_unplug_work(struct work_struct *work)
283 {
284         struct request_queue *q =
285                 container_of(work, struct request_queue, unplug_work);
286
287         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
288                                 q->rq.count[READ] + q->rq.count[WRITE]);
289
290         q->unplug_fn(q);
291 }
292
293 void blk_unplug_timeout(unsigned long data)
294 {
295         struct request_queue *q = (struct request_queue *)data;
296
297         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
298                                 q->rq.count[READ] + q->rq.count[WRITE]);
299
300         kblockd_schedule_work(&q->unplug_work);
301 }
302
303 void blk_unplug(struct request_queue *q)
304 {
305         /*
306          * devices don't necessarily have an ->unplug_fn defined
307          */
308         if (q->unplug_fn) {
309                 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
310                                         q->rq.count[READ] + q->rq.count[WRITE]);
311
312                 q->unplug_fn(q);
313         }
314 }
315 EXPORT_SYMBOL(blk_unplug);
316
317 /**
318  * blk_start_queue - restart a previously stopped queue
319  * @q:    The &struct request_queue in question
320  *
321  * Description:
322  *   blk_start_queue() will clear the stop flag on the queue, and call
323  *   the request_fn for the queue if it was in a stopped state when
324  *   entered. Also see blk_stop_queue(). Queue lock must be held.
325  **/
326 void blk_start_queue(struct request_queue *q)
327 {
328         WARN_ON(!irqs_disabled());
329
330         clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
331
332         /*
333          * one level of recursion is ok and is much faster than kicking
334          * the unplug handling
335          */
336         if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
337                 q->request_fn(q);
338                 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
339         } else {
340                 blk_plug_device(q);
341                 kblockd_schedule_work(&q->unplug_work);
342         }
343 }
344 EXPORT_SYMBOL(blk_start_queue);
345
346 /**
347  * blk_stop_queue - stop a queue
348  * @q:    The &struct request_queue in question
349  *
350  * Description:
351  *   The Linux block layer assumes that a block driver will consume all
352  *   entries on the request queue when the request_fn strategy is called.
353  *   Often this will not happen, because of hardware limitations (queue
354  *   depth settings). If a device driver gets a 'queue full' response,
355  *   or if it simply chooses not to queue more I/O at one point, it can
356  *   call this function to prevent the request_fn from being called until
357  *   the driver has signalled it's ready to go again. This happens by calling
358  *   blk_start_queue() to restart queue operations. Queue lock must be held.
359  **/
360 void blk_stop_queue(struct request_queue *q)
361 {
362         blk_remove_plug(q);
363         set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
364 }
365 EXPORT_SYMBOL(blk_stop_queue);
366
367 /**
368  * blk_sync_queue - cancel any pending callbacks on a queue
369  * @q: the queue
370  *
371  * Description:
372  *     The block layer may perform asynchronous callback activity
373  *     on a queue, such as calling the unplug function after a timeout.
374  *     A block device may call blk_sync_queue to ensure that any
375  *     such activity is cancelled, thus allowing it to release resources
376  *     that the callbacks might use. The caller must already have made sure
377  *     that its ->make_request_fn will not re-add plugging prior to calling
378  *     this function.
379  *
380  */
381 void blk_sync_queue(struct request_queue *q)
382 {
383         del_timer_sync(&q->unplug_timer);
384         kblockd_flush_work(&q->unplug_work);
385 }
386 EXPORT_SYMBOL(blk_sync_queue);
387
388 /**
389  * blk_run_queue - run a single device queue
390  * @q:  The queue to run
391  */
392 void blk_run_queue(struct request_queue *q)
393 {
394         unsigned long flags;
395
396         spin_lock_irqsave(q->queue_lock, flags);
397         blk_remove_plug(q);
398
399         /*
400          * Only recurse once to avoid overrunning the stack, let the unplug
401          * handling reinvoke the handler shortly if we already got there.
402          */
403         if (!elv_queue_empty(q)) {
404                 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
405                         q->request_fn(q);
406                         clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
407                 } else {
408                         blk_plug_device(q);
409                         kblockd_schedule_work(&q->unplug_work);
410                 }
411         }
412
413         spin_unlock_irqrestore(q->queue_lock, flags);
414 }
415 EXPORT_SYMBOL(blk_run_queue);
416
417 void blk_put_queue(struct request_queue *q)
418 {
419         kobject_put(&q->kobj);
420 }
421 EXPORT_SYMBOL(blk_put_queue);
422
423 void blk_cleanup_queue(struct request_queue *q)
424 {
425         mutex_lock(&q->sysfs_lock);
426         set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
427         mutex_unlock(&q->sysfs_lock);
428
429         if (q->elevator)
430                 elevator_exit(q->elevator);
431
432         blk_put_queue(q);
433 }
434 EXPORT_SYMBOL(blk_cleanup_queue);
435
436 static int blk_init_free_list(struct request_queue *q)
437 {
438         struct request_list *rl = &q->rq;
439
440         rl->count[READ] = rl->count[WRITE] = 0;
441         rl->starved[READ] = rl->starved[WRITE] = 0;
442         rl->elvpriv = 0;
443         init_waitqueue_head(&rl->wait[READ]);
444         init_waitqueue_head(&rl->wait[WRITE]);
445
446         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
447                                 mempool_free_slab, request_cachep, q->node);
448
449         if (!rl->rq_pool)
450                 return -ENOMEM;
451
452         return 0;
453 }
454
455 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
456 {
457         return blk_alloc_queue_node(gfp_mask, -1);
458 }
459 EXPORT_SYMBOL(blk_alloc_queue);
460
461 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
462 {
463         struct request_queue *q;
464         int err;
465
466         q = kmem_cache_alloc_node(blk_requestq_cachep,
467                                 gfp_mask | __GFP_ZERO, node_id);
468         if (!q)
469                 return NULL;
470
471         q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
472         q->backing_dev_info.unplug_io_data = q;
473         err = bdi_init(&q->backing_dev_info);
474         if (err) {
475                 kmem_cache_free(blk_requestq_cachep, q);
476                 return NULL;
477         }
478
479         init_timer(&q->unplug_timer);
480
481         kobject_init(&q->kobj, &blk_queue_ktype);
482
483         mutex_init(&q->sysfs_lock);
484
485         return q;
486 }
487 EXPORT_SYMBOL(blk_alloc_queue_node);
488
489 /**
490  * blk_init_queue  - prepare a request queue for use with a block device
491  * @rfn:  The function to be called to process requests that have been
492  *        placed on the queue.
493  * @lock: Request queue spin lock
494  *
495  * Description:
496  *    If a block device wishes to use the standard request handling procedures,
497  *    which sorts requests and coalesces adjacent requests, then it must
498  *    call blk_init_queue().  The function @rfn will be called when there
499  *    are requests on the queue that need to be processed.  If the device
500  *    supports plugging, then @rfn may not be called immediately when requests
501  *    are available on the queue, but may be called at some time later instead.
502  *    Plugged queues are generally unplugged when a buffer belonging to one
503  *    of the requests on the queue is needed, or due to memory pressure.
504  *
505  *    @rfn is not required, or even expected, to remove all requests off the
506  *    queue, but only as many as it can handle at a time.  If it does leave
507  *    requests on the queue, it is responsible for arranging that the requests
508  *    get dealt with eventually.
509  *
510  *    The queue spin lock must be held while manipulating the requests on the
511  *    request queue; this lock will be taken also from interrupt context, so irq
512  *    disabling is needed for it.
513  *
514  *    Function returns a pointer to the initialized request queue, or NULL if
515  *    it didn't succeed.
516  *
517  * Note:
518  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
519  *    when the block device is deactivated (such as at module unload).
520  **/
521
522 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
523 {
524         return blk_init_queue_node(rfn, lock, -1);
525 }
526 EXPORT_SYMBOL(blk_init_queue);
527
528 struct request_queue *
529 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
530 {
531         struct request_queue *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
532
533         if (!q)
534                 return NULL;
535
536         q->node = node_id;
537         if (blk_init_free_list(q)) {
538                 kmem_cache_free(blk_requestq_cachep, q);
539                 return NULL;
540         }
541
542         /*
543          * if caller didn't supply a lock, they get per-queue locking with
544          * our embedded lock
545          */
546         if (!lock) {
547                 spin_lock_init(&q->__queue_lock);
548                 lock = &q->__queue_lock;
549         }
550
551         q->request_fn           = rfn;
552         q->prep_rq_fn           = NULL;
553         q->unplug_fn            = generic_unplug_device;
554         q->queue_flags          = (1 << QUEUE_FLAG_CLUSTER);
555         q->queue_lock           = lock;
556
557         blk_queue_segment_boundary(q, 0xffffffff);
558
559         blk_queue_make_request(q, __make_request);
560         blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
561
562         blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
563         blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
564
565         q->sg_reserved_size = INT_MAX;
566
567         /*
568          * all done
569          */
570         if (!elevator_init(q, NULL)) {
571                 blk_queue_congestion_threshold(q);
572                 return q;
573         }
574
575         blk_put_queue(q);
576         return NULL;
577 }
578 EXPORT_SYMBOL(blk_init_queue_node);
579
580 int blk_get_queue(struct request_queue *q)
581 {
582         if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
583                 kobject_get(&q->kobj);
584                 return 0;
585         }
586
587         return 1;
588 }
589 EXPORT_SYMBOL(blk_get_queue);
590
591 static inline void blk_free_request(struct request_queue *q, struct request *rq)
592 {
593         if (rq->cmd_flags & REQ_ELVPRIV)
594                 elv_put_request(q, rq);
595         mempool_free(rq, q->rq.rq_pool);
596 }
597
598 static struct request *
599 blk_alloc_request(struct request_queue *q, int rw, int priv, gfp_t gfp_mask)
600 {
601         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
602
603         if (!rq)
604                 return NULL;
605
606         /*
607          * first three bits are identical in rq->cmd_flags and bio->bi_rw,
608          * see bio.h and blkdev.h
609          */
610         rq->cmd_flags = rw | REQ_ALLOCED;
611
612         if (priv) {
613                 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
614                         mempool_free(rq, q->rq.rq_pool);
615                         return NULL;
616                 }
617                 rq->cmd_flags |= REQ_ELVPRIV;
618         }
619
620         return rq;
621 }
622
623 /*
624  * ioc_batching returns true if the ioc is a valid batching request and
625  * should be given priority access to a request.
626  */
627 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
628 {
629         if (!ioc)
630                 return 0;
631
632         /*
633          * Make sure the process is able to allocate at least 1 request
634          * even if the batch times out, otherwise we could theoretically
635          * lose wakeups.
636          */
637         return ioc->nr_batch_requests == q->nr_batching ||
638                 (ioc->nr_batch_requests > 0
639                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
640 }
641
642 /*
643  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
644  * will cause the process to be a "batcher" on all queues in the system. This
645  * is the behaviour we want though - once it gets a wakeup it should be given
646  * a nice run.
647  */
648 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
649 {
650         if (!ioc || ioc_batching(q, ioc))
651                 return;
652
653         ioc->nr_batch_requests = q->nr_batching;
654         ioc->last_waited = jiffies;
655 }
656
657 static void __freed_request(struct request_queue *q, int rw)
658 {
659         struct request_list *rl = &q->rq;
660
661         if (rl->count[rw] < queue_congestion_off_threshold(q))
662                 blk_clear_queue_congested(q, rw);
663
664         if (rl->count[rw] + 1 <= q->nr_requests) {
665                 if (waitqueue_active(&rl->wait[rw]))
666                         wake_up(&rl->wait[rw]);
667
668                 blk_clear_queue_full(q, rw);
669         }
670 }
671
672 /*
673  * A request has just been released.  Account for it, update the full and
674  * congestion status, wake up any waiters.   Called under q->queue_lock.
675  */
676 static void freed_request(struct request_queue *q, int rw, int priv)
677 {
678         struct request_list *rl = &q->rq;
679
680         rl->count[rw]--;
681         if (priv)
682                 rl->elvpriv--;
683
684         __freed_request(q, rw);
685
686         if (unlikely(rl->starved[rw ^ 1]))
687                 __freed_request(q, rw ^ 1);
688 }
689
690 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
691 /*
692  * Get a free request, queue_lock must be held.
693  * Returns NULL on failure, with queue_lock held.
694  * Returns !NULL on success, with queue_lock *not held*.
695  */
696 static struct request *get_request(struct request_queue *q, int rw_flags,
697                                    struct bio *bio, gfp_t gfp_mask)
698 {
699         struct request *rq = NULL;
700         struct request_list *rl = &q->rq;
701         struct io_context *ioc = NULL;
702         const int rw = rw_flags & 0x01;
703         int may_queue, priv;
704
705         may_queue = elv_may_queue(q, rw_flags);
706         if (may_queue == ELV_MQUEUE_NO)
707                 goto rq_starved;
708
709         if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
710                 if (rl->count[rw]+1 >= q->nr_requests) {
711                         ioc = current_io_context(GFP_ATOMIC, q->node);
712                         /*
713                          * The queue will fill after this allocation, so set
714                          * it as full, and mark this process as "batching".
715                          * This process will be allowed to complete a batch of
716                          * requests, others will be blocked.
717                          */
718                         if (!blk_queue_full(q, rw)) {
719                                 ioc_set_batching(q, ioc);
720                                 blk_set_queue_full(q, rw);
721                         } else {
722                                 if (may_queue != ELV_MQUEUE_MUST
723                                                 && !ioc_batching(q, ioc)) {
724                                         /*
725                                          * The queue is full and the allocating
726                                          * process is not a "batcher", and not
727                                          * exempted by the IO scheduler
728                                          */
729                                         goto out;
730                                 }
731                         }
732                 }
733                 blk_set_queue_congested(q, rw);
734         }
735
736         /*
737          * Only allow batching queuers to allocate up to 50% over the defined
738          * limit of requests, otherwise we could have thousands of requests
739          * allocated with any setting of ->nr_requests
740          */
741         if (rl->count[rw] >= (3 * q->nr_requests / 2))
742                 goto out;
743
744         rl->count[rw]++;
745         rl->starved[rw] = 0;
746
747         priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
748         if (priv)
749                 rl->elvpriv++;
750
751         spin_unlock_irq(q->queue_lock);
752
753         rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
754         if (unlikely(!rq)) {
755                 /*
756                  * Allocation failed presumably due to memory. Undo anything
757                  * we might have messed up.
758                  *
759                  * Allocating task should really be put onto the front of the
760                  * wait queue, but this is pretty rare.
761                  */
762                 spin_lock_irq(q->queue_lock);
763                 freed_request(q, rw, priv);
764
765                 /*
766                  * in the very unlikely event that allocation failed and no
767                  * requests for this direction was pending, mark us starved
768                  * so that freeing of a request in the other direction will
769                  * notice us. another possible fix would be to split the
770                  * rq mempool into READ and WRITE
771                  */
772 rq_starved:
773                 if (unlikely(rl->count[rw] == 0))
774                         rl->starved[rw] = 1;
775
776                 goto out;
777         }
778
779         /*
780          * ioc may be NULL here, and ioc_batching will be false. That's
781          * OK, if the queue is under the request limit then requests need
782          * not count toward the nr_batch_requests limit. There will always
783          * be some limit enforced by BLK_BATCH_TIME.
784          */
785         if (ioc_batching(q, ioc))
786                 ioc->nr_batch_requests--;
787
788         rq_init(q, rq);
789
790         blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
791 out:
792         return rq;
793 }
794
795 /*
796  * No available requests for this queue, unplug the device and wait for some
797  * requests to become available.
798  *
799  * Called with q->queue_lock held, and returns with it unlocked.
800  */
801 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
802                                         struct bio *bio)
803 {
804         const int rw = rw_flags & 0x01;
805         struct request *rq;
806
807         rq = get_request(q, rw_flags, bio, GFP_NOIO);
808         while (!rq) {
809                 DEFINE_WAIT(wait);
810                 struct request_list *rl = &q->rq;
811
812                 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
813                                 TASK_UNINTERRUPTIBLE);
814
815                 rq = get_request(q, rw_flags, bio, GFP_NOIO);
816
817                 if (!rq) {
818                         struct io_context *ioc;
819
820                         blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
821
822                         __generic_unplug_device(q);
823                         spin_unlock_irq(q->queue_lock);
824                         io_schedule();
825
826                         /*
827                          * After sleeping, we become a "batching" process and
828                          * will be able to allocate at least one request, and
829                          * up to a big batch of them for a small period time.
830                          * See ioc_batching, ioc_set_batching
831                          */
832                         ioc = current_io_context(GFP_NOIO, q->node);
833                         ioc_set_batching(q, ioc);
834
835                         spin_lock_irq(q->queue_lock);
836                 }
837                 finish_wait(&rl->wait[rw], &wait);
838         }
839
840         return rq;
841 }
842
843 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
844 {
845         struct request *rq;
846
847         BUG_ON(rw != READ && rw != WRITE);
848
849         spin_lock_irq(q->queue_lock);
850         if (gfp_mask & __GFP_WAIT) {
851                 rq = get_request_wait(q, rw, NULL);
852         } else {
853                 rq = get_request(q, rw, NULL, gfp_mask);
854                 if (!rq)
855                         spin_unlock_irq(q->queue_lock);
856         }
857         /* q->queue_lock is unlocked at this point */
858
859         return rq;
860 }
861 EXPORT_SYMBOL(blk_get_request);
862
863 /**
864  * blk_start_queueing - initiate dispatch of requests to device
865  * @q:          request queue to kick into gear
866  *
867  * This is basically a helper to remove the need to know whether a queue
868  * is plugged or not if someone just wants to initiate dispatch of requests
869  * for this queue.
870  *
871  * The queue lock must be held with interrupts disabled.
872  */
873 void blk_start_queueing(struct request_queue *q)
874 {
875         if (!blk_queue_plugged(q))
876                 q->request_fn(q);
877         else
878                 __generic_unplug_device(q);
879 }
880 EXPORT_SYMBOL(blk_start_queueing);
881
882 /**
883  * blk_requeue_request - put a request back on queue
884  * @q:          request queue where request should be inserted
885  * @rq:         request to be inserted
886  *
887  * Description:
888  *    Drivers often keep queueing requests until the hardware cannot accept
889  *    more, when that condition happens we need to put the request back
890  *    on the queue. Must be called with queue lock held.
891  */
892 void blk_requeue_request(struct request_queue *q, struct request *rq)
893 {
894         blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
895
896         if (blk_rq_tagged(rq))
897                 blk_queue_end_tag(q, rq);
898
899         elv_requeue_request(q, rq);
900 }
901 EXPORT_SYMBOL(blk_requeue_request);
902
903 /**
904  * blk_insert_request - insert a special request in to a request queue
905  * @q:          request queue where request should be inserted
906  * @rq:         request to be inserted
907  * @at_head:    insert request at head or tail of queue
908  * @data:       private data
909  *
910  * Description:
911  *    Many block devices need to execute commands asynchronously, so they don't
912  *    block the whole kernel from preemption during request execution.  This is
913  *    accomplished normally by inserting aritficial requests tagged as
914  *    REQ_SPECIAL in to the corresponding request queue, and letting them be
915  *    scheduled for actual execution by the request queue.
916  *
917  *    We have the option of inserting the head or the tail of the queue.
918  *    Typically we use the tail for new ioctls and so forth.  We use the head
919  *    of the queue for things like a QUEUE_FULL message from a device, or a
920  *    host that is unable to accept a particular command.
921  */
922 void blk_insert_request(struct request_queue *q, struct request *rq,
923                         int at_head, void *data)
924 {
925         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
926         unsigned long flags;
927
928         /*
929          * tell I/O scheduler that this isn't a regular read/write (ie it
930          * must not attempt merges on this) and that it acts as a soft
931          * barrier
932          */
933         rq->cmd_type = REQ_TYPE_SPECIAL;
934         rq->cmd_flags |= REQ_SOFTBARRIER;
935
936         rq->special = data;
937
938         spin_lock_irqsave(q->queue_lock, flags);
939
940         /*
941          * If command is tagged, release the tag
942          */
943         if (blk_rq_tagged(rq))
944                 blk_queue_end_tag(q, rq);
945
946         drive_stat_acct(rq, 1);
947         __elv_add_request(q, rq, where, 0);
948         blk_start_queueing(q);
949         spin_unlock_irqrestore(q->queue_lock, flags);
950 }
951 EXPORT_SYMBOL(blk_insert_request);
952
953 /*
954  * add-request adds a request to the linked list.
955  * queue lock is held and interrupts disabled, as we muck with the
956  * request queue list.
957  */
958 static inline void add_request(struct request_queue *q, struct request *req)
959 {
960         drive_stat_acct(req, 1);
961
962         /*
963          * elevator indicated where it wants this request to be
964          * inserted at elevator_merge time
965          */
966         __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
967 }
968
969 /*
970  * disk_round_stats()   - Round off the performance stats on a struct
971  * disk_stats.
972  *
973  * The average IO queue length and utilisation statistics are maintained
974  * by observing the current state of the queue length and the amount of
975  * time it has been in this state for.
976  *
977  * Normally, that accounting is done on IO completion, but that can result
978  * in more than a second's worth of IO being accounted for within any one
979  * second, leading to >100% utilisation.  To deal with that, we call this
980  * function to do a round-off before returning the results when reading
981  * /proc/diskstats.  This accounts immediately for all queue usage up to
982  * the current jiffies and restarts the counters again.
983  */
984 void disk_round_stats(struct gendisk *disk)
985 {
986         unsigned long now = jiffies;
987
988         if (now == disk->stamp)
989                 return;
990
991         if (disk->in_flight) {
992                 __disk_stat_add(disk, time_in_queue,
993                                 disk->in_flight * (now - disk->stamp));
994                 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
995         }
996         disk->stamp = now;
997 }
998 EXPORT_SYMBOL_GPL(disk_round_stats);
999
1000 /*
1001  * queue lock must be held
1002  */
1003 void __blk_put_request(struct request_queue *q, struct request *req)
1004 {
1005         if (unlikely(!q))
1006                 return;
1007         if (unlikely(--req->ref_count))
1008                 return;
1009
1010         elv_completed_request(q, req);
1011
1012         /*
1013          * Request may not have originated from ll_rw_blk. if not,
1014          * it didn't come out of our reserved rq pools
1015          */
1016         if (req->cmd_flags & REQ_ALLOCED) {
1017                 int rw = rq_data_dir(req);
1018                 int priv = req->cmd_flags & REQ_ELVPRIV;
1019
1020                 BUG_ON(!list_empty(&req->queuelist));
1021                 BUG_ON(!hlist_unhashed(&req->hash));
1022
1023                 blk_free_request(q, req);
1024                 freed_request(q, rw, priv);
1025         }
1026 }
1027 EXPORT_SYMBOL_GPL(__blk_put_request);
1028
1029 void blk_put_request(struct request *req)
1030 {
1031         unsigned long flags;
1032         struct request_queue *q = req->q;
1033
1034         /*
1035          * Gee, IDE calls in w/ NULL q.  Fix IDE and remove the
1036          * following if (q) test.
1037          */
1038         if (q) {
1039                 spin_lock_irqsave(q->queue_lock, flags);
1040                 __blk_put_request(q, req);
1041                 spin_unlock_irqrestore(q->queue_lock, flags);
1042         }
1043 }
1044 EXPORT_SYMBOL(blk_put_request);
1045
1046 void init_request_from_bio(struct request *req, struct bio *bio)
1047 {
1048         req->cmd_type = REQ_TYPE_FS;
1049
1050         /*
1051          * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
1052          */
1053         if (bio_rw_ahead(bio) || bio_failfast(bio))
1054                 req->cmd_flags |= REQ_FAILFAST;
1055
1056         /*
1057          * REQ_BARRIER implies no merging, but lets make it explicit
1058          */
1059         if (unlikely(bio_barrier(bio)))
1060                 req->cmd_flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
1061
1062         if (bio_sync(bio))
1063                 req->cmd_flags |= REQ_RW_SYNC;
1064         if (bio_rw_meta(bio))
1065                 req->cmd_flags |= REQ_RW_META;
1066
1067         req->errors = 0;
1068         req->hard_sector = req->sector = bio->bi_sector;
1069         req->ioprio = bio_prio(bio);
1070         req->start_time = jiffies;
1071         blk_rq_bio_prep(req->q, req, bio);
1072 }
1073
1074 static int __make_request(struct request_queue *q, struct bio *bio)
1075 {
1076         struct request *req;
1077         int el_ret, nr_sectors, barrier, err;
1078         const unsigned short prio = bio_prio(bio);
1079         const int sync = bio_sync(bio);
1080         int rw_flags;
1081
1082         nr_sectors = bio_sectors(bio);
1083
1084         /*
1085          * low level driver can indicate that it wants pages above a
1086          * certain limit bounced to low memory (ie for highmem, or even
1087          * ISA dma in theory)
1088          */
1089         blk_queue_bounce(q, &bio);
1090
1091         barrier = bio_barrier(bio);
1092         if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
1093                 err = -EOPNOTSUPP;
1094                 goto end_io;
1095         }
1096
1097         spin_lock_irq(q->queue_lock);
1098
1099         if (unlikely(barrier) || elv_queue_empty(q))
1100                 goto get_rq;
1101
1102         el_ret = elv_merge(q, &req, bio);
1103         switch (el_ret) {
1104         case ELEVATOR_BACK_MERGE:
1105                 BUG_ON(!rq_mergeable(req));
1106
1107                 if (!ll_back_merge_fn(q, req, bio))
1108                         break;
1109
1110                 blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
1111
1112                 req->biotail->bi_next = bio;
1113                 req->biotail = bio;
1114                 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1115                 req->ioprio = ioprio_best(req->ioprio, prio);
1116                 drive_stat_acct(req, 0);
1117                 if (!attempt_back_merge(q, req))
1118                         elv_merged_request(q, req, el_ret);
1119                 goto out;
1120
1121         case ELEVATOR_FRONT_MERGE:
1122                 BUG_ON(!rq_mergeable(req));
1123
1124                 if (!ll_front_merge_fn(q, req, bio))
1125                         break;
1126
1127                 blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
1128
1129                 bio->bi_next = req->bio;
1130                 req->bio = bio;
1131
1132                 /*
1133                  * may not be valid. if the low level driver said
1134                  * it didn't need a bounce buffer then it better
1135                  * not touch req->buffer either...
1136                  */
1137                 req->buffer = bio_data(bio);
1138                 req->current_nr_sectors = bio_cur_sectors(bio);
1139                 req->hard_cur_sectors = req->current_nr_sectors;
1140                 req->sector = req->hard_sector = bio->bi_sector;
1141                 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1142                 req->ioprio = ioprio_best(req->ioprio, prio);
1143                 drive_stat_acct(req, 0);
1144                 if (!attempt_front_merge(q, req))
1145                         elv_merged_request(q, req, el_ret);
1146                 goto out;
1147
1148         /* ELV_NO_MERGE: elevator says don't/can't merge. */
1149         default:
1150                 ;
1151         }
1152
1153 get_rq:
1154         /*
1155          * This sync check and mask will be re-done in init_request_from_bio(),
1156          * but we need to set it earlier to expose the sync flag to the
1157          * rq allocator and io schedulers.
1158          */
1159         rw_flags = bio_data_dir(bio);
1160         if (sync)
1161                 rw_flags |= REQ_RW_SYNC;
1162
1163         /*
1164          * Grab a free request. This is might sleep but can not fail.
1165          * Returns with the queue unlocked.
1166          */
1167         req = get_request_wait(q, rw_flags, bio);
1168
1169         /*
1170          * After dropping the lock and possibly sleeping here, our request
1171          * may now be mergeable after it had proven unmergeable (above).
1172          * We don't worry about that case for efficiency. It won't happen
1173          * often, and the elevators are able to handle it.
1174          */
1175         init_request_from_bio(req, bio);
1176
1177         spin_lock_irq(q->queue_lock);
1178         if (elv_queue_empty(q))
1179                 blk_plug_device(q);
1180         add_request(q, req);
1181 out:
1182         if (sync)
1183                 __generic_unplug_device(q);
1184
1185         spin_unlock_irq(q->queue_lock);
1186         return 0;
1187
1188 end_io:
1189         bio_endio(bio, err);
1190         return 0;
1191 }
1192
1193 /*
1194  * If bio->bi_dev is a partition, remap the location
1195  */
1196 static inline void blk_partition_remap(struct bio *bio)
1197 {
1198         struct block_device *bdev = bio->bi_bdev;
1199
1200         if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1201                 struct hd_struct *p = bdev->bd_part;
1202                 const int rw = bio_data_dir(bio);
1203
1204                 p->sectors[rw] += bio_sectors(bio);
1205                 p->ios[rw]++;
1206
1207                 bio->bi_sector += p->start_sect;
1208                 bio->bi_bdev = bdev->bd_contains;
1209
1210                 blk_add_trace_remap(bdev_get_queue(bio->bi_bdev), bio,
1211                                     bdev->bd_dev, bio->bi_sector,
1212                                     bio->bi_sector - p->start_sect);
1213         }
1214 }
1215
1216 static void handle_bad_sector(struct bio *bio)
1217 {
1218         char b[BDEVNAME_SIZE];
1219
1220         printk(KERN_INFO "attempt to access beyond end of device\n");
1221         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1222                         bdevname(bio->bi_bdev, b),
1223                         bio->bi_rw,
1224                         (unsigned long long)bio->bi_sector + bio_sectors(bio),
1225                         (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1226
1227         set_bit(BIO_EOF, &bio->bi_flags);
1228 }
1229
1230 #ifdef CONFIG_FAIL_MAKE_REQUEST
1231
1232 static DECLARE_FAULT_ATTR(fail_make_request);
1233
1234 static int __init setup_fail_make_request(char *str)
1235 {
1236         return setup_fault_attr(&fail_make_request, str);
1237 }
1238 __setup("fail_make_request=", setup_fail_make_request);
1239
1240 static int should_fail_request(struct bio *bio)
1241 {
1242         if ((bio->bi_bdev->bd_disk->flags & GENHD_FL_FAIL) ||
1243             (bio->bi_bdev->bd_part && bio->bi_bdev->bd_part->make_it_fail))
1244                 return should_fail(&fail_make_request, bio->bi_size);
1245
1246         return 0;
1247 }
1248
1249 static int __init fail_make_request_debugfs(void)
1250 {
1251         return init_fault_attr_dentries(&fail_make_request,
1252                                         "fail_make_request");
1253 }
1254
1255 late_initcall(fail_make_request_debugfs);
1256
1257 #else /* CONFIG_FAIL_MAKE_REQUEST */
1258
1259 static inline int should_fail_request(struct bio *bio)
1260 {
1261         return 0;
1262 }
1263
1264 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1265
1266 /*
1267  * Check whether this bio extends beyond the end of the device.
1268  */
1269 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1270 {
1271         sector_t maxsector;
1272
1273         if (!nr_sectors)
1274                 return 0;
1275
1276         /* Test device or partition size, when known. */
1277         maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1278         if (maxsector) {
1279                 sector_t sector = bio->bi_sector;
1280
1281                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1282                         /*
1283                          * This may well happen - the kernel calls bread()
1284                          * without checking the size of the device, e.g., when
1285                          * mounting a device.
1286                          */
1287                         handle_bad_sector(bio);
1288                         return 1;
1289                 }
1290         }
1291
1292         return 0;
1293 }
1294
1295 /**
1296  * generic_make_request: hand a buffer to its device driver for I/O
1297  * @bio:  The bio describing the location in memory and on the device.
1298  *
1299  * generic_make_request() is used to make I/O requests of block
1300  * devices. It is passed a &struct bio, which describes the I/O that needs
1301  * to be done.
1302  *
1303  * generic_make_request() does not return any status.  The
1304  * success/failure status of the request, along with notification of
1305  * completion, is delivered asynchronously through the bio->bi_end_io
1306  * function described (one day) else where.
1307  *
1308  * The caller of generic_make_request must make sure that bi_io_vec
1309  * are set to describe the memory buffer, and that bi_dev and bi_sector are
1310  * set to describe the device address, and the
1311  * bi_end_io and optionally bi_private are set to describe how
1312  * completion notification should be signaled.
1313  *
1314  * generic_make_request and the drivers it calls may use bi_next if this
1315  * bio happens to be merged with someone else, and may change bi_dev and
1316  * bi_sector for remaps as it sees fit.  So the values of these fields
1317  * should NOT be depended on after the call to generic_make_request.
1318  */
1319 static inline void __generic_make_request(struct bio *bio)
1320 {
1321         struct request_queue *q;
1322         sector_t old_sector;
1323         int ret, nr_sectors = bio_sectors(bio);
1324         dev_t old_dev;
1325         int err = -EIO;
1326
1327         might_sleep();
1328
1329         if (bio_check_eod(bio, nr_sectors))
1330                 goto end_io;
1331
1332         /*
1333          * Resolve the mapping until finished. (drivers are
1334          * still free to implement/resolve their own stacking
1335          * by explicitly returning 0)
1336          *
1337          * NOTE: we don't repeat the blk_size check for each new device.
1338          * Stacking drivers are expected to know what they are doing.
1339          */
1340         old_sector = -1;
1341         old_dev = 0;
1342         do {
1343                 char b[BDEVNAME_SIZE];
1344
1345                 q = bdev_get_queue(bio->bi_bdev);
1346                 if (!q) {
1347                         printk(KERN_ERR
1348                                "generic_make_request: Trying to access "
1349                                 "nonexistent block-device %s (%Lu)\n",
1350                                 bdevname(bio->bi_bdev, b),
1351                                 (long long) bio->bi_sector);
1352 end_io:
1353                         bio_endio(bio, err);
1354                         break;
1355                 }
1356
1357                 if (unlikely(nr_sectors > q->max_hw_sectors)) {
1358                         printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1359                                 bdevname(bio->bi_bdev, b),
1360                                 bio_sectors(bio),
1361                                 q->max_hw_sectors);
1362                         goto end_io;
1363                 }
1364
1365                 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1366                         goto end_io;
1367
1368                 if (should_fail_request(bio))
1369                         goto end_io;
1370
1371                 /*
1372                  * If this device has partitions, remap block n
1373                  * of partition p to block n+start(p) of the disk.
1374                  */
1375                 blk_partition_remap(bio);
1376
1377                 if (old_sector != -1)
1378                         blk_add_trace_remap(q, bio, old_dev, bio->bi_sector,
1379                                             old_sector);
1380
1381                 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
1382
1383                 old_sector = bio->bi_sector;
1384                 old_dev = bio->bi_bdev->bd_dev;
1385
1386                 if (bio_check_eod(bio, nr_sectors))
1387                         goto end_io;
1388                 if (bio_empty_barrier(bio) && !q->prepare_flush_fn) {
1389                         err = -EOPNOTSUPP;
1390                         goto end_io;
1391                 }
1392
1393                 ret = q->make_request_fn(q, bio);
1394         } while (ret);
1395 }
1396
1397 /*
1398  * We only want one ->make_request_fn to be active at a time,
1399  * else stack usage with stacked devices could be a problem.
1400  * So use current->bio_{list,tail} to keep a list of requests
1401  * submited by a make_request_fn function.
1402  * current->bio_tail is also used as a flag to say if
1403  * generic_make_request is currently active in this task or not.
1404  * If it is NULL, then no make_request is active.  If it is non-NULL,
1405  * then a make_request is active, and new requests should be added
1406  * at the tail
1407  */
1408 void generic_make_request(struct bio *bio)
1409 {
1410         if (current->bio_tail) {
1411                 /* make_request is active */
1412                 *(current->bio_tail) = bio;
1413                 bio->bi_next = NULL;
1414                 current->bio_tail = &bio->bi_next;
1415                 return;
1416         }
1417         /* following loop may be a bit non-obvious, and so deserves some
1418          * explanation.
1419          * Before entering the loop, bio->bi_next is NULL (as all callers
1420          * ensure that) so we have a list with a single bio.
1421          * We pretend that we have just taken it off a longer list, so
1422          * we assign bio_list to the next (which is NULL) and bio_tail
1423          * to &bio_list, thus initialising the bio_list of new bios to be
1424          * added.  __generic_make_request may indeed add some more bios
1425          * through a recursive call to generic_make_request.  If it
1426          * did, we find a non-NULL value in bio_list and re-enter the loop
1427          * from the top.  In this case we really did just take the bio
1428          * of the top of the list (no pretending) and so fixup bio_list and
1429          * bio_tail or bi_next, and call into __generic_make_request again.
1430          *
1431          * The loop was structured like this to make only one call to
1432          * __generic_make_request (which is important as it is large and
1433          * inlined) and to keep the structure simple.
1434          */
1435         BUG_ON(bio->bi_next);
1436         do {
1437                 current->bio_list = bio->bi_next;
1438                 if (bio->bi_next == NULL)
1439                         current->bio_tail = &current->bio_list;
1440                 else
1441                         bio->bi_next = NULL;
1442                 __generic_make_request(bio);
1443                 bio = current->bio_list;
1444         } while (bio);
1445         current->bio_tail = NULL; /* deactivate */
1446 }
1447 EXPORT_SYMBOL(generic_make_request);
1448
1449 /**
1450  * submit_bio: submit a bio to the block device layer for I/O
1451  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1452  * @bio: The &struct bio which describes the I/O
1453  *
1454  * submit_bio() is very similar in purpose to generic_make_request(), and
1455  * uses that function to do most of the work. Both are fairly rough
1456  * interfaces, @bio must be presetup and ready for I/O.
1457  *
1458  */
1459 void submit_bio(int rw, struct bio *bio)
1460 {
1461         int count = bio_sectors(bio);
1462
1463         bio->bi_rw |= rw;
1464
1465         /*
1466          * If it's a regular read/write or a barrier with data attached,
1467          * go through the normal accounting stuff before submission.
1468          */
1469         if (!bio_empty_barrier(bio)) {
1470
1471                 BIO_BUG_ON(!bio->bi_size);
1472                 BIO_BUG_ON(!bio->bi_io_vec);
1473
1474                 if (rw & WRITE) {
1475                         count_vm_events(PGPGOUT, count);
1476                 } else {
1477                         task_io_account_read(bio->bi_size);
1478                         count_vm_events(PGPGIN, count);
1479                 }
1480
1481                 if (unlikely(block_dump)) {
1482                         char b[BDEVNAME_SIZE];
1483                         printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
1484                         current->comm, task_pid_nr(current),
1485                                 (rw & WRITE) ? "WRITE" : "READ",
1486                                 (unsigned long long)bio->bi_sector,
1487                                 bdevname(bio->bi_bdev, b));
1488                 }
1489         }
1490
1491         generic_make_request(bio);
1492 }
1493 EXPORT_SYMBOL(submit_bio);
1494
1495 /**
1496  * __end_that_request_first - end I/O on a request
1497  * @req:      the request being processed
1498  * @error:    0 for success, < 0 for error
1499  * @nr_bytes: number of bytes to complete
1500  *
1501  * Description:
1502  *     Ends I/O on a number of bytes attached to @req, and sets it up
1503  *     for the next range of segments (if any) in the cluster.
1504  *
1505  * Return:
1506  *     0 - we are done with this request, call end_that_request_last()
1507  *     1 - still buffers pending for this request
1508  **/
1509 static int __end_that_request_first(struct request *req, int error,
1510                                     int nr_bytes)
1511 {
1512         int total_bytes, bio_nbytes, next_idx = 0;
1513         struct bio *bio;
1514
1515         blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
1516
1517         /*
1518          * for a REQ_BLOCK_PC request, we want to carry any eventual
1519          * sense key with us all the way through
1520          */
1521         if (!blk_pc_request(req))
1522                 req->errors = 0;
1523
1524         if (error && (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))) {
1525                 printk(KERN_ERR "end_request: I/O error, dev %s, sector %llu\n",
1526                                 req->rq_disk ? req->rq_disk->disk_name : "?",
1527                                 (unsigned long long)req->sector);
1528         }
1529
1530         if (blk_fs_request(req) && req->rq_disk) {
1531                 const int rw = rq_data_dir(req);
1532
1533                 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
1534         }
1535
1536         total_bytes = bio_nbytes = 0;
1537         while ((bio = req->bio) != NULL) {
1538                 int nbytes;
1539
1540                 /*
1541                  * For an empty barrier request, the low level driver must
1542                  * store a potential error location in ->sector. We pass
1543                  * that back up in ->bi_sector.
1544                  */
1545                 if (blk_empty_barrier(req))
1546                         bio->bi_sector = req->sector;
1547
1548                 if (nr_bytes >= bio->bi_size) {
1549                         req->bio = bio->bi_next;
1550                         nbytes = bio->bi_size;
1551                         req_bio_endio(req, bio, nbytes, error);
1552                         next_idx = 0;
1553                         bio_nbytes = 0;
1554                 } else {
1555                         int idx = bio->bi_idx + next_idx;
1556
1557                         if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
1558                                 blk_dump_rq_flags(req, "__end_that");
1559                                 printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
1560                                                 __FUNCTION__, bio->bi_idx,
1561                                                 bio->bi_vcnt);
1562                                 break;
1563                         }
1564
1565                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
1566                         BIO_BUG_ON(nbytes > bio->bi_size);
1567
1568                         /*
1569                          * not a complete bvec done
1570                          */
1571                         if (unlikely(nbytes > nr_bytes)) {
1572                                 bio_nbytes += nr_bytes;
1573                                 total_bytes += nr_bytes;
1574                                 break;
1575                         }
1576
1577                         /*
1578                          * advance to the next vector
1579                          */
1580                         next_idx++;
1581                         bio_nbytes += nbytes;
1582                 }
1583
1584                 total_bytes += nbytes;
1585                 nr_bytes -= nbytes;
1586
1587                 bio = req->bio;
1588                 if (bio) {
1589                         /*
1590                          * end more in this run, or just return 'not-done'
1591                          */
1592                         if (unlikely(nr_bytes <= 0))
1593                                 break;
1594                 }
1595         }
1596
1597         /*
1598          * completely done
1599          */
1600         if (!req->bio)
1601                 return 0;
1602
1603         /*
1604          * if the request wasn't completed, update state
1605          */
1606         if (bio_nbytes) {
1607                 req_bio_endio(req, bio, bio_nbytes, error);
1608                 bio->bi_idx += next_idx;
1609                 bio_iovec(bio)->bv_offset += nr_bytes;
1610                 bio_iovec(bio)->bv_len -= nr_bytes;
1611         }
1612
1613         blk_recalc_rq_sectors(req, total_bytes >> 9);
1614         blk_recalc_rq_segments(req);
1615         return 1;
1616 }
1617
1618 /*
1619  * splice the completion data to a local structure and hand off to
1620  * process_completion_queue() to complete the requests
1621  */
1622 static void blk_done_softirq(struct softirq_action *h)
1623 {
1624         struct list_head *cpu_list, local_list;
1625
1626         local_irq_disable();
1627         cpu_list = &__get_cpu_var(blk_cpu_done);
1628         list_replace_init(cpu_list, &local_list);
1629         local_irq_enable();
1630
1631         while (!list_empty(&local_list)) {
1632                 struct request *rq;
1633
1634                 rq = list_entry(local_list.next, struct request, donelist);
1635                 list_del_init(&rq->donelist);
1636                 rq->q->softirq_done_fn(rq);
1637         }
1638 }
1639
1640 static int __cpuinit blk_cpu_notify(struct notifier_block *self,
1641                                     unsigned long action, void *hcpu)
1642 {
1643         /*
1644          * If a CPU goes away, splice its entries to the current CPU
1645          * and trigger a run of the softirq
1646          */
1647         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
1648                 int cpu = (unsigned long) hcpu;
1649
1650                 local_irq_disable();
1651                 list_splice_init(&per_cpu(blk_cpu_done, cpu),
1652                                  &__get_cpu_var(blk_cpu_done));
1653                 raise_softirq_irqoff(BLOCK_SOFTIRQ);
1654                 local_irq_enable();
1655         }
1656
1657         return NOTIFY_OK;
1658 }
1659
1660
1661 static struct notifier_block blk_cpu_notifier __cpuinitdata = {
1662         .notifier_call  = blk_cpu_notify,
1663 };
1664
1665 /**
1666  * blk_complete_request - end I/O on a request
1667  * @req:      the request being processed
1668  *
1669  * Description:
1670  *     Ends all I/O on a request. It does not handle partial completions,
1671  *     unless the driver actually implements this in its completion callback
1672  *     through requeueing. The actual completion happens out-of-order,
1673  *     through a softirq handler. The user must have registered a completion
1674  *     callback through blk_queue_softirq_done().
1675  **/
1676
1677 void blk_complete_request(struct request *req)
1678 {
1679         struct list_head *cpu_list;
1680         unsigned long flags;
1681
1682         BUG_ON(!req->q->softirq_done_fn);
1683
1684         local_irq_save(flags);
1685
1686         cpu_list = &__get_cpu_var(blk_cpu_done);
1687         list_add_tail(&req->donelist, cpu_list);
1688         raise_softirq_irqoff(BLOCK_SOFTIRQ);
1689
1690         local_irq_restore(flags);
1691 }
1692 EXPORT_SYMBOL(blk_complete_request);
1693
1694 /*
1695  * queue lock must be held
1696  */
1697 static void end_that_request_last(struct request *req, int error)
1698 {
1699         struct gendisk *disk = req->rq_disk;
1700
1701         if (blk_rq_tagged(req))
1702                 blk_queue_end_tag(req->q, req);
1703
1704         if (blk_queued_rq(req))
1705                 blkdev_dequeue_request(req);
1706
1707         if (unlikely(laptop_mode) && blk_fs_request(req))
1708                 laptop_io_completion();
1709
1710         /*
1711          * Account IO completion.  bar_rq isn't accounted as a normal
1712          * IO on queueing nor completion.  Accounting the containing
1713          * request is enough.
1714          */
1715         if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
1716                 unsigned long duration = jiffies - req->start_time;
1717                 const int rw = rq_data_dir(req);
1718
1719                 __disk_stat_inc(disk, ios[rw]);
1720                 __disk_stat_add(disk, ticks[rw], duration);
1721                 disk_round_stats(disk);
1722                 disk->in_flight--;
1723         }
1724
1725         if (req->end_io)
1726                 req->end_io(req, error);
1727         else {
1728                 if (blk_bidi_rq(req))
1729                         __blk_put_request(req->next_rq->q, req->next_rq);
1730
1731                 __blk_put_request(req->q, req);
1732         }
1733 }
1734
1735 static inline void __end_request(struct request *rq, int uptodate,
1736                                  unsigned int nr_bytes)
1737 {
1738         int error = 0;
1739
1740         if (uptodate <= 0)
1741                 error = uptodate ? uptodate : -EIO;
1742
1743         __blk_end_request(rq, error, nr_bytes);
1744 }
1745
1746 /**
1747  * blk_rq_bytes - Returns bytes left to complete in the entire request
1748  **/
1749 unsigned int blk_rq_bytes(struct request *rq)
1750 {
1751         if (blk_fs_request(rq))
1752                 return rq->hard_nr_sectors << 9;
1753
1754         return rq->data_len;
1755 }
1756 EXPORT_SYMBOL_GPL(blk_rq_bytes);
1757
1758 /**
1759  * blk_rq_cur_bytes - Returns bytes left to complete in the current segment
1760  **/
1761 unsigned int blk_rq_cur_bytes(struct request *rq)
1762 {
1763         if (blk_fs_request(rq))
1764                 return rq->current_nr_sectors << 9;
1765
1766         if (rq->bio)
1767                 return rq->bio->bi_size;
1768
1769         return rq->data_len;
1770 }
1771 EXPORT_SYMBOL_GPL(blk_rq_cur_bytes);
1772
1773 /**
1774  * end_queued_request - end all I/O on a queued request
1775  * @rq:         the request being processed
1776  * @uptodate:   error value or 0/1 uptodate flag
1777  *
1778  * Description:
1779  *     Ends all I/O on a request, and removes it from the block layer queues.
1780  *     Not suitable for normal IO completion, unless the driver still has
1781  *     the request attached to the block layer.
1782  *
1783  **/
1784 void end_queued_request(struct request *rq, int uptodate)
1785 {
1786         __end_request(rq, uptodate, blk_rq_bytes(rq));
1787 }
1788 EXPORT_SYMBOL(end_queued_request);
1789
1790 /**
1791  * end_dequeued_request - end all I/O on a dequeued request
1792  * @rq:         the request being processed
1793  * @uptodate:   error value or 0/1 uptodate flag
1794  *
1795  * Description:
1796  *     Ends all I/O on a request. The request must already have been
1797  *     dequeued using blkdev_dequeue_request(), as is normally the case
1798  *     for most drivers.
1799  *
1800  **/
1801 void end_dequeued_request(struct request *rq, int uptodate)
1802 {
1803         __end_request(rq, uptodate, blk_rq_bytes(rq));
1804 }
1805 EXPORT_SYMBOL(end_dequeued_request);
1806
1807
1808 /**
1809  * end_request - end I/O on the current segment of the request
1810  * @req:        the request being processed
1811  * @uptodate:   error value or 0/1 uptodate flag
1812  *
1813  * Description:
1814  *     Ends I/O on the current segment of a request. If that is the only
1815  *     remaining segment, the request is also completed and freed.
1816  *
1817  *     This is a remnant of how older block drivers handled IO completions.
1818  *     Modern drivers typically end IO on the full request in one go, unless
1819  *     they have a residual value to account for. For that case this function
1820  *     isn't really useful, unless the residual just happens to be the
1821  *     full current segment. In other words, don't use this function in new
1822  *     code. Either use end_request_completely(), or the
1823  *     end_that_request_chunk() (along with end_that_request_last()) for
1824  *     partial completions.
1825  *
1826  **/
1827 void end_request(struct request *req, int uptodate)
1828 {
1829         __end_request(req, uptodate, req->hard_cur_sectors << 9);
1830 }
1831 EXPORT_SYMBOL(end_request);
1832
1833 /**
1834  * blk_end_io - Generic end_io function to complete a request.
1835  * @rq:           the request being processed
1836  * @error:        0 for success, < 0 for error
1837  * @nr_bytes:     number of bytes to complete @rq
1838  * @bidi_bytes:   number of bytes to complete @rq->next_rq
1839  * @drv_callback: function called between completion of bios in the request
1840  *                and completion of the request.
1841  *                If the callback returns non 0, this helper returns without
1842  *                completion of the request.
1843  *
1844  * Description:
1845  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
1846  *     If @rq has leftover, sets it up for the next range of segments.
1847  *
1848  * Return:
1849  *     0 - we are done with this request
1850  *     1 - this request is not freed yet, it still has pending buffers.
1851  **/
1852 static int blk_end_io(struct request *rq, int error, unsigned int nr_bytes,
1853                       unsigned int bidi_bytes,
1854                       int (drv_callback)(struct request *))
1855 {
1856         struct request_queue *q = rq->q;
1857         unsigned long flags = 0UL;
1858
1859         if (blk_fs_request(rq) || blk_pc_request(rq)) {
1860                 if (__end_that_request_first(rq, error, nr_bytes))
1861                         return 1;
1862
1863                 /* Bidi request must be completed as a whole */
1864                 if (blk_bidi_rq(rq) &&
1865                     __end_that_request_first(rq->next_rq, error, bidi_bytes))
1866                         return 1;
1867         }
1868
1869         /* Special feature for tricky drivers */
1870         if (drv_callback && drv_callback(rq))
1871                 return 1;
1872
1873         add_disk_randomness(rq->rq_disk);
1874
1875         spin_lock_irqsave(q->queue_lock, flags);
1876         end_that_request_last(rq, error);
1877         spin_unlock_irqrestore(q->queue_lock, flags);
1878
1879         return 0;
1880 }
1881
1882 /**
1883  * blk_end_request - Helper function for drivers to complete the request.
1884  * @rq:       the request being processed
1885  * @error:    0 for success, < 0 for error
1886  * @nr_bytes: number of bytes to complete
1887  *
1888  * Description:
1889  *     Ends I/O on a number of bytes attached to @rq.
1890  *     If @rq has leftover, sets it up for the next range of segments.
1891  *
1892  * Return:
1893  *     0 - we are done with this request
1894  *     1 - still buffers pending for this request
1895  **/
1896 int blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
1897 {
1898         return blk_end_io(rq, error, nr_bytes, 0, NULL);
1899 }
1900 EXPORT_SYMBOL_GPL(blk_end_request);
1901
1902 /**
1903  * __blk_end_request - Helper function for drivers to complete the request.
1904  * @rq:       the request being processed
1905  * @error:    0 for success, < 0 for error
1906  * @nr_bytes: number of bytes to complete
1907  *
1908  * Description:
1909  *     Must be called with queue lock held unlike blk_end_request().
1910  *
1911  * Return:
1912  *     0 - we are done with this request
1913  *     1 - still buffers pending for this request
1914  **/
1915 int __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
1916 {
1917         if (blk_fs_request(rq) || blk_pc_request(rq)) {
1918                 if (__end_that_request_first(rq, error, nr_bytes))
1919                         return 1;
1920         }
1921
1922         add_disk_randomness(rq->rq_disk);
1923
1924         end_that_request_last(rq, error);
1925
1926         return 0;
1927 }
1928 EXPORT_SYMBOL_GPL(__blk_end_request);
1929
1930 /**
1931  * blk_end_bidi_request - Helper function for drivers to complete bidi request.
1932  * @rq:         the bidi request being processed
1933  * @error:      0 for success, < 0 for error
1934  * @nr_bytes:   number of bytes to complete @rq
1935  * @bidi_bytes: number of bytes to complete @rq->next_rq
1936  *
1937  * Description:
1938  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
1939  *
1940  * Return:
1941  *     0 - we are done with this request
1942  *     1 - still buffers pending for this request
1943  **/
1944 int blk_end_bidi_request(struct request *rq, int error, unsigned int nr_bytes,
1945                          unsigned int bidi_bytes)
1946 {
1947         return blk_end_io(rq, error, nr_bytes, bidi_bytes, NULL);
1948 }
1949 EXPORT_SYMBOL_GPL(blk_end_bidi_request);
1950
1951 /**
1952  * blk_end_request_callback - Special helper function for tricky drivers
1953  * @rq:           the request being processed
1954  * @error:        0 for success, < 0 for error
1955  * @nr_bytes:     number of bytes to complete
1956  * @drv_callback: function called between completion of bios in the request
1957  *                and completion of the request.
1958  *                If the callback returns non 0, this helper returns without
1959  *                completion of the request.
1960  *
1961  * Description:
1962  *     Ends I/O on a number of bytes attached to @rq.
1963  *     If @rq has leftover, sets it up for the next range of segments.
1964  *
1965  *     This special helper function is used only for existing tricky drivers.
1966  *     (e.g. cdrom_newpc_intr() of ide-cd)
1967  *     This interface will be removed when such drivers are rewritten.
1968  *     Don't use this interface in other places anymore.
1969  *
1970  * Return:
1971  *     0 - we are done with this request
1972  *     1 - this request is not freed yet.
1973  *         this request still has pending buffers or
1974  *         the driver doesn't want to finish this request yet.
1975  **/
1976 int blk_end_request_callback(struct request *rq, int error,
1977                              unsigned int nr_bytes,
1978                              int (drv_callback)(struct request *))
1979 {
1980         return blk_end_io(rq, error, nr_bytes, 0, drv_callback);
1981 }
1982 EXPORT_SYMBOL_GPL(blk_end_request_callback);
1983
1984 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
1985                      struct bio *bio)
1986 {
1987         /* first two bits are identical in rq->cmd_flags and bio->bi_rw */
1988         rq->cmd_flags |= (bio->bi_rw & 3);
1989
1990         rq->nr_phys_segments = bio_phys_segments(q, bio);
1991         rq->nr_hw_segments = bio_hw_segments(q, bio);
1992         rq->current_nr_sectors = bio_cur_sectors(bio);
1993         rq->hard_cur_sectors = rq->current_nr_sectors;
1994         rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
1995         rq->buffer = bio_data(bio);
1996         rq->data_len = bio->bi_size;
1997
1998         rq->bio = rq->biotail = bio;
1999
2000         if (bio->bi_bdev)
2001                 rq->rq_disk = bio->bi_bdev->bd_disk;
2002 }
2003
2004 int kblockd_schedule_work(struct work_struct *work)
2005 {
2006         return queue_work(kblockd_workqueue, work);
2007 }
2008 EXPORT_SYMBOL(kblockd_schedule_work);
2009
2010 void kblockd_flush_work(struct work_struct *work)
2011 {
2012         cancel_work_sync(work);
2013 }
2014 EXPORT_SYMBOL(kblockd_flush_work);
2015
2016 int __init blk_dev_init(void)
2017 {
2018         int i;
2019
2020         kblockd_workqueue = create_workqueue("kblockd");
2021         if (!kblockd_workqueue)
2022                 panic("Failed to create kblockd\n");
2023
2024         request_cachep = kmem_cache_create("blkdev_requests",
2025                         sizeof(struct request), 0, SLAB_PANIC, NULL);
2026
2027         blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2028                         sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2029
2030         for_each_possible_cpu(i)
2031                 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
2032
2033         open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
2034         register_hotcpu_notifier(&blk_cpu_notifier);
2035
2036         return 0;
2037 }
2038