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