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