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