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