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