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