Merge branch 'master' of master.kernel.org:/pub/scm/linux/kernel/git/mchehab/v4l-dvb
[pandora-kernel.git] / block / ll_rw_blk.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/bootmem.h>      /* for max_pfn/max_low_pfn */
24 #include <linux/completion.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/task_io_accounting_ops.h>
29 #include <linux/interrupt.h>
30 #include <linux/cpu.h>
31 #include <linux/blktrace_api.h>
32 #include <linux/fault-inject.h>
33
34 /*
35  * for max sense size
36  */
37 #include <scsi/scsi_cmnd.h>
38
39 static void blk_unplug_work(struct work_struct *work);
40 static void blk_unplug_timeout(unsigned long data);
41 static void drive_stat_acct(struct request *rq, int nr_sectors, int new_io);
42 static void init_request_from_bio(struct request *req, struct bio *bio);
43 static int __make_request(request_queue_t *q, struct bio *bio);
44 static struct io_context *current_io_context(gfp_t gfp_flags, int node);
45
46 /*
47  * For the allocated request tables
48  */
49 static struct kmem_cache *request_cachep;
50
51 /*
52  * For queue allocation
53  */
54 static struct kmem_cache *requestq_cachep;
55
56 /*
57  * For io context allocations
58  */
59 static struct kmem_cache *iocontext_cachep;
60
61 /*
62  * Controlling structure to kblockd
63  */
64 static struct workqueue_struct *kblockd_workqueue;
65
66 unsigned long blk_max_low_pfn, blk_max_pfn;
67
68 EXPORT_SYMBOL(blk_max_low_pfn);
69 EXPORT_SYMBOL(blk_max_pfn);
70
71 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
72
73 /* Amount of time in which a process may batch requests */
74 #define BLK_BATCH_TIME  (HZ/50UL)
75
76 /* Number of requests a "batching" process may submit */
77 #define BLK_BATCH_REQ   32
78
79 /*
80  * Return the threshold (number of used requests) at which the queue is
81  * considered to be congested.  It include a little hysteresis to keep the
82  * context switch rate down.
83  */
84 static inline int queue_congestion_on_threshold(struct request_queue *q)
85 {
86         return q->nr_congestion_on;
87 }
88
89 /*
90  * The threshold at which a queue is considered to be uncongested
91  */
92 static inline int queue_congestion_off_threshold(struct request_queue *q)
93 {
94         return q->nr_congestion_off;
95 }
96
97 static void blk_queue_congestion_threshold(struct request_queue *q)
98 {
99         int nr;
100
101         nr = q->nr_requests - (q->nr_requests / 8) + 1;
102         if (nr > q->nr_requests)
103                 nr = q->nr_requests;
104         q->nr_congestion_on = nr;
105
106         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
107         if (nr < 1)
108                 nr = 1;
109         q->nr_congestion_off = nr;
110 }
111
112 /**
113  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
114  * @bdev:       device
115  *
116  * Locates the passed device's request queue and returns the address of its
117  * backing_dev_info
118  *
119  * Will return NULL if the request queue cannot be located.
120  */
121 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
122 {
123         struct backing_dev_info *ret = NULL;
124         request_queue_t *q = bdev_get_queue(bdev);
125
126         if (q)
127                 ret = &q->backing_dev_info;
128         return ret;
129 }
130 EXPORT_SYMBOL(blk_get_backing_dev_info);
131
132 /**
133  * blk_queue_prep_rq - set a prepare_request function for queue
134  * @q:          queue
135  * @pfn:        prepare_request function
136  *
137  * It's possible for a queue to register a prepare_request callback which
138  * is invoked before the request is handed to the request_fn. The goal of
139  * the function is to prepare a request for I/O, it can be used to build a
140  * cdb from the request data for instance.
141  *
142  */
143 void blk_queue_prep_rq(request_queue_t *q, prep_rq_fn *pfn)
144 {
145         q->prep_rq_fn = pfn;
146 }
147
148 EXPORT_SYMBOL(blk_queue_prep_rq);
149
150 /**
151  * blk_queue_merge_bvec - set a merge_bvec function for queue
152  * @q:          queue
153  * @mbfn:       merge_bvec_fn
154  *
155  * Usually queues have static limitations on the max sectors or segments that
156  * we can put in a request. Stacking drivers may have some settings that
157  * are dynamic, and thus we have to query the queue whether it is ok to
158  * add a new bio_vec to a bio at a given offset or not. If the block device
159  * has such limitations, it needs to register a merge_bvec_fn to control
160  * the size of bio's sent to it. Note that a block device *must* allow a
161  * single page to be added to an empty bio. The block device driver may want
162  * to use the bio_split() function to deal with these bio's. By default
163  * no merge_bvec_fn is defined for a queue, and only the fixed limits are
164  * honored.
165  */
166 void blk_queue_merge_bvec(request_queue_t *q, merge_bvec_fn *mbfn)
167 {
168         q->merge_bvec_fn = mbfn;
169 }
170
171 EXPORT_SYMBOL(blk_queue_merge_bvec);
172
173 void blk_queue_softirq_done(request_queue_t *q, softirq_done_fn *fn)
174 {
175         q->softirq_done_fn = fn;
176 }
177
178 EXPORT_SYMBOL(blk_queue_softirq_done);
179
180 /**
181  * blk_queue_make_request - define an alternate make_request function for a device
182  * @q:  the request queue for the device to be affected
183  * @mfn: the alternate make_request function
184  *
185  * Description:
186  *    The normal way for &struct bios to be passed to a device
187  *    driver is for them to be collected into requests on a request
188  *    queue, and then to allow the device driver to select requests
189  *    off that queue when it is ready.  This works well for many block
190  *    devices. However some block devices (typically virtual devices
191  *    such as md or lvm) do not benefit from the processing on the
192  *    request queue, and are served best by having the requests passed
193  *    directly to them.  This can be achieved by providing a function
194  *    to blk_queue_make_request().
195  *
196  * Caveat:
197  *    The driver that does this *must* be able to deal appropriately
198  *    with buffers in "highmemory". This can be accomplished by either calling
199  *    __bio_kmap_atomic() to get a temporary kernel mapping, or by calling
200  *    blk_queue_bounce() to create a buffer in normal memory.
201  **/
202 void blk_queue_make_request(request_queue_t * q, make_request_fn * mfn)
203 {
204         /*
205          * set defaults
206          */
207         q->nr_requests = BLKDEV_MAX_RQ;
208         blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
209         blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
210         q->make_request_fn = mfn;
211         q->backing_dev_info.ra_pages = (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
212         q->backing_dev_info.state = 0;
213         q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
214         blk_queue_max_sectors(q, SAFE_MAX_SECTORS);
215         blk_queue_hardsect_size(q, 512);
216         blk_queue_dma_alignment(q, 511);
217         blk_queue_congestion_threshold(q);
218         q->nr_batching = BLK_BATCH_REQ;
219
220         q->unplug_thresh = 4;           /* hmm */
221         q->unplug_delay = (3 * HZ) / 1000;      /* 3 milliseconds */
222         if (q->unplug_delay == 0)
223                 q->unplug_delay = 1;
224
225         INIT_WORK(&q->unplug_work, blk_unplug_work);
226
227         q->unplug_timer.function = blk_unplug_timeout;
228         q->unplug_timer.data = (unsigned long)q;
229
230         /*
231          * by default assume old behaviour and bounce for any highmem page
232          */
233         blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
234 }
235
236 EXPORT_SYMBOL(blk_queue_make_request);
237
238 static void rq_init(request_queue_t *q, struct request *rq)
239 {
240         INIT_LIST_HEAD(&rq->queuelist);
241         INIT_LIST_HEAD(&rq->donelist);
242
243         rq->errors = 0;
244         rq->bio = rq->biotail = NULL;
245         INIT_HLIST_NODE(&rq->hash);
246         RB_CLEAR_NODE(&rq->rb_node);
247         rq->ioprio = 0;
248         rq->buffer = NULL;
249         rq->ref_count = 1;
250         rq->q = q;
251         rq->special = NULL;
252         rq->data_len = 0;
253         rq->data = NULL;
254         rq->nr_phys_segments = 0;
255         rq->sense = NULL;
256         rq->end_io = NULL;
257         rq->end_io_data = NULL;
258         rq->completion_data = NULL;
259 }
260
261 /**
262  * blk_queue_ordered - does this queue support ordered writes
263  * @q:        the request queue
264  * @ordered:  one of QUEUE_ORDERED_*
265  * @prepare_flush_fn: rq setup helper for cache flush ordered writes
266  *
267  * Description:
268  *   For journalled file systems, doing ordered writes on a commit
269  *   block instead of explicitly doing wait_on_buffer (which is bad
270  *   for performance) can be a big win. Block drivers supporting this
271  *   feature should call this function and indicate so.
272  *
273  **/
274 int blk_queue_ordered(request_queue_t *q, unsigned ordered,
275                       prepare_flush_fn *prepare_flush_fn)
276 {
277         if (ordered & (QUEUE_ORDERED_PREFLUSH | QUEUE_ORDERED_POSTFLUSH) &&
278             prepare_flush_fn == NULL) {
279                 printk(KERN_ERR "blk_queue_ordered: prepare_flush_fn required\n");
280                 return -EINVAL;
281         }
282
283         if (ordered != QUEUE_ORDERED_NONE &&
284             ordered != QUEUE_ORDERED_DRAIN &&
285             ordered != QUEUE_ORDERED_DRAIN_FLUSH &&
286             ordered != QUEUE_ORDERED_DRAIN_FUA &&
287             ordered != QUEUE_ORDERED_TAG &&
288             ordered != QUEUE_ORDERED_TAG_FLUSH &&
289             ordered != QUEUE_ORDERED_TAG_FUA) {
290                 printk(KERN_ERR "blk_queue_ordered: bad value %d\n", ordered);
291                 return -EINVAL;
292         }
293
294         q->ordered = ordered;
295         q->next_ordered = ordered;
296         q->prepare_flush_fn = prepare_flush_fn;
297
298         return 0;
299 }
300
301 EXPORT_SYMBOL(blk_queue_ordered);
302
303 /**
304  * blk_queue_issue_flush_fn - set function for issuing a flush
305  * @q:     the request queue
306  * @iff:   the function to be called issuing the flush
307  *
308  * Description:
309  *   If a driver supports issuing a flush command, the support is notified
310  *   to the block layer by defining it through this call.
311  *
312  **/
313 void blk_queue_issue_flush_fn(request_queue_t *q, issue_flush_fn *iff)
314 {
315         q->issue_flush_fn = iff;
316 }
317
318 EXPORT_SYMBOL(blk_queue_issue_flush_fn);
319
320 /*
321  * Cache flushing for ordered writes handling
322  */
323 inline unsigned blk_ordered_cur_seq(request_queue_t *q)
324 {
325         if (!q->ordseq)
326                 return 0;
327         return 1 << ffz(q->ordseq);
328 }
329
330 unsigned blk_ordered_req_seq(struct request *rq)
331 {
332         request_queue_t *q = rq->q;
333
334         BUG_ON(q->ordseq == 0);
335
336         if (rq == &q->pre_flush_rq)
337                 return QUEUE_ORDSEQ_PREFLUSH;
338         if (rq == &q->bar_rq)
339                 return QUEUE_ORDSEQ_BAR;
340         if (rq == &q->post_flush_rq)
341                 return QUEUE_ORDSEQ_POSTFLUSH;
342
343         if ((rq->cmd_flags & REQ_ORDERED_COLOR) ==
344             (q->orig_bar_rq->cmd_flags & REQ_ORDERED_COLOR))
345                 return QUEUE_ORDSEQ_DRAIN;
346         else
347                 return QUEUE_ORDSEQ_DONE;
348 }
349
350 void blk_ordered_complete_seq(request_queue_t *q, unsigned seq, int error)
351 {
352         struct request *rq;
353         int uptodate;
354
355         if (error && !q->orderr)
356                 q->orderr = error;
357
358         BUG_ON(q->ordseq & seq);
359         q->ordseq |= seq;
360
361         if (blk_ordered_cur_seq(q) != QUEUE_ORDSEQ_DONE)
362                 return;
363
364         /*
365          * Okay, sequence complete.
366          */
367         rq = q->orig_bar_rq;
368         uptodate = q->orderr ? q->orderr : 1;
369
370         q->ordseq = 0;
371
372         end_that_request_first(rq, uptodate, rq->hard_nr_sectors);
373         end_that_request_last(rq, uptodate);
374 }
375
376 static void pre_flush_end_io(struct request *rq, int error)
377 {
378         elv_completed_request(rq->q, rq);
379         blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_PREFLUSH, error);
380 }
381
382 static void bar_end_io(struct request *rq, int error)
383 {
384         elv_completed_request(rq->q, rq);
385         blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_BAR, error);
386 }
387
388 static void post_flush_end_io(struct request *rq, int error)
389 {
390         elv_completed_request(rq->q, rq);
391         blk_ordered_complete_seq(rq->q, QUEUE_ORDSEQ_POSTFLUSH, error);
392 }
393
394 static void queue_flush(request_queue_t *q, unsigned which)
395 {
396         struct request *rq;
397         rq_end_io_fn *end_io;
398
399         if (which == QUEUE_ORDERED_PREFLUSH) {
400                 rq = &q->pre_flush_rq;
401                 end_io = pre_flush_end_io;
402         } else {
403                 rq = &q->post_flush_rq;
404                 end_io = post_flush_end_io;
405         }
406
407         rq->cmd_flags = REQ_HARDBARRIER;
408         rq_init(q, rq);
409         rq->elevator_private = NULL;
410         rq->elevator_private2 = NULL;
411         rq->rq_disk = q->bar_rq.rq_disk;
412         rq->end_io = end_io;
413         q->prepare_flush_fn(q, rq);
414
415         elv_insert(q, rq, ELEVATOR_INSERT_FRONT);
416 }
417
418 static inline struct request *start_ordered(request_queue_t *q,
419                                             struct request *rq)
420 {
421         q->bi_size = 0;
422         q->orderr = 0;
423         q->ordered = q->next_ordered;
424         q->ordseq |= QUEUE_ORDSEQ_STARTED;
425
426         /*
427          * Prep proxy barrier request.
428          */
429         blkdev_dequeue_request(rq);
430         q->orig_bar_rq = rq;
431         rq = &q->bar_rq;
432         rq->cmd_flags = 0;
433         rq_init(q, rq);
434         if (bio_data_dir(q->orig_bar_rq->bio) == WRITE)
435                 rq->cmd_flags |= REQ_RW;
436         rq->cmd_flags |= q->ordered & QUEUE_ORDERED_FUA ? REQ_FUA : 0;
437         rq->elevator_private = NULL;
438         rq->elevator_private2 = NULL;
439         init_request_from_bio(rq, q->orig_bar_rq->bio);
440         rq->end_io = bar_end_io;
441
442         /*
443          * Queue ordered sequence.  As we stack them at the head, we
444          * need to queue in reverse order.  Note that we rely on that
445          * no fs request uses ELEVATOR_INSERT_FRONT and thus no fs
446          * request gets inbetween ordered sequence.
447          */
448         if (q->ordered & QUEUE_ORDERED_POSTFLUSH)
449                 queue_flush(q, QUEUE_ORDERED_POSTFLUSH);
450         else
451                 q->ordseq |= QUEUE_ORDSEQ_POSTFLUSH;
452
453         elv_insert(q, rq, ELEVATOR_INSERT_FRONT);
454
455         if (q->ordered & QUEUE_ORDERED_PREFLUSH) {
456                 queue_flush(q, QUEUE_ORDERED_PREFLUSH);
457                 rq = &q->pre_flush_rq;
458         } else
459                 q->ordseq |= QUEUE_ORDSEQ_PREFLUSH;
460
461         if ((q->ordered & QUEUE_ORDERED_TAG) || q->in_flight == 0)
462                 q->ordseq |= QUEUE_ORDSEQ_DRAIN;
463         else
464                 rq = NULL;
465
466         return rq;
467 }
468
469 int blk_do_ordered(request_queue_t *q, struct request **rqp)
470 {
471         struct request *rq = *rqp;
472         int is_barrier = blk_fs_request(rq) && blk_barrier_rq(rq);
473
474         if (!q->ordseq) {
475                 if (!is_barrier)
476                         return 1;
477
478                 if (q->next_ordered != QUEUE_ORDERED_NONE) {
479                         *rqp = start_ordered(q, rq);
480                         return 1;
481                 } else {
482                         /*
483                          * This can happen when the queue switches to
484                          * ORDERED_NONE while this request is on it.
485                          */
486                         blkdev_dequeue_request(rq);
487                         end_that_request_first(rq, -EOPNOTSUPP,
488                                                rq->hard_nr_sectors);
489                         end_that_request_last(rq, -EOPNOTSUPP);
490                         *rqp = NULL;
491                         return 0;
492                 }
493         }
494
495         /*
496          * Ordered sequence in progress
497          */
498
499         /* Special requests are not subject to ordering rules. */
500         if (!blk_fs_request(rq) &&
501             rq != &q->pre_flush_rq && rq != &q->post_flush_rq)
502                 return 1;
503
504         if (q->ordered & QUEUE_ORDERED_TAG) {
505                 /* Ordered by tag.  Blocking the next barrier is enough. */
506                 if (is_barrier && rq != &q->bar_rq)
507                         *rqp = NULL;
508         } else {
509                 /* Ordered by draining.  Wait for turn. */
510                 WARN_ON(blk_ordered_req_seq(rq) < blk_ordered_cur_seq(q));
511                 if (blk_ordered_req_seq(rq) > blk_ordered_cur_seq(q))
512                         *rqp = NULL;
513         }
514
515         return 1;
516 }
517
518 static int flush_dry_bio_endio(struct bio *bio, unsigned int bytes, int error)
519 {
520         request_queue_t *q = bio->bi_private;
521         struct bio_vec *bvec;
522         int i;
523
524         /*
525          * This is dry run, restore bio_sector and size.  We'll finish
526          * this request again with the original bi_end_io after an
527          * error occurs or post flush is complete.
528          */
529         q->bi_size += bytes;
530
531         if (bio->bi_size)
532                 return 1;
533
534         /* Rewind bvec's */
535         bio->bi_idx = 0;
536         bio_for_each_segment(bvec, bio, i) {
537                 bvec->bv_len += bvec->bv_offset;
538                 bvec->bv_offset = 0;
539         }
540
541         /* Reset bio */
542         set_bit(BIO_UPTODATE, &bio->bi_flags);
543         bio->bi_size = q->bi_size;
544         bio->bi_sector -= (q->bi_size >> 9);
545         q->bi_size = 0;
546
547         return 0;
548 }
549
550 static int ordered_bio_endio(struct request *rq, struct bio *bio,
551                              unsigned int nbytes, int error)
552 {
553         request_queue_t *q = rq->q;
554         bio_end_io_t *endio;
555         void *private;
556
557         if (&q->bar_rq != rq)
558                 return 0;
559
560         /*
561          * Okay, this is the barrier request in progress, dry finish it.
562          */
563         if (error && !q->orderr)
564                 q->orderr = error;
565
566         endio = bio->bi_end_io;
567         private = bio->bi_private;
568         bio->bi_end_io = flush_dry_bio_endio;
569         bio->bi_private = q;
570
571         bio_endio(bio, nbytes, error);
572
573         bio->bi_end_io = endio;
574         bio->bi_private = private;
575
576         return 1;
577 }
578
579 /**
580  * blk_queue_bounce_limit - set bounce buffer limit for queue
581  * @q:  the request queue for the device
582  * @dma_addr:   bus address limit
583  *
584  * Description:
585  *    Different hardware can have different requirements as to what pages
586  *    it can do I/O directly to. A low level driver can call
587  *    blk_queue_bounce_limit to have lower memory pages allocated as bounce
588  *    buffers for doing I/O to pages residing above @page.
589  **/
590 void blk_queue_bounce_limit(request_queue_t *q, u64 dma_addr)
591 {
592         unsigned long bounce_pfn = dma_addr >> PAGE_SHIFT;
593         int dma = 0;
594
595         q->bounce_gfp = GFP_NOIO;
596 #if BITS_PER_LONG == 64
597         /* Assume anything <= 4GB can be handled by IOMMU.
598            Actually some IOMMUs can handle everything, but I don't
599            know of a way to test this here. */
600         if (bounce_pfn < (min_t(u64,0xffffffff,BLK_BOUNCE_HIGH) >> PAGE_SHIFT))
601                 dma = 1;
602         q->bounce_pfn = max_low_pfn;
603 #else
604         if (bounce_pfn < blk_max_low_pfn)
605                 dma = 1;
606         q->bounce_pfn = bounce_pfn;
607 #endif
608         if (dma) {
609                 init_emergency_isa_pool();
610                 q->bounce_gfp = GFP_NOIO | GFP_DMA;
611                 q->bounce_pfn = bounce_pfn;
612         }
613 }
614
615 EXPORT_SYMBOL(blk_queue_bounce_limit);
616
617 /**
618  * blk_queue_max_sectors - set max sectors for a request for this queue
619  * @q:  the request queue for the device
620  * @max_sectors:  max sectors in the usual 512b unit
621  *
622  * Description:
623  *    Enables a low level driver to set an upper limit on the size of
624  *    received requests.
625  **/
626 void blk_queue_max_sectors(request_queue_t *q, unsigned int max_sectors)
627 {
628         if ((max_sectors << 9) < PAGE_CACHE_SIZE) {
629                 max_sectors = 1 << (PAGE_CACHE_SHIFT - 9);
630                 printk("%s: set to minimum %d\n", __FUNCTION__, max_sectors);
631         }
632
633         if (BLK_DEF_MAX_SECTORS > max_sectors)
634                 q->max_hw_sectors = q->max_sectors = max_sectors;
635         else {
636                 q->max_sectors = BLK_DEF_MAX_SECTORS;
637                 q->max_hw_sectors = max_sectors;
638         }
639 }
640
641 EXPORT_SYMBOL(blk_queue_max_sectors);
642
643 /**
644  * blk_queue_max_phys_segments - set max phys segments for a request for this queue
645  * @q:  the request queue for the device
646  * @max_segments:  max number of segments
647  *
648  * Description:
649  *    Enables a low level driver to set an upper limit on the number of
650  *    physical data segments in a request.  This would be the largest sized
651  *    scatter list the driver could handle.
652  **/
653 void blk_queue_max_phys_segments(request_queue_t *q, unsigned short max_segments)
654 {
655         if (!max_segments) {
656                 max_segments = 1;
657                 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
658         }
659
660         q->max_phys_segments = max_segments;
661 }
662
663 EXPORT_SYMBOL(blk_queue_max_phys_segments);
664
665 /**
666  * blk_queue_max_hw_segments - set max hw segments for a request for this queue
667  * @q:  the request queue for the device
668  * @max_segments:  max number of segments
669  *
670  * Description:
671  *    Enables a low level driver to set an upper limit on the number of
672  *    hw data segments in a request.  This would be the largest number of
673  *    address/length pairs the host adapter can actually give as once
674  *    to the device.
675  **/
676 void blk_queue_max_hw_segments(request_queue_t *q, unsigned short max_segments)
677 {
678         if (!max_segments) {
679                 max_segments = 1;
680                 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
681         }
682
683         q->max_hw_segments = max_segments;
684 }
685
686 EXPORT_SYMBOL(blk_queue_max_hw_segments);
687
688 /**
689  * blk_queue_max_segment_size - set max segment size for blk_rq_map_sg
690  * @q:  the request queue for the device
691  * @max_size:  max size of segment in bytes
692  *
693  * Description:
694  *    Enables a low level driver to set an upper limit on the size of a
695  *    coalesced segment
696  **/
697 void blk_queue_max_segment_size(request_queue_t *q, unsigned int max_size)
698 {
699         if (max_size < PAGE_CACHE_SIZE) {
700                 max_size = PAGE_CACHE_SIZE;
701                 printk("%s: set to minimum %d\n", __FUNCTION__, max_size);
702         }
703
704         q->max_segment_size = max_size;
705 }
706
707 EXPORT_SYMBOL(blk_queue_max_segment_size);
708
709 /**
710  * blk_queue_hardsect_size - set hardware sector size for the queue
711  * @q:  the request queue for the device
712  * @size:  the hardware sector size, in bytes
713  *
714  * Description:
715  *   This should typically be set to the lowest possible sector size
716  *   that the hardware can operate on (possible without reverting to
717  *   even internal read-modify-write operations). Usually the default
718  *   of 512 covers most hardware.
719  **/
720 void blk_queue_hardsect_size(request_queue_t *q, unsigned short size)
721 {
722         q->hardsect_size = size;
723 }
724
725 EXPORT_SYMBOL(blk_queue_hardsect_size);
726
727 /*
728  * Returns the minimum that is _not_ zero, unless both are zero.
729  */
730 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
731
732 /**
733  * blk_queue_stack_limits - inherit underlying queue limits for stacked drivers
734  * @t:  the stacking driver (top)
735  * @b:  the underlying device (bottom)
736  **/
737 void blk_queue_stack_limits(request_queue_t *t, request_queue_t *b)
738 {
739         /* zero is "infinity" */
740         t->max_sectors = min_not_zero(t->max_sectors,b->max_sectors);
741         t->max_hw_sectors = min_not_zero(t->max_hw_sectors,b->max_hw_sectors);
742
743         t->max_phys_segments = min(t->max_phys_segments,b->max_phys_segments);
744         t->max_hw_segments = min(t->max_hw_segments,b->max_hw_segments);
745         t->max_segment_size = min(t->max_segment_size,b->max_segment_size);
746         t->hardsect_size = max(t->hardsect_size,b->hardsect_size);
747         if (!test_bit(QUEUE_FLAG_CLUSTER, &b->queue_flags))
748                 clear_bit(QUEUE_FLAG_CLUSTER, &t->queue_flags);
749 }
750
751 EXPORT_SYMBOL(blk_queue_stack_limits);
752
753 /**
754  * blk_queue_segment_boundary - set boundary rules for segment merging
755  * @q:  the request queue for the device
756  * @mask:  the memory boundary mask
757  **/
758 void blk_queue_segment_boundary(request_queue_t *q, unsigned long mask)
759 {
760         if (mask < PAGE_CACHE_SIZE - 1) {
761                 mask = PAGE_CACHE_SIZE - 1;
762                 printk("%s: set to minimum %lx\n", __FUNCTION__, mask);
763         }
764
765         q->seg_boundary_mask = mask;
766 }
767
768 EXPORT_SYMBOL(blk_queue_segment_boundary);
769
770 /**
771  * blk_queue_dma_alignment - set dma length and memory alignment
772  * @q:     the request queue for the device
773  * @mask:  alignment mask
774  *
775  * description:
776  *    set required memory and length aligment for direct dma transactions.
777  *    this is used when buiding direct io requests for the queue.
778  *
779  **/
780 void blk_queue_dma_alignment(request_queue_t *q, int mask)
781 {
782         q->dma_alignment = mask;
783 }
784
785 EXPORT_SYMBOL(blk_queue_dma_alignment);
786
787 /**
788  * blk_queue_find_tag - find a request by its tag and queue
789  * @q:   The request queue for the device
790  * @tag: The tag of the request
791  *
792  * Notes:
793  *    Should be used when a device returns a tag and you want to match
794  *    it with a request.
795  *
796  *    no locks need be held.
797  **/
798 struct request *blk_queue_find_tag(request_queue_t *q, int tag)
799 {
800         return blk_map_queue_find_tag(q->queue_tags, tag);
801 }
802
803 EXPORT_SYMBOL(blk_queue_find_tag);
804
805 /**
806  * __blk_free_tags - release a given set of tag maintenance info
807  * @bqt:        the tag map to free
808  *
809  * Tries to free the specified @bqt@.  Returns true if it was
810  * actually freed and false if there are still references using it
811  */
812 static int __blk_free_tags(struct blk_queue_tag *bqt)
813 {
814         int retval;
815
816         retval = atomic_dec_and_test(&bqt->refcnt);
817         if (retval) {
818                 BUG_ON(bqt->busy);
819                 BUG_ON(!list_empty(&bqt->busy_list));
820
821                 kfree(bqt->tag_index);
822                 bqt->tag_index = NULL;
823
824                 kfree(bqt->tag_map);
825                 bqt->tag_map = NULL;
826
827                 kfree(bqt);
828
829         }
830
831         return retval;
832 }
833
834 /**
835  * __blk_queue_free_tags - release tag maintenance info
836  * @q:  the request queue for the device
837  *
838  *  Notes:
839  *    blk_cleanup_queue() will take care of calling this function, if tagging
840  *    has been used. So there's no need to call this directly.
841  **/
842 static void __blk_queue_free_tags(request_queue_t *q)
843 {
844         struct blk_queue_tag *bqt = q->queue_tags;
845
846         if (!bqt)
847                 return;
848
849         __blk_free_tags(bqt);
850
851         q->queue_tags = NULL;
852         q->queue_flags &= ~(1 << QUEUE_FLAG_QUEUED);
853 }
854
855
856 /**
857  * blk_free_tags - release a given set of tag maintenance info
858  * @bqt:        the tag map to free
859  *
860  * For externally managed @bqt@ frees the map.  Callers of this
861  * function must guarantee to have released all the queues that
862  * might have been using this tag map.
863  */
864 void blk_free_tags(struct blk_queue_tag *bqt)
865 {
866         if (unlikely(!__blk_free_tags(bqt)))
867                 BUG();
868 }
869 EXPORT_SYMBOL(blk_free_tags);
870
871 /**
872  * blk_queue_free_tags - release tag maintenance info
873  * @q:  the request queue for the device
874  *
875  *  Notes:
876  *      This is used to disabled tagged queuing to a device, yet leave
877  *      queue in function.
878  **/
879 void blk_queue_free_tags(request_queue_t *q)
880 {
881         clear_bit(QUEUE_FLAG_QUEUED, &q->queue_flags);
882 }
883
884 EXPORT_SYMBOL(blk_queue_free_tags);
885
886 static int
887 init_tag_map(request_queue_t *q, struct blk_queue_tag *tags, int depth)
888 {
889         struct request **tag_index;
890         unsigned long *tag_map;
891         int nr_ulongs;
892
893         if (q && depth > q->nr_requests * 2) {
894                 depth = q->nr_requests * 2;
895                 printk(KERN_ERR "%s: adjusted depth to %d\n",
896                                 __FUNCTION__, depth);
897         }
898
899         tag_index = kzalloc(depth * sizeof(struct request *), GFP_ATOMIC);
900         if (!tag_index)
901                 goto fail;
902
903         nr_ulongs = ALIGN(depth, BITS_PER_LONG) / BITS_PER_LONG;
904         tag_map = kzalloc(nr_ulongs * sizeof(unsigned long), GFP_ATOMIC);
905         if (!tag_map)
906                 goto fail;
907
908         tags->real_max_depth = depth;
909         tags->max_depth = depth;
910         tags->tag_index = tag_index;
911         tags->tag_map = tag_map;
912
913         return 0;
914 fail:
915         kfree(tag_index);
916         return -ENOMEM;
917 }
918
919 static struct blk_queue_tag *__blk_queue_init_tags(struct request_queue *q,
920                                                    int depth)
921 {
922         struct blk_queue_tag *tags;
923
924         tags = kmalloc(sizeof(struct blk_queue_tag), GFP_ATOMIC);
925         if (!tags)
926                 goto fail;
927
928         if (init_tag_map(q, tags, depth))
929                 goto fail;
930
931         INIT_LIST_HEAD(&tags->busy_list);
932         tags->busy = 0;
933         atomic_set(&tags->refcnt, 1);
934         return tags;
935 fail:
936         kfree(tags);
937         return NULL;
938 }
939
940 /**
941  * blk_init_tags - initialize the tag info for an external tag map
942  * @depth:      the maximum queue depth supported
943  * @tags: the tag to use
944  **/
945 struct blk_queue_tag *blk_init_tags(int depth)
946 {
947         return __blk_queue_init_tags(NULL, depth);
948 }
949 EXPORT_SYMBOL(blk_init_tags);
950
951 /**
952  * blk_queue_init_tags - initialize the queue tag info
953  * @q:  the request queue for the device
954  * @depth:  the maximum queue depth supported
955  * @tags: the tag to use
956  **/
957 int blk_queue_init_tags(request_queue_t *q, int depth,
958                         struct blk_queue_tag *tags)
959 {
960         int rc;
961
962         BUG_ON(tags && q->queue_tags && tags != q->queue_tags);
963
964         if (!tags && !q->queue_tags) {
965                 tags = __blk_queue_init_tags(q, depth);
966
967                 if (!tags)
968                         goto fail;
969         } else if (q->queue_tags) {
970                 if ((rc = blk_queue_resize_tags(q, depth)))
971                         return rc;
972                 set_bit(QUEUE_FLAG_QUEUED, &q->queue_flags);
973                 return 0;
974         } else
975                 atomic_inc(&tags->refcnt);
976
977         /*
978          * assign it, all done
979          */
980         q->queue_tags = tags;
981         q->queue_flags |= (1 << QUEUE_FLAG_QUEUED);
982         return 0;
983 fail:
984         kfree(tags);
985         return -ENOMEM;
986 }
987
988 EXPORT_SYMBOL(blk_queue_init_tags);
989
990 /**
991  * blk_queue_resize_tags - change the queueing depth
992  * @q:  the request queue for the device
993  * @new_depth: the new max command queueing depth
994  *
995  *  Notes:
996  *    Must be called with the queue lock held.
997  **/
998 int blk_queue_resize_tags(request_queue_t *q, int new_depth)
999 {
1000         struct blk_queue_tag *bqt = q->queue_tags;
1001         struct request **tag_index;
1002         unsigned long *tag_map;
1003         int max_depth, nr_ulongs;
1004
1005         if (!bqt)
1006                 return -ENXIO;
1007
1008         /*
1009          * if we already have large enough real_max_depth.  just
1010          * adjust max_depth.  *NOTE* as requests with tag value
1011          * between new_depth and real_max_depth can be in-flight, tag
1012          * map can not be shrunk blindly here.
1013          */
1014         if (new_depth <= bqt->real_max_depth) {
1015                 bqt->max_depth = new_depth;
1016                 return 0;
1017         }
1018
1019         /*
1020          * Currently cannot replace a shared tag map with a new
1021          * one, so error out if this is the case
1022          */
1023         if (atomic_read(&bqt->refcnt) != 1)
1024                 return -EBUSY;
1025
1026         /*
1027          * save the old state info, so we can copy it back
1028          */
1029         tag_index = bqt->tag_index;
1030         tag_map = bqt->tag_map;
1031         max_depth = bqt->real_max_depth;
1032
1033         if (init_tag_map(q, bqt, new_depth))
1034                 return -ENOMEM;
1035
1036         memcpy(bqt->tag_index, tag_index, max_depth * sizeof(struct request *));
1037         nr_ulongs = ALIGN(max_depth, BITS_PER_LONG) / BITS_PER_LONG;
1038         memcpy(bqt->tag_map, tag_map, nr_ulongs * sizeof(unsigned long));
1039
1040         kfree(tag_index);
1041         kfree(tag_map);
1042         return 0;
1043 }
1044
1045 EXPORT_SYMBOL(blk_queue_resize_tags);
1046
1047 /**
1048  * blk_queue_end_tag - end tag operations for a request
1049  * @q:  the request queue for the device
1050  * @rq: the request that has completed
1051  *
1052  *  Description:
1053  *    Typically called when end_that_request_first() returns 0, meaning
1054  *    all transfers have been done for a request. It's important to call
1055  *    this function before end_that_request_last(), as that will put the
1056  *    request back on the free list thus corrupting the internal tag list.
1057  *
1058  *  Notes:
1059  *   queue lock must be held.
1060  **/
1061 void blk_queue_end_tag(request_queue_t *q, struct request *rq)
1062 {
1063         struct blk_queue_tag *bqt = q->queue_tags;
1064         int tag = rq->tag;
1065
1066         BUG_ON(tag == -1);
1067
1068         if (unlikely(tag >= bqt->real_max_depth))
1069                 /*
1070                  * This can happen after tag depth has been reduced.
1071                  * FIXME: how about a warning or info message here?
1072                  */
1073                 return;
1074
1075         if (unlikely(!__test_and_clear_bit(tag, bqt->tag_map))) {
1076                 printk(KERN_ERR "%s: attempt to clear non-busy tag (%d)\n",
1077                        __FUNCTION__, tag);
1078                 return;
1079         }
1080
1081         list_del_init(&rq->queuelist);
1082         rq->cmd_flags &= ~REQ_QUEUED;
1083         rq->tag = -1;
1084
1085         if (unlikely(bqt->tag_index[tag] == NULL))
1086                 printk(KERN_ERR "%s: tag %d is missing\n",
1087                        __FUNCTION__, tag);
1088
1089         bqt->tag_index[tag] = NULL;
1090         bqt->busy--;
1091 }
1092
1093 EXPORT_SYMBOL(blk_queue_end_tag);
1094
1095 /**
1096  * blk_queue_start_tag - find a free tag and assign it
1097  * @q:  the request queue for the device
1098  * @rq:  the block request that needs tagging
1099  *
1100  *  Description:
1101  *    This can either be used as a stand-alone helper, or possibly be
1102  *    assigned as the queue &prep_rq_fn (in which case &struct request
1103  *    automagically gets a tag assigned). Note that this function
1104  *    assumes that any type of request can be queued! if this is not
1105  *    true for your device, you must check the request type before
1106  *    calling this function.  The request will also be removed from
1107  *    the request queue, so it's the drivers responsibility to readd
1108  *    it if it should need to be restarted for some reason.
1109  *
1110  *  Notes:
1111  *   queue lock must be held.
1112  **/
1113 int blk_queue_start_tag(request_queue_t *q, struct request *rq)
1114 {
1115         struct blk_queue_tag *bqt = q->queue_tags;
1116         int tag;
1117
1118         if (unlikely((rq->cmd_flags & REQ_QUEUED))) {
1119                 printk(KERN_ERR 
1120                        "%s: request %p for device [%s] already tagged %d",
1121                        __FUNCTION__, rq,
1122                        rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->tag);
1123                 BUG();
1124         }
1125
1126         /*
1127          * Protect against shared tag maps, as we may not have exclusive
1128          * access to the tag map.
1129          */
1130         do {
1131                 tag = find_first_zero_bit(bqt->tag_map, bqt->max_depth);
1132                 if (tag >= bqt->max_depth)
1133                         return 1;
1134
1135         } while (test_and_set_bit(tag, bqt->tag_map));
1136
1137         rq->cmd_flags |= REQ_QUEUED;
1138         rq->tag = tag;
1139         bqt->tag_index[tag] = rq;
1140         blkdev_dequeue_request(rq);
1141         list_add(&rq->queuelist, &bqt->busy_list);
1142         bqt->busy++;
1143         return 0;
1144 }
1145
1146 EXPORT_SYMBOL(blk_queue_start_tag);
1147
1148 /**
1149  * blk_queue_invalidate_tags - invalidate all pending tags
1150  * @q:  the request queue for the device
1151  *
1152  *  Description:
1153  *   Hardware conditions may dictate a need to stop all pending requests.
1154  *   In this case, we will safely clear the block side of the tag queue and
1155  *   readd all requests to the request queue in the right order.
1156  *
1157  *  Notes:
1158  *   queue lock must be held.
1159  **/
1160 void blk_queue_invalidate_tags(request_queue_t *q)
1161 {
1162         struct blk_queue_tag *bqt = q->queue_tags;
1163         struct list_head *tmp, *n;
1164         struct request *rq;
1165
1166         list_for_each_safe(tmp, n, &bqt->busy_list) {
1167                 rq = list_entry_rq(tmp);
1168
1169                 if (rq->tag == -1) {
1170                         printk(KERN_ERR
1171                                "%s: bad tag found on list\n", __FUNCTION__);
1172                         list_del_init(&rq->queuelist);
1173                         rq->cmd_flags &= ~REQ_QUEUED;
1174                 } else
1175                         blk_queue_end_tag(q, rq);
1176
1177                 rq->cmd_flags &= ~REQ_STARTED;
1178                 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
1179         }
1180 }
1181
1182 EXPORT_SYMBOL(blk_queue_invalidate_tags);
1183
1184 void blk_dump_rq_flags(struct request *rq, char *msg)
1185 {
1186         int bit;
1187
1188         printk("%s: dev %s: type=%x, flags=%x\n", msg,
1189                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
1190                 rq->cmd_flags);
1191
1192         printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
1193                                                        rq->nr_sectors,
1194                                                        rq->current_nr_sectors);
1195         printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
1196
1197         if (blk_pc_request(rq)) {
1198                 printk("cdb: ");
1199                 for (bit = 0; bit < sizeof(rq->cmd); bit++)
1200                         printk("%02x ", rq->cmd[bit]);
1201                 printk("\n");
1202         }
1203 }
1204
1205 EXPORT_SYMBOL(blk_dump_rq_flags);
1206
1207 void blk_recount_segments(request_queue_t *q, struct bio *bio)
1208 {
1209         struct bio_vec *bv, *bvprv = NULL;
1210         int i, nr_phys_segs, nr_hw_segs, seg_size, hw_seg_size, cluster;
1211         int high, highprv = 1;
1212
1213         if (unlikely(!bio->bi_io_vec))
1214                 return;
1215
1216         cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
1217         hw_seg_size = seg_size = nr_phys_segs = nr_hw_segs = 0;
1218         bio_for_each_segment(bv, bio, i) {
1219                 /*
1220                  * the trick here is making sure that a high page is never
1221                  * considered part of another segment, since that might
1222                  * change with the bounce page.
1223                  */
1224                 high = page_to_pfn(bv->bv_page) >= q->bounce_pfn;
1225                 if (high || highprv)
1226                         goto new_hw_segment;
1227                 if (cluster) {
1228                         if (seg_size + bv->bv_len > q->max_segment_size)
1229                                 goto new_segment;
1230                         if (!BIOVEC_PHYS_MERGEABLE(bvprv, bv))
1231                                 goto new_segment;
1232                         if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bv))
1233                                 goto new_segment;
1234                         if (BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len))
1235                                 goto new_hw_segment;
1236
1237                         seg_size += bv->bv_len;
1238                         hw_seg_size += bv->bv_len;
1239                         bvprv = bv;
1240                         continue;
1241                 }
1242 new_segment:
1243                 if (BIOVEC_VIRT_MERGEABLE(bvprv, bv) &&
1244                     !BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len)) {
1245                         hw_seg_size += bv->bv_len;
1246                 } else {
1247 new_hw_segment:
1248                         if (hw_seg_size > bio->bi_hw_front_size)
1249                                 bio->bi_hw_front_size = hw_seg_size;
1250                         hw_seg_size = BIOVEC_VIRT_START_SIZE(bv) + bv->bv_len;
1251                         nr_hw_segs++;
1252                 }
1253
1254                 nr_phys_segs++;
1255                 bvprv = bv;
1256                 seg_size = bv->bv_len;
1257                 highprv = high;
1258         }
1259         if (hw_seg_size > bio->bi_hw_back_size)
1260                 bio->bi_hw_back_size = hw_seg_size;
1261         if (nr_hw_segs == 1 && hw_seg_size > bio->bi_hw_front_size)
1262                 bio->bi_hw_front_size = hw_seg_size;
1263         bio->bi_phys_segments = nr_phys_segs;
1264         bio->bi_hw_segments = nr_hw_segs;
1265         bio->bi_flags |= (1 << BIO_SEG_VALID);
1266 }
1267
1268
1269 static int blk_phys_contig_segment(request_queue_t *q, struct bio *bio,
1270                                    struct bio *nxt)
1271 {
1272         if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
1273                 return 0;
1274
1275         if (!BIOVEC_PHYS_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
1276                 return 0;
1277         if (bio->bi_size + nxt->bi_size > q->max_segment_size)
1278                 return 0;
1279
1280         /*
1281          * bio and nxt are contigous in memory, check if the queue allows
1282          * these two to be merged into one
1283          */
1284         if (BIO_SEG_BOUNDARY(q, bio, nxt))
1285                 return 1;
1286
1287         return 0;
1288 }
1289
1290 static int blk_hw_contig_segment(request_queue_t *q, struct bio *bio,
1291                                  struct bio *nxt)
1292 {
1293         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1294                 blk_recount_segments(q, bio);
1295         if (unlikely(!bio_flagged(nxt, BIO_SEG_VALID)))
1296                 blk_recount_segments(q, nxt);
1297         if (!BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)) ||
1298             BIOVEC_VIRT_OVERSIZE(bio->bi_hw_front_size + bio->bi_hw_back_size))
1299                 return 0;
1300         if (bio->bi_size + nxt->bi_size > q->max_segment_size)
1301                 return 0;
1302
1303         return 1;
1304 }
1305
1306 /*
1307  * map a request to scatterlist, return number of sg entries setup. Caller
1308  * must make sure sg can hold rq->nr_phys_segments entries
1309  */
1310 int blk_rq_map_sg(request_queue_t *q, struct request *rq, struct scatterlist *sg)
1311 {
1312         struct bio_vec *bvec, *bvprv;
1313         struct bio *bio;
1314         int nsegs, i, cluster;
1315
1316         nsegs = 0;
1317         cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
1318
1319         /*
1320          * for each bio in rq
1321          */
1322         bvprv = NULL;
1323         rq_for_each_bio(bio, rq) {
1324                 /*
1325                  * for each segment in bio
1326                  */
1327                 bio_for_each_segment(bvec, bio, i) {
1328                         int nbytes = bvec->bv_len;
1329
1330                         if (bvprv && cluster) {
1331                                 if (sg[nsegs - 1].length + nbytes > q->max_segment_size)
1332                                         goto new_segment;
1333
1334                                 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bvec))
1335                                         goto new_segment;
1336                                 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bvec))
1337                                         goto new_segment;
1338
1339                                 sg[nsegs - 1].length += nbytes;
1340                         } else {
1341 new_segment:
1342                                 memset(&sg[nsegs],0,sizeof(struct scatterlist));
1343                                 sg[nsegs].page = bvec->bv_page;
1344                                 sg[nsegs].length = nbytes;
1345                                 sg[nsegs].offset = bvec->bv_offset;
1346
1347                                 nsegs++;
1348                         }
1349                         bvprv = bvec;
1350                 } /* segments in bio */
1351         } /* bios in rq */
1352
1353         return nsegs;
1354 }
1355
1356 EXPORT_SYMBOL(blk_rq_map_sg);
1357
1358 /*
1359  * the standard queue merge functions, can be overridden with device
1360  * specific ones if so desired
1361  */
1362
1363 static inline int ll_new_mergeable(request_queue_t *q,
1364                                    struct request *req,
1365                                    struct bio *bio)
1366 {
1367         int nr_phys_segs = bio_phys_segments(q, bio);
1368
1369         if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
1370                 req->cmd_flags |= REQ_NOMERGE;
1371                 if (req == q->last_merge)
1372                         q->last_merge = NULL;
1373                 return 0;
1374         }
1375
1376         /*
1377          * A hw segment is just getting larger, bump just the phys
1378          * counter.
1379          */
1380         req->nr_phys_segments += nr_phys_segs;
1381         return 1;
1382 }
1383
1384 static inline int ll_new_hw_segment(request_queue_t *q,
1385                                     struct request *req,
1386                                     struct bio *bio)
1387 {
1388         int nr_hw_segs = bio_hw_segments(q, bio);
1389         int nr_phys_segs = bio_phys_segments(q, bio);
1390
1391         if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
1392             || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
1393                 req->cmd_flags |= REQ_NOMERGE;
1394                 if (req == q->last_merge)
1395                         q->last_merge = NULL;
1396                 return 0;
1397         }
1398
1399         /*
1400          * This will form the start of a new hw segment.  Bump both
1401          * counters.
1402          */
1403         req->nr_hw_segments += nr_hw_segs;
1404         req->nr_phys_segments += nr_phys_segs;
1405         return 1;
1406 }
1407
1408 static int ll_back_merge_fn(request_queue_t *q, struct request *req, 
1409                             struct bio *bio)
1410 {
1411         unsigned short max_sectors;
1412         int len;
1413
1414         if (unlikely(blk_pc_request(req)))
1415                 max_sectors = q->max_hw_sectors;
1416         else
1417                 max_sectors = q->max_sectors;
1418
1419         if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
1420                 req->cmd_flags |= REQ_NOMERGE;
1421                 if (req == q->last_merge)
1422                         q->last_merge = NULL;
1423                 return 0;
1424         }
1425         if (unlikely(!bio_flagged(req->biotail, BIO_SEG_VALID)))
1426                 blk_recount_segments(q, req->biotail);
1427         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1428                 blk_recount_segments(q, bio);
1429         len = req->biotail->bi_hw_back_size + bio->bi_hw_front_size;
1430         if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)) &&
1431             !BIOVEC_VIRT_OVERSIZE(len)) {
1432                 int mergeable =  ll_new_mergeable(q, req, bio);
1433
1434                 if (mergeable) {
1435                         if (req->nr_hw_segments == 1)
1436                                 req->bio->bi_hw_front_size = len;
1437                         if (bio->bi_hw_segments == 1)
1438                                 bio->bi_hw_back_size = len;
1439                 }
1440                 return mergeable;
1441         }
1442
1443         return ll_new_hw_segment(q, req, bio);
1444 }
1445
1446 static int ll_front_merge_fn(request_queue_t *q, struct request *req, 
1447                              struct bio *bio)
1448 {
1449         unsigned short max_sectors;
1450         int len;
1451
1452         if (unlikely(blk_pc_request(req)))
1453                 max_sectors = q->max_hw_sectors;
1454         else
1455                 max_sectors = q->max_sectors;
1456
1457
1458         if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
1459                 req->cmd_flags |= REQ_NOMERGE;
1460                 if (req == q->last_merge)
1461                         q->last_merge = NULL;
1462                 return 0;
1463         }
1464         len = bio->bi_hw_back_size + req->bio->bi_hw_front_size;
1465         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1466                 blk_recount_segments(q, bio);
1467         if (unlikely(!bio_flagged(req->bio, BIO_SEG_VALID)))
1468                 blk_recount_segments(q, req->bio);
1469         if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)) &&
1470             !BIOVEC_VIRT_OVERSIZE(len)) {
1471                 int mergeable =  ll_new_mergeable(q, req, bio);
1472
1473                 if (mergeable) {
1474                         if (bio->bi_hw_segments == 1)
1475                                 bio->bi_hw_front_size = len;
1476                         if (req->nr_hw_segments == 1)
1477                                 req->biotail->bi_hw_back_size = len;
1478                 }
1479                 return mergeable;
1480         }
1481
1482         return ll_new_hw_segment(q, req, bio);
1483 }
1484
1485 static int ll_merge_requests_fn(request_queue_t *q, struct request *req,
1486                                 struct request *next)
1487 {
1488         int total_phys_segments;
1489         int total_hw_segments;
1490
1491         /*
1492          * First check if the either of the requests are re-queued
1493          * requests.  Can't merge them if they are.
1494          */
1495         if (req->special || next->special)
1496                 return 0;
1497
1498         /*
1499          * Will it become too large?
1500          */
1501         if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
1502                 return 0;
1503
1504         total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
1505         if (blk_phys_contig_segment(q, req->biotail, next->bio))
1506                 total_phys_segments--;
1507
1508         if (total_phys_segments > q->max_phys_segments)
1509                 return 0;
1510
1511         total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1512         if (blk_hw_contig_segment(q, req->biotail, next->bio)) {
1513                 int len = req->biotail->bi_hw_back_size + next->bio->bi_hw_front_size;
1514                 /*
1515                  * propagate the combined length to the end of the requests
1516                  */
1517                 if (req->nr_hw_segments == 1)
1518                         req->bio->bi_hw_front_size = len;
1519                 if (next->nr_hw_segments == 1)
1520                         next->biotail->bi_hw_back_size = len;
1521                 total_hw_segments--;
1522         }
1523
1524         if (total_hw_segments > q->max_hw_segments)
1525                 return 0;
1526
1527         /* Merge is OK... */
1528         req->nr_phys_segments = total_phys_segments;
1529         req->nr_hw_segments = total_hw_segments;
1530         return 1;
1531 }
1532
1533 /*
1534  * "plug" the device if there are no outstanding requests: this will
1535  * force the transfer to start only after we have put all the requests
1536  * on the list.
1537  *
1538  * This is called with interrupts off and no requests on the queue and
1539  * with the queue lock held.
1540  */
1541 void blk_plug_device(request_queue_t *q)
1542 {
1543         WARN_ON(!irqs_disabled());
1544
1545         /*
1546          * don't plug a stopped queue, it must be paired with blk_start_queue()
1547          * which will restart the queueing
1548          */
1549         if (blk_queue_stopped(q))
1550                 return;
1551
1552         if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
1553                 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
1554                 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
1555         }
1556 }
1557
1558 EXPORT_SYMBOL(blk_plug_device);
1559
1560 /*
1561  * remove the queue from the plugged list, if present. called with
1562  * queue lock held and interrupts disabled.
1563  */
1564 int blk_remove_plug(request_queue_t *q)
1565 {
1566         WARN_ON(!irqs_disabled());
1567
1568         if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1569                 return 0;
1570
1571         del_timer(&q->unplug_timer);
1572         return 1;
1573 }
1574
1575 EXPORT_SYMBOL(blk_remove_plug);
1576
1577 /*
1578  * remove the plug and let it rip..
1579  */
1580 void __generic_unplug_device(request_queue_t *q)
1581 {
1582         if (unlikely(blk_queue_stopped(q)))
1583                 return;
1584
1585         if (!blk_remove_plug(q))
1586                 return;
1587
1588         q->request_fn(q);
1589 }
1590 EXPORT_SYMBOL(__generic_unplug_device);
1591
1592 /**
1593  * generic_unplug_device - fire a request queue
1594  * @q:    The &request_queue_t in question
1595  *
1596  * Description:
1597  *   Linux uses plugging to build bigger requests queues before letting
1598  *   the device have at them. If a queue is plugged, the I/O scheduler
1599  *   is still adding and merging requests on the queue. Once the queue
1600  *   gets unplugged, the request_fn defined for the queue is invoked and
1601  *   transfers started.
1602  **/
1603 void generic_unplug_device(request_queue_t *q)
1604 {
1605         spin_lock_irq(q->queue_lock);
1606         __generic_unplug_device(q);
1607         spin_unlock_irq(q->queue_lock);
1608 }
1609 EXPORT_SYMBOL(generic_unplug_device);
1610
1611 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
1612                                    struct page *page)
1613 {
1614         request_queue_t *q = bdi->unplug_io_data;
1615
1616         /*
1617          * devices don't necessarily have an ->unplug_fn defined
1618          */
1619         if (q->unplug_fn) {
1620                 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
1621                                         q->rq.count[READ] + q->rq.count[WRITE]);
1622
1623                 q->unplug_fn(q);
1624         }
1625 }
1626
1627 static void blk_unplug_work(struct work_struct *work)
1628 {
1629         request_queue_t *q = container_of(work, request_queue_t, unplug_work);
1630
1631         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
1632                                 q->rq.count[READ] + q->rq.count[WRITE]);
1633
1634         q->unplug_fn(q);
1635 }
1636
1637 static void blk_unplug_timeout(unsigned long data)
1638 {
1639         request_queue_t *q = (request_queue_t *)data;
1640
1641         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
1642                                 q->rq.count[READ] + q->rq.count[WRITE]);
1643
1644         kblockd_schedule_work(&q->unplug_work);
1645 }
1646
1647 /**
1648  * blk_start_queue - restart a previously stopped queue
1649  * @q:    The &request_queue_t in question
1650  *
1651  * Description:
1652  *   blk_start_queue() will clear the stop flag on the queue, and call
1653  *   the request_fn for the queue if it was in a stopped state when
1654  *   entered. Also see blk_stop_queue(). Queue lock must be held.
1655  **/
1656 void blk_start_queue(request_queue_t *q)
1657 {
1658         WARN_ON(!irqs_disabled());
1659
1660         clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1661
1662         /*
1663          * one level of recursion is ok and is much faster than kicking
1664          * the unplug handling
1665          */
1666         if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1667                 q->request_fn(q);
1668                 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1669         } else {
1670                 blk_plug_device(q);
1671                 kblockd_schedule_work(&q->unplug_work);
1672         }
1673 }
1674
1675 EXPORT_SYMBOL(blk_start_queue);
1676
1677 /**
1678  * blk_stop_queue - stop a queue
1679  * @q:    The &request_queue_t in question
1680  *
1681  * Description:
1682  *   The Linux block layer assumes that a block driver will consume all
1683  *   entries on the request queue when the request_fn strategy is called.
1684  *   Often this will not happen, because of hardware limitations (queue
1685  *   depth settings). If a device driver gets a 'queue full' response,
1686  *   or if it simply chooses not to queue more I/O at one point, it can
1687  *   call this function to prevent the request_fn from being called until
1688  *   the driver has signalled it's ready to go again. This happens by calling
1689  *   blk_start_queue() to restart queue operations. Queue lock must be held.
1690  **/
1691 void blk_stop_queue(request_queue_t *q)
1692 {
1693         blk_remove_plug(q);
1694         set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1695 }
1696 EXPORT_SYMBOL(blk_stop_queue);
1697
1698 /**
1699  * blk_sync_queue - cancel any pending callbacks on a queue
1700  * @q: the queue
1701  *
1702  * Description:
1703  *     The block layer may perform asynchronous callback activity
1704  *     on a queue, such as calling the unplug function after a timeout.
1705  *     A block device may call blk_sync_queue to ensure that any
1706  *     such activity is cancelled, thus allowing it to release resources
1707  *     the the callbacks might use. The caller must already have made sure
1708  *     that its ->make_request_fn will not re-add plugging prior to calling
1709  *     this function.
1710  *
1711  */
1712 void blk_sync_queue(struct request_queue *q)
1713 {
1714         del_timer_sync(&q->unplug_timer);
1715         kblockd_flush();
1716 }
1717 EXPORT_SYMBOL(blk_sync_queue);
1718
1719 /**
1720  * blk_run_queue - run a single device queue
1721  * @q:  The queue to run
1722  */
1723 void blk_run_queue(struct request_queue *q)
1724 {
1725         unsigned long flags;
1726
1727         spin_lock_irqsave(q->queue_lock, flags);
1728         blk_remove_plug(q);
1729
1730         /*
1731          * Only recurse once to avoid overrunning the stack, let the unplug
1732          * handling reinvoke the handler shortly if we already got there.
1733          */
1734         if (!elv_queue_empty(q)) {
1735                 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1736                         q->request_fn(q);
1737                         clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1738                 } else {
1739                         blk_plug_device(q);
1740                         kblockd_schedule_work(&q->unplug_work);
1741                 }
1742         }
1743
1744         spin_unlock_irqrestore(q->queue_lock, flags);
1745 }
1746 EXPORT_SYMBOL(blk_run_queue);
1747
1748 /**
1749  * blk_cleanup_queue: - release a &request_queue_t when it is no longer needed
1750  * @kobj:    the kobj belonging of the request queue to be released
1751  *
1752  * Description:
1753  *     blk_cleanup_queue is the pair to blk_init_queue() or
1754  *     blk_queue_make_request().  It should be called when a request queue is
1755  *     being released; typically when a block device is being de-registered.
1756  *     Currently, its primary task it to free all the &struct request
1757  *     structures that were allocated to the queue and the queue itself.
1758  *
1759  * Caveat:
1760  *     Hopefully the low level driver will have finished any
1761  *     outstanding requests first...
1762  **/
1763 static void blk_release_queue(struct kobject *kobj)
1764 {
1765         request_queue_t *q = container_of(kobj, struct request_queue, kobj);
1766         struct request_list *rl = &q->rq;
1767
1768         blk_sync_queue(q);
1769
1770         if (rl->rq_pool)
1771                 mempool_destroy(rl->rq_pool);
1772
1773         if (q->queue_tags)
1774                 __blk_queue_free_tags(q);
1775
1776         blk_trace_shutdown(q);
1777
1778         kmem_cache_free(requestq_cachep, q);
1779 }
1780
1781 void blk_put_queue(request_queue_t *q)
1782 {
1783         kobject_put(&q->kobj);
1784 }
1785 EXPORT_SYMBOL(blk_put_queue);
1786
1787 void blk_cleanup_queue(request_queue_t * q)
1788 {
1789         mutex_lock(&q->sysfs_lock);
1790         set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
1791         mutex_unlock(&q->sysfs_lock);
1792
1793         if (q->elevator)
1794                 elevator_exit(q->elevator);
1795
1796         blk_put_queue(q);
1797 }
1798
1799 EXPORT_SYMBOL(blk_cleanup_queue);
1800
1801 static int blk_init_free_list(request_queue_t *q)
1802 {
1803         struct request_list *rl = &q->rq;
1804
1805         rl->count[READ] = rl->count[WRITE] = 0;
1806         rl->starved[READ] = rl->starved[WRITE] = 0;
1807         rl->elvpriv = 0;
1808         init_waitqueue_head(&rl->wait[READ]);
1809         init_waitqueue_head(&rl->wait[WRITE]);
1810
1811         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
1812                                 mempool_free_slab, request_cachep, q->node);
1813
1814         if (!rl->rq_pool)
1815                 return -ENOMEM;
1816
1817         return 0;
1818 }
1819
1820 request_queue_t *blk_alloc_queue(gfp_t gfp_mask)
1821 {
1822         return blk_alloc_queue_node(gfp_mask, -1);
1823 }
1824 EXPORT_SYMBOL(blk_alloc_queue);
1825
1826 static struct kobj_type queue_ktype;
1827
1828 request_queue_t *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1829 {
1830         request_queue_t *q;
1831
1832         q = kmem_cache_alloc_node(requestq_cachep, gfp_mask, node_id);
1833         if (!q)
1834                 return NULL;
1835
1836         memset(q, 0, sizeof(*q));
1837         init_timer(&q->unplug_timer);
1838
1839         snprintf(q->kobj.name, KOBJ_NAME_LEN, "%s", "queue");
1840         q->kobj.ktype = &queue_ktype;
1841         kobject_init(&q->kobj);
1842
1843         q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
1844         q->backing_dev_info.unplug_io_data = q;
1845
1846         mutex_init(&q->sysfs_lock);
1847
1848         return q;
1849 }
1850 EXPORT_SYMBOL(blk_alloc_queue_node);
1851
1852 /**
1853  * blk_init_queue  - prepare a request queue for use with a block device
1854  * @rfn:  The function to be called to process requests that have been
1855  *        placed on the queue.
1856  * @lock: Request queue spin lock
1857  *
1858  * Description:
1859  *    If a block device wishes to use the standard request handling procedures,
1860  *    which sorts requests and coalesces adjacent requests, then it must
1861  *    call blk_init_queue().  The function @rfn will be called when there
1862  *    are requests on the queue that need to be processed.  If the device
1863  *    supports plugging, then @rfn may not be called immediately when requests
1864  *    are available on the queue, but may be called at some time later instead.
1865  *    Plugged queues are generally unplugged when a buffer belonging to one
1866  *    of the requests on the queue is needed, or due to memory pressure.
1867  *
1868  *    @rfn is not required, or even expected, to remove all requests off the
1869  *    queue, but only as many as it can handle at a time.  If it does leave
1870  *    requests on the queue, it is responsible for arranging that the requests
1871  *    get dealt with eventually.
1872  *
1873  *    The queue spin lock must be held while manipulating the requests on the
1874  *    request queue; this lock will be taken also from interrupt context, so irq
1875  *    disabling is needed for it.
1876  *
1877  *    Function returns a pointer to the initialized request queue, or NULL if
1878  *    it didn't succeed.
1879  *
1880  * Note:
1881  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
1882  *    when the block device is deactivated (such as at module unload).
1883  **/
1884
1885 request_queue_t *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1886 {
1887         return blk_init_queue_node(rfn, lock, -1);
1888 }
1889 EXPORT_SYMBOL(blk_init_queue);
1890
1891 request_queue_t *
1892 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
1893 {
1894         request_queue_t *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
1895
1896         if (!q)
1897                 return NULL;
1898
1899         q->node = node_id;
1900         if (blk_init_free_list(q)) {
1901                 kmem_cache_free(requestq_cachep, q);
1902                 return NULL;
1903         }
1904
1905         /*
1906          * if caller didn't supply a lock, they get per-queue locking with
1907          * our embedded lock
1908          */
1909         if (!lock) {
1910                 spin_lock_init(&q->__queue_lock);
1911                 lock = &q->__queue_lock;
1912         }
1913
1914         q->request_fn           = rfn;
1915         q->back_merge_fn        = ll_back_merge_fn;
1916         q->front_merge_fn       = ll_front_merge_fn;
1917         q->merge_requests_fn    = ll_merge_requests_fn;
1918         q->prep_rq_fn           = NULL;
1919         q->unplug_fn            = generic_unplug_device;
1920         q->queue_flags          = (1 << QUEUE_FLAG_CLUSTER);
1921         q->queue_lock           = lock;
1922
1923         blk_queue_segment_boundary(q, 0xffffffff);
1924
1925         blk_queue_make_request(q, __make_request);
1926         blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
1927
1928         blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
1929         blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
1930
1931         /*
1932          * all done
1933          */
1934         if (!elevator_init(q, NULL)) {
1935                 blk_queue_congestion_threshold(q);
1936                 return q;
1937         }
1938
1939         blk_put_queue(q);
1940         return NULL;
1941 }
1942 EXPORT_SYMBOL(blk_init_queue_node);
1943
1944 int blk_get_queue(request_queue_t *q)
1945 {
1946         if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
1947                 kobject_get(&q->kobj);
1948                 return 0;
1949         }
1950
1951         return 1;
1952 }
1953
1954 EXPORT_SYMBOL(blk_get_queue);
1955
1956 static inline void blk_free_request(request_queue_t *q, struct request *rq)
1957 {
1958         if (rq->cmd_flags & REQ_ELVPRIV)
1959                 elv_put_request(q, rq);
1960         mempool_free(rq, q->rq.rq_pool);
1961 }
1962
1963 static struct request *
1964 blk_alloc_request(request_queue_t *q, int rw, int priv, gfp_t gfp_mask)
1965 {
1966         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
1967
1968         if (!rq)
1969                 return NULL;
1970
1971         /*
1972          * first three bits are identical in rq->cmd_flags and bio->bi_rw,
1973          * see bio.h and blkdev.h
1974          */
1975         rq->cmd_flags = rw | REQ_ALLOCED;
1976
1977         if (priv) {
1978                 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
1979                         mempool_free(rq, q->rq.rq_pool);
1980                         return NULL;
1981                 }
1982                 rq->cmd_flags |= REQ_ELVPRIV;
1983         }
1984
1985         return rq;
1986 }
1987
1988 /*
1989  * ioc_batching returns true if the ioc is a valid batching request and
1990  * should be given priority access to a request.
1991  */
1992 static inline int ioc_batching(request_queue_t *q, struct io_context *ioc)
1993 {
1994         if (!ioc)
1995                 return 0;
1996
1997         /*
1998          * Make sure the process is able to allocate at least 1 request
1999          * even if the batch times out, otherwise we could theoretically
2000          * lose wakeups.
2001          */
2002         return ioc->nr_batch_requests == q->nr_batching ||
2003                 (ioc->nr_batch_requests > 0
2004                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
2005 }
2006
2007 /*
2008  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
2009  * will cause the process to be a "batcher" on all queues in the system. This
2010  * is the behaviour we want though - once it gets a wakeup it should be given
2011  * a nice run.
2012  */
2013 static void ioc_set_batching(request_queue_t *q, struct io_context *ioc)
2014 {
2015         if (!ioc || ioc_batching(q, ioc))
2016                 return;
2017
2018         ioc->nr_batch_requests = q->nr_batching;
2019         ioc->last_waited = jiffies;
2020 }
2021
2022 static void __freed_request(request_queue_t *q, int rw)
2023 {
2024         struct request_list *rl = &q->rq;
2025
2026         if (rl->count[rw] < queue_congestion_off_threshold(q))
2027                 blk_clear_queue_congested(q, rw);
2028
2029         if (rl->count[rw] + 1 <= q->nr_requests) {
2030                 if (waitqueue_active(&rl->wait[rw]))
2031                         wake_up(&rl->wait[rw]);
2032
2033                 blk_clear_queue_full(q, rw);
2034         }
2035 }
2036
2037 /*
2038  * A request has just been released.  Account for it, update the full and
2039  * congestion status, wake up any waiters.   Called under q->queue_lock.
2040  */
2041 static void freed_request(request_queue_t *q, int rw, int priv)
2042 {
2043         struct request_list *rl = &q->rq;
2044
2045         rl->count[rw]--;
2046         if (priv)
2047                 rl->elvpriv--;
2048
2049         __freed_request(q, rw);
2050
2051         if (unlikely(rl->starved[rw ^ 1]))
2052                 __freed_request(q, rw ^ 1);
2053 }
2054
2055 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
2056 /*
2057  * Get a free request, queue_lock must be held.
2058  * Returns NULL on failure, with queue_lock held.
2059  * Returns !NULL on success, with queue_lock *not held*.
2060  */
2061 static struct request *get_request(request_queue_t *q, int rw, struct bio *bio,
2062                                    gfp_t gfp_mask)
2063 {
2064         struct request *rq = NULL;
2065         struct request_list *rl = &q->rq;
2066         struct io_context *ioc = NULL;
2067         int may_queue, priv;
2068
2069         may_queue = elv_may_queue(q, rw);
2070         if (may_queue == ELV_MQUEUE_NO)
2071                 goto rq_starved;
2072
2073         if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
2074                 if (rl->count[rw]+1 >= q->nr_requests) {
2075                         ioc = current_io_context(GFP_ATOMIC, q->node);
2076                         /*
2077                          * The queue will fill after this allocation, so set
2078                          * it as full, and mark this process as "batching".
2079                          * This process will be allowed to complete a batch of
2080                          * requests, others will be blocked.
2081                          */
2082                         if (!blk_queue_full(q, rw)) {
2083                                 ioc_set_batching(q, ioc);
2084                                 blk_set_queue_full(q, rw);
2085                         } else {
2086                                 if (may_queue != ELV_MQUEUE_MUST
2087                                                 && !ioc_batching(q, ioc)) {
2088                                         /*
2089                                          * The queue is full and the allocating
2090                                          * process is not a "batcher", and not
2091                                          * exempted by the IO scheduler
2092                                          */
2093                                         goto out;
2094                                 }
2095                         }
2096                 }
2097                 blk_set_queue_congested(q, rw);
2098         }
2099
2100         /*
2101          * Only allow batching queuers to allocate up to 50% over the defined
2102          * limit of requests, otherwise we could have thousands of requests
2103          * allocated with any setting of ->nr_requests
2104          */
2105         if (rl->count[rw] >= (3 * q->nr_requests / 2))
2106                 goto out;
2107
2108         rl->count[rw]++;
2109         rl->starved[rw] = 0;
2110
2111         priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
2112         if (priv)
2113                 rl->elvpriv++;
2114
2115         spin_unlock_irq(q->queue_lock);
2116
2117         rq = blk_alloc_request(q, rw, priv, gfp_mask);
2118         if (unlikely(!rq)) {
2119                 /*
2120                  * Allocation failed presumably due to memory. Undo anything
2121                  * we might have messed up.
2122                  *
2123                  * Allocating task should really be put onto the front of the
2124                  * wait queue, but this is pretty rare.
2125                  */
2126                 spin_lock_irq(q->queue_lock);
2127                 freed_request(q, rw, priv);
2128
2129                 /*
2130                  * in the very unlikely event that allocation failed and no
2131                  * requests for this direction was pending, mark us starved
2132                  * so that freeing of a request in the other direction will
2133                  * notice us. another possible fix would be to split the
2134                  * rq mempool into READ and WRITE
2135                  */
2136 rq_starved:
2137                 if (unlikely(rl->count[rw] == 0))
2138                         rl->starved[rw] = 1;
2139
2140                 goto out;
2141         }
2142
2143         /*
2144          * ioc may be NULL here, and ioc_batching will be false. That's
2145          * OK, if the queue is under the request limit then requests need
2146          * not count toward the nr_batch_requests limit. There will always
2147          * be some limit enforced by BLK_BATCH_TIME.
2148          */
2149         if (ioc_batching(q, ioc))
2150                 ioc->nr_batch_requests--;
2151         
2152         rq_init(q, rq);
2153
2154         blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
2155 out:
2156         return rq;
2157 }
2158
2159 /*
2160  * No available requests for this queue, unplug the device and wait for some
2161  * requests to become available.
2162  *
2163  * Called with q->queue_lock held, and returns with it unlocked.
2164  */
2165 static struct request *get_request_wait(request_queue_t *q, int rw,
2166                                         struct bio *bio)
2167 {
2168         struct request *rq;
2169
2170         rq = get_request(q, rw, bio, GFP_NOIO);
2171         while (!rq) {
2172                 DEFINE_WAIT(wait);
2173                 struct request_list *rl = &q->rq;
2174
2175                 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
2176                                 TASK_UNINTERRUPTIBLE);
2177
2178                 rq = get_request(q, rw, bio, GFP_NOIO);
2179
2180                 if (!rq) {
2181                         struct io_context *ioc;
2182
2183                         blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
2184
2185                         __generic_unplug_device(q);
2186                         spin_unlock_irq(q->queue_lock);
2187                         io_schedule();
2188
2189                         /*
2190                          * After sleeping, we become a "batching" process and
2191                          * will be able to allocate at least one request, and
2192                          * up to a big batch of them for a small period time.
2193                          * See ioc_batching, ioc_set_batching
2194                          */
2195                         ioc = current_io_context(GFP_NOIO, q->node);
2196                         ioc_set_batching(q, ioc);
2197
2198                         spin_lock_irq(q->queue_lock);
2199                 }
2200                 finish_wait(&rl->wait[rw], &wait);
2201         }
2202
2203         return rq;
2204 }
2205
2206 struct request *blk_get_request(request_queue_t *q, int rw, gfp_t gfp_mask)
2207 {
2208         struct request *rq;
2209
2210         BUG_ON(rw != READ && rw != WRITE);
2211
2212         spin_lock_irq(q->queue_lock);
2213         if (gfp_mask & __GFP_WAIT) {
2214                 rq = get_request_wait(q, rw, NULL);
2215         } else {
2216                 rq = get_request(q, rw, NULL, gfp_mask);
2217                 if (!rq)
2218                         spin_unlock_irq(q->queue_lock);
2219         }
2220         /* q->queue_lock is unlocked at this point */
2221
2222         return rq;
2223 }
2224 EXPORT_SYMBOL(blk_get_request);
2225
2226 /**
2227  * blk_start_queueing - initiate dispatch of requests to device
2228  * @q:          request queue to kick into gear
2229  *
2230  * This is basically a helper to remove the need to know whether a queue
2231  * is plugged or not if someone just wants to initiate dispatch of requests
2232  * for this queue.
2233  *
2234  * The queue lock must be held with interrupts disabled.
2235  */
2236 void blk_start_queueing(request_queue_t *q)
2237 {
2238         if (!blk_queue_plugged(q))
2239                 q->request_fn(q);
2240         else
2241                 __generic_unplug_device(q);
2242 }
2243 EXPORT_SYMBOL(blk_start_queueing);
2244
2245 /**
2246  * blk_requeue_request - put a request back on queue
2247  * @q:          request queue where request should be inserted
2248  * @rq:         request to be inserted
2249  *
2250  * Description:
2251  *    Drivers often keep queueing requests until the hardware cannot accept
2252  *    more, when that condition happens we need to put the request back
2253  *    on the queue. Must be called with queue lock held.
2254  */
2255 void blk_requeue_request(request_queue_t *q, struct request *rq)
2256 {
2257         blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
2258
2259         if (blk_rq_tagged(rq))
2260                 blk_queue_end_tag(q, rq);
2261
2262         elv_requeue_request(q, rq);
2263 }
2264
2265 EXPORT_SYMBOL(blk_requeue_request);
2266
2267 /**
2268  * blk_insert_request - insert a special request in to a request queue
2269  * @q:          request queue where request should be inserted
2270  * @rq:         request to be inserted
2271  * @at_head:    insert request at head or tail of queue
2272  * @data:       private data
2273  *
2274  * Description:
2275  *    Many block devices need to execute commands asynchronously, so they don't
2276  *    block the whole kernel from preemption during request execution.  This is
2277  *    accomplished normally by inserting aritficial requests tagged as
2278  *    REQ_SPECIAL in to the corresponding request queue, and letting them be
2279  *    scheduled for actual execution by the request queue.
2280  *
2281  *    We have the option of inserting the head or the tail of the queue.
2282  *    Typically we use the tail for new ioctls and so forth.  We use the head
2283  *    of the queue for things like a QUEUE_FULL message from a device, or a
2284  *    host that is unable to accept a particular command.
2285  */
2286 void blk_insert_request(request_queue_t *q, struct request *rq,
2287                         int at_head, void *data)
2288 {
2289         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
2290         unsigned long flags;
2291
2292         /*
2293          * tell I/O scheduler that this isn't a regular read/write (ie it
2294          * must not attempt merges on this) and that it acts as a soft
2295          * barrier
2296          */
2297         rq->cmd_type = REQ_TYPE_SPECIAL;
2298         rq->cmd_flags |= REQ_SOFTBARRIER;
2299
2300         rq->special = data;
2301
2302         spin_lock_irqsave(q->queue_lock, flags);
2303
2304         /*
2305          * If command is tagged, release the tag
2306          */
2307         if (blk_rq_tagged(rq))
2308                 blk_queue_end_tag(q, rq);
2309
2310         drive_stat_acct(rq, rq->nr_sectors, 1);
2311         __elv_add_request(q, rq, where, 0);
2312         blk_start_queueing(q);
2313         spin_unlock_irqrestore(q->queue_lock, flags);
2314 }
2315
2316 EXPORT_SYMBOL(blk_insert_request);
2317
2318 static int __blk_rq_unmap_user(struct bio *bio)
2319 {
2320         int ret = 0;
2321
2322         if (bio) {
2323                 if (bio_flagged(bio, BIO_USER_MAPPED))
2324                         bio_unmap_user(bio);
2325                 else
2326                         ret = bio_uncopy_user(bio);
2327         }
2328
2329         return ret;
2330 }
2331
2332 static int __blk_rq_map_user(request_queue_t *q, struct request *rq,
2333                              void __user *ubuf, unsigned int len)
2334 {
2335         unsigned long uaddr;
2336         struct bio *bio, *orig_bio;
2337         int reading, ret;
2338
2339         reading = rq_data_dir(rq) == READ;
2340
2341         /*
2342          * if alignment requirement is satisfied, map in user pages for
2343          * direct dma. else, set up kernel bounce buffers
2344          */
2345         uaddr = (unsigned long) ubuf;
2346         if (!(uaddr & queue_dma_alignment(q)) && !(len & queue_dma_alignment(q)))
2347                 bio = bio_map_user(q, NULL, uaddr, len, reading);
2348         else
2349                 bio = bio_copy_user(q, uaddr, len, reading);
2350
2351         if (IS_ERR(bio)) {
2352                 return PTR_ERR(bio);
2353         }
2354
2355         orig_bio = bio;
2356         blk_queue_bounce(q, &bio);
2357         /*
2358          * We link the bounce buffer in and could have to traverse it
2359          * later so we have to get a ref to prevent it from being freed
2360          */
2361         bio_get(bio);
2362
2363         /*
2364          * for most (all? don't know of any) queues we could
2365          * skip grabbing the queue lock here. only drivers with
2366          * funky private ->back_merge_fn() function could be
2367          * problematic.
2368          */
2369         spin_lock_irq(q->queue_lock);
2370         if (!rq->bio)
2371                 blk_rq_bio_prep(q, rq, bio);
2372         else if (!q->back_merge_fn(q, rq, bio)) {
2373                 ret = -EINVAL;
2374                 spin_unlock_irq(q->queue_lock);
2375                 goto unmap_bio;
2376         } else {
2377                 rq->biotail->bi_next = bio;
2378                 rq->biotail = bio;
2379
2380                 rq->nr_sectors += bio_sectors(bio);
2381                 rq->hard_nr_sectors = rq->nr_sectors;
2382                 rq->data_len += bio->bi_size;
2383         }
2384         spin_unlock_irq(q->queue_lock);
2385
2386         return bio->bi_size;
2387
2388 unmap_bio:
2389         /* if it was boucned we must call the end io function */
2390         bio_endio(bio, bio->bi_size, 0);
2391         __blk_rq_unmap_user(orig_bio);
2392         bio_put(bio);
2393         return ret;
2394 }
2395
2396 /**
2397  * blk_rq_map_user - map user data to a request, for REQ_BLOCK_PC usage
2398  * @q:          request queue where request should be inserted
2399  * @rq:         request structure to fill
2400  * @ubuf:       the user buffer
2401  * @len:        length of user data
2402  *
2403  * Description:
2404  *    Data will be mapped directly for zero copy io, if possible. Otherwise
2405  *    a kernel bounce buffer is used.
2406  *
2407  *    A matching blk_rq_unmap_user() must be issued at the end of io, while
2408  *    still in process context.
2409  *
2410  *    Note: The mapped bio may need to be bounced through blk_queue_bounce()
2411  *    before being submitted to the device, as pages mapped may be out of
2412  *    reach. It's the callers responsibility to make sure this happens. The
2413  *    original bio must be passed back in to blk_rq_unmap_user() for proper
2414  *    unmapping.
2415  */
2416 int blk_rq_map_user(request_queue_t *q, struct request *rq, void __user *ubuf,
2417                     unsigned long len)
2418 {
2419         unsigned long bytes_read = 0;
2420         int ret;
2421
2422         if (len > (q->max_hw_sectors << 9))
2423                 return -EINVAL;
2424         if (!len || !ubuf)
2425                 return -EINVAL;
2426
2427         while (bytes_read != len) {
2428                 unsigned long map_len, end, start;
2429
2430                 map_len = min_t(unsigned long, len - bytes_read, BIO_MAX_SIZE);
2431                 end = ((unsigned long)ubuf + map_len + PAGE_SIZE - 1)
2432                                                                 >> PAGE_SHIFT;
2433                 start = (unsigned long)ubuf >> PAGE_SHIFT;
2434
2435                 /*
2436                  * A bad offset could cause us to require BIO_MAX_PAGES + 1
2437                  * pages. If this happens we just lower the requested
2438                  * mapping len by a page so that we can fit
2439                  */
2440                 if (end - start > BIO_MAX_PAGES)
2441                         map_len -= PAGE_SIZE;
2442
2443                 ret = __blk_rq_map_user(q, rq, ubuf, map_len);
2444                 if (ret < 0)
2445                         goto unmap_rq;
2446                 bytes_read += ret;
2447                 ubuf += ret;
2448         }
2449
2450         rq->buffer = rq->data = NULL;
2451         return 0;
2452 unmap_rq:
2453         blk_rq_unmap_user(rq);
2454         return ret;
2455 }
2456
2457 EXPORT_SYMBOL(blk_rq_map_user);
2458
2459 /**
2460  * blk_rq_map_user_iov - map user data to a request, for REQ_BLOCK_PC usage
2461  * @q:          request queue where request should be inserted
2462  * @rq:         request to map data to
2463  * @iov:        pointer to the iovec
2464  * @iov_count:  number of elements in the iovec
2465  *
2466  * Description:
2467  *    Data will be mapped directly for zero copy io, if possible. Otherwise
2468  *    a kernel bounce buffer is used.
2469  *
2470  *    A matching blk_rq_unmap_user() must be issued at the end of io, while
2471  *    still in process context.
2472  *
2473  *    Note: The mapped bio may need to be bounced through blk_queue_bounce()
2474  *    before being submitted to the device, as pages mapped may be out of
2475  *    reach. It's the callers responsibility to make sure this happens. The
2476  *    original bio must be passed back in to blk_rq_unmap_user() for proper
2477  *    unmapping.
2478  */
2479 int blk_rq_map_user_iov(request_queue_t *q, struct request *rq,
2480                         struct sg_iovec *iov, int iov_count, unsigned int len)
2481 {
2482         struct bio *bio;
2483
2484         if (!iov || iov_count <= 0)
2485                 return -EINVAL;
2486
2487         /* we don't allow misaligned data like bio_map_user() does.  If the
2488          * user is using sg, they're expected to know the alignment constraints
2489          * and respect them accordingly */
2490         bio = bio_map_user_iov(q, NULL, iov, iov_count, rq_data_dir(rq)== READ);
2491         if (IS_ERR(bio))
2492                 return PTR_ERR(bio);
2493
2494         if (bio->bi_size != len) {
2495                 bio_endio(bio, bio->bi_size, 0);
2496                 bio_unmap_user(bio);
2497                 return -EINVAL;
2498         }
2499
2500         bio_get(bio);
2501         blk_rq_bio_prep(q, rq, bio);
2502         rq->buffer = rq->data = NULL;
2503         return 0;
2504 }
2505
2506 EXPORT_SYMBOL(blk_rq_map_user_iov);
2507
2508 /**
2509  * blk_rq_unmap_user - unmap a request with user data
2510  * @rq:         rq to be unmapped
2511  *
2512  * Description:
2513  *    Unmap a rq previously mapped by blk_rq_map_user().
2514  *    rq->bio must be set to the original head of the request.
2515  */
2516 int blk_rq_unmap_user(struct request *rq)
2517 {
2518         struct bio *bio, *mapped_bio;
2519
2520         while ((bio = rq->bio)) {
2521                 if (bio_flagged(bio, BIO_BOUNCED))
2522                         mapped_bio = bio->bi_private;
2523                 else
2524                         mapped_bio = bio;
2525
2526                 __blk_rq_unmap_user(mapped_bio);
2527                 rq->bio = bio->bi_next;
2528                 bio_put(bio);
2529         }
2530         return 0;
2531 }
2532
2533 EXPORT_SYMBOL(blk_rq_unmap_user);
2534
2535 /**
2536  * blk_rq_map_kern - map kernel data to a request, for REQ_BLOCK_PC usage
2537  * @q:          request queue where request should be inserted
2538  * @rq:         request to fill
2539  * @kbuf:       the kernel buffer
2540  * @len:        length of user data
2541  * @gfp_mask:   memory allocation flags
2542  */
2543 int blk_rq_map_kern(request_queue_t *q, struct request *rq, void *kbuf,
2544                     unsigned int len, gfp_t gfp_mask)
2545 {
2546         struct bio *bio;
2547
2548         if (len > (q->max_hw_sectors << 9))
2549                 return -EINVAL;
2550         if (!len || !kbuf)
2551                 return -EINVAL;
2552
2553         bio = bio_map_kern(q, kbuf, len, gfp_mask);
2554         if (IS_ERR(bio))
2555                 return PTR_ERR(bio);
2556
2557         if (rq_data_dir(rq) == WRITE)
2558                 bio->bi_rw |= (1 << BIO_RW);
2559
2560         blk_rq_bio_prep(q, rq, bio);
2561         rq->buffer = rq->data = NULL;
2562         return 0;
2563 }
2564
2565 EXPORT_SYMBOL(blk_rq_map_kern);
2566
2567 /**
2568  * blk_execute_rq_nowait - insert a request into queue for execution
2569  * @q:          queue to insert the request in
2570  * @bd_disk:    matching gendisk
2571  * @rq:         request to insert
2572  * @at_head:    insert request at head or tail of queue
2573  * @done:       I/O completion handler
2574  *
2575  * Description:
2576  *    Insert a fully prepared request at the back of the io scheduler queue
2577  *    for execution.  Don't wait for completion.
2578  */
2579 void blk_execute_rq_nowait(request_queue_t *q, struct gendisk *bd_disk,
2580                            struct request *rq, int at_head,
2581                            rq_end_io_fn *done)
2582 {
2583         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
2584
2585         rq->rq_disk = bd_disk;
2586         rq->cmd_flags |= REQ_NOMERGE;
2587         rq->end_io = done;
2588         WARN_ON(irqs_disabled());
2589         spin_lock_irq(q->queue_lock);
2590         __elv_add_request(q, rq, where, 1);
2591         __generic_unplug_device(q);
2592         spin_unlock_irq(q->queue_lock);
2593 }
2594 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
2595
2596 /**
2597  * blk_execute_rq - insert a request into queue for execution
2598  * @q:          queue to insert the request in
2599  * @bd_disk:    matching gendisk
2600  * @rq:         request to insert
2601  * @at_head:    insert request at head or tail of queue
2602  *
2603  * Description:
2604  *    Insert a fully prepared request at the back of the io scheduler queue
2605  *    for execution and wait for completion.
2606  */
2607 int blk_execute_rq(request_queue_t *q, struct gendisk *bd_disk,
2608                    struct request *rq, int at_head)
2609 {
2610         DECLARE_COMPLETION_ONSTACK(wait);
2611         char sense[SCSI_SENSE_BUFFERSIZE];
2612         int err = 0;
2613
2614         /*
2615          * we need an extra reference to the request, so we can look at
2616          * it after io completion
2617          */
2618         rq->ref_count++;
2619
2620         if (!rq->sense) {
2621                 memset(sense, 0, sizeof(sense));
2622                 rq->sense = sense;
2623                 rq->sense_len = 0;
2624         }
2625
2626         rq->end_io_data = &wait;
2627         blk_execute_rq_nowait(q, bd_disk, rq, at_head, blk_end_sync_rq);
2628         wait_for_completion(&wait);
2629
2630         if (rq->errors)
2631                 err = -EIO;
2632
2633         return err;
2634 }
2635
2636 EXPORT_SYMBOL(blk_execute_rq);
2637
2638 /**
2639  * blkdev_issue_flush - queue a flush
2640  * @bdev:       blockdev to issue flush for
2641  * @error_sector:       error sector
2642  *
2643  * Description:
2644  *    Issue a flush for the block device in question. Caller can supply
2645  *    room for storing the error offset in case of a flush error, if they
2646  *    wish to.  Caller must run wait_for_completion() on its own.
2647  */
2648 int blkdev_issue_flush(struct block_device *bdev, sector_t *error_sector)
2649 {
2650         request_queue_t *q;
2651
2652         if (bdev->bd_disk == NULL)
2653                 return -ENXIO;
2654
2655         q = bdev_get_queue(bdev);
2656         if (!q)
2657                 return -ENXIO;
2658         if (!q->issue_flush_fn)
2659                 return -EOPNOTSUPP;
2660
2661         return q->issue_flush_fn(q, bdev->bd_disk, error_sector);
2662 }
2663
2664 EXPORT_SYMBOL(blkdev_issue_flush);
2665
2666 static void drive_stat_acct(struct request *rq, int nr_sectors, int new_io)
2667 {
2668         int rw = rq_data_dir(rq);
2669
2670         if (!blk_fs_request(rq) || !rq->rq_disk)
2671                 return;
2672
2673         if (!new_io) {
2674                 __disk_stat_inc(rq->rq_disk, merges[rw]);
2675         } else {
2676                 disk_round_stats(rq->rq_disk);
2677                 rq->rq_disk->in_flight++;
2678         }
2679 }
2680
2681 /*
2682  * add-request adds a request to the linked list.
2683  * queue lock is held and interrupts disabled, as we muck with the
2684  * request queue list.
2685  */
2686 static inline void add_request(request_queue_t * q, struct request * req)
2687 {
2688         drive_stat_acct(req, req->nr_sectors, 1);
2689
2690         /*
2691          * elevator indicated where it wants this request to be
2692          * inserted at elevator_merge time
2693          */
2694         __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
2695 }
2696  
2697 /*
2698  * disk_round_stats()   - Round off the performance stats on a struct
2699  * disk_stats.
2700  *
2701  * The average IO queue length and utilisation statistics are maintained
2702  * by observing the current state of the queue length and the amount of
2703  * time it has been in this state for.
2704  *
2705  * Normally, that accounting is done on IO completion, but that can result
2706  * in more than a second's worth of IO being accounted for within any one
2707  * second, leading to >100% utilisation.  To deal with that, we call this
2708  * function to do a round-off before returning the results when reading
2709  * /proc/diskstats.  This accounts immediately for all queue usage up to
2710  * the current jiffies and restarts the counters again.
2711  */
2712 void disk_round_stats(struct gendisk *disk)
2713 {
2714         unsigned long now = jiffies;
2715
2716         if (now == disk->stamp)
2717                 return;
2718
2719         if (disk->in_flight) {
2720                 __disk_stat_add(disk, time_in_queue,
2721                                 disk->in_flight * (now - disk->stamp));
2722                 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
2723         }
2724         disk->stamp = now;
2725 }
2726
2727 EXPORT_SYMBOL_GPL(disk_round_stats);
2728
2729 /*
2730  * queue lock must be held
2731  */
2732 void __blk_put_request(request_queue_t *q, struct request *req)
2733 {
2734         if (unlikely(!q))
2735                 return;
2736         if (unlikely(--req->ref_count))
2737                 return;
2738
2739         elv_completed_request(q, req);
2740
2741         /*
2742          * Request may not have originated from ll_rw_blk. if not,
2743          * it didn't come out of our reserved rq pools
2744          */
2745         if (req->cmd_flags & REQ_ALLOCED) {
2746                 int rw = rq_data_dir(req);
2747                 int priv = req->cmd_flags & REQ_ELVPRIV;
2748
2749                 BUG_ON(!list_empty(&req->queuelist));
2750                 BUG_ON(!hlist_unhashed(&req->hash));
2751
2752                 blk_free_request(q, req);
2753                 freed_request(q, rw, priv);
2754         }
2755 }
2756
2757 EXPORT_SYMBOL_GPL(__blk_put_request);
2758
2759 void blk_put_request(struct request *req)
2760 {
2761         unsigned long flags;
2762         request_queue_t *q = req->q;
2763
2764         /*
2765          * Gee, IDE calls in w/ NULL q.  Fix IDE and remove the
2766          * following if (q) test.
2767          */
2768         if (q) {
2769                 spin_lock_irqsave(q->queue_lock, flags);
2770                 __blk_put_request(q, req);
2771                 spin_unlock_irqrestore(q->queue_lock, flags);
2772         }
2773 }
2774
2775 EXPORT_SYMBOL(blk_put_request);
2776
2777 /**
2778  * blk_end_sync_rq - executes a completion event on a request
2779  * @rq: request to complete
2780  * @error: end io status of the request
2781  */
2782 void blk_end_sync_rq(struct request *rq, int error)
2783 {
2784         struct completion *waiting = rq->end_io_data;
2785
2786         rq->end_io_data = NULL;
2787         __blk_put_request(rq->q, rq);
2788
2789         /*
2790          * complete last, if this is a stack request the process (and thus
2791          * the rq pointer) could be invalid right after this complete()
2792          */
2793         complete(waiting);
2794 }
2795 EXPORT_SYMBOL(blk_end_sync_rq);
2796
2797 /*
2798  * Has to be called with the request spinlock acquired
2799  */
2800 static int attempt_merge(request_queue_t *q, struct request *req,
2801                           struct request *next)
2802 {
2803         if (!rq_mergeable(req) || !rq_mergeable(next))
2804                 return 0;
2805
2806         /*
2807          * not contiguous
2808          */
2809         if (req->sector + req->nr_sectors != next->sector)
2810                 return 0;
2811
2812         if (rq_data_dir(req) != rq_data_dir(next)
2813             || req->rq_disk != next->rq_disk
2814             || next->special)
2815                 return 0;
2816
2817         /*
2818          * If we are allowed to merge, then append bio list
2819          * from next to rq and release next. merge_requests_fn
2820          * will have updated segment counts, update sector
2821          * counts here.
2822          */
2823         if (!q->merge_requests_fn(q, req, next))
2824                 return 0;
2825
2826         /*
2827          * At this point we have either done a back merge
2828          * or front merge. We need the smaller start_time of
2829          * the merged requests to be the current request
2830          * for accounting purposes.
2831          */
2832         if (time_after(req->start_time, next->start_time))
2833                 req->start_time = next->start_time;
2834
2835         req->biotail->bi_next = next->bio;
2836         req->biotail = next->biotail;
2837
2838         req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
2839
2840         elv_merge_requests(q, req, next);
2841
2842         if (req->rq_disk) {
2843                 disk_round_stats(req->rq_disk);
2844                 req->rq_disk->in_flight--;
2845         }
2846
2847         req->ioprio = ioprio_best(req->ioprio, next->ioprio);
2848
2849         __blk_put_request(q, next);
2850         return 1;
2851 }
2852
2853 static inline int attempt_back_merge(request_queue_t *q, struct request *rq)
2854 {
2855         struct request *next = elv_latter_request(q, rq);
2856
2857         if (next)
2858                 return attempt_merge(q, rq, next);
2859
2860         return 0;
2861 }
2862
2863 static inline int attempt_front_merge(request_queue_t *q, struct request *rq)
2864 {
2865         struct request *prev = elv_former_request(q, rq);
2866
2867         if (prev)
2868                 return attempt_merge(q, prev, rq);
2869
2870         return 0;
2871 }
2872
2873 static void init_request_from_bio(struct request *req, struct bio *bio)
2874 {
2875         req->cmd_type = REQ_TYPE_FS;
2876
2877         /*
2878          * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
2879          */
2880         if (bio_rw_ahead(bio) || bio_failfast(bio))
2881                 req->cmd_flags |= REQ_FAILFAST;
2882
2883         /*
2884          * REQ_BARRIER implies no merging, but lets make it explicit
2885          */
2886         if (unlikely(bio_barrier(bio)))
2887                 req->cmd_flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
2888
2889         if (bio_sync(bio))
2890                 req->cmd_flags |= REQ_RW_SYNC;
2891         if (bio_rw_meta(bio))
2892                 req->cmd_flags |= REQ_RW_META;
2893
2894         req->errors = 0;
2895         req->hard_sector = req->sector = bio->bi_sector;
2896         req->hard_nr_sectors = req->nr_sectors = bio_sectors(bio);
2897         req->current_nr_sectors = req->hard_cur_sectors = bio_cur_sectors(bio);
2898         req->nr_phys_segments = bio_phys_segments(req->q, bio);
2899         req->nr_hw_segments = bio_hw_segments(req->q, bio);
2900         req->buffer = bio_data(bio);    /* see ->buffer comment above */
2901         req->bio = req->biotail = bio;
2902         req->ioprio = bio_prio(bio);
2903         req->rq_disk = bio->bi_bdev->bd_disk;
2904         req->start_time = jiffies;
2905 }
2906
2907 static int __make_request(request_queue_t *q, struct bio *bio)
2908 {
2909         struct request *req;
2910         int el_ret, nr_sectors, barrier, err;
2911         const unsigned short prio = bio_prio(bio);
2912         const int sync = bio_sync(bio);
2913
2914         nr_sectors = bio_sectors(bio);
2915
2916         /*
2917          * low level driver can indicate that it wants pages above a
2918          * certain limit bounced to low memory (ie for highmem, or even
2919          * ISA dma in theory)
2920          */
2921         blk_queue_bounce(q, &bio);
2922
2923         barrier = bio_barrier(bio);
2924         if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
2925                 err = -EOPNOTSUPP;
2926                 goto end_io;
2927         }
2928
2929         spin_lock_irq(q->queue_lock);
2930
2931         if (unlikely(barrier) || elv_queue_empty(q))
2932                 goto get_rq;
2933
2934         el_ret = elv_merge(q, &req, bio);
2935         switch (el_ret) {
2936                 case ELEVATOR_BACK_MERGE:
2937                         BUG_ON(!rq_mergeable(req));
2938
2939                         if (!q->back_merge_fn(q, req, bio))
2940                                 break;
2941
2942                         blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
2943
2944                         req->biotail->bi_next = bio;
2945                         req->biotail = bio;
2946                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2947                         req->ioprio = ioprio_best(req->ioprio, prio);
2948                         drive_stat_acct(req, nr_sectors, 0);
2949                         if (!attempt_back_merge(q, req))
2950                                 elv_merged_request(q, req, el_ret);
2951                         goto out;
2952
2953                 case ELEVATOR_FRONT_MERGE:
2954                         BUG_ON(!rq_mergeable(req));
2955
2956                         if (!q->front_merge_fn(q, req, bio))
2957                                 break;
2958
2959                         blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
2960
2961                         bio->bi_next = req->bio;
2962                         req->bio = bio;
2963
2964                         /*
2965                          * may not be valid. if the low level driver said
2966                          * it didn't need a bounce buffer then it better
2967                          * not touch req->buffer either...
2968                          */
2969                         req->buffer = bio_data(bio);
2970                         req->current_nr_sectors = bio_cur_sectors(bio);
2971                         req->hard_cur_sectors = req->current_nr_sectors;
2972                         req->sector = req->hard_sector = bio->bi_sector;
2973                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2974                         req->ioprio = ioprio_best(req->ioprio, prio);
2975                         drive_stat_acct(req, nr_sectors, 0);
2976                         if (!attempt_front_merge(q, req))
2977                                 elv_merged_request(q, req, el_ret);
2978                         goto out;
2979
2980                 /* ELV_NO_MERGE: elevator says don't/can't merge. */
2981                 default:
2982                         ;
2983         }
2984
2985 get_rq:
2986         /*
2987          * Grab a free request. This is might sleep but can not fail.
2988          * Returns with the queue unlocked.
2989          */
2990         req = get_request_wait(q, bio_data_dir(bio), bio);
2991
2992         /*
2993          * After dropping the lock and possibly sleeping here, our request
2994          * may now be mergeable after it had proven unmergeable (above).
2995          * We don't worry about that case for efficiency. It won't happen
2996          * often, and the elevators are able to handle it.
2997          */
2998         init_request_from_bio(req, bio);
2999
3000         spin_lock_irq(q->queue_lock);
3001         if (elv_queue_empty(q))
3002                 blk_plug_device(q);
3003         add_request(q, req);
3004 out:
3005         if (sync)
3006                 __generic_unplug_device(q);
3007
3008         spin_unlock_irq(q->queue_lock);
3009         return 0;
3010
3011 end_io:
3012         bio_endio(bio, nr_sectors << 9, err);
3013         return 0;
3014 }
3015
3016 /*
3017  * If bio->bi_dev is a partition, remap the location
3018  */
3019 static inline void blk_partition_remap(struct bio *bio)
3020 {
3021         struct block_device *bdev = bio->bi_bdev;
3022
3023         if (bdev != bdev->bd_contains) {
3024                 struct hd_struct *p = bdev->bd_part;
3025                 const int rw = bio_data_dir(bio);
3026
3027                 p->sectors[rw] += bio_sectors(bio);
3028                 p->ios[rw]++;
3029
3030                 bio->bi_sector += p->start_sect;
3031                 bio->bi_bdev = bdev->bd_contains;
3032         }
3033 }
3034
3035 static void handle_bad_sector(struct bio *bio)
3036 {
3037         char b[BDEVNAME_SIZE];
3038
3039         printk(KERN_INFO "attempt to access beyond end of device\n");
3040         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
3041                         bdevname(bio->bi_bdev, b),
3042                         bio->bi_rw,
3043                         (unsigned long long)bio->bi_sector + bio_sectors(bio),
3044                         (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
3045
3046         set_bit(BIO_EOF, &bio->bi_flags);
3047 }
3048
3049 #ifdef CONFIG_FAIL_MAKE_REQUEST
3050
3051 static DECLARE_FAULT_ATTR(fail_make_request);
3052
3053 static int __init setup_fail_make_request(char *str)
3054 {
3055         return setup_fault_attr(&fail_make_request, str);
3056 }
3057 __setup("fail_make_request=", setup_fail_make_request);
3058
3059 static int should_fail_request(struct bio *bio)
3060 {
3061         if ((bio->bi_bdev->bd_disk->flags & GENHD_FL_FAIL) ||
3062             (bio->bi_bdev->bd_part && bio->bi_bdev->bd_part->make_it_fail))
3063                 return should_fail(&fail_make_request, bio->bi_size);
3064
3065         return 0;
3066 }
3067
3068 static int __init fail_make_request_debugfs(void)
3069 {
3070         return init_fault_attr_dentries(&fail_make_request,
3071                                         "fail_make_request");
3072 }
3073
3074 late_initcall(fail_make_request_debugfs);
3075
3076 #else /* CONFIG_FAIL_MAKE_REQUEST */
3077
3078 static inline int should_fail_request(struct bio *bio)
3079 {
3080         return 0;
3081 }
3082
3083 #endif /* CONFIG_FAIL_MAKE_REQUEST */
3084
3085 /**
3086  * generic_make_request: hand a buffer to its device driver for I/O
3087  * @bio:  The bio describing the location in memory and on the device.
3088  *
3089  * generic_make_request() is used to make I/O requests of block
3090  * devices. It is passed a &struct bio, which describes the I/O that needs
3091  * to be done.
3092  *
3093  * generic_make_request() does not return any status.  The
3094  * success/failure status of the request, along with notification of
3095  * completion, is delivered asynchronously through the bio->bi_end_io
3096  * function described (one day) else where.
3097  *
3098  * The caller of generic_make_request must make sure that bi_io_vec
3099  * are set to describe the memory buffer, and that bi_dev and bi_sector are
3100  * set to describe the device address, and the
3101  * bi_end_io and optionally bi_private are set to describe how
3102  * completion notification should be signaled.
3103  *
3104  * generic_make_request and the drivers it calls may use bi_next if this
3105  * bio happens to be merged with someone else, and may change bi_dev and
3106  * bi_sector for remaps as it sees fit.  So the values of these fields
3107  * should NOT be depended on after the call to generic_make_request.
3108  */
3109 void generic_make_request(struct bio *bio)
3110 {
3111         request_queue_t *q;
3112         sector_t maxsector;
3113         sector_t old_sector;
3114         int ret, nr_sectors = bio_sectors(bio);
3115         dev_t old_dev;
3116
3117         might_sleep();
3118         /* Test device or partition size, when known. */
3119         maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
3120         if (maxsector) {
3121                 sector_t sector = bio->bi_sector;
3122
3123                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
3124                         /*
3125                          * This may well happen - the kernel calls bread()
3126                          * without checking the size of the device, e.g., when
3127                          * mounting a device.
3128                          */
3129                         handle_bad_sector(bio);
3130                         goto end_io;
3131                 }
3132         }
3133
3134         /*
3135          * Resolve the mapping until finished. (drivers are
3136          * still free to implement/resolve their own stacking
3137          * by explicitly returning 0)
3138          *
3139          * NOTE: we don't repeat the blk_size check for each new device.
3140          * Stacking drivers are expected to know what they are doing.
3141          */
3142         old_sector = -1;
3143         old_dev = 0;
3144         do {
3145                 char b[BDEVNAME_SIZE];
3146
3147                 q = bdev_get_queue(bio->bi_bdev);
3148                 if (!q) {
3149                         printk(KERN_ERR
3150                                "generic_make_request: Trying to access "
3151                                 "nonexistent block-device %s (%Lu)\n",
3152                                 bdevname(bio->bi_bdev, b),
3153                                 (long long) bio->bi_sector);
3154 end_io:
3155                         bio_endio(bio, bio->bi_size, -EIO);
3156                         break;
3157                 }
3158
3159                 if (unlikely(bio_sectors(bio) > q->max_hw_sectors)) {
3160                         printk("bio too big device %s (%u > %u)\n", 
3161                                 bdevname(bio->bi_bdev, b),
3162                                 bio_sectors(bio),
3163                                 q->max_hw_sectors);
3164                         goto end_io;
3165                 }
3166
3167                 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
3168                         goto end_io;
3169
3170                 if (should_fail_request(bio))
3171                         goto end_io;
3172
3173                 /*
3174                  * If this device has partitions, remap block n
3175                  * of partition p to block n+start(p) of the disk.
3176                  */
3177                 blk_partition_remap(bio);
3178
3179                 if (old_sector != -1)
3180                         blk_add_trace_remap(q, bio, old_dev, bio->bi_sector, 
3181                                             old_sector);
3182
3183                 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
3184
3185                 old_sector = bio->bi_sector;
3186                 old_dev = bio->bi_bdev->bd_dev;
3187
3188                 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
3189                 if (maxsector) {
3190                         sector_t sector = bio->bi_sector;
3191
3192                         if (maxsector < nr_sectors ||
3193                                         maxsector - nr_sectors < sector) {
3194                                 /*
3195                                  * This may well happen - partitions are not
3196                                  * checked to make sure they are within the size
3197                                  * of the whole device.
3198                                  */
3199                                 handle_bad_sector(bio);
3200                                 goto end_io;
3201                         }
3202                 }
3203
3204                 ret = q->make_request_fn(q, bio);
3205         } while (ret);
3206 }
3207
3208 EXPORT_SYMBOL(generic_make_request);
3209
3210 /**
3211  * submit_bio: submit a bio to the block device layer for I/O
3212  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
3213  * @bio: The &struct bio which describes the I/O
3214  *
3215  * submit_bio() is very similar in purpose to generic_make_request(), and
3216  * uses that function to do most of the work. Both are fairly rough
3217  * interfaces, @bio must be presetup and ready for I/O.
3218  *
3219  */
3220 void submit_bio(int rw, struct bio *bio)
3221 {
3222         int count = bio_sectors(bio);
3223
3224         BIO_BUG_ON(!bio->bi_size);
3225         BIO_BUG_ON(!bio->bi_io_vec);
3226         bio->bi_rw |= rw;
3227         if (rw & WRITE) {
3228                 count_vm_events(PGPGOUT, count);
3229         } else {
3230                 task_io_account_read(bio->bi_size);
3231                 count_vm_events(PGPGIN, count);
3232         }
3233
3234         if (unlikely(block_dump)) {
3235                 char b[BDEVNAME_SIZE];
3236                 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
3237                         current->comm, current->pid,
3238                         (rw & WRITE) ? "WRITE" : "READ",
3239                         (unsigned long long)bio->bi_sector,
3240                         bdevname(bio->bi_bdev,b));
3241         }
3242
3243         generic_make_request(bio);
3244 }
3245
3246 EXPORT_SYMBOL(submit_bio);
3247
3248 static void blk_recalc_rq_segments(struct request *rq)
3249 {
3250         struct bio *bio, *prevbio = NULL;
3251         int nr_phys_segs, nr_hw_segs;
3252         unsigned int phys_size, hw_size;
3253         request_queue_t *q = rq->q;
3254
3255         if (!rq->bio)
3256                 return;
3257
3258         phys_size = hw_size = nr_phys_segs = nr_hw_segs = 0;
3259         rq_for_each_bio(bio, rq) {
3260                 /* Force bio hw/phys segs to be recalculated. */
3261                 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
3262
3263                 nr_phys_segs += bio_phys_segments(q, bio);
3264                 nr_hw_segs += bio_hw_segments(q, bio);
3265                 if (prevbio) {
3266                         int pseg = phys_size + prevbio->bi_size + bio->bi_size;
3267                         int hseg = hw_size + prevbio->bi_size + bio->bi_size;
3268
3269                         if (blk_phys_contig_segment(q, prevbio, bio) &&
3270                             pseg <= q->max_segment_size) {
3271                                 nr_phys_segs--;
3272                                 phys_size += prevbio->bi_size + bio->bi_size;
3273                         } else
3274                                 phys_size = 0;
3275
3276                         if (blk_hw_contig_segment(q, prevbio, bio) &&
3277                             hseg <= q->max_segment_size) {
3278                                 nr_hw_segs--;
3279                                 hw_size += prevbio->bi_size + bio->bi_size;
3280                         } else
3281                                 hw_size = 0;
3282                 }
3283                 prevbio = bio;
3284         }
3285
3286         rq->nr_phys_segments = nr_phys_segs;
3287         rq->nr_hw_segments = nr_hw_segs;
3288 }
3289
3290 static void blk_recalc_rq_sectors(struct request *rq, int nsect)
3291 {
3292         if (blk_fs_request(rq)) {
3293                 rq->hard_sector += nsect;
3294                 rq->hard_nr_sectors -= nsect;
3295
3296                 /*
3297                  * Move the I/O submission pointers ahead if required.
3298                  */
3299                 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
3300                     (rq->sector <= rq->hard_sector)) {
3301                         rq->sector = rq->hard_sector;
3302                         rq->nr_sectors = rq->hard_nr_sectors;
3303                         rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
3304                         rq->current_nr_sectors = rq->hard_cur_sectors;
3305                         rq->buffer = bio_data(rq->bio);
3306                 }
3307
3308                 /*
3309                  * if total number of sectors is less than the first segment
3310                  * size, something has gone terribly wrong
3311                  */
3312                 if (rq->nr_sectors < rq->current_nr_sectors) {
3313                         printk("blk: request botched\n");
3314                         rq->nr_sectors = rq->current_nr_sectors;
3315                 }
3316         }
3317 }
3318
3319 static int __end_that_request_first(struct request *req, int uptodate,
3320                                     int nr_bytes)
3321 {
3322         int total_bytes, bio_nbytes, error, next_idx = 0;
3323         struct bio *bio;
3324
3325         blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
3326
3327         /*
3328          * extend uptodate bool to allow < 0 value to be direct io error
3329          */
3330         error = 0;
3331         if (end_io_error(uptodate))
3332                 error = !uptodate ? -EIO : uptodate;
3333
3334         /*
3335          * for a REQ_BLOCK_PC request, we want to carry any eventual
3336          * sense key with us all the way through
3337          */
3338         if (!blk_pc_request(req))
3339                 req->errors = 0;
3340
3341         if (!uptodate) {
3342                 if (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))
3343                         printk("end_request: I/O error, dev %s, sector %llu\n",
3344                                 req->rq_disk ? req->rq_disk->disk_name : "?",
3345                                 (unsigned long long)req->sector);
3346         }
3347
3348         if (blk_fs_request(req) && req->rq_disk) {
3349                 const int rw = rq_data_dir(req);
3350
3351                 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
3352         }
3353
3354         total_bytes = bio_nbytes = 0;
3355         while ((bio = req->bio) != NULL) {
3356                 int nbytes;
3357
3358                 if (nr_bytes >= bio->bi_size) {
3359                         req->bio = bio->bi_next;
3360                         nbytes = bio->bi_size;
3361                         if (!ordered_bio_endio(req, bio, nbytes, error))
3362                                 bio_endio(bio, nbytes, error);
3363                         next_idx = 0;
3364                         bio_nbytes = 0;
3365                 } else {
3366                         int idx = bio->bi_idx + next_idx;
3367
3368                         if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
3369                                 blk_dump_rq_flags(req, "__end_that");
3370                                 printk("%s: bio idx %d >= vcnt %d\n",
3371                                                 __FUNCTION__,
3372                                                 bio->bi_idx, bio->bi_vcnt);
3373                                 break;
3374                         }
3375
3376                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
3377                         BIO_BUG_ON(nbytes > bio->bi_size);
3378
3379                         /*
3380                          * not a complete bvec done
3381                          */
3382                         if (unlikely(nbytes > nr_bytes)) {
3383                                 bio_nbytes += nr_bytes;
3384                                 total_bytes += nr_bytes;
3385                                 break;
3386                         }
3387
3388                         /*
3389                          * advance to the next vector
3390                          */
3391                         next_idx++;
3392                         bio_nbytes += nbytes;
3393                 }
3394
3395                 total_bytes += nbytes;
3396                 nr_bytes -= nbytes;
3397
3398                 if ((bio = req->bio)) {
3399                         /*
3400                          * end more in this run, or just return 'not-done'
3401                          */
3402                         if (unlikely(nr_bytes <= 0))
3403                                 break;
3404                 }
3405         }
3406
3407         /*
3408          * completely done
3409          */
3410         if (!req->bio)
3411                 return 0;
3412
3413         /*
3414          * if the request wasn't completed, update state
3415          */
3416         if (bio_nbytes) {
3417                 if (!ordered_bio_endio(req, bio, bio_nbytes, error))
3418                         bio_endio(bio, bio_nbytes, error);
3419                 bio->bi_idx += next_idx;
3420                 bio_iovec(bio)->bv_offset += nr_bytes;
3421                 bio_iovec(bio)->bv_len -= nr_bytes;
3422         }
3423
3424         blk_recalc_rq_sectors(req, total_bytes >> 9);
3425         blk_recalc_rq_segments(req);
3426         return 1;
3427 }
3428
3429 /**
3430  * end_that_request_first - end I/O on a request
3431  * @req:      the request being processed
3432  * @uptodate: 1 for success, 0 for I/O error, < 0 for specific error
3433  * @nr_sectors: number of sectors to end I/O on
3434  *
3435  * Description:
3436  *     Ends I/O on a number of sectors attached to @req, and sets it up
3437  *     for the next range of segments (if any) in the cluster.
3438  *
3439  * Return:
3440  *     0 - we are done with this request, call end_that_request_last()
3441  *     1 - still buffers pending for this request
3442  **/
3443 int end_that_request_first(struct request *req, int uptodate, int nr_sectors)
3444 {
3445         return __end_that_request_first(req, uptodate, nr_sectors << 9);
3446 }
3447
3448 EXPORT_SYMBOL(end_that_request_first);
3449
3450 /**
3451  * end_that_request_chunk - end I/O on a request
3452  * @req:      the request being processed
3453  * @uptodate: 1 for success, 0 for I/O error, < 0 for specific error
3454  * @nr_bytes: number of bytes to complete
3455  *
3456  * Description:
3457  *     Ends I/O on a number of bytes attached to @req, and sets it up
3458  *     for the next range of segments (if any). Like end_that_request_first(),
3459  *     but deals with bytes instead of sectors.
3460  *
3461  * Return:
3462  *     0 - we are done with this request, call end_that_request_last()
3463  *     1 - still buffers pending for this request
3464  **/
3465 int end_that_request_chunk(struct request *req, int uptodate, int nr_bytes)
3466 {
3467         return __end_that_request_first(req, uptodate, nr_bytes);
3468 }
3469
3470 EXPORT_SYMBOL(end_that_request_chunk);
3471
3472 /*
3473  * splice the completion data to a local structure and hand off to
3474  * process_completion_queue() to complete the requests
3475  */
3476 static void blk_done_softirq(struct softirq_action *h)
3477 {
3478         struct list_head *cpu_list, local_list;
3479
3480         local_irq_disable();
3481         cpu_list = &__get_cpu_var(blk_cpu_done);
3482         list_replace_init(cpu_list, &local_list);
3483         local_irq_enable();
3484
3485         while (!list_empty(&local_list)) {
3486                 struct request *rq = list_entry(local_list.next, struct request, donelist);
3487
3488                 list_del_init(&rq->donelist);
3489                 rq->q->softirq_done_fn(rq);
3490         }
3491 }
3492
3493 static int blk_cpu_notify(struct notifier_block *self, unsigned long action,
3494                           void *hcpu)
3495 {
3496         /*
3497          * If a CPU goes away, splice its entries to the current CPU
3498          * and trigger a run of the softirq
3499          */
3500         if (action == CPU_DEAD) {
3501                 int cpu = (unsigned long) hcpu;
3502
3503                 local_irq_disable();
3504                 list_splice_init(&per_cpu(blk_cpu_done, cpu),
3505                                  &__get_cpu_var(blk_cpu_done));
3506                 raise_softirq_irqoff(BLOCK_SOFTIRQ);
3507                 local_irq_enable();
3508         }
3509
3510         return NOTIFY_OK;
3511 }
3512
3513
3514 static struct notifier_block __devinitdata blk_cpu_notifier = {
3515         .notifier_call  = blk_cpu_notify,
3516 };
3517
3518 /**
3519  * blk_complete_request - end I/O on a request
3520  * @req:      the request being processed
3521  *
3522  * Description:
3523  *     Ends all I/O on a request. It does not handle partial completions,
3524  *     unless the driver actually implements this in its completion callback
3525  *     through requeueing. Theh actual completion happens out-of-order,
3526  *     through a softirq handler. The user must have registered a completion
3527  *     callback through blk_queue_softirq_done().
3528  **/
3529
3530 void blk_complete_request(struct request *req)
3531 {
3532         struct list_head *cpu_list;
3533         unsigned long flags;
3534
3535         BUG_ON(!req->q->softirq_done_fn);
3536                 
3537         local_irq_save(flags);
3538
3539         cpu_list = &__get_cpu_var(blk_cpu_done);
3540         list_add_tail(&req->donelist, cpu_list);
3541         raise_softirq_irqoff(BLOCK_SOFTIRQ);
3542
3543         local_irq_restore(flags);
3544 }
3545
3546 EXPORT_SYMBOL(blk_complete_request);
3547         
3548 /*
3549  * queue lock must be held
3550  */
3551 void end_that_request_last(struct request *req, int uptodate)
3552 {
3553         struct gendisk *disk = req->rq_disk;
3554         int error;
3555
3556         /*
3557          * extend uptodate bool to allow < 0 value to be direct io error
3558          */
3559         error = 0;
3560         if (end_io_error(uptodate))
3561                 error = !uptodate ? -EIO : uptodate;
3562
3563         if (unlikely(laptop_mode) && blk_fs_request(req))
3564                 laptop_io_completion();
3565
3566         /*
3567          * Account IO completion.  bar_rq isn't accounted as a normal
3568          * IO on queueing nor completion.  Accounting the containing
3569          * request is enough.
3570          */
3571         if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
3572                 unsigned long duration = jiffies - req->start_time;
3573                 const int rw = rq_data_dir(req);
3574
3575                 __disk_stat_inc(disk, ios[rw]);
3576                 __disk_stat_add(disk, ticks[rw], duration);
3577                 disk_round_stats(disk);
3578                 disk->in_flight--;
3579         }
3580         if (req->end_io)
3581                 req->end_io(req, error);
3582         else
3583                 __blk_put_request(req->q, req);
3584 }
3585
3586 EXPORT_SYMBOL(end_that_request_last);
3587
3588 void end_request(struct request *req, int uptodate)
3589 {
3590         if (!end_that_request_first(req, uptodate, req->hard_cur_sectors)) {
3591                 add_disk_randomness(req->rq_disk);
3592                 blkdev_dequeue_request(req);
3593                 end_that_request_last(req, uptodate);
3594         }
3595 }
3596
3597 EXPORT_SYMBOL(end_request);
3598
3599 void blk_rq_bio_prep(request_queue_t *q, struct request *rq, struct bio *bio)
3600 {
3601         /* first two bits are identical in rq->cmd_flags and bio->bi_rw */
3602         rq->cmd_flags |= (bio->bi_rw & 3);
3603
3604         rq->nr_phys_segments = bio_phys_segments(q, bio);
3605         rq->nr_hw_segments = bio_hw_segments(q, bio);
3606         rq->current_nr_sectors = bio_cur_sectors(bio);
3607         rq->hard_cur_sectors = rq->current_nr_sectors;
3608         rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
3609         rq->buffer = bio_data(bio);
3610         rq->data_len = bio->bi_size;
3611
3612         rq->bio = rq->biotail = bio;
3613 }
3614
3615 EXPORT_SYMBOL(blk_rq_bio_prep);
3616
3617 int kblockd_schedule_work(struct work_struct *work)
3618 {
3619         return queue_work(kblockd_workqueue, work);
3620 }
3621
3622 EXPORT_SYMBOL(kblockd_schedule_work);
3623
3624 void kblockd_flush(void)
3625 {
3626         flush_workqueue(kblockd_workqueue);
3627 }
3628 EXPORT_SYMBOL(kblockd_flush);
3629
3630 int __init blk_dev_init(void)
3631 {
3632         int i;
3633
3634         kblockd_workqueue = create_workqueue("kblockd");
3635         if (!kblockd_workqueue)
3636                 panic("Failed to create kblockd\n");
3637
3638         request_cachep = kmem_cache_create("blkdev_requests",
3639                         sizeof(struct request), 0, SLAB_PANIC, NULL, NULL);
3640
3641         requestq_cachep = kmem_cache_create("blkdev_queue",
3642                         sizeof(request_queue_t), 0, SLAB_PANIC, NULL, NULL);
3643
3644         iocontext_cachep = kmem_cache_create("blkdev_ioc",
3645                         sizeof(struct io_context), 0, SLAB_PANIC, NULL, NULL);
3646
3647         for_each_possible_cpu(i)
3648                 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
3649
3650         open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
3651         register_hotcpu_notifier(&blk_cpu_notifier);
3652
3653         blk_max_low_pfn = max_low_pfn;
3654         blk_max_pfn = max_pfn;
3655
3656         return 0;
3657 }
3658
3659 /*
3660  * IO Context helper functions
3661  */
3662 void put_io_context(struct io_context *ioc)
3663 {
3664         if (ioc == NULL)
3665                 return;
3666
3667         BUG_ON(atomic_read(&ioc->refcount) == 0);
3668
3669         if (atomic_dec_and_test(&ioc->refcount)) {
3670                 struct cfq_io_context *cic;
3671
3672                 rcu_read_lock();
3673                 if (ioc->aic && ioc->aic->dtor)
3674                         ioc->aic->dtor(ioc->aic);
3675                 if (ioc->cic_root.rb_node != NULL) {
3676                         struct rb_node *n = rb_first(&ioc->cic_root);
3677
3678                         cic = rb_entry(n, struct cfq_io_context, rb_node);
3679                         cic->dtor(ioc);
3680                 }
3681                 rcu_read_unlock();
3682
3683                 kmem_cache_free(iocontext_cachep, ioc);
3684         }
3685 }
3686 EXPORT_SYMBOL(put_io_context);
3687
3688 /* Called by the exitting task */
3689 void exit_io_context(void)
3690 {
3691         struct io_context *ioc;
3692         struct cfq_io_context *cic;
3693
3694         task_lock(current);
3695         ioc = current->io_context;
3696         current->io_context = NULL;
3697         task_unlock(current);
3698
3699         ioc->task = NULL;
3700         if (ioc->aic && ioc->aic->exit)
3701                 ioc->aic->exit(ioc->aic);
3702         if (ioc->cic_root.rb_node != NULL) {
3703                 cic = rb_entry(rb_first(&ioc->cic_root), struct cfq_io_context, rb_node);
3704                 cic->exit(ioc);
3705         }
3706
3707         put_io_context(ioc);
3708 }
3709
3710 /*
3711  * If the current task has no IO context then create one and initialise it.
3712  * Otherwise, return its existing IO context.
3713  *
3714  * This returned IO context doesn't have a specifically elevated refcount,
3715  * but since the current task itself holds a reference, the context can be
3716  * used in general code, so long as it stays within `current` context.
3717  */
3718 static struct io_context *current_io_context(gfp_t gfp_flags, int node)
3719 {
3720         struct task_struct *tsk = current;
3721         struct io_context *ret;
3722
3723         ret = tsk->io_context;
3724         if (likely(ret))
3725                 return ret;
3726
3727         ret = kmem_cache_alloc_node(iocontext_cachep, gfp_flags, node);
3728         if (ret) {
3729                 atomic_set(&ret->refcount, 1);
3730                 ret->task = current;
3731                 ret->ioprio_changed = 0;
3732                 ret->last_waited = jiffies; /* doesn't matter... */
3733                 ret->nr_batch_requests = 0; /* because this is 0 */
3734                 ret->aic = NULL;
3735                 ret->cic_root.rb_node = NULL;
3736                 /* make sure set_task_ioprio() sees the settings above */
3737                 smp_wmb();
3738                 tsk->io_context = ret;
3739         }
3740
3741         return ret;
3742 }
3743 EXPORT_SYMBOL(current_io_context);
3744
3745 /*
3746  * If the current task has no IO context then create one and initialise it.
3747  * If it does have a context, take a ref on it.
3748  *
3749  * This is always called in the context of the task which submitted the I/O.
3750  */
3751 struct io_context *get_io_context(gfp_t gfp_flags, int node)
3752 {
3753         struct io_context *ret;
3754         ret = current_io_context(gfp_flags, node);
3755         if (likely(ret))
3756                 atomic_inc(&ret->refcount);
3757         return ret;
3758 }
3759 EXPORT_SYMBOL(get_io_context);
3760
3761 void copy_io_context(struct io_context **pdst, struct io_context **psrc)
3762 {
3763         struct io_context *src = *psrc;
3764         struct io_context *dst = *pdst;
3765
3766         if (src) {
3767                 BUG_ON(atomic_read(&src->refcount) == 0);
3768                 atomic_inc(&src->refcount);
3769                 put_io_context(dst);
3770                 *pdst = src;
3771         }
3772 }
3773 EXPORT_SYMBOL(copy_io_context);
3774
3775 void swap_io_context(struct io_context **ioc1, struct io_context **ioc2)
3776 {
3777         struct io_context *temp;
3778         temp = *ioc1;
3779         *ioc1 = *ioc2;
3780         *ioc2 = temp;
3781 }
3782 EXPORT_SYMBOL(swap_io_context);
3783
3784 /*
3785  * sysfs parts below
3786  */
3787 struct queue_sysfs_entry {
3788         struct attribute attr;
3789         ssize_t (*show)(struct request_queue *, char *);
3790         ssize_t (*store)(struct request_queue *, const char *, size_t);
3791 };
3792
3793 static ssize_t
3794 queue_var_show(unsigned int var, char *page)
3795 {
3796         return sprintf(page, "%d\n", var);
3797 }
3798
3799 static ssize_t
3800 queue_var_store(unsigned long *var, const char *page, size_t count)
3801 {
3802         char *p = (char *) page;
3803
3804         *var = simple_strtoul(p, &p, 10);
3805         return count;
3806 }
3807
3808 static ssize_t queue_requests_show(struct request_queue *q, char *page)
3809 {
3810         return queue_var_show(q->nr_requests, (page));
3811 }
3812
3813 static ssize_t
3814 queue_requests_store(struct request_queue *q, const char *page, size_t count)
3815 {
3816         struct request_list *rl = &q->rq;
3817         unsigned long nr;
3818         int ret = queue_var_store(&nr, page, count);
3819         if (nr < BLKDEV_MIN_RQ)
3820                 nr = BLKDEV_MIN_RQ;
3821
3822         spin_lock_irq(q->queue_lock);
3823         q->nr_requests = nr;
3824         blk_queue_congestion_threshold(q);
3825
3826         if (rl->count[READ] >= queue_congestion_on_threshold(q))
3827                 blk_set_queue_congested(q, READ);
3828         else if (rl->count[READ] < queue_congestion_off_threshold(q))
3829                 blk_clear_queue_congested(q, READ);
3830
3831         if (rl->count[WRITE] >= queue_congestion_on_threshold(q))
3832                 blk_set_queue_congested(q, WRITE);
3833         else if (rl->count[WRITE] < queue_congestion_off_threshold(q))
3834                 blk_clear_queue_congested(q, WRITE);
3835
3836         if (rl->count[READ] >= q->nr_requests) {
3837                 blk_set_queue_full(q, READ);
3838         } else if (rl->count[READ]+1 <= q->nr_requests) {
3839                 blk_clear_queue_full(q, READ);
3840                 wake_up(&rl->wait[READ]);
3841         }
3842
3843         if (rl->count[WRITE] >= q->nr_requests) {
3844                 blk_set_queue_full(q, WRITE);
3845         } else if (rl->count[WRITE]+1 <= q->nr_requests) {
3846                 blk_clear_queue_full(q, WRITE);
3847                 wake_up(&rl->wait[WRITE]);
3848         }
3849         spin_unlock_irq(q->queue_lock);
3850         return ret;
3851 }
3852
3853 static ssize_t queue_ra_show(struct request_queue *q, char *page)
3854 {
3855         int ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3856
3857         return queue_var_show(ra_kb, (page));
3858 }
3859
3860 static ssize_t
3861 queue_ra_store(struct request_queue *q, const char *page, size_t count)
3862 {
3863         unsigned long ra_kb;
3864         ssize_t ret = queue_var_store(&ra_kb, page, count);
3865
3866         spin_lock_irq(q->queue_lock);
3867         q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10);
3868         spin_unlock_irq(q->queue_lock);
3869
3870         return ret;
3871 }
3872
3873 static ssize_t queue_max_sectors_show(struct request_queue *q, char *page)
3874 {
3875         int max_sectors_kb = q->max_sectors >> 1;
3876
3877         return queue_var_show(max_sectors_kb, (page));
3878 }
3879
3880 static ssize_t
3881 queue_max_sectors_store(struct request_queue *q, const char *page, size_t count)
3882 {
3883         unsigned long max_sectors_kb,
3884                         max_hw_sectors_kb = q->max_hw_sectors >> 1,
3885                         page_kb = 1 << (PAGE_CACHE_SHIFT - 10);
3886         ssize_t ret = queue_var_store(&max_sectors_kb, page, count);
3887         int ra_kb;
3888
3889         if (max_sectors_kb > max_hw_sectors_kb || max_sectors_kb < page_kb)
3890                 return -EINVAL;
3891         /*
3892          * Take the queue lock to update the readahead and max_sectors
3893          * values synchronously:
3894          */
3895         spin_lock_irq(q->queue_lock);
3896         /*
3897          * Trim readahead window as well, if necessary:
3898          */
3899         ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3900         if (ra_kb > max_sectors_kb)
3901                 q->backing_dev_info.ra_pages =
3902                                 max_sectors_kb >> (PAGE_CACHE_SHIFT - 10);
3903
3904         q->max_sectors = max_sectors_kb << 1;
3905         spin_unlock_irq(q->queue_lock);
3906
3907         return ret;
3908 }
3909
3910 static ssize_t queue_max_hw_sectors_show(struct request_queue *q, char *page)
3911 {
3912         int max_hw_sectors_kb = q->max_hw_sectors >> 1;
3913
3914         return queue_var_show(max_hw_sectors_kb, (page));
3915 }
3916
3917
3918 static struct queue_sysfs_entry queue_requests_entry = {
3919         .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR },
3920         .show = queue_requests_show,
3921         .store = queue_requests_store,
3922 };
3923
3924 static struct queue_sysfs_entry queue_ra_entry = {
3925         .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR },
3926         .show = queue_ra_show,
3927         .store = queue_ra_store,
3928 };
3929
3930 static struct queue_sysfs_entry queue_max_sectors_entry = {
3931         .attr = {.name = "max_sectors_kb", .mode = S_IRUGO | S_IWUSR },
3932         .show = queue_max_sectors_show,
3933         .store = queue_max_sectors_store,
3934 };
3935
3936 static struct queue_sysfs_entry queue_max_hw_sectors_entry = {
3937         .attr = {.name = "max_hw_sectors_kb", .mode = S_IRUGO },
3938         .show = queue_max_hw_sectors_show,
3939 };
3940
3941 static struct queue_sysfs_entry queue_iosched_entry = {
3942         .attr = {.name = "scheduler", .mode = S_IRUGO | S_IWUSR },
3943         .show = elv_iosched_show,
3944         .store = elv_iosched_store,
3945 };
3946
3947 static struct attribute *default_attrs[] = {
3948         &queue_requests_entry.attr,
3949         &queue_ra_entry.attr,
3950         &queue_max_hw_sectors_entry.attr,
3951         &queue_max_sectors_entry.attr,
3952         &queue_iosched_entry.attr,
3953         NULL,
3954 };
3955
3956 #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr)
3957
3958 static ssize_t
3959 queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3960 {
3961         struct queue_sysfs_entry *entry = to_queue(attr);
3962         request_queue_t *q = container_of(kobj, struct request_queue, kobj);
3963         ssize_t res;
3964
3965         if (!entry->show)
3966                 return -EIO;
3967         mutex_lock(&q->sysfs_lock);
3968         if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
3969                 mutex_unlock(&q->sysfs_lock);
3970                 return -ENOENT;
3971         }
3972         res = entry->show(q, page);
3973         mutex_unlock(&q->sysfs_lock);
3974         return res;
3975 }
3976
3977 static ssize_t
3978 queue_attr_store(struct kobject *kobj, struct attribute *attr,
3979                     const char *page, size_t length)
3980 {
3981         struct queue_sysfs_entry *entry = to_queue(attr);
3982         request_queue_t *q = container_of(kobj, struct request_queue, kobj);
3983
3984         ssize_t res;
3985
3986         if (!entry->store)
3987                 return -EIO;
3988         mutex_lock(&q->sysfs_lock);
3989         if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
3990                 mutex_unlock(&q->sysfs_lock);
3991                 return -ENOENT;
3992         }
3993         res = entry->store(q, page, length);
3994         mutex_unlock(&q->sysfs_lock);
3995         return res;
3996 }
3997
3998 static struct sysfs_ops queue_sysfs_ops = {
3999         .show   = queue_attr_show,
4000         .store  = queue_attr_store,
4001 };
4002
4003 static struct kobj_type queue_ktype = {
4004         .sysfs_ops      = &queue_sysfs_ops,
4005         .default_attrs  = default_attrs,
4006         .release        = blk_release_queue,
4007 };
4008
4009 int blk_register_queue(struct gendisk *disk)
4010 {
4011         int ret;
4012
4013         request_queue_t *q = disk->queue;
4014
4015         if (!q || !q->request_fn)
4016                 return -ENXIO;
4017
4018         q->kobj.parent = kobject_get(&disk->kobj);
4019
4020         ret = kobject_add(&q->kobj);
4021         if (ret < 0)
4022                 return ret;
4023
4024         kobject_uevent(&q->kobj, KOBJ_ADD);
4025
4026         ret = elv_register_queue(q);
4027         if (ret) {
4028                 kobject_uevent(&q->kobj, KOBJ_REMOVE);
4029                 kobject_del(&q->kobj);
4030                 return ret;
4031         }
4032
4033         return 0;
4034 }
4035
4036 void blk_unregister_queue(struct gendisk *disk)
4037 {
4038         request_queue_t *q = disk->queue;
4039
4040         if (q && q->request_fn) {
4041                 elv_unregister_queue(q);
4042
4043                 kobject_uevent(&q->kobj, KOBJ_REMOVE);
4044                 kobject_del(&q->kobj);
4045                 kobject_put(&disk->kobj);
4046         }
4047 }