This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / drivers / block / ll_rw_blk.c
1 /*
2  *  linux/drivers/block/ll_rw_blk.c
3  *
4  * Copyright (C) 1991, 1992 Linus Torvalds
5  * Copyright (C) 1994,      Karl Keyte: Added support for disk statistics
6  * Elevator latency, (C) 2000  Andrea Arcangeli <andrea@suse.de> SuSE
7  * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
8  * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au> -  July2000
9  * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
10  */
11
12 /*
13  * This handles all read/write requests to block devices
14  */
15 #include <linux/config.h>
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/backing-dev.h>
19 #include <linux/bio.h>
20 #include <linux/blkdev.h>
21 #include <linux/highmem.h>
22 #include <linux/mm.h>
23 #include <linux/kernel_stat.h>
24 #include <linux/string.h>
25 #include <linux/init.h>
26 #include <linux/bootmem.h>      /* for max_pfn/max_low_pfn */
27 #include <linux/completion.h>
28 #include <linux/slab.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31
32 /*
33  * for max sense size
34  */
35 #include <scsi/scsi_cmnd.h>
36
37 static void blk_unplug_work(void *data);
38 static void blk_unplug_timeout(unsigned long data);
39
40 /*
41  * For the allocated request tables
42  */
43 static kmem_cache_t *request_cachep;
44
45 /*
46  * For queue allocation
47  */
48 static kmem_cache_t *requestq_cachep;
49
50 /*
51  * For io context allocations
52  */
53 static kmem_cache_t *iocontext_cachep;
54
55 static wait_queue_head_t congestion_wqh[2] = {
56                 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[0]),
57                 __WAIT_QUEUE_HEAD_INITIALIZER(congestion_wqh[1])
58         };
59
60 /*
61  * Controlling structure to kblockd
62  */
63 static struct workqueue_struct *kblockd_workqueue; 
64
65 unsigned long blk_max_low_pfn, blk_max_pfn;
66
67 EXPORT_SYMBOL(blk_max_low_pfn);
68 EXPORT_SYMBOL(blk_max_pfn);
69
70 /* Amount of time in which a process may batch requests */
71 #define BLK_BATCH_TIME  (HZ/50UL)
72
73 /* Number of requests a "batching" process may submit */
74 #define BLK_BATCH_REQ   32
75
76 /*
77  * Return the threshold (number of used requests) at which the queue is
78  * considered to be congested.  It include a little hysteresis to keep the
79  * context switch rate down.
80  */
81 static inline int queue_congestion_on_threshold(struct request_queue *q)
82 {
83         return q->nr_congestion_on;
84 }
85
86 /*
87  * The threshold at which a queue is considered to be uncongested
88  */
89 static inline int queue_congestion_off_threshold(struct request_queue *q)
90 {
91         return q->nr_congestion_off;
92 }
93
94 static void blk_queue_congestion_threshold(struct request_queue *q)
95 {
96         int nr;
97
98         nr = q->nr_requests - (q->nr_requests / 8) + 1;
99         if (nr > q->nr_requests)
100                 nr = q->nr_requests;
101         q->nr_congestion_on = nr;
102
103         nr = q->nr_requests - (q->nr_requests / 8) - 1;
104         if (nr < 1)
105                 nr = 1;
106         q->nr_congestion_off = nr;
107 }
108
109 /*
110  * A queue has just exitted congestion.  Note this in the global counter of
111  * congested queues, and wake up anyone who was waiting for requests to be
112  * put back.
113  */
114 static void clear_queue_congested(request_queue_t *q, int rw)
115 {
116         enum bdi_state bit;
117         wait_queue_head_t *wqh = &congestion_wqh[rw];
118
119         bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
120         clear_bit(bit, &q->backing_dev_info.state);
121         smp_mb__after_clear_bit();
122         if (waitqueue_active(wqh))
123                 wake_up(wqh);
124 }
125
126 /*
127  * A queue has just entered congestion.  Flag that in the queue's VM-visible
128  * state flags and increment the global gounter of congested queues.
129  */
130 static void set_queue_congested(request_queue_t *q, int rw)
131 {
132         enum bdi_state bit;
133
134         bit = (rw == WRITE) ? BDI_write_congested : BDI_read_congested;
135         set_bit(bit, &q->backing_dev_info.state);
136 }
137
138 /**
139  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
140  * @bdev:       device
141  *
142  * Locates the passed device's request queue and returns the address of its
143  * backing_dev_info
144  *
145  * Will return NULL if the request queue cannot be located.
146  */
147 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
148 {
149         struct backing_dev_info *ret = NULL;
150         request_queue_t *q = bdev_get_queue(bdev);
151
152         if (q)
153                 ret = &q->backing_dev_info;
154         return ret;
155 }
156
157 void blk_queue_activity_fn(request_queue_t *q, activity_fn *fn, void *data)
158 {
159         q->activity_fn = fn;
160         q->activity_data = data;
161 }
162
163 EXPORT_SYMBOL(blk_queue_activity_fn);
164
165 /**
166  * blk_queue_prep_rq - set a prepare_request function for queue
167  * @q:          queue
168  * @pfn:        prepare_request function
169  *
170  * It's possible for a queue to register a prepare_request callback which
171  * is invoked before the request is handed to the request_fn. The goal of
172  * the function is to prepare a request for I/O, it can be used to build a
173  * cdb from the request data for instance.
174  *
175  */
176 void blk_queue_prep_rq(request_queue_t *q, prep_rq_fn *pfn)
177 {
178         q->prep_rq_fn = pfn;
179 }
180
181 EXPORT_SYMBOL(blk_queue_prep_rq);
182
183 /**
184  * blk_queue_merge_bvec - set a merge_bvec function for queue
185  * @q:          queue
186  * @mbfn:       merge_bvec_fn
187  *
188  * Usually queues have static limitations on the max sectors or segments that
189  * we can put in a request. Stacking drivers may have some settings that
190  * are dynamic, and thus we have to query the queue whether it is ok to
191  * add a new bio_vec to a bio at a given offset or not. If the block device
192  * has such limitations, it needs to register a merge_bvec_fn to control
193  * the size of bio's sent to it. Note that a block device *must* allow a
194  * single page to be added to an empty bio. The block device driver may want
195  * to use the bio_split() function to deal with these bio's. By default
196  * no merge_bvec_fn is defined for a queue, and only the fixed limits are
197  * honored.
198  */
199 void blk_queue_merge_bvec(request_queue_t *q, merge_bvec_fn *mbfn)
200 {
201         q->merge_bvec_fn = mbfn;
202 }
203
204 EXPORT_SYMBOL(blk_queue_merge_bvec);
205
206 /**
207  * blk_queue_make_request - define an alternate make_request function for a device
208  * @q:  the request queue for the device to be affected
209  * @mfn: the alternate make_request function
210  *
211  * Description:
212  *    The normal way for &struct bios to be passed to a device
213  *    driver is for them to be collected into requests on a request
214  *    queue, and then to allow the device driver to select requests
215  *    off that queue when it is ready.  This works well for many block
216  *    devices. However some block devices (typically virtual devices
217  *    such as md or lvm) do not benefit from the processing on the
218  *    request queue, and are served best by having the requests passed
219  *    directly to them.  This can be achieved by providing a function
220  *    to blk_queue_make_request().
221  *
222  * Caveat:
223  *    The driver that does this *must* be able to deal appropriately
224  *    with buffers in "highmemory". This can be accomplished by either calling
225  *    __bio_kmap_atomic() to get a temporary kernel mapping, or by calling
226  *    blk_queue_bounce() to create a buffer in normal memory.
227  **/
228 void blk_queue_make_request(request_queue_t * q, make_request_fn * mfn)
229 {
230         /*
231          * set defaults
232          */
233         q->nr_requests = BLKDEV_MAX_RQ;
234         q->max_phys_segments = MAX_PHYS_SEGMENTS;
235         q->max_hw_segments = MAX_HW_SEGMENTS;
236         q->make_request_fn = mfn;
237         q->backing_dev_info.ra_pages = (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
238         q->backing_dev_info.state = 0;
239         q->backing_dev_info.memory_backed = 0;
240         blk_queue_max_sectors(q, MAX_SECTORS);
241         blk_queue_hardsect_size(q, 512);
242         blk_queue_dma_alignment(q, 511);
243         blk_queue_congestion_threshold(q);
244
245         q->unplug_thresh = 4;           /* hmm */
246         q->unplug_delay = (3 * HZ) / 1000;      /* 3 milliseconds */
247         if (q->unplug_delay == 0)
248                 q->unplug_delay = 1;
249
250         INIT_WORK(&q->unplug_work, blk_unplug_work, q);
251
252         q->unplug_timer.function = blk_unplug_timeout;
253         q->unplug_timer.data = (unsigned long)q;
254
255         /*
256          * by default assume old behaviour and bounce for any highmem page
257          */
258         blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
259
260         blk_queue_activity_fn(q, NULL, NULL);
261 }
262
263 EXPORT_SYMBOL(blk_queue_make_request);
264
265 /**
266  * blk_queue_bounce_limit - set bounce buffer limit for queue
267  * @q:  the request queue for the device
268  * @dma_addr:   bus address limit
269  *
270  * Description:
271  *    Different hardware can have different requirements as to what pages
272  *    it can do I/O directly to. A low level driver can call
273  *    blk_queue_bounce_limit to have lower memory pages allocated as bounce
274  *    buffers for doing I/O to pages residing above @page. By default
275  *    the block layer sets this to the highest numbered "low" memory page.
276  **/
277 void blk_queue_bounce_limit(request_queue_t *q, u64 dma_addr)
278 {
279         unsigned long bounce_pfn = dma_addr >> PAGE_SHIFT;
280
281         /*
282          * set appropriate bounce gfp mask -- unfortunately we don't have a
283          * full 4GB zone, so we have to resort to low memory for any bounces.
284          * ISA has its own < 16MB zone.
285          */
286         if (bounce_pfn < blk_max_low_pfn) {
287                 BUG_ON(dma_addr < BLK_BOUNCE_ISA);
288                 init_emergency_isa_pool();
289                 q->bounce_gfp = GFP_NOIO | GFP_DMA;
290         } else
291                 q->bounce_gfp = GFP_NOIO;
292
293         q->bounce_pfn = bounce_pfn;
294 }
295
296 EXPORT_SYMBOL(blk_queue_bounce_limit);
297
298 /**
299  * blk_queue_max_sectors - set max sectors for a request for this queue
300  * @q:  the request queue for the device
301  * @max_sectors:  max sectors in the usual 512b unit
302  *
303  * Description:
304  *    Enables a low level driver to set an upper limit on the size of
305  *    received requests.
306  **/
307 void blk_queue_max_sectors(request_queue_t *q, unsigned short max_sectors)
308 {
309         if ((max_sectors << 9) < PAGE_CACHE_SIZE) {
310                 max_sectors = 1 << (PAGE_CACHE_SHIFT - 9);
311                 printk("%s: set to minimum %d\n", __FUNCTION__, max_sectors);
312         }
313
314         q->max_sectors = max_sectors;
315 }
316
317 EXPORT_SYMBOL(blk_queue_max_sectors);
318
319 /**
320  * blk_queue_max_phys_segments - set max phys segments for a request for this queue
321  * @q:  the request queue for the device
322  * @max_segments:  max number of segments
323  *
324  * Description:
325  *    Enables a low level driver to set an upper limit on the number of
326  *    physical data segments in a request.  This would be the largest sized
327  *    scatter list the driver could handle.
328  **/
329 void blk_queue_max_phys_segments(request_queue_t *q, unsigned short max_segments)
330 {
331         if (!max_segments) {
332                 max_segments = 1;
333                 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
334         }
335
336         q->max_phys_segments = max_segments;
337 }
338
339 EXPORT_SYMBOL(blk_queue_max_phys_segments);
340
341 /**
342  * blk_queue_max_hw_segments - set max hw segments for a request for this queue
343  * @q:  the request queue for the device
344  * @max_segments:  max number of segments
345  *
346  * Description:
347  *    Enables a low level driver to set an upper limit on the number of
348  *    hw data segments in a request.  This would be the largest number of
349  *    address/length pairs the host adapter can actually give as once
350  *    to the device.
351  **/
352 void blk_queue_max_hw_segments(request_queue_t *q, unsigned short max_segments)
353 {
354         if (!max_segments) {
355                 max_segments = 1;
356                 printk("%s: set to minimum %d\n", __FUNCTION__, max_segments);
357         }
358
359         q->max_hw_segments = max_segments;
360 }
361
362 EXPORT_SYMBOL(blk_queue_max_hw_segments);
363
364 /**
365  * blk_queue_max_segment_size - set max segment size for blk_rq_map_sg
366  * @q:  the request queue for the device
367  * @max_size:  max size of segment in bytes
368  *
369  * Description:
370  *    Enables a low level driver to set an upper limit on the size of a
371  *    coalesced segment
372  **/
373 void blk_queue_max_segment_size(request_queue_t *q, unsigned int max_size)
374 {
375         if (max_size < PAGE_CACHE_SIZE) {
376                 max_size = PAGE_CACHE_SIZE;
377                 printk("%s: set to minimum %d\n", __FUNCTION__, max_size);
378         }
379
380         q->max_segment_size = max_size;
381 }
382
383 EXPORT_SYMBOL(blk_queue_max_segment_size);
384
385 /**
386  * blk_queue_hardsect_size - set hardware sector size for the queue
387  * @q:  the request queue for the device
388  * @size:  the hardware sector size, in bytes
389  *
390  * Description:
391  *   This should typically be set to the lowest possible sector size
392  *   that the hardware can operate on (possible without reverting to
393  *   even internal read-modify-write operations). Usually the default
394  *   of 512 covers most hardware.
395  **/
396 void blk_queue_hardsect_size(request_queue_t *q, unsigned short size)
397 {
398         q->hardsect_size = size;
399 }
400
401 EXPORT_SYMBOL(blk_queue_hardsect_size);
402
403 /*
404  * Returns the minimum that is _not_ zero, unless both are zero.
405  */
406 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
407
408 /**
409  * blk_queue_stack_limits - inherit underlying queue limits for stacked drivers
410  * @t:  the stacking driver (top)
411  * @b:  the underlying device (bottom)
412  **/
413 void blk_queue_stack_limits(request_queue_t *t, request_queue_t *b)
414 {
415         /* zero is "infinity" */
416         t->max_sectors = min_not_zero(t->max_sectors,b->max_sectors);
417
418         t->max_phys_segments = min(t->max_phys_segments,b->max_phys_segments);
419         t->max_hw_segments = min(t->max_hw_segments,b->max_hw_segments);
420         t->max_segment_size = min(t->max_segment_size,b->max_segment_size);
421         t->hardsect_size = max(t->hardsect_size,b->hardsect_size);
422 }
423
424 EXPORT_SYMBOL(blk_queue_stack_limits);
425
426 /**
427  * blk_queue_segment_boundary - set boundary rules for segment merging
428  * @q:  the request queue for the device
429  * @mask:  the memory boundary mask
430  **/
431 void blk_queue_segment_boundary(request_queue_t *q, unsigned long mask)
432 {
433         if (mask < PAGE_CACHE_SIZE - 1) {
434                 mask = PAGE_CACHE_SIZE - 1;
435                 printk("%s: set to minimum %lx\n", __FUNCTION__, mask);
436         }
437
438         q->seg_boundary_mask = mask;
439 }
440
441 EXPORT_SYMBOL(blk_queue_segment_boundary);
442
443 /**
444  * blk_queue_dma_alignment - set dma length and memory alignment
445  * @q:     the request queue for the device
446  * @mask:  alignment mask
447  *
448  * description:
449  *    set required memory and length aligment for direct dma transactions.
450  *    this is used when buiding direct io requests for the queue.
451  *
452  **/
453 void blk_queue_dma_alignment(request_queue_t *q, int mask)
454 {
455         q->dma_alignment = mask;
456 }
457
458 EXPORT_SYMBOL(blk_queue_dma_alignment);
459
460 /**
461  * blk_queue_find_tag - find a request by its tag and queue
462  *
463  * @q:   The request queue for the device
464  * @tag: The tag of the request
465  *
466  * Notes:
467  *    Should be used when a device returns a tag and you want to match
468  *    it with a request.
469  *
470  *    no locks need be held.
471  **/
472 struct request *blk_queue_find_tag(request_queue_t *q, int tag)
473 {
474         struct blk_queue_tag *bqt = q->queue_tags;
475
476         if (unlikely(bqt == NULL || tag >= bqt->real_max_depth))
477                 return NULL;
478
479         return bqt->tag_index[tag];
480 }
481
482 EXPORT_SYMBOL(blk_queue_find_tag);
483
484 /**
485  * blk_queue_free_tags - release tag maintenance info
486  * @q:  the request queue for the device
487  *
488  *  Notes:
489  *    blk_cleanup_queue() will take care of calling this function, if tagging
490  *    has been used. So there's usually no need to call this directly, unless
491  *    tagging is just being disabled but the queue remains in function.
492  **/
493 void blk_queue_free_tags(request_queue_t *q)
494 {
495         struct blk_queue_tag *bqt = q->queue_tags;
496
497         if (!bqt)
498                 return;
499
500         if (atomic_dec_and_test(&bqt->refcnt)) {
501                 BUG_ON(bqt->busy);
502                 BUG_ON(!list_empty(&bqt->busy_list));
503
504                 kfree(bqt->tag_index);
505                 bqt->tag_index = NULL;
506
507                 kfree(bqt->tag_map);
508                 bqt->tag_map = NULL;
509
510                 kfree(bqt);
511         }
512
513         q->queue_tags = NULL;
514         q->queue_flags &= ~(1 << QUEUE_FLAG_QUEUED);
515 }
516
517 EXPORT_SYMBOL(blk_queue_free_tags);
518
519 static int
520 init_tag_map(request_queue_t *q, struct blk_queue_tag *tags, int depth)
521 {
522         int bits, i;
523
524         if (depth > q->nr_requests * 2) {
525                 depth = q->nr_requests * 2;
526                 printk(KERN_ERR "%s: adjusted depth to %d\n",
527                                 __FUNCTION__, depth);
528         }
529
530         tags->tag_index = kmalloc(depth * sizeof(struct request *), GFP_ATOMIC);
531         if (!tags->tag_index)
532                 goto fail;
533
534         bits = (depth / BLK_TAGS_PER_LONG) + 1;
535         tags->tag_map = kmalloc(bits * sizeof(unsigned long), GFP_ATOMIC);
536         if (!tags->tag_map)
537                 goto fail;
538
539         memset(tags->tag_index, 0, depth * sizeof(struct request *));
540         memset(tags->tag_map, 0, bits * sizeof(unsigned long));
541         tags->max_depth = depth;
542         tags->real_max_depth = bits * BITS_PER_LONG;
543
544         /*
545          * set the upper bits if the depth isn't a multiple of the word size
546          */
547         for (i = depth; i < bits * BLK_TAGS_PER_LONG; i++)
548                 __set_bit(i, tags->tag_map);
549
550         INIT_LIST_HEAD(&tags->busy_list);
551         tags->busy = 0;
552         atomic_set(&tags->refcnt, 1);
553         return 0;
554 fail:
555         kfree(tags->tag_index);
556         return -ENOMEM;
557 }
558
559 /**
560  * blk_queue_init_tags - initialize the queue tag info
561  * @q:  the request queue for the device
562  * @depth:  the maximum queue depth supported
563  **/
564 int blk_queue_init_tags(request_queue_t *q, int depth,
565                         struct blk_queue_tag *tags)
566 {
567         if (!tags) {
568                 tags = kmalloc(sizeof(struct blk_queue_tag), GFP_ATOMIC);
569                 if (!tags)
570                         goto fail;
571
572                 if (init_tag_map(q, tags, depth))
573                         goto fail;
574         } else
575                 atomic_inc(&tags->refcnt);
576
577         /*
578          * assign it, all done
579          */
580         q->queue_tags = tags;
581         q->queue_flags |= (1 << QUEUE_FLAG_QUEUED);
582         return 0;
583 fail:
584         kfree(tags);
585         return -ENOMEM;
586 }
587
588 EXPORT_SYMBOL(blk_queue_init_tags);
589
590 /**
591  * blk_queue_resize_tags - change the queueing depth
592  * @q:  the request queue for the device
593  * @new_depth: the new max command queueing depth
594  *
595  *  Notes:
596  *    Must be called with the queue lock held.
597  **/
598 int blk_queue_resize_tags(request_queue_t *q, int new_depth)
599 {
600         struct blk_queue_tag *bqt = q->queue_tags;
601         struct request **tag_index;
602         unsigned long *tag_map;
603         int bits, max_depth;
604
605         if (!bqt)
606                 return -ENXIO;
607
608         /*
609          * don't bother sizing down
610          */
611         if (new_depth <= bqt->real_max_depth) {
612                 bqt->max_depth = new_depth;
613                 return 0;
614         }
615
616         /*
617          * save the old state info, so we can copy it back
618          */
619         tag_index = bqt->tag_index;
620         tag_map = bqt->tag_map;
621         max_depth = bqt->real_max_depth;
622
623         if (init_tag_map(q, bqt, new_depth))
624                 return -ENOMEM;
625
626         memcpy(bqt->tag_index, tag_index, max_depth * sizeof(struct request *));
627         bits = max_depth / BLK_TAGS_PER_LONG;
628         memcpy(bqt->tag_map, tag_map, bits * sizeof(unsigned long));
629
630         kfree(tag_index);
631         kfree(tag_map);
632         return 0;
633 }
634
635 /**
636  * blk_queue_end_tag - end tag operations for a request
637  * @q:  the request queue for the device
638  * @rq: the request that has completed
639  *
640  *  Description:
641  *    Typically called when end_that_request_first() returns 0, meaning
642  *    all transfers have been done for a request. It's important to call
643  *    this function before end_that_request_last(), as that will put the
644  *    request back on the free list thus corrupting the internal tag list.
645  *
646  *  Notes:
647  *   queue lock must be held.
648  **/
649 void blk_queue_end_tag(request_queue_t *q, struct request *rq)
650 {
651         struct blk_queue_tag *bqt = q->queue_tags;
652         int tag = rq->tag;
653
654         BUG_ON(tag == -1);
655
656         if (unlikely(tag >= bqt->real_max_depth))
657                 return;
658
659         if (unlikely(!__test_and_clear_bit(tag, bqt->tag_map))) {
660                 printk("attempt to clear non-busy tag (%d)\n", tag);
661                 return;
662         }
663
664         list_del_init(&rq->queuelist);
665         rq->flags &= ~REQ_QUEUED;
666         rq->tag = -1;
667
668         if (unlikely(bqt->tag_index[tag] == NULL))
669                 printk("tag %d is missing\n", tag);
670
671         bqt->tag_index[tag] = NULL;
672         bqt->busy--;
673 }
674
675 EXPORT_SYMBOL(blk_queue_end_tag);
676
677 /**
678  * blk_queue_start_tag - find a free tag and assign it
679  * @q:  the request queue for the device
680  * @rq:  the block request that needs tagging
681  *
682  *  Description:
683  *    This can either be used as a stand-alone helper, or possibly be
684  *    assigned as the queue &prep_rq_fn (in which case &struct request
685  *    automagically gets a tag assigned). Note that this function
686  *    assumes that any type of request can be queued! if this is not
687  *    true for your device, you must check the request type before
688  *    calling this function.  The request will also be removed from
689  *    the request queue, so it's the drivers responsibility to readd
690  *    it if it should need to be restarted for some reason.
691  *
692  *  Notes:
693  *   queue lock must be held.
694  **/
695 int blk_queue_start_tag(request_queue_t *q, struct request *rq)
696 {
697         struct blk_queue_tag *bqt = q->queue_tags;
698         unsigned long *map = bqt->tag_map;
699         int tag = 0;
700
701         if (unlikely((rq->flags & REQ_QUEUED))) {
702                 printk(KERN_ERR 
703                        "request %p for device [%s] already tagged %d",
704                        rq, rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->tag);
705                 BUG();
706         }
707
708         for (map = bqt->tag_map; *map == -1UL; map++) {
709                 tag += BLK_TAGS_PER_LONG;
710
711                 if (tag >= bqt->max_depth)
712                         return 1;
713         }
714
715         tag += ffz(*map);
716         __set_bit(tag, bqt->tag_map);
717
718         rq->flags |= REQ_QUEUED;
719         rq->tag = tag;
720         bqt->tag_index[tag] = rq;
721         blkdev_dequeue_request(rq);
722         list_add(&rq->queuelist, &bqt->busy_list);
723         bqt->busy++;
724         return 0;
725 }
726
727 EXPORT_SYMBOL(blk_queue_start_tag);
728
729 /**
730  * blk_queue_invalidate_tags - invalidate all pending tags
731  * @q:  the request queue for the device
732  *
733  *  Description:
734  *   Hardware conditions may dictate a need to stop all pending requests.
735  *   In this case, we will safely clear the block side of the tag queue and
736  *   readd all requests to the request queue in the right order.
737  *
738  *  Notes:
739  *   queue lock must be held.
740  **/
741 void blk_queue_invalidate_tags(request_queue_t *q)
742 {
743         struct blk_queue_tag *bqt = q->queue_tags;
744         struct list_head *tmp, *n;
745         struct request *rq;
746
747         list_for_each_safe(tmp, n, &bqt->busy_list) {
748                 rq = list_entry_rq(tmp);
749
750                 if (rq->tag == -1) {
751                         printk("bad tag found on list\n");
752                         list_del_init(&rq->queuelist);
753                         rq->flags &= ~REQ_QUEUED;
754                 } else
755                         blk_queue_end_tag(q, rq);
756
757                 rq->flags &= ~REQ_STARTED;
758                 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
759         }
760 }
761
762 EXPORT_SYMBOL(blk_queue_invalidate_tags);
763
764 static char *rq_flags[] = {
765         "REQ_RW",
766         "REQ_FAILFAST",
767         "REQ_SOFTBARRIER",
768         "REQ_HARDBARRIER",
769         "REQ_CMD",
770         "REQ_NOMERGE",
771         "REQ_STARTED",
772         "REQ_DONTPREP",
773         "REQ_QUEUED",
774         "REQ_PC",
775         "REQ_BLOCK_PC",
776         "REQ_SENSE",
777         "REQ_FAILED",
778         "REQ_QUIET",
779         "REQ_SPECIAL",
780         "REQ_DRIVE_CMD",
781         "REQ_DRIVE_TASK",
782         "REQ_DRIVE_TASKFILE",
783         "REQ_PREEMPT",
784         "REQ_PM_SUSPEND",
785         "REQ_PM_RESUME",
786         "REQ_PM_SHUTDOWN",
787 };
788
789 void blk_dump_rq_flags(struct request *rq, char *msg)
790 {
791         int bit;
792
793         printk("%s: dev %s: flags = ", msg,
794                 rq->rq_disk ? rq->rq_disk->disk_name : "?");
795         bit = 0;
796         do {
797                 if (rq->flags & (1 << bit))
798                         printk("%s ", rq_flags[bit]);
799                 bit++;
800         } while (bit < __REQ_NR_BITS);
801
802         printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
803                                                        rq->nr_sectors,
804                                                        rq->current_nr_sectors);
805         printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
806
807         if (rq->flags & (REQ_BLOCK_PC | REQ_PC)) {
808                 printk("cdb: ");
809                 for (bit = 0; bit < sizeof(rq->cmd); bit++)
810                         printk("%02x ", rq->cmd[bit]);
811                 printk("\n");
812         }
813 }
814
815 EXPORT_SYMBOL(blk_dump_rq_flags);
816
817 void blk_recount_segments(request_queue_t *q, struct bio *bio)
818 {
819         struct bio_vec *bv, *bvprv = NULL;
820         int i, nr_phys_segs, nr_hw_segs, seg_size, hw_seg_size, cluster;
821         int high, highprv = 1;
822
823         if (unlikely(!bio->bi_io_vec))
824                 return;
825
826         cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
827         hw_seg_size = seg_size = nr_phys_segs = nr_hw_segs = 0;
828         bio_for_each_segment(bv, bio, i) {
829                 /*
830                  * the trick here is making sure that a high page is never
831                  * considered part of another segment, since that might
832                  * change with the bounce page.
833                  */
834                 high = page_to_pfn(bv->bv_page) >= q->bounce_pfn;
835                 if (high || highprv)
836                         goto new_hw_segment;
837                 if (cluster) {
838                         if (seg_size + bv->bv_len > q->max_segment_size)
839                                 goto new_segment;
840                         if (!BIOVEC_PHYS_MERGEABLE(bvprv, bv))
841                                 goto new_segment;
842                         if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bv))
843                                 goto new_segment;
844                         if (BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len))
845                                 goto new_hw_segment;
846
847                         seg_size += bv->bv_len;
848                         hw_seg_size += bv->bv_len;
849                         bvprv = bv;
850                         continue;
851                 }
852 new_segment:
853                 if (BIOVEC_VIRT_MERGEABLE(bvprv, bv) &&
854                     !BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len)) {
855                         hw_seg_size += bv->bv_len;
856                 } else {
857 new_hw_segment:
858                         if (hw_seg_size > bio->bi_hw_front_size)
859                                 bio->bi_hw_front_size = hw_seg_size;
860                         hw_seg_size = BIOVEC_VIRT_START_SIZE(bv) + bv->bv_len;
861                         nr_hw_segs++;
862                 }
863
864                 nr_phys_segs++;
865                 bvprv = bv;
866                 seg_size = bv->bv_len;
867                 highprv = high;
868         }
869         if (hw_seg_size > bio->bi_hw_back_size)
870                 bio->bi_hw_back_size = hw_seg_size;
871         if (nr_hw_segs == 1 && hw_seg_size > bio->bi_hw_front_size)
872                 bio->bi_hw_front_size = hw_seg_size;
873         bio->bi_phys_segments = nr_phys_segs;
874         bio->bi_hw_segments = nr_hw_segs;
875         bio->bi_flags |= (1 << BIO_SEG_VALID);
876 }
877
878
879 int blk_phys_contig_segment(request_queue_t *q, struct bio *bio,
880                                    struct bio *nxt)
881 {
882         if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
883                 return 0;
884
885         if (!BIOVEC_PHYS_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
886                 return 0;
887         if (bio->bi_size + nxt->bi_size > q->max_segment_size)
888                 return 0;
889
890         /*
891          * bio and nxt are contigous in memory, check if the queue allows
892          * these two to be merged into one
893          */
894         if (BIO_SEG_BOUNDARY(q, bio, nxt))
895                 return 1;
896
897         return 0;
898 }
899
900 EXPORT_SYMBOL(blk_phys_contig_segment);
901
902 int blk_hw_contig_segment(request_queue_t *q, struct bio *bio,
903                                  struct bio *nxt)
904 {
905         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
906                 blk_recount_segments(q, bio);
907         if (unlikely(!bio_flagged(nxt, BIO_SEG_VALID)))
908                 blk_recount_segments(q, nxt);
909         if (!BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)) ||
910             BIOVEC_VIRT_OVERSIZE(bio->bi_hw_front_size + bio->bi_hw_back_size))
911                 return 0;
912         if (bio->bi_size + nxt->bi_size > q->max_segment_size)
913                 return 0;
914
915         return 1;
916 }
917
918 EXPORT_SYMBOL(blk_hw_contig_segment);
919
920 /*
921  * map a request to scatterlist, return number of sg entries setup. Caller
922  * must make sure sg can hold rq->nr_phys_segments entries
923  */
924 int blk_rq_map_sg(request_queue_t *q, struct request *rq, struct scatterlist *sg)
925 {
926         struct bio_vec *bvec, *bvprv;
927         struct bio *bio;
928         int nsegs, i, cluster;
929
930         nsegs = 0;
931         cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
932
933         /*
934          * for each bio in rq
935          */
936         bvprv = NULL;
937         rq_for_each_bio(bio, rq) {
938                 /*
939                  * for each segment in bio
940                  */
941                 bio_for_each_segment(bvec, bio, i) {
942                         int nbytes = bvec->bv_len;
943
944                         if (bvprv && cluster) {
945                                 if (sg[nsegs - 1].length + nbytes > q->max_segment_size)
946                                         goto new_segment;
947
948                                 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bvec))
949                                         goto new_segment;
950                                 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bvec))
951                                         goto new_segment;
952
953                                 sg[nsegs - 1].length += nbytes;
954                         } else {
955 new_segment:
956                                 memset(&sg[nsegs],0,sizeof(struct scatterlist));
957                                 sg[nsegs].page = bvec->bv_page;
958                                 sg[nsegs].length = nbytes;
959                                 sg[nsegs].offset = bvec->bv_offset;
960
961                                 nsegs++;
962                         }
963                         bvprv = bvec;
964                 } /* segments in bio */
965         } /* bios in rq */
966
967         return nsegs;
968 }
969
970 EXPORT_SYMBOL(blk_rq_map_sg);
971
972 /*
973  * the standard queue merge functions, can be overridden with device
974  * specific ones if so desired
975  */
976
977 static inline int ll_new_mergeable(request_queue_t *q,
978                                    struct request *req,
979                                    struct bio *bio)
980 {
981         int nr_phys_segs = bio_phys_segments(q, bio);
982
983         if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
984                 req->flags |= REQ_NOMERGE;
985                 if (req == q->last_merge)
986                         q->last_merge = NULL;
987                 return 0;
988         }
989
990         /*
991          * A hw segment is just getting larger, bump just the phys
992          * counter.
993          */
994         req->nr_phys_segments += nr_phys_segs;
995         return 1;
996 }
997
998 static inline int ll_new_hw_segment(request_queue_t *q,
999                                     struct request *req,
1000                                     struct bio *bio)
1001 {
1002         int nr_hw_segs = bio_hw_segments(q, bio);
1003         int nr_phys_segs = bio_phys_segments(q, bio);
1004
1005         if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
1006             || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
1007                 req->flags |= REQ_NOMERGE;
1008                 if (req == q->last_merge)
1009                         q->last_merge = NULL;
1010                 return 0;
1011         }
1012
1013         /*
1014          * This will form the start of a new hw segment.  Bump both
1015          * counters.
1016          */
1017         req->nr_hw_segments += nr_hw_segs;
1018         req->nr_phys_segments += nr_phys_segs;
1019         return 1;
1020 }
1021
1022 static int ll_back_merge_fn(request_queue_t *q, struct request *req, 
1023                             struct bio *bio)
1024 {
1025         int len;
1026
1027         if (req->nr_sectors + bio_sectors(bio) > q->max_sectors) {
1028                 req->flags |= REQ_NOMERGE;
1029                 if (req == q->last_merge)
1030                         q->last_merge = NULL;
1031                 return 0;
1032         }
1033         if (unlikely(!bio_flagged(req->biotail, BIO_SEG_VALID)))
1034                 blk_recount_segments(q, req->biotail);
1035         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1036                 blk_recount_segments(q, bio);
1037         len = req->biotail->bi_hw_back_size + bio->bi_hw_front_size;
1038         if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)) &&
1039             !BIOVEC_VIRT_OVERSIZE(len)) {
1040                 int mergeable =  ll_new_mergeable(q, req, bio);
1041
1042                 if (mergeable) {
1043                         if (req->nr_hw_segments == 1)
1044                                 req->bio->bi_hw_front_size = len;
1045                         if (bio->bi_hw_segments == 1)
1046                                 bio->bi_hw_back_size = len;
1047                 }
1048                 return mergeable;
1049         }
1050
1051         return ll_new_hw_segment(q, req, bio);
1052 }
1053
1054 static int ll_front_merge_fn(request_queue_t *q, struct request *req, 
1055                              struct bio *bio)
1056 {
1057         int len;
1058
1059         if (req->nr_sectors + bio_sectors(bio) > q->max_sectors) {
1060                 req->flags |= REQ_NOMERGE;
1061                 if (req == q->last_merge)
1062                         q->last_merge = NULL;
1063                 return 0;
1064         }
1065         len = bio->bi_hw_back_size + req->bio->bi_hw_front_size;
1066         if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
1067                 blk_recount_segments(q, bio);
1068         if (unlikely(!bio_flagged(req->bio, BIO_SEG_VALID)))
1069                 blk_recount_segments(q, req->bio);
1070         if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)) &&
1071             !BIOVEC_VIRT_OVERSIZE(len)) {
1072                 int mergeable =  ll_new_mergeable(q, req, bio);
1073
1074                 if (mergeable) {
1075                         if (bio->bi_hw_segments == 1)
1076                                 bio->bi_hw_front_size = len;
1077                         if (req->nr_hw_segments == 1)
1078                                 req->biotail->bi_hw_back_size = len;
1079                 }
1080                 return mergeable;
1081         }
1082
1083         return ll_new_hw_segment(q, req, bio);
1084 }
1085
1086 static int ll_merge_requests_fn(request_queue_t *q, struct request *req,
1087                                 struct request *next)
1088 {
1089         int total_phys_segments = req->nr_phys_segments +next->nr_phys_segments;
1090         int total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1091
1092         /*
1093          * First check if the either of the requests are re-queued
1094          * requests.  Can't merge them if they are.
1095          */
1096         if (req->special || next->special)
1097                 return 0;
1098
1099         /*
1100          * Will it become to large?
1101          */
1102         if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
1103                 return 0;
1104
1105         total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
1106         if (blk_phys_contig_segment(q, req->biotail, next->bio))
1107                 total_phys_segments--;
1108
1109         if (total_phys_segments > q->max_phys_segments)
1110                 return 0;
1111
1112         total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
1113         if (blk_hw_contig_segment(q, req->biotail, next->bio)) {
1114                 int len = req->biotail->bi_hw_back_size + next->bio->bi_hw_front_size;
1115                 /*
1116                  * propagate the combined length to the end of the requests
1117                  */
1118                 if (req->nr_hw_segments == 1)
1119                         req->bio->bi_hw_front_size = len;
1120                 if (next->nr_hw_segments == 1)
1121                         next->biotail->bi_hw_back_size = len;
1122                 total_hw_segments--;
1123         }
1124
1125         if (total_hw_segments > q->max_hw_segments)
1126                 return 0;
1127
1128         /* Merge is OK... */
1129         req->nr_phys_segments = total_phys_segments;
1130         req->nr_hw_segments = total_hw_segments;
1131         return 1;
1132 }
1133
1134 /*
1135  * "plug" the device if there are no outstanding requests: this will
1136  * force the transfer to start only after we have put all the requests
1137  * on the list.
1138  *
1139  * This is called with interrupts off and no requests on the queue and
1140  * with the queue lock held.
1141  */
1142 void blk_plug_device(request_queue_t *q)
1143 {
1144         WARN_ON(!irqs_disabled());
1145
1146         /*
1147          * don't plug a stopped queue, it must be paired with blk_start_queue()
1148          * which will restart the queueing
1149          */
1150         if (test_bit(QUEUE_FLAG_STOPPED, &q->queue_flags))
1151                 return;
1152
1153         if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1154                 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
1155 }
1156
1157 EXPORT_SYMBOL(blk_plug_device);
1158
1159 /*
1160  * remove the queue from the plugged list, if present. called with
1161  * queue lock held and interrupts disabled.
1162  */
1163 int blk_remove_plug(request_queue_t *q)
1164 {
1165         WARN_ON(!irqs_disabled());
1166
1167         if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
1168                 return 0;
1169
1170         del_timer(&q->unplug_timer);
1171         return 1;
1172 }
1173
1174 EXPORT_SYMBOL(blk_remove_plug);
1175
1176 /*
1177  * remove the plug and let it rip..
1178  */
1179 void __generic_unplug_device(request_queue_t *q)
1180 {
1181         if (test_bit(QUEUE_FLAG_STOPPED, &q->queue_flags))
1182                 return;
1183
1184         if (!blk_remove_plug(q))
1185                 return;
1186
1187         /*
1188          * was plugged, fire request_fn if queue has stuff to do
1189          */
1190         if (elv_next_request(q))
1191                 q->request_fn(q);
1192 }
1193 EXPORT_SYMBOL(__generic_unplug_device);
1194
1195 /**
1196  * generic_unplug_device - fire a request queue
1197  * @q:    The &request_queue_t in question
1198  *
1199  * Description:
1200  *   Linux uses plugging to build bigger requests queues before letting
1201  *   the device have at them. If a queue is plugged, the I/O scheduler
1202  *   is still adding and merging requests on the queue. Once the queue
1203  *   gets unplugged, the request_fn defined for the queue is invoked and
1204  *   transfers started.
1205  **/
1206 void generic_unplug_device(request_queue_t *q)
1207 {
1208         spin_lock_irq(q->queue_lock);
1209         __generic_unplug_device(q);
1210         spin_unlock_irq(q->queue_lock);
1211 }
1212 EXPORT_SYMBOL(generic_unplug_device);
1213
1214 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
1215                                    struct page *page)
1216 {
1217         request_queue_t *q = bdi->unplug_io_data;
1218
1219         /*
1220          * devices don't necessarily have an ->unplug_fn defined
1221          */
1222         if (q->unplug_fn)
1223                 q->unplug_fn(q);
1224 }
1225
1226 static void blk_unplug_work(void *data)
1227 {
1228         request_queue_t *q = data;
1229
1230         q->unplug_fn(q);
1231 }
1232
1233 static void blk_unplug_timeout(unsigned long data)
1234 {
1235         request_queue_t *q = (request_queue_t *)data;
1236
1237         kblockd_schedule_work(&q->unplug_work);
1238 }
1239
1240 /**
1241  * blk_start_queue - restart a previously stopped queue
1242  * @q:    The &request_queue_t in question
1243  *
1244  * Description:
1245  *   blk_start_queue() will clear the stop flag on the queue, and call
1246  *   the request_fn for the queue if it was in a stopped state when
1247  *   entered. Also see blk_stop_queue(). Queue lock must be held.
1248  **/
1249 void blk_start_queue(request_queue_t *q)
1250 {
1251         clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1252
1253         /*
1254          * one level of recursion is ok and is much faster than kicking
1255          * the unplug handling
1256          */
1257         if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
1258                 q->request_fn(q);
1259                 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
1260         } else {
1261                 blk_plug_device(q);
1262                 kblockd_schedule_work(&q->unplug_work);
1263         }
1264 }
1265
1266 EXPORT_SYMBOL(blk_start_queue);
1267
1268 /**
1269  * blk_stop_queue - stop a queue
1270  * @q:    The &request_queue_t in question
1271  *
1272  * Description:
1273  *   The Linux block layer assumes that a block driver will consume all
1274  *   entries on the request queue when the request_fn strategy is called.
1275  *   Often this will not happen, because of hardware limitations (queue
1276  *   depth settings). If a device driver gets a 'queue full' response,
1277  *   or if it simply chooses not to queue more I/O at one point, it can
1278  *   call this function to prevent the request_fn from being called until
1279  *   the driver has signalled it's ready to go again. This happens by calling
1280  *   blk_start_queue() to restart queue operations. Queue lock must be held.
1281  **/
1282 void blk_stop_queue(request_queue_t *q)
1283 {
1284         blk_remove_plug(q);
1285         set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
1286 }
1287
1288 EXPORT_SYMBOL(blk_stop_queue);
1289
1290 /**
1291  * blk_run_queue - run a single device queue
1292  * @q:  The queue to run
1293  */
1294 void blk_run_queue(struct request_queue *q)
1295 {
1296         unsigned long flags;
1297
1298         spin_lock_irqsave(q->queue_lock, flags);
1299         blk_remove_plug(q);
1300         q->request_fn(q);
1301         spin_unlock_irqrestore(q->queue_lock, flags);
1302 }
1303
1304 EXPORT_SYMBOL(blk_run_queue);
1305
1306 /**
1307  * blk_cleanup_queue: - release a &request_queue_t when it is no longer needed
1308  * @q:    the request queue to be released
1309  *
1310  * Description:
1311  *     blk_cleanup_queue is the pair to blk_init_queue() or
1312  *     blk_queue_make_request().  It should be called when a request queue is
1313  *     being released; typically when a block device is being de-registered.
1314  *     Currently, its primary task it to free all the &struct request
1315  *     structures that were allocated to the queue and the queue itself.
1316  *
1317  * Caveat:
1318  *     Hopefully the low level driver will have finished any
1319  *     outstanding requests first...
1320  **/
1321 void blk_cleanup_queue(request_queue_t * q)
1322 {
1323         struct request_list *rl = &q->rq;
1324
1325         if (!atomic_dec_and_test(&q->refcnt))
1326                 return;
1327
1328         elevator_exit(q);
1329
1330         del_timer_sync(&q->unplug_timer);
1331         kblockd_flush();
1332
1333         if (rl->rq_pool)
1334                 mempool_destroy(rl->rq_pool);
1335
1336         if (blk_queue_tagged(q))
1337                 blk_queue_free_tags(q);
1338
1339         kmem_cache_free(requestq_cachep, q);
1340 }
1341
1342 EXPORT_SYMBOL(blk_cleanup_queue);
1343
1344 static int blk_init_free_list(request_queue_t *q)
1345 {
1346         struct request_list *rl = &q->rq;
1347
1348         rl->count[READ] = rl->count[WRITE] = 0;
1349         init_waitqueue_head(&rl->wait[READ]);
1350         init_waitqueue_head(&rl->wait[WRITE]);
1351
1352         rl->rq_pool = mempool_create(BLKDEV_MIN_RQ, mempool_alloc_slab, mempool_free_slab, request_cachep);
1353
1354         if (!rl->rq_pool)
1355                 return -ENOMEM;
1356
1357         return 0;
1358 }
1359
1360 static int __make_request(request_queue_t *, struct bio *);
1361
1362 static elevator_t *chosen_elevator =
1363 #if defined(CONFIG_IOSCHED_CFQ)
1364         &iosched_cfq;
1365 #elif defined(CONFIG_IOSCHED_AS)
1366         &iosched_as;
1367 #elif defined(CONFIG_IOSCHED_DEADLINE)
1368         &iosched_deadline;
1369 #elif defined(CONFIG_IOSCHED_NOOP)
1370         &elevator_noop;
1371 #else
1372         NULL;
1373 #error "You must have at least 1 I/O scheduler selected"
1374 #endif
1375
1376 #if defined(CONFIG_IOSCHED_AS) || defined(CONFIG_IOSCHED_DEADLINE) || defined (CONFIG_IOSCHED_NOOP)
1377 static int __init elevator_setup(char *str)
1378 {
1379 #ifdef CONFIG_IOSCHED_DEADLINE
1380         if (!strcmp(str, "deadline"))
1381                 chosen_elevator = &iosched_deadline;
1382 #endif
1383 #ifdef CONFIG_IOSCHED_AS
1384         if (!strcmp(str, "as"))
1385                 chosen_elevator = &iosched_as;
1386 #endif
1387 #ifdef CONFIG_IOSCHED_CFQ
1388         if (!strcmp(str, "cfq"))
1389                 chosen_elevator = &iosched_cfq;
1390 #endif
1391 #ifdef CONFIG_IOSCHED_NOOP
1392         if (!strcmp(str, "noop"))
1393                 chosen_elevator = &elevator_noop;
1394 #endif
1395         return 1;
1396 }
1397
1398 __setup("elevator=", elevator_setup);
1399 #endif /* CONFIG_IOSCHED_AS || CONFIG_IOSCHED_DEADLINE || CONFIG_IOSCHED_NOOP */
1400
1401 request_queue_t *blk_alloc_queue(int gfp_mask)
1402 {
1403         request_queue_t *q = kmem_cache_alloc(requestq_cachep, gfp_mask);
1404
1405         if (!q)
1406                 return NULL;
1407
1408         memset(q, 0, sizeof(*q));
1409         init_timer(&q->unplug_timer);
1410         atomic_set(&q->refcnt, 1);
1411
1412         q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
1413         q->backing_dev_info.unplug_io_data = q;
1414
1415         return q;
1416 }
1417
1418 EXPORT_SYMBOL(blk_alloc_queue);
1419
1420 /**
1421  * blk_init_queue  - prepare a request queue for use with a block device
1422  * @rfn:  The function to be called to process requests that have been
1423  *        placed on the queue.
1424  * @lock: Request queue spin lock
1425  *
1426  * Description:
1427  *    If a block device wishes to use the standard request handling procedures,
1428  *    which sorts requests and coalesces adjacent requests, then it must
1429  *    call blk_init_queue().  The function @rfn will be called when there
1430  *    are requests on the queue that need to be processed.  If the device
1431  *    supports plugging, then @rfn may not be called immediately when requests
1432  *    are available on the queue, but may be called at some time later instead.
1433  *    Plugged queues are generally unplugged when a buffer belonging to one
1434  *    of the requests on the queue is needed, or due to memory pressure.
1435  *
1436  *    @rfn is not required, or even expected, to remove all requests off the
1437  *    queue, but only as many as it can handle at a time.  If it does leave
1438  *    requests on the queue, it is responsible for arranging that the requests
1439  *    get dealt with eventually.
1440  *
1441  *    The queue spin lock must be held while manipulating the requests on the
1442  *    request queue.
1443  *
1444  *    Function returns a pointer to the initialized request queue, or NULL if
1445  *    it didn't succeed.
1446  *
1447  * Note:
1448  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
1449  *    when the block device is deactivated (such as at module unload).
1450  **/
1451 request_queue_t *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1452 {
1453         request_queue_t *q;
1454         static int printed;
1455
1456         q = blk_alloc_queue(GFP_KERNEL);
1457         if (!q)
1458                 return NULL;
1459
1460         if (blk_init_free_list(q))
1461                 goto out_init;
1462
1463         if (!printed) {
1464                 printed = 1;
1465                 printk("Using %s io scheduler\n", chosen_elevator->elevator_name);
1466         }
1467
1468         if (elevator_init(q, chosen_elevator))
1469                 goto out_elv;
1470
1471         q->request_fn           = rfn;
1472         q->back_merge_fn        = ll_back_merge_fn;
1473         q->front_merge_fn       = ll_front_merge_fn;
1474         q->merge_requests_fn    = ll_merge_requests_fn;
1475         q->prep_rq_fn           = NULL;
1476         q->unplug_fn            = generic_unplug_device;
1477         q->queue_flags          = (1 << QUEUE_FLAG_CLUSTER);
1478         q->queue_lock           = lock;
1479
1480         blk_queue_segment_boundary(q, 0xffffffff);
1481
1482         blk_queue_make_request(q, __make_request);
1483         blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
1484
1485         blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
1486         blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
1487
1488         return q;
1489 out_elv:
1490         blk_cleanup_queue(q);
1491 out_init:
1492         kmem_cache_free(requestq_cachep, q);
1493         return NULL;
1494 }
1495
1496 EXPORT_SYMBOL(blk_init_queue);
1497
1498 int blk_get_queue(request_queue_t *q)
1499 {
1500         if (!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)) {
1501                 atomic_inc(&q->refcnt);
1502                 return 0;
1503         }
1504
1505         return 1;
1506 }
1507
1508 EXPORT_SYMBOL(blk_get_queue);
1509
1510 static inline void blk_free_request(request_queue_t *q, struct request *rq)
1511 {
1512         elv_put_request(q, rq);
1513         mempool_free(rq, q->rq.rq_pool);
1514 }
1515
1516 static inline struct request *blk_alloc_request(request_queue_t *q,int gfp_mask)
1517 {
1518         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
1519
1520         if (!rq)
1521                 return NULL;
1522
1523         if (!elv_set_request(q, rq, gfp_mask))
1524                 return rq;
1525
1526         mempool_free(rq, q->rq.rq_pool);
1527         return NULL;
1528 }
1529
1530 /*
1531  * ioc_batching returns true if the ioc is a valid batching request and
1532  * should be given priority access to a request.
1533  */
1534 static inline int ioc_batching(struct io_context *ioc)
1535 {
1536         if (!ioc)
1537                 return 0;
1538
1539         /*
1540          * Make sure the process is able to allocate at least 1 request
1541          * even if the batch times out, otherwise we could theoretically
1542          * lose wakeups.
1543          */
1544         return ioc->nr_batch_requests == BLK_BATCH_REQ ||
1545                 (ioc->nr_batch_requests > 0
1546                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
1547 }
1548
1549 /*
1550  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1551  * will cause the process to be a "batcher" on all queues in the system. This
1552  * is the behaviour we want though - once it gets a wakeup it should be given
1553  * a nice run.
1554  */
1555 void ioc_set_batching(struct io_context *ioc)
1556 {
1557         if (!ioc || ioc_batching(ioc))
1558                 return;
1559
1560         ioc->nr_batch_requests = BLK_BATCH_REQ;
1561         ioc->last_waited = jiffies;
1562 }
1563
1564 /*
1565  * A request has just been released.  Account for it, update the full and
1566  * congestion status, wake up any waiters.   Called under q->queue_lock.
1567  */
1568 static void freed_request(request_queue_t *q, int rw)
1569 {
1570         struct request_list *rl = &q->rq;
1571
1572         rl->count[rw]--;
1573         if (rl->count[rw] < queue_congestion_off_threshold(q))
1574                 clear_queue_congested(q, rw);
1575         if (rl->count[rw]+1 <= q->nr_requests) {
1576                 if (waitqueue_active(&rl->wait[rw]))
1577                         wake_up(&rl->wait[rw]);
1578                 if (!waitqueue_active(&rl->wait[rw]))
1579                         blk_clear_queue_full(q, rw);
1580         }
1581 }
1582
1583 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
1584 /*
1585  * Get a free request, queue_lock must not be held
1586  */
1587 static struct request *get_request(request_queue_t *q, int rw, int gfp_mask)
1588 {
1589         struct request *rq = NULL;
1590         struct request_list *rl = &q->rq;
1591         struct io_context *ioc = get_io_context(gfp_mask);
1592
1593         spin_lock_irq(q->queue_lock);
1594         if (rl->count[rw]+1 >= q->nr_requests) {
1595                 /*
1596                  * The queue will fill after this allocation, so set it as
1597                  * full, and mark this process as "batching". This process
1598                  * will be allowed to complete a batch of requests, others
1599                  * will be blocked.
1600                  */
1601                 if (!blk_queue_full(q, rw)) {
1602                         ioc_set_batching(ioc);
1603                         blk_set_queue_full(q, rw);
1604                 }
1605         }
1606
1607         if (blk_queue_full(q, rw)
1608                         && !ioc_batching(ioc) && !elv_may_queue(q, rw)) {
1609                 /*
1610                  * The queue is full and the allocating process is not a
1611                  * "batcher", and not exempted by the IO scheduler
1612                  */
1613                 spin_unlock_irq(q->queue_lock);
1614                 goto out;
1615         }
1616
1617         rl->count[rw]++;
1618         if (rl->count[rw] >= queue_congestion_on_threshold(q))
1619                 set_queue_congested(q, rw);
1620         spin_unlock_irq(q->queue_lock);
1621
1622         rq = blk_alloc_request(q, gfp_mask);
1623         if (!rq) {
1624                 /*
1625                  * Allocation failed presumably due to memory. Undo anything
1626                  * we might have messed up.
1627                  *
1628                  * Allocating task should really be put onto the front of the
1629                  * wait queue, but this is pretty rare.
1630                  */
1631                 spin_lock_irq(q->queue_lock);
1632                 freed_request(q, rw);
1633                 spin_unlock_irq(q->queue_lock);
1634                 goto out;
1635         }
1636
1637         if (ioc_batching(ioc))
1638                 ioc->nr_batch_requests--;
1639         
1640         INIT_LIST_HEAD(&rq->queuelist);
1641
1642         /*
1643          * first three bits are identical in rq->flags and bio->bi_rw,
1644          * see bio.h and blkdev.h
1645          */
1646         rq->flags = rw;
1647
1648         rq->errors = 0;
1649         rq->rq_status = RQ_ACTIVE;
1650         rq->bio = rq->biotail = NULL;
1651         rq->buffer = NULL;
1652         rq->ref_count = 1;
1653         rq->q = q;
1654         rq->rl = rl;
1655         rq->waiting = NULL;
1656         rq->special = NULL;
1657         rq->data_len = 0;
1658         rq->data = NULL;
1659         rq->sense = NULL;
1660
1661 out:
1662         put_io_context(ioc);
1663         return rq;
1664 }
1665
1666 /*
1667  * No available requests for this queue, unplug the device and wait for some
1668  * requests to become available.
1669  */
1670 static struct request *get_request_wait(request_queue_t *q, int rw)
1671 {
1672         DEFINE_WAIT(wait);
1673         struct request *rq;
1674
1675         generic_unplug_device(q);
1676         do {
1677                 struct request_list *rl = &q->rq;
1678
1679                 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
1680                                 TASK_UNINTERRUPTIBLE);
1681
1682                 rq = get_request(q, rw, GFP_NOIO);
1683
1684                 if (!rq) {
1685                         struct io_context *ioc;
1686
1687                         io_schedule();
1688
1689                         /*
1690                          * After sleeping, we become a "batching" process and
1691                          * will be able to allocate at least one request, and
1692                          * up to a big batch of them for a small period time.
1693                          * See ioc_batching, ioc_set_batching
1694                          */
1695                         ioc = get_io_context(GFP_NOIO);
1696                         ioc_set_batching(ioc);
1697                         put_io_context(ioc);
1698                 }
1699                 finish_wait(&rl->wait[rw], &wait);
1700         } while (!rq);
1701
1702         return rq;
1703 }
1704
1705 struct request *blk_get_request(request_queue_t *q, int rw, int gfp_mask)
1706 {
1707         struct request *rq;
1708
1709         BUG_ON(rw != READ && rw != WRITE);
1710
1711         if (gfp_mask & __GFP_WAIT)
1712                 rq = get_request_wait(q, rw);
1713         else
1714                 rq = get_request(q, rw, gfp_mask);
1715
1716         return rq;
1717 }
1718
1719 EXPORT_SYMBOL(blk_get_request);
1720
1721 /**
1722  * blk_requeue_request - put a request back on queue
1723  * @q:          request queue where request should be inserted
1724  * @rq:         request to be inserted
1725  *
1726  * Description:
1727  *    Drivers often keep queueing requests until the hardware cannot accept
1728  *    more, when that condition happens we need to put the request back
1729  *    on the queue. Must be called with queue lock held.
1730  */
1731 void blk_requeue_request(request_queue_t *q, struct request *rq)
1732 {
1733         if (blk_rq_tagged(rq))
1734                 blk_queue_end_tag(q, rq);
1735
1736         elv_requeue_request(q, rq);
1737 }
1738
1739 EXPORT_SYMBOL(blk_requeue_request);
1740
1741 /**
1742  * blk_insert_request - insert a special request in to a request queue
1743  * @q:          request queue where request should be inserted
1744  * @rq:         request to be inserted
1745  * @at_head:    insert request at head or tail of queue
1746  * @data:       private data
1747  * @reinsert:   true if request it a reinsertion of previously processed one
1748  *
1749  * Description:
1750  *    Many block devices need to execute commands asynchronously, so they don't
1751  *    block the whole kernel from preemption during request execution.  This is
1752  *    accomplished normally by inserting aritficial requests tagged as
1753  *    REQ_SPECIAL in to the corresponding request queue, and letting them be
1754  *    scheduled for actual execution by the request queue.
1755  *
1756  *    We have the option of inserting the head or the tail of the queue.
1757  *    Typically we use the tail for new ioctls and so forth.  We use the head
1758  *    of the queue for things like a QUEUE_FULL message from a device, or a
1759  *    host that is unable to accept a particular command.
1760  */
1761 void blk_insert_request(request_queue_t *q, struct request *rq,
1762                         int at_head, void *data, int reinsert)
1763 {
1764         unsigned long flags;
1765
1766         /*
1767          * tell I/O scheduler that this isn't a regular read/write (ie it
1768          * must not attempt merges on this) and that it acts as a soft
1769          * barrier
1770          */
1771         rq->flags |= REQ_SPECIAL | REQ_SOFTBARRIER;
1772
1773         rq->special = data;
1774
1775         spin_lock_irqsave(q->queue_lock, flags);
1776
1777         /*
1778          * If command is tagged, release the tag
1779          */
1780         if (reinsert)
1781                 blk_requeue_request(q, rq);
1782         else {
1783                 int where = ELEVATOR_INSERT_BACK;
1784
1785                 if (at_head)
1786                         where = ELEVATOR_INSERT_FRONT;
1787
1788                 if (blk_rq_tagged(rq))
1789                         blk_queue_end_tag(q, rq);
1790
1791                 drive_stat_acct(rq, rq->nr_sectors, 1);
1792                 __elv_add_request(q, rq, where, 0);
1793         }
1794         if (blk_queue_plugged(q))
1795                 __generic_unplug_device(q);
1796         else
1797                 q->request_fn(q);
1798         spin_unlock_irqrestore(q->queue_lock, flags);
1799 }
1800
1801 EXPORT_SYMBOL(blk_insert_request);
1802
1803 /**
1804  * blk_rq_map_user - map user data to a request, for REQ_BLOCK_PC usage
1805  * @q:          request queue where request should be inserted
1806  * @rw:         READ or WRITE data
1807  * @ubuf:       the user buffer
1808  * @len:        length of user data
1809  *
1810  * Description:
1811  *    Data will be mapped directly for zero copy io, if possible. Otherwise
1812  *    a kernel bounce buffer is used.
1813  *
1814  *    A matching blk_rq_unmap_user() must be issued at the end of io, while
1815  *    still in process context.
1816  */
1817 struct request *blk_rq_map_user(request_queue_t *q, int rw, void __user *ubuf,
1818                                 unsigned int len)
1819 {
1820         struct request *rq = NULL;
1821         char *buf = NULL;
1822         struct bio *bio;
1823         int ret;
1824
1825         rq = blk_get_request(q, rw, __GFP_WAIT);
1826         if (!rq)
1827                 return ERR_PTR(-ENOMEM);
1828
1829         bio = bio_map_user(q, NULL, (unsigned long) ubuf, len, rw == READ);
1830         if (!bio) {
1831                 int bytes = (len + 511) & ~511;
1832
1833                 buf = kmalloc(bytes, q->bounce_gfp | GFP_USER);
1834                 if (!buf) {
1835                         ret = -ENOMEM;
1836                         goto fault;
1837                 }
1838
1839                 if (rw == WRITE) {
1840                         if (copy_from_user(buf, ubuf, len)) {
1841                                 ret = -EFAULT;
1842                                 goto fault;
1843                         }
1844                 } else
1845                         memset(buf, 0, len);
1846         }
1847
1848         rq->bio = rq->biotail = bio;
1849         if (rq->bio)
1850                 blk_rq_bio_prep(q, rq, bio);
1851
1852         rq->buffer = rq->data = buf;
1853         rq->data_len = len;
1854         return rq;
1855 fault:
1856         if (buf)
1857                 kfree(buf);
1858         if (bio)
1859                 bio_unmap_user(bio, 1);
1860         if (rq)
1861                 blk_put_request(rq);
1862
1863         return ERR_PTR(ret);
1864 }
1865
1866 EXPORT_SYMBOL(blk_rq_map_user);
1867
1868 /**
1869  * blk_rq_unmap_user - unmap a request with user data
1870  * @rq:         request to be unmapped
1871  * @ubuf:       user buffer
1872  * @ulen:       length of user buffer
1873  *
1874  * Description:
1875  *    Unmap a request previously mapped by blk_rq_map_user().
1876  */
1877 int blk_rq_unmap_user(struct request *rq, void __user *ubuf, struct bio *bio,
1878                       unsigned int ulen)
1879 {
1880         const int read = rq_data_dir(rq) == READ;
1881         int ret = 0;
1882
1883         if (bio)
1884                 bio_unmap_user(bio, read);
1885         if (rq->buffer) {
1886                 if (read && copy_to_user(ubuf, rq->buffer, ulen))
1887                         ret = -EFAULT;
1888                 kfree(rq->buffer);
1889         }
1890
1891         blk_put_request(rq);
1892         return ret;
1893 }
1894
1895 EXPORT_SYMBOL(blk_rq_unmap_user);
1896
1897 /**
1898  * blk_execute_rq - insert a request into queue for execution
1899  * @q:          queue to insert the request in
1900  * @bd_disk:    matching gendisk
1901  * @rq:         request to insert
1902  *
1903  * Description:
1904  *    Insert a fully prepared request at the back of the io scheduler queue
1905  *    for execution.
1906  */
1907 int blk_execute_rq(request_queue_t *q, struct gendisk *bd_disk,
1908                    struct request *rq)
1909 {
1910         DECLARE_COMPLETION(wait);
1911         char sense[SCSI_SENSE_BUFFERSIZE];
1912         int err = 0;
1913
1914         rq->rq_disk = bd_disk;
1915
1916         /*
1917          * we need an extra reference to the request, so we can look at
1918          * it after io completion
1919          */
1920         rq->ref_count++;
1921
1922         if (!rq->sense) {
1923                 memset(sense, 0, sizeof(sense));
1924                 rq->sense = sense;
1925                 rq->sense_len = 0;
1926         }
1927
1928         rq->flags |= REQ_NOMERGE;
1929         rq->waiting = &wait;
1930         elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 1);
1931         generic_unplug_device(q);
1932         wait_for_completion(&wait);
1933         rq->waiting = NULL;
1934
1935         if (rq->errors)
1936                 err = -EIO;
1937
1938         return err;
1939 }
1940
1941 EXPORT_SYMBOL(blk_execute_rq);
1942
1943 void drive_stat_acct(struct request *rq, int nr_sectors, int new_io)
1944 {
1945         int rw = rq_data_dir(rq);
1946
1947         if (!blk_fs_request(rq) || !rq->rq_disk)
1948                 return;
1949
1950         if (rw == READ) {
1951                 disk_stat_add(rq->rq_disk, read_sectors, nr_sectors);
1952                 if (!new_io)
1953                         disk_stat_inc(rq->rq_disk, read_merges);
1954         } else if (rw == WRITE) {
1955                 disk_stat_add(rq->rq_disk, write_sectors, nr_sectors);
1956                 if (!new_io)
1957                         disk_stat_inc(rq->rq_disk, write_merges);
1958         }
1959         if (new_io) {
1960                 disk_round_stats(rq->rq_disk);
1961                 rq->rq_disk->in_flight++;
1962         }
1963 }
1964
1965 /*
1966  * add-request adds a request to the linked list.
1967  * queue lock is held and interrupts disabled, as we muck with the
1968  * request queue list.
1969  */
1970 static inline void add_request(request_queue_t * q, struct request * req)
1971 {
1972         drive_stat_acct(req, req->nr_sectors, 1);
1973
1974         if (q->activity_fn)
1975                 q->activity_fn(q->activity_data, rq_data_dir(req));
1976
1977         /*
1978          * elevator indicated where it wants this request to be
1979          * inserted at elevator_merge time
1980          */
1981         __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1982 }
1983  
1984 /*
1985  * disk_round_stats()   - Round off the performance stats on a struct
1986  * disk_stats.
1987  *
1988  * The average IO queue length and utilisation statistics are maintained
1989  * by observing the current state of the queue length and the amount of
1990  * time it has been in this state for.
1991  *
1992  * Normally, that accounting is done on IO completion, but that can result
1993  * in more than a second's worth of IO being accounted for within any one
1994  * second, leading to >100% utilisation.  To deal with that, we call this
1995  * function to do a round-off before returning the results when reading
1996  * /proc/diskstats.  This accounts immediately for all queue usage up to
1997  * the current jiffies and restarts the counters again.
1998  */
1999 void disk_round_stats(struct gendisk *disk)
2000 {
2001         unsigned long now = jiffies;
2002
2003         disk_stat_add(disk, time_in_queue, 
2004                         disk->in_flight * (now - disk->stamp));
2005         disk->stamp = now;
2006
2007         if (disk->in_flight)
2008                 disk_stat_add(disk, io_ticks, (now - disk->stamp_idle));
2009         disk->stamp_idle = now;
2010 }
2011
2012 /*
2013  * queue lock must be held
2014  */
2015 void __blk_put_request(request_queue_t *q, struct request *req)
2016 {
2017         struct request_list *rl = req->rl;
2018
2019         if (unlikely(!q))
2020                 return;
2021         if (unlikely(--req->ref_count))
2022                 return;
2023
2024         req->rq_status = RQ_INACTIVE;
2025         req->q = NULL;
2026         req->rl = NULL;
2027
2028         /*
2029          * Request may not have originated from ll_rw_blk. if not,
2030          * it didn't come out of our reserved rq pools
2031          */
2032         if (rl) {
2033                 int rw = rq_data_dir(req);
2034
2035                 elv_completed_request(q, req);
2036
2037                 BUG_ON(!list_empty(&req->queuelist));
2038
2039                 blk_free_request(q, req);
2040                 freed_request(q, rw);
2041         }
2042 }
2043
2044 void blk_put_request(struct request *req)
2045 {
2046         /*
2047          * if req->rl isn't set, this request didnt originate from the
2048          * block layer, so it's safe to just disregard it
2049          */
2050         if (req->rl) {
2051                 unsigned long flags;
2052                 request_queue_t *q = req->q;
2053
2054                 spin_lock_irqsave(q->queue_lock, flags);
2055                 __blk_put_request(q, req);
2056                 spin_unlock_irqrestore(q->queue_lock, flags);
2057         }
2058 }
2059
2060 EXPORT_SYMBOL(blk_put_request);
2061
2062 /**
2063  * blk_congestion_wait - wait for a queue to become uncongested
2064  * @rw: READ or WRITE
2065  * @timeout: timeout in jiffies
2066  *
2067  * Waits for up to @timeout jiffies for a queue (any queue) to exit congestion.
2068  * If no queues are congested then just wait for the next request to be
2069  * returned.
2070  */
2071 long blk_congestion_wait(int rw, long timeout)
2072 {
2073         long ret;
2074         DEFINE_WAIT(wait);
2075         wait_queue_head_t *wqh = &congestion_wqh[rw];
2076
2077         prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
2078         ret = io_schedule_timeout(timeout);
2079         finish_wait(wqh, &wait);
2080         return ret;
2081 }
2082
2083 EXPORT_SYMBOL(blk_congestion_wait);
2084
2085 /*
2086  * Has to be called with the request spinlock acquired
2087  */
2088 static int attempt_merge(request_queue_t *q, struct request *req,
2089                           struct request *next)
2090 {
2091         if (!rq_mergeable(req) || !rq_mergeable(next))
2092                 return 0;
2093
2094         /*
2095          * not contigious
2096          */
2097         if (req->sector + req->nr_sectors != next->sector)
2098                 return 0;
2099
2100         if (rq_data_dir(req) != rq_data_dir(next)
2101             || req->rq_disk != next->rq_disk
2102             || next->waiting || next->special)
2103                 return 0;
2104
2105         /*
2106          * If we are allowed to merge, then append bio list
2107          * from next to rq and release next. merge_requests_fn
2108          * will have updated segment counts, update sector
2109          * counts here.
2110          */
2111         if (!q->merge_requests_fn(q, req, next))
2112                 return 0;
2113
2114         /*
2115          * At this point we have either done a back merge
2116          * or front merge. We need the smaller start_time of
2117          * the merged requests to be the current request
2118          * for accounting purposes.
2119          */
2120         if (time_after(req->start_time, next->start_time))
2121                 req->start_time = next->start_time;
2122
2123         req->biotail->bi_next = next->bio;
2124         req->biotail = next->biotail;
2125
2126         req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
2127
2128         elv_merge_requests(q, req, next);
2129
2130         if (req->rq_disk) {
2131                 disk_round_stats(req->rq_disk);
2132                 req->rq_disk->in_flight--;
2133         }
2134
2135         __blk_put_request(q, next);
2136         return 1;
2137 }
2138
2139 static inline int attempt_back_merge(request_queue_t *q, struct request *rq)
2140 {
2141         struct request *next = elv_latter_request(q, rq);
2142
2143         if (next)
2144                 return attempt_merge(q, rq, next);
2145
2146         return 0;
2147 }
2148
2149 static inline int attempt_front_merge(request_queue_t *q, struct request *rq)
2150 {
2151         struct request *prev = elv_former_request(q, rq);
2152
2153         if (prev)
2154                 return attempt_merge(q, prev, rq);
2155
2156         return 0;
2157 }
2158
2159 /**
2160  * blk_attempt_remerge  - attempt to remerge active head with next request
2161  * @q:    The &request_queue_t belonging to the device
2162  * @rq:   The head request (usually)
2163  *
2164  * Description:
2165  *    For head-active devices, the queue can easily be unplugged so quickly
2166  *    that proper merging is not done on the front request. This may hurt
2167  *    performance greatly for some devices. The block layer cannot safely
2168  *    do merging on that first request for these queues, but the driver can
2169  *    call this function and make it happen any way. Only the driver knows
2170  *    when it is safe to do so.
2171  **/
2172 void blk_attempt_remerge(request_queue_t *q, struct request *rq)
2173 {
2174         unsigned long flags;
2175
2176         spin_lock_irqsave(q->queue_lock, flags);
2177         attempt_back_merge(q, rq);
2178         spin_unlock_irqrestore(q->queue_lock, flags);
2179 }
2180
2181 EXPORT_SYMBOL(blk_attempt_remerge);
2182
2183 /*
2184  * Non-locking blk_attempt_remerge variant.
2185  */
2186 void __blk_attempt_remerge(request_queue_t *q, struct request *rq)
2187 {
2188         attempt_back_merge(q, rq);
2189 }
2190
2191 EXPORT_SYMBOL(__blk_attempt_remerge);
2192
2193 static int __make_request(request_queue_t *q, struct bio *bio)
2194 {
2195         struct request *req, *freereq = NULL;
2196         int el_ret, rw, nr_sectors, cur_nr_sectors, barrier, ra;
2197         sector_t sector;
2198
2199         sector = bio->bi_sector;
2200         nr_sectors = bio_sectors(bio);
2201         cur_nr_sectors = bio_cur_sectors(bio);
2202
2203         rw = bio_data_dir(bio);
2204
2205         /*
2206          * low level driver can indicate that it wants pages above a
2207          * certain limit bounced to low memory (ie for highmem, or even
2208          * ISA dma in theory)
2209          */
2210         blk_queue_bounce(q, &bio);
2211
2212         spin_lock_prefetch(q->queue_lock);
2213
2214         barrier = test_bit(BIO_RW_BARRIER, &bio->bi_rw);
2215
2216         ra = bio->bi_rw & (1 << BIO_RW_AHEAD);
2217
2218 again:
2219         spin_lock_irq(q->queue_lock);
2220
2221         if (elv_queue_empty(q)) {
2222                 blk_plug_device(q);
2223                 goto get_rq;
2224         }
2225         if (barrier)
2226                 goto get_rq;
2227
2228         el_ret = elv_merge(q, &req, bio);
2229         switch (el_ret) {
2230                 case ELEVATOR_BACK_MERGE:
2231                         BUG_ON(!rq_mergeable(req));
2232
2233                         if (!q->back_merge_fn(q, req, bio))
2234                                 break;
2235
2236                         req->biotail->bi_next = bio;
2237                         req->biotail = bio;
2238                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2239                         drive_stat_acct(req, nr_sectors, 0);
2240                         if (!attempt_back_merge(q, req))
2241                                 elv_merged_request(q, req);
2242                         goto out;
2243
2244                 case ELEVATOR_FRONT_MERGE:
2245                         BUG_ON(!rq_mergeable(req));
2246
2247                         if (!q->front_merge_fn(q, req, bio))
2248                                 break;
2249
2250                         bio->bi_next = req->bio;
2251                         req->cbio = req->bio = bio;
2252                         req->nr_cbio_segments = bio_segments(bio);
2253                         req->nr_cbio_sectors = bio_sectors(bio);
2254
2255                         /*
2256                          * may not be valid. if the low level driver said
2257                          * it didn't need a bounce buffer then it better
2258                          * not touch req->buffer either...
2259                          */
2260                         req->buffer = bio_data(bio);
2261                         req->current_nr_sectors = cur_nr_sectors;
2262                         req->hard_cur_sectors = cur_nr_sectors;
2263                         req->sector = req->hard_sector = sector;
2264                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
2265                         drive_stat_acct(req, nr_sectors, 0);
2266                         if (!attempt_front_merge(q, req))
2267                                 elv_merged_request(q, req);
2268                         goto out;
2269
2270                 /*
2271                  * elevator says don't/can't merge. get new request
2272                  */
2273                 case ELEVATOR_NO_MERGE:
2274                         break;
2275
2276                 default:
2277                         printk("elevator returned crap (%d)\n", el_ret);
2278                         BUG();
2279         }
2280
2281         /*
2282          * Grab a free request from the freelist - if that is empty, check
2283          * if we are doing read ahead and abort instead of blocking for
2284          * a free slot.
2285          */
2286 get_rq:
2287         if (freereq) {
2288                 req = freereq;
2289                 freereq = NULL;
2290         } else {
2291                 spin_unlock_irq(q->queue_lock);
2292                 if ((freereq = get_request(q, rw, GFP_ATOMIC)) == NULL) {
2293                         /*
2294                          * READA bit set
2295                          */
2296                         if (ra)
2297                                 goto end_io;
2298         
2299                         freereq = get_request_wait(q, rw);
2300                 }
2301                 goto again;
2302         }
2303
2304         req->flags |= REQ_CMD;
2305
2306         /*
2307          * inherit FAILFAST from bio and don't stack up
2308          * retries for read ahead
2309          */
2310         if (ra || test_bit(BIO_RW_FAILFAST, &bio->bi_rw))       
2311                 req->flags |= REQ_FAILFAST;
2312
2313         /*
2314          * REQ_BARRIER implies no merging, but lets make it explicit
2315          */
2316         if (barrier)
2317                 req->flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
2318
2319         req->errors = 0;
2320         req->hard_sector = req->sector = sector;
2321         req->hard_nr_sectors = req->nr_sectors = nr_sectors;
2322         req->current_nr_sectors = req->hard_cur_sectors = cur_nr_sectors;
2323         req->nr_phys_segments = bio_phys_segments(q, bio);
2324         req->nr_hw_segments = bio_hw_segments(q, bio);
2325         req->nr_cbio_segments = bio_segments(bio);
2326         req->nr_cbio_sectors = bio_sectors(bio);
2327         req->buffer = bio_data(bio);    /* see ->buffer comment above */
2328         req->waiting = NULL;
2329         req->cbio = req->bio = req->biotail = bio;
2330         req->rq_disk = bio->bi_bdev->bd_disk;
2331         req->start_time = jiffies;
2332
2333         add_request(q, req);
2334 out:
2335         if (freereq)
2336                 __blk_put_request(q, freereq);
2337         if (bio_sync(bio))
2338                 __generic_unplug_device(q);
2339
2340         spin_unlock_irq(q->queue_lock);
2341         return 0;
2342
2343 end_io:
2344         bio_endio(bio, nr_sectors << 9, -EWOULDBLOCK);
2345         return 0;
2346 }
2347
2348 /*
2349  * If bio->bi_dev is a partition, remap the location
2350  */
2351 static inline void blk_partition_remap(struct bio *bio)
2352 {
2353         struct block_device *bdev = bio->bi_bdev;
2354
2355         if (bdev != bdev->bd_contains) {
2356                 struct hd_struct *p = bdev->bd_part;
2357
2358                 switch (bio->bi_rw) {
2359                 case READ:
2360                         p->read_sectors += bio_sectors(bio);
2361                         p->reads++;
2362                         break;
2363                 case WRITE:
2364                         p->write_sectors += bio_sectors(bio);
2365                         p->writes++;
2366                         break;
2367                 }
2368                 bio->bi_sector += p->start_sect;
2369                 bio->bi_bdev = bdev->bd_contains;
2370         }
2371 }
2372
2373 /**
2374  * generic_make_request: hand a buffer to its device driver for I/O
2375  * @bio:  The bio describing the location in memory and on the device.
2376  *
2377  * generic_make_request() is used to make I/O requests of block
2378  * devices. It is passed a &struct bio, which describes the I/O that needs
2379  * to be done.
2380  *
2381  * generic_make_request() does not return any status.  The
2382  * success/failure status of the request, along with notification of
2383  * completion, is delivered asynchronously through the bio->bi_end_io
2384  * function described (one day) else where.
2385  *
2386  * The caller of generic_make_request must make sure that bi_io_vec
2387  * are set to describe the memory buffer, and that bi_dev and bi_sector are
2388  * set to describe the device address, and the
2389  * bi_end_io and optionally bi_private are set to describe how
2390  * completion notification should be signaled.
2391  *
2392  * generic_make_request and the drivers it calls may use bi_next if this
2393  * bio happens to be merged with someone else, and may change bi_dev and
2394  * bi_sector for remaps as it sees fit.  So the values of these fields
2395  * should NOT be depended on after the call to generic_make_request.
2396  */
2397 void generic_make_request(struct bio *bio)
2398 {
2399         request_queue_t *q;
2400         sector_t maxsector;
2401         int ret, nr_sectors = bio_sectors(bio);
2402
2403         might_sleep();
2404         /* Test device or partition size, when known. */
2405         maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
2406         if (maxsector) {
2407                 sector_t sector = bio->bi_sector;
2408
2409                 if (maxsector < nr_sectors ||
2410                     maxsector - nr_sectors < sector) {
2411                         char b[BDEVNAME_SIZE];
2412                         /* This may well happen - the kernel calls
2413                          * bread() without checking the size of the
2414                          * device, e.g., when mounting a device. */
2415                         printk(KERN_INFO
2416                                "attempt to access beyond end of device\n");
2417                         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
2418                                bdevname(bio->bi_bdev, b),
2419                                bio->bi_rw,
2420                                (unsigned long long) sector + nr_sectors,
2421                                (long long) maxsector);
2422
2423                         set_bit(BIO_EOF, &bio->bi_flags);
2424                         goto end_io;
2425                 }
2426         }
2427
2428         /*
2429          * Resolve the mapping until finished. (drivers are
2430          * still free to implement/resolve their own stacking
2431          * by explicitly returning 0)
2432          *
2433          * NOTE: we don't repeat the blk_size check for each new device.
2434          * Stacking drivers are expected to know what they are doing.
2435          */
2436         do {
2437                 char b[BDEVNAME_SIZE];
2438
2439                 q = bdev_get_queue(bio->bi_bdev);
2440                 if (!q) {
2441                         printk(KERN_ERR
2442                                "generic_make_request: Trying to access "
2443                                 "nonexistent block-device %s (%Lu)\n",
2444                                 bdevname(bio->bi_bdev, b),
2445                                 (long long) bio->bi_sector);
2446 end_io:
2447                         bio_endio(bio, bio->bi_size, -EIO);
2448                         break;
2449                 }
2450
2451                 if (unlikely(bio_sectors(bio) > q->max_sectors)) {
2452                         printk("bio too big device %s (%u > %u)\n", 
2453                                 bdevname(bio->bi_bdev, b),
2454                                 bio_sectors(bio),
2455                                 q->max_sectors);
2456                         goto end_io;
2457                 }
2458
2459                 if (test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))
2460                         goto end_io;
2461
2462                 /*
2463                  * If this device has partitions, remap block n
2464                  * of partition p to block n+start(p) of the disk.
2465                  */
2466                 blk_partition_remap(bio);
2467
2468                 ret = q->make_request_fn(q, bio);
2469         } while (ret);
2470 }
2471
2472 EXPORT_SYMBOL(generic_make_request);
2473
2474 /**
2475  * submit_bio: submit a bio to the block device layer for I/O
2476  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2477  * @bio: The &struct bio which describes the I/O
2478  *
2479  * submit_bio() is very similar in purpose to generic_make_request(), and
2480  * uses that function to do most of the work. Both are fairly rough
2481  * interfaces, @bio must be presetup and ready for I/O.
2482  *
2483  */
2484 void submit_bio(int rw, struct bio *bio)
2485 {
2486         int count = bio_sectors(bio);
2487
2488         BIO_BUG_ON(!bio->bi_size);
2489         BIO_BUG_ON(!bio->bi_io_vec);
2490         bio->bi_rw = rw;
2491         if (rw & WRITE)
2492                 mod_page_state(pgpgout, count);
2493         else
2494                 mod_page_state(pgpgin, count);
2495
2496         if (unlikely(block_dump)) {
2497                 char b[BDEVNAME_SIZE];
2498                 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
2499                         current->comm, current->pid,
2500                         (rw & WRITE) ? "WRITE" : "READ",
2501                         (unsigned long long)bio->bi_sector,
2502                         bdevname(bio->bi_bdev,b));
2503         }
2504
2505         generic_make_request(bio);
2506 }
2507
2508 EXPORT_SYMBOL(submit_bio);
2509
2510 /**
2511  * blk_rq_next_segment
2512  * @rq:         the request being processed
2513  *
2514  * Description:
2515  *      Points to the next segment in the request if the current segment
2516  *      is complete. Leaves things unchanged if this segment is not over
2517  *      or if no more segments are left in this request.
2518  *
2519  *      Meant to be used for bio traversal during I/O submission
2520  *      Does not affect any I/O completions or update completion state
2521  *      in the request, and does not modify any bio fields.
2522  *
2523  *      Decrementing rq->nr_sectors, rq->current_nr_sectors and
2524  *      rq->nr_cbio_sectors as data is transferred is the caller's
2525  *      responsibility and should be done before calling this routine.
2526  **/
2527 void blk_rq_next_segment(struct request *rq)
2528 {
2529         if (rq->current_nr_sectors > 0)
2530                 return;
2531
2532         if (rq->nr_cbio_sectors > 0) {
2533                 --rq->nr_cbio_segments;
2534                 rq->current_nr_sectors = blk_rq_vec(rq)->bv_len >> 9;
2535         } else {
2536                 if ((rq->cbio = rq->cbio->bi_next)) {
2537                         rq->nr_cbio_segments = bio_segments(rq->cbio);
2538                         rq->nr_cbio_sectors = bio_sectors(rq->cbio);
2539                         rq->current_nr_sectors = bio_cur_sectors(rq->cbio);
2540                 }
2541         }
2542
2543         /* remember the size of this segment before we start I/O */
2544         rq->hard_cur_sectors = rq->current_nr_sectors;
2545 }
2546
2547 /**
2548  * process_that_request_first   -       process partial request submission
2549  * @req:        the request being processed
2550  * @nr_sectors: number of sectors I/O has been submitted on
2551  *
2552  * Description:
2553  *      May be used for processing bio's while submitting I/O without
2554  *      signalling completion. Fails if more data is requested than is
2555  *      available in the request in which case it doesn't advance any
2556  *      pointers.
2557  *
2558  *      Assumes a request is correctly set up. No sanity checks.
2559  *
2560  * Return:
2561  *      0 - no more data left to submit (not processed)
2562  *      1 - data available to submit for this request (processed)
2563  **/
2564 int process_that_request_first(struct request *req, unsigned int nr_sectors)
2565 {
2566         unsigned int nsect;
2567
2568         if (req->nr_sectors < nr_sectors)
2569                 return 0;
2570
2571         req->nr_sectors -= nr_sectors;
2572         req->sector += nr_sectors;
2573         while (nr_sectors) {
2574                 nsect = min_t(unsigned, req->current_nr_sectors, nr_sectors);
2575                 req->current_nr_sectors -= nsect;
2576                 nr_sectors -= nsect;
2577                 if (req->cbio) {
2578                         req->nr_cbio_sectors -= nsect;
2579                         blk_rq_next_segment(req);
2580                 }
2581         }
2582         return 1;
2583 }
2584
2585 EXPORT_SYMBOL(process_that_request_first);
2586
2587 void blk_recalc_rq_segments(struct request *rq)
2588 {
2589         struct bio *bio, *prevbio = NULL;
2590         int nr_phys_segs, nr_hw_segs;
2591
2592         if (!rq->bio)
2593                 return;
2594
2595         nr_phys_segs = nr_hw_segs = 0;
2596         rq_for_each_bio(bio, rq) {
2597                 /* Force bio hw/phys segs to be recalculated. */
2598                 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
2599
2600                 nr_phys_segs += bio_phys_segments(rq->q, bio);
2601                 nr_hw_segs += bio_hw_segments(rq->q, bio);
2602                 if (prevbio) {
2603                         if (blk_phys_contig_segment(rq->q, prevbio, bio))
2604                                 nr_phys_segs--;
2605                         if (blk_hw_contig_segment(rq->q, prevbio, bio))
2606                                 nr_hw_segs--;
2607                 }
2608                 prevbio = bio;
2609         }
2610
2611         rq->nr_phys_segments = nr_phys_segs;
2612         rq->nr_hw_segments = nr_hw_segs;
2613 }
2614
2615 void blk_recalc_rq_sectors(struct request *rq, int nsect)
2616 {
2617         if (blk_fs_request(rq)) {
2618                 rq->hard_sector += nsect;
2619                 rq->hard_nr_sectors -= nsect;
2620
2621                 /*
2622                  * Move the I/O submission pointers ahead if required,
2623                  * i.e. for drivers not aware of rq->cbio.
2624                  */
2625                 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
2626                     (rq->sector <= rq->hard_sector)) {
2627                         rq->sector = rq->hard_sector;
2628                         rq->nr_sectors = rq->hard_nr_sectors;
2629                         rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
2630                         rq->current_nr_sectors = rq->hard_cur_sectors;
2631                         rq->nr_cbio_segments = bio_segments(rq->bio);
2632                         rq->nr_cbio_sectors = bio_sectors(rq->bio);
2633                         rq->buffer = bio_data(rq->bio);
2634
2635                         rq->cbio = rq->bio;
2636                 }
2637
2638                 /*
2639                  * if total number of sectors is less than the first segment
2640                  * size, something has gone terribly wrong
2641                  */
2642                 if (rq->nr_sectors < rq->current_nr_sectors) {
2643                         printk("blk: request botched\n");
2644                         rq->nr_sectors = rq->current_nr_sectors;
2645                 }
2646         }
2647 }
2648
2649 static int __end_that_request_first(struct request *req, int uptodate,
2650                                     int nr_bytes)
2651 {
2652         int total_bytes, bio_nbytes, error = 0, next_idx = 0;
2653         struct bio *bio;
2654
2655         /*
2656          * for a REQ_BLOCK_PC request, we want to carry any eventual
2657          * sense key with us all the way through
2658          */
2659         if (!blk_pc_request(req))
2660                 req->errors = 0;
2661
2662         if (!uptodate) {
2663                 error = -EIO;
2664                 if (blk_fs_request(req) && !(req->flags & REQ_QUIET))
2665                         printk("end_request: I/O error, dev %s, sector %llu\n",
2666                                 req->rq_disk ? req->rq_disk->disk_name : "?",
2667                                 (unsigned long long)req->sector);
2668         }
2669
2670         total_bytes = bio_nbytes = 0;
2671         while ((bio = req->bio) != NULL) {
2672                 int nbytes;
2673
2674                 if (nr_bytes >= bio->bi_size) {
2675                         req->bio = bio->bi_next;
2676                         nbytes = bio->bi_size;
2677                         bio_endio(bio, nbytes, error);
2678                         next_idx = 0;
2679                         bio_nbytes = 0;
2680                 } else {
2681                         int idx = bio->bi_idx + next_idx;
2682
2683                         if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
2684                                 blk_dump_rq_flags(req, "__end_that");
2685                                 printk("%s: bio idx %d >= vcnt %d\n",
2686                                                 __FUNCTION__,
2687                                                 bio->bi_idx, bio->bi_vcnt);
2688                                 break;
2689                         }
2690
2691                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
2692                         BIO_BUG_ON(nbytes > bio->bi_size);
2693
2694                         /*
2695                          * not a complete bvec done
2696                          */
2697                         if (unlikely(nbytes > nr_bytes)) {
2698                                 bio_nbytes += nr_bytes;
2699                                 total_bytes += nr_bytes;
2700                                 break;
2701                         }
2702
2703                         /*
2704                          * advance to the next vector
2705                          */
2706                         next_idx++;
2707                         bio_nbytes += nbytes;
2708                 }
2709
2710                 total_bytes += nbytes;
2711                 nr_bytes -= nbytes;
2712
2713                 if ((bio = req->bio)) {
2714                         /*
2715                          * end more in this run, or just return 'not-done'
2716                          */
2717                         if (unlikely(nr_bytes <= 0))
2718                                 break;
2719                 }
2720         }
2721
2722         /*
2723          * completely done
2724          */
2725         if (!req->bio)
2726                 return 0;
2727
2728         /*
2729          * if the request wasn't completed, update state
2730          */
2731         if (bio_nbytes) {
2732                 bio_endio(bio, bio_nbytes, error);
2733                 bio->bi_idx += next_idx;
2734                 bio_iovec(bio)->bv_offset += nr_bytes;
2735                 bio_iovec(bio)->bv_len -= nr_bytes;
2736         }
2737
2738         blk_recalc_rq_sectors(req, total_bytes >> 9);
2739         blk_recalc_rq_segments(req);
2740         return 1;
2741 }
2742
2743 /**
2744  * end_that_request_first - end I/O on a request
2745  * @req:      the request being processed
2746  * @uptodate: 0 for I/O error
2747  * @nr_sectors: number of sectors to end I/O on
2748  *
2749  * Description:
2750  *     Ends I/O on a number of sectors attached to @req, and sets it up
2751  *     for the next range of segments (if any) in the cluster.
2752  *
2753  * Return:
2754  *     0 - we are done with this request, call end_that_request_last()
2755  *     1 - still buffers pending for this request
2756  **/
2757 int end_that_request_first(struct request *req, int uptodate, int nr_sectors)
2758 {
2759         return __end_that_request_first(req, uptodate, nr_sectors << 9);
2760 }
2761
2762 EXPORT_SYMBOL(end_that_request_first);
2763
2764 /**
2765  * end_that_request_chunk - end I/O on a request
2766  * @req:      the request being processed
2767  * @uptodate: 0 for I/O error
2768  * @nr_bytes: number of bytes to complete
2769  *
2770  * Description:
2771  *     Ends I/O on a number of bytes attached to @req, and sets it up
2772  *     for the next range of segments (if any). Like end_that_request_first(),
2773  *     but deals with bytes instead of sectors.
2774  *
2775  * Return:
2776  *     0 - we are done with this request, call end_that_request_last()
2777  *     1 - still buffers pending for this request
2778  **/
2779 int end_that_request_chunk(struct request *req, int uptodate, int nr_bytes)
2780 {
2781         return __end_that_request_first(req, uptodate, nr_bytes);
2782 }
2783
2784 EXPORT_SYMBOL(end_that_request_chunk);
2785
2786 /*
2787  * queue lock must be held
2788  */
2789 void end_that_request_last(struct request *req)
2790 {
2791         struct gendisk *disk = req->rq_disk;
2792         struct completion *waiting = req->waiting;
2793
2794         if (unlikely(laptop_mode) && blk_fs_request(req))
2795                 laptop_io_completion();
2796
2797         if (disk && blk_fs_request(req)) {
2798                 unsigned long duration = jiffies - req->start_time;
2799                 switch (rq_data_dir(req)) {
2800                     case WRITE:
2801                         disk_stat_inc(disk, writes);
2802                         disk_stat_add(disk, write_ticks, duration);
2803                         break;
2804                     case READ:
2805                         disk_stat_inc(disk, reads);
2806                         disk_stat_add(disk, read_ticks, duration);
2807                         break;
2808                 }
2809                 disk_round_stats(disk);
2810                 disk->in_flight--;
2811         }
2812         __blk_put_request(req->q, req);
2813         /* Do this LAST! The structure may be freed immediately afterwards */
2814         if (waiting)
2815                 complete(waiting);
2816 }
2817
2818 EXPORT_SYMBOL(end_that_request_last);
2819
2820 void end_request(struct request *req, int uptodate)
2821 {
2822         if (!end_that_request_first(req, uptodate, req->hard_cur_sectors)) {
2823                 add_disk_randomness(req->rq_disk);
2824                 blkdev_dequeue_request(req);
2825                 end_that_request_last(req);
2826         }
2827 }
2828
2829 EXPORT_SYMBOL(end_request);
2830
2831 void blk_rq_bio_prep(request_queue_t *q, struct request *rq, struct bio *bio)
2832 {
2833         /* first three bits are identical in rq->flags and bio->bi_rw */
2834         rq->flags |= (bio->bi_rw & 7);
2835
2836         rq->nr_phys_segments = bio_phys_segments(q, bio);
2837         rq->nr_hw_segments = bio_hw_segments(q, bio);
2838         rq->current_nr_sectors = bio_cur_sectors(bio);
2839         rq->hard_cur_sectors = rq->current_nr_sectors;
2840         rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
2841         rq->nr_cbio_segments = bio_segments(bio);
2842         rq->nr_cbio_sectors = bio_sectors(bio);
2843         rq->buffer = bio_data(bio);
2844
2845         rq->cbio = rq->bio = rq->biotail = bio;
2846 }
2847
2848 EXPORT_SYMBOL(blk_rq_bio_prep);
2849
2850 void blk_rq_prep_restart(struct request *rq)
2851 {
2852         struct bio *bio;
2853
2854         bio = rq->cbio = rq->bio;
2855         if (bio) {
2856                 rq->nr_cbio_segments = bio_segments(bio);
2857                 rq->nr_cbio_sectors = bio_sectors(bio);
2858                 rq->hard_cur_sectors = bio_cur_sectors(bio);
2859                 rq->buffer = bio_data(bio);
2860         }
2861         rq->sector = rq->hard_sector;
2862         rq->nr_sectors = rq->hard_nr_sectors;
2863         rq->current_nr_sectors = rq->hard_cur_sectors;
2864 }
2865
2866 EXPORT_SYMBOL(blk_rq_prep_restart);
2867
2868 int kblockd_schedule_work(struct work_struct *work)
2869 {
2870         return queue_work(kblockd_workqueue, work);
2871 }
2872
2873 void kblockd_flush(void)
2874 {
2875         flush_workqueue(kblockd_workqueue);
2876 }
2877
2878 int __init blk_dev_init(void)
2879 {
2880         kblockd_workqueue = create_workqueue("kblockd");
2881         if (!kblockd_workqueue)
2882                 panic("Failed to create kblockd\n");
2883
2884         request_cachep = kmem_cache_create("blkdev_requests",
2885                         sizeof(struct request), 0, SLAB_PANIC, NULL, NULL);
2886
2887         requestq_cachep = kmem_cache_create("blkdev_queue",
2888                         sizeof(request_queue_t), 0, SLAB_PANIC, NULL, NULL);
2889
2890         iocontext_cachep = kmem_cache_create("blkdev_ioc",
2891                         sizeof(struct io_context), 0, SLAB_PANIC, NULL, NULL);
2892
2893         blk_max_low_pfn = max_low_pfn;
2894         blk_max_pfn = max_pfn;
2895         return 0;
2896 }
2897
2898 /*
2899  * IO Context helper functions
2900  */
2901 void put_io_context(struct io_context *ioc)
2902 {
2903         if (ioc == NULL)
2904                 return;
2905
2906         BUG_ON(atomic_read(&ioc->refcount) == 0);
2907
2908         if (atomic_dec_and_test(&ioc->refcount)) {
2909                 if (ioc->aic && ioc->aic->dtor)
2910                         ioc->aic->dtor(ioc->aic);
2911                 kmem_cache_free(iocontext_cachep, ioc);
2912         }
2913 }
2914
2915 /* Called by the exitting task */
2916 void exit_io_context(void)
2917 {
2918         unsigned long flags;
2919         struct io_context *ioc;
2920
2921         local_irq_save(flags);
2922         ioc = current->io_context;
2923         if (ioc) {
2924                 if (ioc->aic && ioc->aic->exit)
2925                         ioc->aic->exit(ioc->aic);
2926                 put_io_context(ioc);
2927                 current->io_context = NULL;
2928         } else
2929                 WARN_ON(1);
2930         local_irq_restore(flags);
2931 }
2932
2933 /*
2934  * If the current task has no IO context then create one and initialise it.
2935  * If it does have a context, take a ref on it.
2936  *
2937  * This is always called in the context of the task which submitted the I/O.
2938  * But weird things happen, so we disable local interrupts to ensure exclusive
2939  * access to *current.
2940  */
2941 struct io_context *get_io_context(int gfp_flags)
2942 {
2943         struct task_struct *tsk = current;
2944         unsigned long flags;
2945         struct io_context *ret;
2946
2947         local_irq_save(flags);
2948         ret = tsk->io_context;
2949         if (ret == NULL) {
2950                 ret = kmem_cache_alloc(iocontext_cachep, GFP_ATOMIC);
2951                 if (ret) {
2952                         atomic_set(&ret->refcount, 1);
2953                         ret->pid = tsk->pid;
2954                         ret->last_waited = jiffies; /* doesn't matter... */
2955                         ret->nr_batch_requests = 0; /* because this is 0 */
2956                         ret->aic = NULL;
2957                         tsk->io_context = ret;
2958                 }
2959         }
2960         if (ret)
2961                 atomic_inc(&ret->refcount);
2962         local_irq_restore(flags);
2963         return ret;
2964 }
2965
2966 void copy_io_context(struct io_context **pdst, struct io_context **psrc)
2967 {
2968         struct io_context *src = *psrc;
2969         struct io_context *dst = *pdst;
2970
2971         if (src) {
2972                 BUG_ON(atomic_read(&src->refcount) == 0);
2973                 atomic_inc(&src->refcount);
2974                 put_io_context(dst);
2975                 *pdst = src;
2976         }
2977 }
2978
2979 void swap_io_context(struct io_context **ioc1, struct io_context **ioc2)
2980 {
2981         struct io_context *temp;
2982         temp = *ioc1;
2983         *ioc1 = *ioc2;
2984         *ioc2 = temp;
2985 }
2986
2987
2988 /*
2989  * sysfs parts below
2990  */
2991 struct queue_sysfs_entry {
2992         struct attribute attr;
2993         ssize_t (*show)(struct request_queue *, char *);
2994         ssize_t (*store)(struct request_queue *, const char *, size_t);
2995 };
2996
2997 static ssize_t
2998 queue_var_show(unsigned int var, char *page)
2999 {
3000         return sprintf(page, "%d\n", var);
3001 }
3002
3003 static ssize_t
3004 queue_var_store(unsigned long *var, const char *page, size_t count)
3005 {
3006         char *p = (char *) page;
3007
3008         *var = simple_strtoul(p, &p, 10);
3009         return count;
3010 }
3011
3012 static ssize_t queue_requests_show(struct request_queue *q, char *page)
3013 {
3014         return queue_var_show(q->nr_requests, (page));
3015 }
3016
3017 static ssize_t
3018 queue_requests_store(struct request_queue *q, const char *page, size_t count)
3019 {
3020         struct request_list *rl = &q->rq;
3021
3022         int ret = queue_var_store(&q->nr_requests, page, count);
3023         if (q->nr_requests < BLKDEV_MIN_RQ)
3024                 q->nr_requests = BLKDEV_MIN_RQ;
3025         blk_queue_congestion_threshold(q);
3026
3027         if (rl->count[READ] >= queue_congestion_on_threshold(q))
3028                 set_queue_congested(q, READ);
3029         else if (rl->count[READ] < queue_congestion_off_threshold(q))
3030                 clear_queue_congested(q, READ);
3031
3032         if (rl->count[WRITE] >= queue_congestion_on_threshold(q))
3033                 set_queue_congested(q, WRITE);
3034         else if (rl->count[WRITE] < queue_congestion_off_threshold(q))
3035                 clear_queue_congested(q, WRITE);
3036
3037         if (rl->count[READ] >= q->nr_requests) {
3038                 blk_set_queue_full(q, READ);
3039         } else if (rl->count[READ]+1 <= q->nr_requests) {
3040                 blk_clear_queue_full(q, READ);
3041                 wake_up(&rl->wait[READ]);
3042         }
3043
3044         if (rl->count[WRITE] >= q->nr_requests) {
3045                 blk_set_queue_full(q, WRITE);
3046         } else if (rl->count[WRITE]+1 <= q->nr_requests) {
3047                 blk_clear_queue_full(q, WRITE);
3048                 wake_up(&rl->wait[WRITE]);
3049         }
3050         return ret;
3051 }
3052
3053 static ssize_t queue_ra_show(struct request_queue *q, char *page)
3054 {
3055         int ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10);
3056
3057         return queue_var_show(ra_kb, (page));
3058 }
3059
3060 static ssize_t
3061 queue_ra_store(struct request_queue *q, const char *page, size_t count)
3062 {
3063         unsigned long ra_kb;
3064         ssize_t ret = queue_var_store(&ra_kb, page, count);
3065
3066         if (ra_kb > (q->max_sectors >> 1))
3067                 ra_kb = (q->max_sectors >> 1);
3068
3069         q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10);
3070         return ret;
3071 }
3072
3073 static struct queue_sysfs_entry queue_requests_entry = {
3074         .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR },
3075         .show = queue_requests_show,
3076         .store = queue_requests_store,
3077 };
3078
3079 static struct queue_sysfs_entry queue_ra_entry = {
3080         .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR },
3081         .show = queue_ra_show,
3082         .store = queue_ra_store,
3083 };
3084
3085 static struct attribute *default_attrs[] = {
3086         &queue_requests_entry.attr,
3087         &queue_ra_entry.attr,
3088         NULL,
3089 };
3090
3091 #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr)
3092
3093 static ssize_t
3094 queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3095 {
3096         struct queue_sysfs_entry *entry = to_queue(attr);
3097         struct request_queue *q;
3098
3099         q = container_of(kobj, struct request_queue, kobj);
3100         if (!entry->show)
3101                 return 0;
3102
3103         return entry->show(q, page);
3104 }
3105
3106 static ssize_t
3107 queue_attr_store(struct kobject *kobj, struct attribute *attr,
3108                     const char *page, size_t length)
3109 {
3110         struct queue_sysfs_entry *entry = to_queue(attr);
3111         struct request_queue *q;
3112
3113         q = container_of(kobj, struct request_queue, kobj);
3114         if (!entry->store)
3115                 return -EINVAL;
3116
3117         return entry->store(q, page, length);
3118 }
3119
3120 static struct sysfs_ops queue_sysfs_ops = {
3121         .show   = queue_attr_show,
3122         .store  = queue_attr_store,
3123 };
3124
3125 struct kobj_type queue_ktype = {
3126         .sysfs_ops      = &queue_sysfs_ops,
3127         .default_attrs  = default_attrs,
3128 };
3129
3130 int blk_register_queue(struct gendisk *disk)
3131 {
3132         int ret;
3133
3134         request_queue_t *q = disk->queue;
3135
3136         if (!q || !q->request_fn)
3137                 return -ENXIO;
3138
3139         q->kobj.parent = kobject_get(&disk->kobj);
3140         if (!q->kobj.parent)
3141                 return -EBUSY;
3142
3143         snprintf(q->kobj.name, KOBJ_NAME_LEN, "%s", "queue");
3144         q->kobj.ktype = &queue_ktype;
3145
3146         ret = kobject_register(&q->kobj);
3147         if (ret < 0)
3148                 return ret;
3149
3150         ret = elv_register_queue(q);
3151         if (ret) {
3152                 kobject_unregister(&q->kobj);
3153                 return ret;
3154         }
3155
3156         return 0;
3157 }
3158
3159 void blk_unregister_queue(struct gendisk *disk)
3160 {
3161         request_queue_t *q = disk->queue;
3162
3163         if (q && q->request_fn) {
3164                 elv_unregister_queue(q);
3165
3166                 kobject_unregister(&q->kobj);
3167                 kobject_put(&disk->kobj);
3168         }
3169 }