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