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