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