block: new end request handling interface should take unsigned byte counts
[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/completion.h>
24 #include <linux/slab.h>
25 #include <linux/swap.h>
26 #include <linux/writeback.h>
27 #include <linux/task_io_accounting_ops.h>
28 #include <linux/interrupt.h>
29 #include <linux/cpu.h>
30 #include <linux/blktrace_api.h>
31 #include <linux/fault-inject.h>
32
33 #include "blk.h"
34
35 static int __make_request(struct request_queue *q, struct bio *bio);
36
37 /*
38  * For the allocated request tables
39  */
40 struct kmem_cache *request_cachep;
41
42 /*
43  * For queue allocation
44  */
45 struct kmem_cache *blk_requestq_cachep = NULL;
46
47 /*
48  * Controlling structure to kblockd
49  */
50 static struct workqueue_struct *kblockd_workqueue;
51
52 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
53
54 static void drive_stat_acct(struct request *rq, int new_io)
55 {
56         int rw = rq_data_dir(rq);
57
58         if (!blk_fs_request(rq) || !rq->rq_disk)
59                 return;
60
61         if (!new_io) {
62                 __disk_stat_inc(rq->rq_disk, merges[rw]);
63         } else {
64                 disk_round_stats(rq->rq_disk);
65                 rq->rq_disk->in_flight++;
66         }
67 }
68
69 void blk_queue_congestion_threshold(struct request_queue *q)
70 {
71         int nr;
72
73         nr = q->nr_requests - (q->nr_requests / 8) + 1;
74         if (nr > q->nr_requests)
75                 nr = q->nr_requests;
76         q->nr_congestion_on = nr;
77
78         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
79         if (nr < 1)
80                 nr = 1;
81         q->nr_congestion_off = nr;
82 }
83
84 /**
85  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
86  * @bdev:       device
87  *
88  * Locates the passed device's request queue and returns the address of its
89  * backing_dev_info
90  *
91  * Will return NULL if the request queue cannot be located.
92  */
93 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
94 {
95         struct backing_dev_info *ret = NULL;
96         struct request_queue *q = bdev_get_queue(bdev);
97
98         if (q)
99                 ret = &q->backing_dev_info;
100         return ret;
101 }
102 EXPORT_SYMBOL(blk_get_backing_dev_info);
103
104 void rq_init(struct request_queue *q, struct request *rq)
105 {
106         INIT_LIST_HEAD(&rq->queuelist);
107         INIT_LIST_HEAD(&rq->donelist);
108
109         rq->errors = 0;
110         rq->bio = rq->biotail = NULL;
111         INIT_HLIST_NODE(&rq->hash);
112         RB_CLEAR_NODE(&rq->rb_node);
113         rq->ioprio = 0;
114         rq->buffer = NULL;
115         rq->ref_count = 1;
116         rq->q = q;
117         rq->special = NULL;
118         rq->data_len = 0;
119         rq->data = NULL;
120         rq->nr_phys_segments = 0;
121         rq->sense = NULL;
122         rq->end_io = NULL;
123         rq->end_io_data = NULL;
124         rq->completion_data = NULL;
125         rq->next_rq = NULL;
126 }
127
128 static void req_bio_endio(struct request *rq, struct bio *bio,
129                           unsigned int nbytes, int error)
130 {
131         struct request_queue *q = rq->q;
132
133         if (&q->bar_rq != rq) {
134                 if (error)
135                         clear_bit(BIO_UPTODATE, &bio->bi_flags);
136                 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
137                         error = -EIO;
138
139                 if (unlikely(nbytes > bio->bi_size)) {
140                         printk("%s: want %u bytes done, only %u left\n",
141                                __FUNCTION__, nbytes, bio->bi_size);
142                         nbytes = bio->bi_size;
143                 }
144
145                 bio->bi_size -= nbytes;
146                 bio->bi_sector += (nbytes >> 9);
147                 if (bio->bi_size == 0)
148                         bio_endio(bio, error);
149         } else {
150
151                 /*
152                  * Okay, this is the barrier request in progress, just
153                  * record the error;
154                  */
155                 if (error && !q->orderr)
156                         q->orderr = error;
157         }
158 }
159
160 void blk_dump_rq_flags(struct request *rq, char *msg)
161 {
162         int bit;
163
164         printk("%s: dev %s: type=%x, flags=%x\n", msg,
165                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
166                 rq->cmd_flags);
167
168         printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
169                                                        rq->nr_sectors,
170                                                        rq->current_nr_sectors);
171         printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
172
173         if (blk_pc_request(rq)) {
174                 printk("cdb: ");
175                 for (bit = 0; bit < sizeof(rq->cmd); bit++)
176                         printk("%02x ", rq->cmd[bit]);
177                 printk("\n");
178         }
179 }
180
181 EXPORT_SYMBOL(blk_dump_rq_flags);
182
183 /*
184  * "plug" the device if there are no outstanding requests: this will
185  * force the transfer to start only after we have put all the requests
186  * on the list.
187  *
188  * This is called with interrupts off and no requests on the queue and
189  * with the queue lock held.
190  */
191 void blk_plug_device(struct request_queue *q)
192 {
193         WARN_ON(!irqs_disabled());
194
195         /*
196          * don't plug a stopped queue, it must be paired with blk_start_queue()
197          * which will restart the queueing
198          */
199         if (blk_queue_stopped(q))
200                 return;
201
202         if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
203                 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
204                 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
205         }
206 }
207
208 EXPORT_SYMBOL(blk_plug_device);
209
210 /*
211  * remove the queue from the plugged list, if present. called with
212  * queue lock held and interrupts disabled.
213  */
214 int blk_remove_plug(struct request_queue *q)
215 {
216         WARN_ON(!irqs_disabled());
217
218         if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
219                 return 0;
220
221         del_timer(&q->unplug_timer);
222         return 1;
223 }
224
225 EXPORT_SYMBOL(blk_remove_plug);
226
227 /*
228  * remove the plug and let it rip..
229  */
230 void __generic_unplug_device(struct request_queue *q)
231 {
232         if (unlikely(blk_queue_stopped(q)))
233                 return;
234
235         if (!blk_remove_plug(q))
236                 return;
237
238         q->request_fn(q);
239 }
240 EXPORT_SYMBOL(__generic_unplug_device);
241
242 /**
243  * generic_unplug_device - fire a request queue
244  * @q:    The &struct request_queue in question
245  *
246  * Description:
247  *   Linux uses plugging to build bigger requests queues before letting
248  *   the device have at them. If a queue is plugged, the I/O scheduler
249  *   is still adding and merging requests on the queue. Once the queue
250  *   gets unplugged, the request_fn defined for the queue is invoked and
251  *   transfers started.
252  **/
253 void generic_unplug_device(struct request_queue *q)
254 {
255         spin_lock_irq(q->queue_lock);
256         __generic_unplug_device(q);
257         spin_unlock_irq(q->queue_lock);
258 }
259 EXPORT_SYMBOL(generic_unplug_device);
260
261 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
262                                    struct page *page)
263 {
264         struct request_queue *q = bdi->unplug_io_data;
265
266         blk_unplug(q);
267 }
268
269 void blk_unplug_work(struct work_struct *work)
270 {
271         struct request_queue *q =
272                 container_of(work, struct request_queue, unplug_work);
273
274         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
275                                 q->rq.count[READ] + q->rq.count[WRITE]);
276
277         q->unplug_fn(q);
278 }
279
280 void blk_unplug_timeout(unsigned long data)
281 {
282         struct request_queue *q = (struct request_queue *)data;
283
284         blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
285                                 q->rq.count[READ] + q->rq.count[WRITE]);
286
287         kblockd_schedule_work(&q->unplug_work);
288 }
289
290 void blk_unplug(struct request_queue *q)
291 {
292         /*
293          * devices don't necessarily have an ->unplug_fn defined
294          */
295         if (q->unplug_fn) {
296                 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
297                                         q->rq.count[READ] + q->rq.count[WRITE]);
298
299                 q->unplug_fn(q);
300         }
301 }
302 EXPORT_SYMBOL(blk_unplug);
303
304 /**
305  * blk_start_queue - restart a previously stopped queue
306  * @q:    The &struct request_queue in question
307  *
308  * Description:
309  *   blk_start_queue() will clear the stop flag on the queue, and call
310  *   the request_fn for the queue if it was in a stopped state when
311  *   entered. Also see blk_stop_queue(). Queue lock must be held.
312  **/
313 void blk_start_queue(struct request_queue *q)
314 {
315         WARN_ON(!irqs_disabled());
316
317         clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
318
319         /*
320          * one level of recursion is ok and is much faster than kicking
321          * the unplug handling
322          */
323         if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
324                 q->request_fn(q);
325                 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
326         } else {
327                 blk_plug_device(q);
328                 kblockd_schedule_work(&q->unplug_work);
329         }
330 }
331
332 EXPORT_SYMBOL(blk_start_queue);
333
334 /**
335  * blk_stop_queue - stop a queue
336  * @q:    The &struct request_queue in question
337  *
338  * Description:
339  *   The Linux block layer assumes that a block driver will consume all
340  *   entries on the request queue when the request_fn strategy is called.
341  *   Often this will not happen, because of hardware limitations (queue
342  *   depth settings). If a device driver gets a 'queue full' response,
343  *   or if it simply chooses not to queue more I/O at one point, it can
344  *   call this function to prevent the request_fn from being called until
345  *   the driver has signalled it's ready to go again. This happens by calling
346  *   blk_start_queue() to restart queue operations. Queue lock must be held.
347  **/
348 void blk_stop_queue(struct request_queue *q)
349 {
350         blk_remove_plug(q);
351         set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
352 }
353 EXPORT_SYMBOL(blk_stop_queue);
354
355 /**
356  * blk_sync_queue - cancel any pending callbacks on a queue
357  * @q: the queue
358  *
359  * Description:
360  *     The block layer may perform asynchronous callback activity
361  *     on a queue, such as calling the unplug function after a timeout.
362  *     A block device may call blk_sync_queue to ensure that any
363  *     such activity is cancelled, thus allowing it to release resources
364  *     that the callbacks might use. The caller must already have made sure
365  *     that its ->make_request_fn will not re-add plugging prior to calling
366  *     this function.
367  *
368  */
369 void blk_sync_queue(struct request_queue *q)
370 {
371         del_timer_sync(&q->unplug_timer);
372         kblockd_flush_work(&q->unplug_work);
373 }
374 EXPORT_SYMBOL(blk_sync_queue);
375
376 /**
377  * blk_run_queue - run a single device queue
378  * @q:  The queue to run
379  */
380 void blk_run_queue(struct request_queue *q)
381 {
382         unsigned long flags;
383
384         spin_lock_irqsave(q->queue_lock, flags);
385         blk_remove_plug(q);
386
387         /*
388          * Only recurse once to avoid overrunning the stack, let the unplug
389          * handling reinvoke the handler shortly if we already got there.
390          */
391         if (!elv_queue_empty(q)) {
392                 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
393                         q->request_fn(q);
394                         clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
395                 } else {
396                         blk_plug_device(q);
397                         kblockd_schedule_work(&q->unplug_work);
398                 }
399         }
400
401         spin_unlock_irqrestore(q->queue_lock, flags);
402 }
403 EXPORT_SYMBOL(blk_run_queue);
404
405 void blk_put_queue(struct request_queue *q)
406 {
407         kobject_put(&q->kobj);
408 }
409 EXPORT_SYMBOL(blk_put_queue);
410
411 void blk_cleanup_queue(struct request_queue * q)
412 {
413         mutex_lock(&q->sysfs_lock);
414         set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
415         mutex_unlock(&q->sysfs_lock);
416
417         if (q->elevator)
418                 elevator_exit(q->elevator);
419
420         blk_put_queue(q);
421 }
422
423 EXPORT_SYMBOL(blk_cleanup_queue);
424
425 static int blk_init_free_list(struct request_queue *q)
426 {
427         struct request_list *rl = &q->rq;
428
429         rl->count[READ] = rl->count[WRITE] = 0;
430         rl->starved[READ] = rl->starved[WRITE] = 0;
431         rl->elvpriv = 0;
432         init_waitqueue_head(&rl->wait[READ]);
433         init_waitqueue_head(&rl->wait[WRITE]);
434
435         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
436                                 mempool_free_slab, request_cachep, q->node);
437
438         if (!rl->rq_pool)
439                 return -ENOMEM;
440
441         return 0;
442 }
443
444 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
445 {
446         return blk_alloc_queue_node(gfp_mask, -1);
447 }
448 EXPORT_SYMBOL(blk_alloc_queue);
449
450 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
451 {
452         struct request_queue *q;
453         int err;
454
455         q = kmem_cache_alloc_node(blk_requestq_cachep,
456                                 gfp_mask | __GFP_ZERO, node_id);
457         if (!q)
458                 return NULL;
459
460         q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
461         q->backing_dev_info.unplug_io_data = q;
462         err = bdi_init(&q->backing_dev_info);
463         if (err) {
464                 kmem_cache_free(blk_requestq_cachep, q);
465                 return NULL;
466         }
467
468         init_timer(&q->unplug_timer);
469
470         kobject_init(&q->kobj, &blk_queue_ktype);
471
472         mutex_init(&q->sysfs_lock);
473
474         return q;
475 }
476 EXPORT_SYMBOL(blk_alloc_queue_node);
477
478 /**
479  * blk_init_queue  - prepare a request queue for use with a block device
480  * @rfn:  The function to be called to process requests that have been
481  *        placed on the queue.
482  * @lock: Request queue spin lock
483  *
484  * Description:
485  *    If a block device wishes to use the standard request handling procedures,
486  *    which sorts requests and coalesces adjacent requests, then it must
487  *    call blk_init_queue().  The function @rfn will be called when there
488  *    are requests on the queue that need to be processed.  If the device
489  *    supports plugging, then @rfn may not be called immediately when requests
490  *    are available on the queue, but may be called at some time later instead.
491  *    Plugged queues are generally unplugged when a buffer belonging to one
492  *    of the requests on the queue is needed, or due to memory pressure.
493  *
494  *    @rfn is not required, or even expected, to remove all requests off the
495  *    queue, but only as many as it can handle at a time.  If it does leave
496  *    requests on the queue, it is responsible for arranging that the requests
497  *    get dealt with eventually.
498  *
499  *    The queue spin lock must be held while manipulating the requests on the
500  *    request queue; this lock will be taken also from interrupt context, so irq
501  *    disabling is needed for it.
502  *
503  *    Function returns a pointer to the initialized request queue, or NULL if
504  *    it didn't succeed.
505  *
506  * Note:
507  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
508  *    when the block device is deactivated (such as at module unload).
509  **/
510
511 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
512 {
513         return blk_init_queue_node(rfn, lock, -1);
514 }
515 EXPORT_SYMBOL(blk_init_queue);
516
517 struct request_queue *
518 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
519 {
520         struct request_queue *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
521
522         if (!q)
523                 return NULL;
524
525         q->node = node_id;
526         if (blk_init_free_list(q)) {
527                 kmem_cache_free(blk_requestq_cachep, q);
528                 return NULL;
529         }
530
531         /*
532          * if caller didn't supply a lock, they get per-queue locking with
533          * our embedded lock
534          */
535         if (!lock) {
536                 spin_lock_init(&q->__queue_lock);
537                 lock = &q->__queue_lock;
538         }
539
540         q->request_fn           = rfn;
541         q->prep_rq_fn           = NULL;
542         q->unplug_fn            = generic_unplug_device;
543         q->queue_flags          = (1 << QUEUE_FLAG_CLUSTER);
544         q->queue_lock           = lock;
545
546         blk_queue_segment_boundary(q, 0xffffffff);
547
548         blk_queue_make_request(q, __make_request);
549         blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
550
551         blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
552         blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
553
554         q->sg_reserved_size = INT_MAX;
555
556         /*
557          * all done
558          */
559         if (!elevator_init(q, NULL)) {
560                 blk_queue_congestion_threshold(q);
561                 return q;
562         }
563
564         blk_put_queue(q);
565         return NULL;
566 }
567 EXPORT_SYMBOL(blk_init_queue_node);
568
569 int blk_get_queue(struct request_queue *q)
570 {
571         if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
572                 kobject_get(&q->kobj);
573                 return 0;
574         }
575
576         return 1;
577 }
578
579 EXPORT_SYMBOL(blk_get_queue);
580
581 static inline void blk_free_request(struct request_queue *q, struct request *rq)
582 {
583         if (rq->cmd_flags & REQ_ELVPRIV)
584                 elv_put_request(q, rq);
585         mempool_free(rq, q->rq.rq_pool);
586 }
587
588 static struct request *
589 blk_alloc_request(struct request_queue *q, int rw, int priv, gfp_t gfp_mask)
590 {
591         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
592
593         if (!rq)
594                 return NULL;
595
596         /*
597          * first three bits are identical in rq->cmd_flags and bio->bi_rw,
598          * see bio.h and blkdev.h
599          */
600         rq->cmd_flags = rw | REQ_ALLOCED;
601
602         if (priv) {
603                 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
604                         mempool_free(rq, q->rq.rq_pool);
605                         return NULL;
606                 }
607                 rq->cmd_flags |= REQ_ELVPRIV;
608         }
609
610         return rq;
611 }
612
613 /*
614  * ioc_batching returns true if the ioc is a valid batching request and
615  * should be given priority access to a request.
616  */
617 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
618 {
619         if (!ioc)
620                 return 0;
621
622         /*
623          * Make sure the process is able to allocate at least 1 request
624          * even if the batch times out, otherwise we could theoretically
625          * lose wakeups.
626          */
627         return ioc->nr_batch_requests == q->nr_batching ||
628                 (ioc->nr_batch_requests > 0
629                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
630 }
631
632 /*
633  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
634  * will cause the process to be a "batcher" on all queues in the system. This
635  * is the behaviour we want though - once it gets a wakeup it should be given
636  * a nice run.
637  */
638 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
639 {
640         if (!ioc || ioc_batching(q, ioc))
641                 return;
642
643         ioc->nr_batch_requests = q->nr_batching;
644         ioc->last_waited = jiffies;
645 }
646
647 static void __freed_request(struct request_queue *q, int rw)
648 {
649         struct request_list *rl = &q->rq;
650
651         if (rl->count[rw] < queue_congestion_off_threshold(q))
652                 blk_clear_queue_congested(q, rw);
653
654         if (rl->count[rw] + 1 <= q->nr_requests) {
655                 if (waitqueue_active(&rl->wait[rw]))
656                         wake_up(&rl->wait[rw]);
657
658                 blk_clear_queue_full(q, rw);
659         }
660 }
661
662 /*
663  * A request has just been released.  Account for it, update the full and
664  * congestion status, wake up any waiters.   Called under q->queue_lock.
665  */
666 static void freed_request(struct request_queue *q, int rw, int priv)
667 {
668         struct request_list *rl = &q->rq;
669
670         rl->count[rw]--;
671         if (priv)
672                 rl->elvpriv--;
673
674         __freed_request(q, rw);
675
676         if (unlikely(rl->starved[rw ^ 1]))
677                 __freed_request(q, rw ^ 1);
678 }
679
680 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
681 /*
682  * Get a free request, queue_lock must be held.
683  * Returns NULL on failure, with queue_lock held.
684  * Returns !NULL on success, with queue_lock *not held*.
685  */
686 static struct request *get_request(struct request_queue *q, int rw_flags,
687                                    struct bio *bio, gfp_t gfp_mask)
688 {
689         struct request *rq = NULL;
690         struct request_list *rl = &q->rq;
691         struct io_context *ioc = NULL;
692         const int rw = rw_flags & 0x01;
693         int may_queue, priv;
694
695         may_queue = elv_may_queue(q, rw_flags);
696         if (may_queue == ELV_MQUEUE_NO)
697                 goto rq_starved;
698
699         if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
700                 if (rl->count[rw]+1 >= q->nr_requests) {
701                         ioc = current_io_context(GFP_ATOMIC, q->node);
702                         /*
703                          * The queue will fill after this allocation, so set
704                          * it as full, and mark this process as "batching".
705                          * This process will be allowed to complete a batch of
706                          * requests, others will be blocked.
707                          */
708                         if (!blk_queue_full(q, rw)) {
709                                 ioc_set_batching(q, ioc);
710                                 blk_set_queue_full(q, rw);
711                         } else {
712                                 if (may_queue != ELV_MQUEUE_MUST
713                                                 && !ioc_batching(q, ioc)) {
714                                         /*
715                                          * The queue is full and the allocating
716                                          * process is not a "batcher", and not
717                                          * exempted by the IO scheduler
718                                          */
719                                         goto out;
720                                 }
721                         }
722                 }
723                 blk_set_queue_congested(q, rw);
724         }
725
726         /*
727          * Only allow batching queuers to allocate up to 50% over the defined
728          * limit of requests, otherwise we could have thousands of requests
729          * allocated with any setting of ->nr_requests
730          */
731         if (rl->count[rw] >= (3 * q->nr_requests / 2))
732                 goto out;
733
734         rl->count[rw]++;
735         rl->starved[rw] = 0;
736
737         priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
738         if (priv)
739                 rl->elvpriv++;
740
741         spin_unlock_irq(q->queue_lock);
742
743         rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
744         if (unlikely(!rq)) {
745                 /*
746                  * Allocation failed presumably due to memory. Undo anything
747                  * we might have messed up.
748                  *
749                  * Allocating task should really be put onto the front of the
750                  * wait queue, but this is pretty rare.
751                  */
752                 spin_lock_irq(q->queue_lock);
753                 freed_request(q, rw, priv);
754
755                 /*
756                  * in the very unlikely event that allocation failed and no
757                  * requests for this direction was pending, mark us starved
758                  * so that freeing of a request in the other direction will
759                  * notice us. another possible fix would be to split the
760                  * rq mempool into READ and WRITE
761                  */
762 rq_starved:
763                 if (unlikely(rl->count[rw] == 0))
764                         rl->starved[rw] = 1;
765
766                 goto out;
767         }
768
769         /*
770          * ioc may be NULL here, and ioc_batching will be false. That's
771          * OK, if the queue is under the request limit then requests need
772          * not count toward the nr_batch_requests limit. There will always
773          * be some limit enforced by BLK_BATCH_TIME.
774          */
775         if (ioc_batching(q, ioc))
776                 ioc->nr_batch_requests--;
777         
778         rq_init(q, rq);
779
780         blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
781 out:
782         return rq;
783 }
784
785 /*
786  * No available requests for this queue, unplug the device and wait for some
787  * requests to become available.
788  *
789  * Called with q->queue_lock held, and returns with it unlocked.
790  */
791 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
792                                         struct bio *bio)
793 {
794         const int rw = rw_flags & 0x01;
795         struct request *rq;
796
797         rq = get_request(q, rw_flags, bio, GFP_NOIO);
798         while (!rq) {
799                 DEFINE_WAIT(wait);
800                 struct request_list *rl = &q->rq;
801
802                 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
803                                 TASK_UNINTERRUPTIBLE);
804
805                 rq = get_request(q, rw_flags, bio, GFP_NOIO);
806
807                 if (!rq) {
808                         struct io_context *ioc;
809
810                         blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
811
812                         __generic_unplug_device(q);
813                         spin_unlock_irq(q->queue_lock);
814                         io_schedule();
815
816                         /*
817                          * After sleeping, we become a "batching" process and
818                          * will be able to allocate at least one request, and
819                          * up to a big batch of them for a small period time.
820                          * See ioc_batching, ioc_set_batching
821                          */
822                         ioc = current_io_context(GFP_NOIO, q->node);
823                         ioc_set_batching(q, ioc);
824
825                         spin_lock_irq(q->queue_lock);
826                 }
827                 finish_wait(&rl->wait[rw], &wait);
828         }
829
830         return rq;
831 }
832
833 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
834 {
835         struct request *rq;
836
837         BUG_ON(rw != READ && rw != WRITE);
838
839         spin_lock_irq(q->queue_lock);
840         if (gfp_mask & __GFP_WAIT) {
841                 rq = get_request_wait(q, rw, NULL);
842         } else {
843                 rq = get_request(q, rw, NULL, gfp_mask);
844                 if (!rq)
845                         spin_unlock_irq(q->queue_lock);
846         }
847         /* q->queue_lock is unlocked at this point */
848
849         return rq;
850 }
851 EXPORT_SYMBOL(blk_get_request);
852
853 /**
854  * blk_start_queueing - initiate dispatch of requests to device
855  * @q:          request queue to kick into gear
856  *
857  * This is basically a helper to remove the need to know whether a queue
858  * is plugged or not if someone just wants to initiate dispatch of requests
859  * for this queue.
860  *
861  * The queue lock must be held with interrupts disabled.
862  */
863 void blk_start_queueing(struct request_queue *q)
864 {
865         if (!blk_queue_plugged(q))
866                 q->request_fn(q);
867         else
868                 __generic_unplug_device(q);
869 }
870 EXPORT_SYMBOL(blk_start_queueing);
871
872 /**
873  * blk_requeue_request - put a request back on queue
874  * @q:          request queue where request should be inserted
875  * @rq:         request to be inserted
876  *
877  * Description:
878  *    Drivers often keep queueing requests until the hardware cannot accept
879  *    more, when that condition happens we need to put the request back
880  *    on the queue. Must be called with queue lock held.
881  */
882 void blk_requeue_request(struct request_queue *q, struct request *rq)
883 {
884         blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
885
886         if (blk_rq_tagged(rq))
887                 blk_queue_end_tag(q, rq);
888
889         elv_requeue_request(q, rq);
890 }
891
892 EXPORT_SYMBOL(blk_requeue_request);
893
894 /**
895  * blk_insert_request - insert a special request in to a request queue
896  * @q:          request queue where request should be inserted
897  * @rq:         request to be inserted
898  * @at_head:    insert request at head or tail of queue
899  * @data:       private data
900  *
901  * Description:
902  *    Many block devices need to execute commands asynchronously, so they don't
903  *    block the whole kernel from preemption during request execution.  This is
904  *    accomplished normally by inserting aritficial requests tagged as
905  *    REQ_SPECIAL in to the corresponding request queue, and letting them be
906  *    scheduled for actual execution by the request queue.
907  *
908  *    We have the option of inserting the head or the tail of the queue.
909  *    Typically we use the tail for new ioctls and so forth.  We use the head
910  *    of the queue for things like a QUEUE_FULL message from a device, or a
911  *    host that is unable to accept a particular command.
912  */
913 void blk_insert_request(struct request_queue *q, struct request *rq,
914                         int at_head, void *data)
915 {
916         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
917         unsigned long flags;
918
919         /*
920          * tell I/O scheduler that this isn't a regular read/write (ie it
921          * must not attempt merges on this) and that it acts as a soft
922          * barrier
923          */
924         rq->cmd_type = REQ_TYPE_SPECIAL;
925         rq->cmd_flags |= REQ_SOFTBARRIER;
926
927         rq->special = data;
928
929         spin_lock_irqsave(q->queue_lock, flags);
930
931         /*
932          * If command is tagged, release the tag
933          */
934         if (blk_rq_tagged(rq))
935                 blk_queue_end_tag(q, rq);
936
937         drive_stat_acct(rq, 1);
938         __elv_add_request(q, rq, where, 0);
939         blk_start_queueing(q);
940         spin_unlock_irqrestore(q->queue_lock, flags);
941 }
942
943 EXPORT_SYMBOL(blk_insert_request);
944
945 /*
946  * add-request adds a request to the linked list.
947  * queue lock is held and interrupts disabled, as we muck with the
948  * request queue list.
949  */
950 static inline void add_request(struct request_queue * q, struct request * req)
951 {
952         drive_stat_acct(req, 1);
953
954         /*
955          * elevator indicated where it wants this request to be
956          * inserted at elevator_merge time
957          */
958         __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
959 }
960  
961 /*
962  * disk_round_stats()   - Round off the performance stats on a struct
963  * disk_stats.
964  *
965  * The average IO queue length and utilisation statistics are maintained
966  * by observing the current state of the queue length and the amount of
967  * time it has been in this state for.
968  *
969  * Normally, that accounting is done on IO completion, but that can result
970  * in more than a second's worth of IO being accounted for within any one
971  * second, leading to >100% utilisation.  To deal with that, we call this
972  * function to do a round-off before returning the results when reading
973  * /proc/diskstats.  This accounts immediately for all queue usage up to
974  * the current jiffies and restarts the counters again.
975  */
976 void disk_round_stats(struct gendisk *disk)
977 {
978         unsigned long now = jiffies;
979
980         if (now == disk->stamp)
981                 return;
982
983         if (disk->in_flight) {
984                 __disk_stat_add(disk, time_in_queue,
985                                 disk->in_flight * (now - disk->stamp));
986                 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
987         }
988         disk->stamp = now;
989 }
990
991 EXPORT_SYMBOL_GPL(disk_round_stats);
992
993 /*
994  * queue lock must be held
995  */
996 void __blk_put_request(struct request_queue *q, struct request *req)
997 {
998         if (unlikely(!q))
999                 return;
1000         if (unlikely(--req->ref_count))
1001                 return;
1002
1003         elv_completed_request(q, req);
1004
1005         /*
1006          * Request may not have originated from ll_rw_blk. if not,
1007          * it didn't come out of our reserved rq pools
1008          */
1009         if (req->cmd_flags & REQ_ALLOCED) {
1010                 int rw = rq_data_dir(req);
1011                 int priv = req->cmd_flags & REQ_ELVPRIV;
1012
1013                 BUG_ON(!list_empty(&req->queuelist));
1014                 BUG_ON(!hlist_unhashed(&req->hash));
1015
1016                 blk_free_request(q, req);
1017                 freed_request(q, rw, priv);
1018         }
1019 }
1020
1021 EXPORT_SYMBOL_GPL(__blk_put_request);
1022
1023 void blk_put_request(struct request *req)
1024 {
1025         unsigned long flags;
1026         struct request_queue *q = req->q;
1027
1028         /*
1029          * Gee, IDE calls in w/ NULL q.  Fix IDE and remove the
1030          * following if (q) test.
1031          */
1032         if (q) {
1033                 spin_lock_irqsave(q->queue_lock, flags);
1034                 __blk_put_request(q, req);
1035                 spin_unlock_irqrestore(q->queue_lock, flags);
1036         }
1037 }
1038
1039 EXPORT_SYMBOL(blk_put_request);
1040
1041 void init_request_from_bio(struct request *req, struct bio *bio)
1042 {
1043         req->cmd_type = REQ_TYPE_FS;
1044
1045         /*
1046          * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
1047          */
1048         if (bio_rw_ahead(bio) || bio_failfast(bio))
1049                 req->cmd_flags |= REQ_FAILFAST;
1050
1051         /*
1052          * REQ_BARRIER implies no merging, but lets make it explicit
1053          */
1054         if (unlikely(bio_barrier(bio)))
1055                 req->cmd_flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
1056
1057         if (bio_sync(bio))
1058                 req->cmd_flags |= REQ_RW_SYNC;
1059         if (bio_rw_meta(bio))
1060                 req->cmd_flags |= REQ_RW_META;
1061
1062         req->errors = 0;
1063         req->hard_sector = req->sector = bio->bi_sector;
1064         req->ioprio = bio_prio(bio);
1065         req->start_time = jiffies;
1066         blk_rq_bio_prep(req->q, req, bio);
1067 }
1068
1069 static int __make_request(struct request_queue *q, struct bio *bio)
1070 {
1071         struct request *req;
1072         int el_ret, nr_sectors, barrier, err;
1073         const unsigned short prio = bio_prio(bio);
1074         const int sync = bio_sync(bio);
1075         int rw_flags;
1076
1077         nr_sectors = bio_sectors(bio);
1078
1079         /*
1080          * low level driver can indicate that it wants pages above a
1081          * certain limit bounced to low memory (ie for highmem, or even
1082          * ISA dma in theory)
1083          */
1084         blk_queue_bounce(q, &bio);
1085
1086         barrier = bio_barrier(bio);
1087         if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
1088                 err = -EOPNOTSUPP;
1089                 goto end_io;
1090         }
1091
1092         spin_lock_irq(q->queue_lock);
1093
1094         if (unlikely(barrier) || elv_queue_empty(q))
1095                 goto get_rq;
1096
1097         el_ret = elv_merge(q, &req, bio);
1098         switch (el_ret) {
1099                 case ELEVATOR_BACK_MERGE:
1100                         BUG_ON(!rq_mergeable(req));
1101
1102                         if (!ll_back_merge_fn(q, req, bio))
1103                                 break;
1104
1105                         blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
1106
1107                         req->biotail->bi_next = bio;
1108                         req->biotail = bio;
1109                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1110                         req->ioprio = ioprio_best(req->ioprio, prio);
1111                         drive_stat_acct(req, 0);
1112                         if (!attempt_back_merge(q, req))
1113                                 elv_merged_request(q, req, el_ret);
1114                         goto out;
1115
1116                 case ELEVATOR_FRONT_MERGE:
1117                         BUG_ON(!rq_mergeable(req));
1118
1119                         if (!ll_front_merge_fn(q, req, bio))
1120                                 break;
1121
1122                         blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
1123
1124                         bio->bi_next = req->bio;
1125                         req->bio = bio;
1126
1127                         /*
1128                          * may not be valid. if the low level driver said
1129                          * it didn't need a bounce buffer then it better
1130                          * not touch req->buffer either...
1131                          */
1132                         req->buffer = bio_data(bio);
1133                         req->current_nr_sectors = bio_cur_sectors(bio);
1134                         req->hard_cur_sectors = req->current_nr_sectors;
1135                         req->sector = req->hard_sector = bio->bi_sector;
1136                         req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1137                         req->ioprio = ioprio_best(req->ioprio, prio);
1138                         drive_stat_acct(req, 0);
1139                         if (!attempt_front_merge(q, req))
1140                                 elv_merged_request(q, req, el_ret);
1141                         goto out;
1142
1143                 /* ELV_NO_MERGE: elevator says don't/can't merge. */
1144                 default:
1145                         ;
1146         }
1147
1148 get_rq:
1149         /*
1150          * This sync check and mask will be re-done in init_request_from_bio(),
1151          * but we need to set it earlier to expose the sync flag to the
1152          * rq allocator and io schedulers.
1153          */
1154         rw_flags = bio_data_dir(bio);
1155         if (sync)
1156                 rw_flags |= REQ_RW_SYNC;
1157
1158         /*
1159          * Grab a free request. This is might sleep but can not fail.
1160          * Returns with the queue unlocked.
1161          */
1162         req = get_request_wait(q, rw_flags, bio);
1163
1164         /*
1165          * After dropping the lock and possibly sleeping here, our request
1166          * may now be mergeable after it had proven unmergeable (above).
1167          * We don't worry about that case for efficiency. It won't happen
1168          * often, and the elevators are able to handle it.
1169          */
1170         init_request_from_bio(req, bio);
1171
1172         spin_lock_irq(q->queue_lock);
1173         if (elv_queue_empty(q))
1174                 blk_plug_device(q);
1175         add_request(q, req);
1176 out:
1177         if (sync)
1178                 __generic_unplug_device(q);
1179
1180         spin_unlock_irq(q->queue_lock);
1181         return 0;
1182
1183 end_io:
1184         bio_endio(bio, err);
1185         return 0;
1186 }
1187
1188 /*
1189  * If bio->bi_dev is a partition, remap the location
1190  */
1191 static inline void blk_partition_remap(struct bio *bio)
1192 {
1193         struct block_device *bdev = bio->bi_bdev;
1194
1195         if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1196                 struct hd_struct *p = bdev->bd_part;
1197                 const int rw = bio_data_dir(bio);
1198
1199                 p->sectors[rw] += bio_sectors(bio);
1200                 p->ios[rw]++;
1201
1202                 bio->bi_sector += p->start_sect;
1203                 bio->bi_bdev = bdev->bd_contains;
1204
1205                 blk_add_trace_remap(bdev_get_queue(bio->bi_bdev), bio,
1206                                     bdev->bd_dev, bio->bi_sector,
1207                                     bio->bi_sector - p->start_sect);
1208         }
1209 }
1210
1211 static void handle_bad_sector(struct bio *bio)
1212 {
1213         char b[BDEVNAME_SIZE];
1214
1215         printk(KERN_INFO "attempt to access beyond end of device\n");
1216         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1217                         bdevname(bio->bi_bdev, b),
1218                         bio->bi_rw,
1219                         (unsigned long long)bio->bi_sector + bio_sectors(bio),
1220                         (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1221
1222         set_bit(BIO_EOF, &bio->bi_flags);
1223 }
1224
1225 #ifdef CONFIG_FAIL_MAKE_REQUEST
1226
1227 static DECLARE_FAULT_ATTR(fail_make_request);
1228
1229 static int __init setup_fail_make_request(char *str)
1230 {
1231         return setup_fault_attr(&fail_make_request, str);
1232 }
1233 __setup("fail_make_request=", setup_fail_make_request);
1234
1235 static int should_fail_request(struct bio *bio)
1236 {
1237         if ((bio->bi_bdev->bd_disk->flags & GENHD_FL_FAIL) ||
1238             (bio->bi_bdev->bd_part && bio->bi_bdev->bd_part->make_it_fail))
1239                 return should_fail(&fail_make_request, bio->bi_size);
1240
1241         return 0;
1242 }
1243
1244 static int __init fail_make_request_debugfs(void)
1245 {
1246         return init_fault_attr_dentries(&fail_make_request,
1247                                         "fail_make_request");
1248 }
1249
1250 late_initcall(fail_make_request_debugfs);
1251
1252 #else /* CONFIG_FAIL_MAKE_REQUEST */
1253
1254 static inline int should_fail_request(struct bio *bio)
1255 {
1256         return 0;
1257 }
1258
1259 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1260
1261 /*
1262  * Check whether this bio extends beyond the end of the device.
1263  */
1264 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1265 {
1266         sector_t maxsector;
1267
1268         if (!nr_sectors)
1269                 return 0;
1270
1271         /* Test device or partition size, when known. */
1272         maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1273         if (maxsector) {
1274                 sector_t sector = bio->bi_sector;
1275
1276                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1277                         /*
1278                          * This may well happen - the kernel calls bread()
1279                          * without checking the size of the device, e.g., when
1280                          * mounting a device.
1281                          */
1282                         handle_bad_sector(bio);
1283                         return 1;
1284                 }
1285         }
1286
1287         return 0;
1288 }
1289
1290 /**
1291  * generic_make_request: hand a buffer to its device driver for I/O
1292  * @bio:  The bio describing the location in memory and on the device.
1293  *
1294  * generic_make_request() is used to make I/O requests of block
1295  * devices. It is passed a &struct bio, which describes the I/O that needs
1296  * to be done.
1297  *
1298  * generic_make_request() does not return any status.  The
1299  * success/failure status of the request, along with notification of
1300  * completion, is delivered asynchronously through the bio->bi_end_io
1301  * function described (one day) else where.
1302  *
1303  * The caller of generic_make_request must make sure that bi_io_vec
1304  * are set to describe the memory buffer, and that bi_dev and bi_sector are
1305  * set to describe the device address, and the
1306  * bi_end_io and optionally bi_private are set to describe how
1307  * completion notification should be signaled.
1308  *
1309  * generic_make_request and the drivers it calls may use bi_next if this
1310  * bio happens to be merged with someone else, and may change bi_dev and
1311  * bi_sector for remaps as it sees fit.  So the values of these fields
1312  * should NOT be depended on after the call to generic_make_request.
1313  */
1314 static inline void __generic_make_request(struct bio *bio)
1315 {
1316         struct request_queue *q;
1317         sector_t old_sector;
1318         int ret, nr_sectors = bio_sectors(bio);
1319         dev_t old_dev;
1320         int err = -EIO;
1321
1322         might_sleep();
1323
1324         if (bio_check_eod(bio, nr_sectors))
1325                 goto end_io;
1326
1327         /*
1328          * Resolve the mapping until finished. (drivers are
1329          * still free to implement/resolve their own stacking
1330          * by explicitly returning 0)
1331          *
1332          * NOTE: we don't repeat the blk_size check for each new device.
1333          * Stacking drivers are expected to know what they are doing.
1334          */
1335         old_sector = -1;
1336         old_dev = 0;
1337         do {
1338                 char b[BDEVNAME_SIZE];
1339
1340                 q = bdev_get_queue(bio->bi_bdev);
1341                 if (!q) {
1342                         printk(KERN_ERR
1343                                "generic_make_request: Trying to access "
1344                                 "nonexistent block-device %s (%Lu)\n",
1345                                 bdevname(bio->bi_bdev, b),
1346                                 (long long) bio->bi_sector);
1347 end_io:
1348                         bio_endio(bio, err);
1349                         break;
1350                 }
1351
1352                 if (unlikely(nr_sectors > q->max_hw_sectors)) {
1353                         printk("bio too big device %s (%u > %u)\n", 
1354                                 bdevname(bio->bi_bdev, b),
1355                                 bio_sectors(bio),
1356                                 q->max_hw_sectors);
1357                         goto end_io;
1358                 }
1359
1360                 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1361                         goto end_io;
1362
1363                 if (should_fail_request(bio))
1364                         goto end_io;
1365
1366                 /*
1367                  * If this device has partitions, remap block n
1368                  * of partition p to block n+start(p) of the disk.
1369                  */
1370                 blk_partition_remap(bio);
1371
1372                 if (old_sector != -1)
1373                         blk_add_trace_remap(q, bio, old_dev, bio->bi_sector,
1374                                             old_sector);
1375
1376                 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
1377
1378                 old_sector = bio->bi_sector;
1379                 old_dev = bio->bi_bdev->bd_dev;
1380
1381                 if (bio_check_eod(bio, nr_sectors))
1382                         goto end_io;
1383                 if (bio_empty_barrier(bio) && !q->prepare_flush_fn) {
1384                         err = -EOPNOTSUPP;
1385                         goto end_io;
1386                 }
1387
1388                 ret = q->make_request_fn(q, bio);
1389         } while (ret);
1390 }
1391
1392 /*
1393  * We only want one ->make_request_fn to be active at a time,
1394  * else stack usage with stacked devices could be a problem.
1395  * So use current->bio_{list,tail} to keep a list of requests
1396  * submited by a make_request_fn function.
1397  * current->bio_tail is also used as a flag to say if
1398  * generic_make_request is currently active in this task or not.
1399  * If it is NULL, then no make_request is active.  If it is non-NULL,
1400  * then a make_request is active, and new requests should be added
1401  * at the tail
1402  */
1403 void generic_make_request(struct bio *bio)
1404 {
1405         if (current->bio_tail) {
1406                 /* make_request is active */
1407                 *(current->bio_tail) = bio;
1408                 bio->bi_next = NULL;
1409                 current->bio_tail = &bio->bi_next;
1410                 return;
1411         }
1412         /* following loop may be a bit non-obvious, and so deserves some
1413          * explanation.
1414          * Before entering the loop, bio->bi_next is NULL (as all callers
1415          * ensure that) so we have a list with a single bio.
1416          * We pretend that we have just taken it off a longer list, so
1417          * we assign bio_list to the next (which is NULL) and bio_tail
1418          * to &bio_list, thus initialising the bio_list of new bios to be
1419          * added.  __generic_make_request may indeed add some more bios
1420          * through a recursive call to generic_make_request.  If it
1421          * did, we find a non-NULL value in bio_list and re-enter the loop
1422          * from the top.  In this case we really did just take the bio
1423          * of the top of the list (no pretending) and so fixup bio_list and
1424          * bio_tail or bi_next, and call into __generic_make_request again.
1425          *
1426          * The loop was structured like this to make only one call to
1427          * __generic_make_request (which is important as it is large and
1428          * inlined) and to keep the structure simple.
1429          */
1430         BUG_ON(bio->bi_next);
1431         do {
1432                 current->bio_list = bio->bi_next;
1433                 if (bio->bi_next == NULL)
1434                         current->bio_tail = &current->bio_list;
1435                 else
1436                         bio->bi_next = NULL;
1437                 __generic_make_request(bio);
1438                 bio = current->bio_list;
1439         } while (bio);
1440         current->bio_tail = NULL; /* deactivate */
1441 }
1442
1443 EXPORT_SYMBOL(generic_make_request);
1444
1445 /**
1446  * submit_bio: submit a bio to the block device layer for I/O
1447  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1448  * @bio: The &struct bio which describes the I/O
1449  *
1450  * submit_bio() is very similar in purpose to generic_make_request(), and
1451  * uses that function to do most of the work. Both are fairly rough
1452  * interfaces, @bio must be presetup and ready for I/O.
1453  *
1454  */
1455 void submit_bio(int rw, struct bio *bio)
1456 {
1457         int count = bio_sectors(bio);
1458
1459         bio->bi_rw |= rw;
1460
1461         /*
1462          * If it's a regular read/write or a barrier with data attached,
1463          * go through the normal accounting stuff before submission.
1464          */
1465         if (!bio_empty_barrier(bio)) {
1466
1467                 BIO_BUG_ON(!bio->bi_size);
1468                 BIO_BUG_ON(!bio->bi_io_vec);
1469
1470                 if (rw & WRITE) {
1471                         count_vm_events(PGPGOUT, count);
1472                 } else {
1473                         task_io_account_read(bio->bi_size);
1474                         count_vm_events(PGPGIN, count);
1475                 }
1476
1477                 if (unlikely(block_dump)) {
1478                         char b[BDEVNAME_SIZE];
1479                         printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
1480                         current->comm, task_pid_nr(current),
1481                                 (rw & WRITE) ? "WRITE" : "READ",
1482                                 (unsigned long long)bio->bi_sector,
1483                                 bdevname(bio->bi_bdev,b));
1484                 }
1485         }
1486
1487         generic_make_request(bio);
1488 }
1489
1490 EXPORT_SYMBOL(submit_bio);
1491
1492 /**
1493  * __end_that_request_first - end I/O on a request
1494  * @req:      the request being processed
1495  * @error:    0 for success, < 0 for error
1496  * @nr_bytes: number of bytes to complete
1497  *
1498  * Description:
1499  *     Ends I/O on a number of bytes attached to @req, and sets it up
1500  *     for the next range of segments (if any) in the cluster.
1501  *
1502  * Return:
1503  *     0 - we are done with this request, call end_that_request_last()
1504  *     1 - still buffers pending for this request
1505  **/
1506 static int __end_that_request_first(struct request *req, int error,
1507                                     int nr_bytes)
1508 {
1509         int total_bytes, bio_nbytes, next_idx = 0;
1510         struct bio *bio;
1511
1512         blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
1513
1514         /*
1515          * for a REQ_BLOCK_PC request, we want to carry any eventual
1516          * sense key with us all the way through
1517          */
1518         if (!blk_pc_request(req))
1519                 req->errors = 0;
1520
1521         if (error) {
1522                 if (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))
1523                         printk("end_request: I/O error, dev %s, sector %llu\n",
1524                                 req->rq_disk ? req->rq_disk->disk_name : "?",
1525                                 (unsigned long long)req->sector);
1526         }
1527
1528         if (blk_fs_request(req) && req->rq_disk) {
1529                 const int rw = rq_data_dir(req);
1530
1531                 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
1532         }
1533
1534         total_bytes = bio_nbytes = 0;
1535         while ((bio = req->bio) != NULL) {
1536                 int nbytes;
1537
1538                 /*
1539                  * For an empty barrier request, the low level driver must
1540                  * store a potential error location in ->sector. We pass
1541                  * that back up in ->bi_sector.
1542                  */
1543                 if (blk_empty_barrier(req))
1544                         bio->bi_sector = req->sector;
1545
1546                 if (nr_bytes >= bio->bi_size) {
1547                         req->bio = bio->bi_next;
1548                         nbytes = bio->bi_size;
1549                         req_bio_endio(req, bio, nbytes, error);
1550                         next_idx = 0;
1551                         bio_nbytes = 0;
1552                 } else {
1553                         int idx = bio->bi_idx + next_idx;
1554
1555                         if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
1556                                 blk_dump_rq_flags(req, "__end_that");
1557                                 printk("%s: bio idx %d >= vcnt %d\n",
1558                                                 __FUNCTION__,
1559                                                 bio->bi_idx, bio->bi_vcnt);
1560                                 break;
1561                         }
1562
1563                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
1564                         BIO_BUG_ON(nbytes > bio->bi_size);
1565
1566                         /*
1567                          * not a complete bvec done
1568                          */
1569                         if (unlikely(nbytes > nr_bytes)) {
1570                                 bio_nbytes += nr_bytes;
1571                                 total_bytes += nr_bytes;
1572                                 break;
1573                         }
1574
1575                         /*
1576                          * advance to the next vector
1577                          */
1578                         next_idx++;
1579                         bio_nbytes += nbytes;
1580                 }
1581
1582                 total_bytes += nbytes;
1583                 nr_bytes -= nbytes;
1584
1585                 if ((bio = req->bio)) {
1586                         /*
1587                          * end more in this run, or just return 'not-done'
1588                          */
1589                         if (unlikely(nr_bytes <= 0))
1590                                 break;
1591                 }
1592         }
1593
1594         /*
1595          * completely done
1596          */
1597         if (!req->bio)
1598                 return 0;
1599
1600         /*
1601          * if the request wasn't completed, update state
1602          */
1603         if (bio_nbytes) {
1604                 req_bio_endio(req, bio, bio_nbytes, error);
1605                 bio->bi_idx += next_idx;
1606                 bio_iovec(bio)->bv_offset += nr_bytes;
1607                 bio_iovec(bio)->bv_len -= nr_bytes;
1608         }
1609
1610         blk_recalc_rq_sectors(req, total_bytes >> 9);
1611         blk_recalc_rq_segments(req);
1612         return 1;
1613 }
1614
1615 /*
1616  * splice the completion data to a local structure and hand off to
1617  * process_completion_queue() to complete the requests
1618  */
1619 static void blk_done_softirq(struct softirq_action *h)
1620 {
1621         struct list_head *cpu_list, local_list;
1622
1623         local_irq_disable();
1624         cpu_list = &__get_cpu_var(blk_cpu_done);
1625         list_replace_init(cpu_list, &local_list);
1626         local_irq_enable();
1627
1628         while (!list_empty(&local_list)) {
1629                 struct request *rq = list_entry(local_list.next, struct request, donelist);
1630
1631                 list_del_init(&rq->donelist);
1632                 rq->q->softirq_done_fn(rq);
1633         }
1634 }
1635
1636 static int __cpuinit blk_cpu_notify(struct notifier_block *self, unsigned long action,
1637                           void *hcpu)
1638 {
1639         /*
1640          * If a CPU goes away, splice its entries to the current CPU
1641          * and trigger a run of the softirq
1642          */
1643         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
1644                 int cpu = (unsigned long) hcpu;
1645
1646                 local_irq_disable();
1647                 list_splice_init(&per_cpu(blk_cpu_done, cpu),
1648                                  &__get_cpu_var(blk_cpu_done));
1649                 raise_softirq_irqoff(BLOCK_SOFTIRQ);
1650                 local_irq_enable();
1651         }
1652
1653         return NOTIFY_OK;
1654 }
1655
1656
1657 static struct notifier_block blk_cpu_notifier __cpuinitdata = {
1658         .notifier_call  = blk_cpu_notify,
1659 };
1660
1661 /**
1662  * blk_complete_request - end I/O on a request
1663  * @req:      the request being processed
1664  *
1665  * Description:
1666  *     Ends all I/O on a request. It does not handle partial completions,
1667  *     unless the driver actually implements this in its completion callback
1668  *     through requeueing. The actual completion happens out-of-order,
1669  *     through a softirq handler. The user must have registered a completion
1670  *     callback through blk_queue_softirq_done().
1671  **/
1672
1673 void blk_complete_request(struct request *req)
1674 {
1675         struct list_head *cpu_list;
1676         unsigned long flags;
1677
1678         BUG_ON(!req->q->softirq_done_fn);
1679                 
1680         local_irq_save(flags);
1681
1682         cpu_list = &__get_cpu_var(blk_cpu_done);
1683         list_add_tail(&req->donelist, cpu_list);
1684         raise_softirq_irqoff(BLOCK_SOFTIRQ);
1685
1686         local_irq_restore(flags);
1687 }
1688
1689 EXPORT_SYMBOL(blk_complete_request);
1690         
1691 /*
1692  * queue lock must be held
1693  */
1694 static void end_that_request_last(struct request *req, int error)
1695 {
1696         struct gendisk *disk = req->rq_disk;
1697
1698         if (blk_rq_tagged(req))
1699                 blk_queue_end_tag(req->q, req);
1700
1701         if (blk_queued_rq(req))
1702                 blkdev_dequeue_request(req);
1703
1704         if (unlikely(laptop_mode) && blk_fs_request(req))
1705                 laptop_io_completion();
1706
1707         /*
1708          * Account IO completion.  bar_rq isn't accounted as a normal
1709          * IO on queueing nor completion.  Accounting the containing
1710          * request is enough.
1711          */
1712         if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
1713                 unsigned long duration = jiffies - req->start_time;
1714                 const int rw = rq_data_dir(req);
1715
1716                 __disk_stat_inc(disk, ios[rw]);
1717                 __disk_stat_add(disk, ticks[rw], duration);
1718                 disk_round_stats(disk);
1719                 disk->in_flight--;
1720         }
1721
1722         if (req->end_io)
1723                 req->end_io(req, error);
1724         else {
1725                 if (blk_bidi_rq(req))
1726                         __blk_put_request(req->next_rq->q, req->next_rq);
1727
1728                 __blk_put_request(req->q, req);
1729         }
1730 }
1731
1732 static inline void __end_request(struct request *rq, int uptodate,
1733                                  unsigned int nr_bytes)
1734 {
1735         int error = 0;
1736
1737         if (uptodate <= 0)
1738                 error = uptodate ? uptodate : -EIO;
1739
1740         __blk_end_request(rq, error, nr_bytes);
1741 }
1742
1743 /**
1744  * blk_rq_bytes - Returns bytes left to complete in the entire request
1745  **/
1746 unsigned int blk_rq_bytes(struct request *rq)
1747 {
1748         if (blk_fs_request(rq))
1749                 return rq->hard_nr_sectors << 9;
1750
1751         return rq->data_len;
1752 }
1753 EXPORT_SYMBOL_GPL(blk_rq_bytes);
1754
1755 /**
1756  * blk_rq_cur_bytes - Returns bytes left to complete in the current segment
1757  **/
1758 unsigned int blk_rq_cur_bytes(struct request *rq)
1759 {
1760         if (blk_fs_request(rq))
1761                 return rq->current_nr_sectors << 9;
1762
1763         if (rq->bio)
1764                 return rq->bio->bi_size;
1765
1766         return rq->data_len;
1767 }
1768 EXPORT_SYMBOL_GPL(blk_rq_cur_bytes);
1769
1770 /**
1771  * end_queued_request - end all I/O on a queued request
1772  * @rq:         the request being processed
1773  * @uptodate:   error value or 0/1 uptodate flag
1774  *
1775  * Description:
1776  *     Ends all I/O on a request, and removes it from the block layer queues.
1777  *     Not suitable for normal IO completion, unless the driver still has
1778  *     the request attached to the block layer.
1779  *
1780  **/
1781 void end_queued_request(struct request *rq, int uptodate)
1782 {
1783         __end_request(rq, uptodate, blk_rq_bytes(rq));
1784 }
1785 EXPORT_SYMBOL(end_queued_request);
1786
1787 /**
1788  * end_dequeued_request - end all I/O on a dequeued request
1789  * @rq:         the request being processed
1790  * @uptodate:   error value or 0/1 uptodate flag
1791  *
1792  * Description:
1793  *     Ends all I/O on a request. The request must already have been
1794  *     dequeued using blkdev_dequeue_request(), as is normally the case
1795  *     for most drivers.
1796  *
1797  **/
1798 void end_dequeued_request(struct request *rq, int uptodate)
1799 {
1800         __end_request(rq, uptodate, blk_rq_bytes(rq));
1801 }
1802 EXPORT_SYMBOL(end_dequeued_request);
1803
1804
1805 /**
1806  * end_request - end I/O on the current segment of the request
1807  * @req:        the request being processed
1808  * @uptodate:   error value or 0/1 uptodate flag
1809  *
1810  * Description:
1811  *     Ends I/O on the current segment of a request. If that is the only
1812  *     remaining segment, the request is also completed and freed.
1813  *
1814  *     This is a remnant of how older block drivers handled IO completions.
1815  *     Modern drivers typically end IO on the full request in one go, unless
1816  *     they have a residual value to account for. For that case this function
1817  *     isn't really useful, unless the residual just happens to be the
1818  *     full current segment. In other words, don't use this function in new
1819  *     code. Either use end_request_completely(), or the
1820  *     end_that_request_chunk() (along with end_that_request_last()) for
1821  *     partial completions.
1822  *
1823  **/
1824 void end_request(struct request *req, int uptodate)
1825 {
1826         __end_request(req, uptodate, req->hard_cur_sectors << 9);
1827 }
1828 EXPORT_SYMBOL(end_request);
1829
1830 /**
1831  * blk_end_io - Generic end_io function to complete a request.
1832  * @rq:           the request being processed
1833  * @error:        0 for success, < 0 for error
1834  * @nr_bytes:     number of bytes to complete @rq
1835  * @bidi_bytes:   number of bytes to complete @rq->next_rq
1836  * @drv_callback: function called between completion of bios in the request
1837  *                and completion of the request.
1838  *                If the callback returns non 0, this helper returns without
1839  *                completion of the request.
1840  *
1841  * Description:
1842  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
1843  *     If @rq has leftover, sets it up for the next range of segments.
1844  *
1845  * Return:
1846  *     0 - we are done with this request
1847  *     1 - this request is not freed yet, it still has pending buffers.
1848  **/
1849 static int blk_end_io(struct request *rq, int error, unsigned int nr_bytes,
1850                       unsigned int bidi_bytes,
1851                       int (drv_callback)(struct request *))
1852 {
1853         struct request_queue *q = rq->q;
1854         unsigned long flags = 0UL;
1855
1856         if (blk_fs_request(rq) || blk_pc_request(rq)) {
1857                 if (__end_that_request_first(rq, error, nr_bytes))
1858                         return 1;
1859
1860                 /* Bidi request must be completed as a whole */
1861                 if (blk_bidi_rq(rq) &&
1862                     __end_that_request_first(rq->next_rq, error, bidi_bytes))
1863                         return 1;
1864         }
1865
1866         /* Special feature for tricky drivers */
1867         if (drv_callback && drv_callback(rq))
1868                 return 1;
1869
1870         add_disk_randomness(rq->rq_disk);
1871
1872         spin_lock_irqsave(q->queue_lock, flags);
1873         end_that_request_last(rq, error);
1874         spin_unlock_irqrestore(q->queue_lock, flags);
1875
1876         return 0;
1877 }
1878
1879 /**
1880  * blk_end_request - Helper function for drivers to complete the request.
1881  * @rq:       the request being processed
1882  * @error:    0 for success, < 0 for error
1883  * @nr_bytes: number of bytes to complete
1884  *
1885  * Description:
1886  *     Ends I/O on a number of bytes attached to @rq.
1887  *     If @rq has leftover, sets it up for the next range of segments.
1888  *
1889  * Return:
1890  *     0 - we are done with this request
1891  *     1 - still buffers pending for this request
1892  **/
1893 int blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
1894 {
1895         return blk_end_io(rq, error, nr_bytes, 0, NULL);
1896 }
1897 EXPORT_SYMBOL_GPL(blk_end_request);
1898
1899 /**
1900  * __blk_end_request - Helper function for drivers to complete the request.
1901  * @rq:       the request being processed
1902  * @error:    0 for success, < 0 for error
1903  * @nr_bytes: number of bytes to complete
1904  *
1905  * Description:
1906  *     Must be called with queue lock held unlike blk_end_request().
1907  *
1908  * Return:
1909  *     0 - we are done with this request
1910  *     1 - still buffers pending for this request
1911  **/
1912 int __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
1913 {
1914         if (blk_fs_request(rq) || blk_pc_request(rq)) {
1915                 if (__end_that_request_first(rq, error, nr_bytes))
1916                         return 1;
1917         }
1918
1919         add_disk_randomness(rq->rq_disk);
1920
1921         end_that_request_last(rq, error);
1922
1923         return 0;
1924 }
1925 EXPORT_SYMBOL_GPL(__blk_end_request);
1926
1927 /**
1928  * blk_end_bidi_request - Helper function for drivers to complete bidi request.
1929  * @rq:         the bidi request being processed
1930  * @error:      0 for success, < 0 for error
1931  * @nr_bytes:   number of bytes to complete @rq
1932  * @bidi_bytes: number of bytes to complete @rq->next_rq
1933  *
1934  * Description:
1935  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
1936  *
1937  * Return:
1938  *     0 - we are done with this request
1939  *     1 - still buffers pending for this request
1940  **/
1941 int blk_end_bidi_request(struct request *rq, int error, unsigned int nr_bytes,
1942                          unsigned int bidi_bytes)
1943 {
1944         return blk_end_io(rq, error, nr_bytes, bidi_bytes, NULL);
1945 }
1946 EXPORT_SYMBOL_GPL(blk_end_bidi_request);
1947
1948 /**
1949  * blk_end_request_callback - Special helper function for tricky drivers
1950  * @rq:           the request being processed
1951  * @error:        0 for success, < 0 for error
1952  * @nr_bytes:     number of bytes to complete
1953  * @drv_callback: function called between completion of bios in the request
1954  *                and completion of the request.
1955  *                If the callback returns non 0, this helper returns without
1956  *                completion of the request.
1957  *
1958  * Description:
1959  *     Ends I/O on a number of bytes attached to @rq.
1960  *     If @rq has leftover, sets it up for the next range of segments.
1961  *
1962  *     This special helper function is used only for existing tricky drivers.
1963  *     (e.g. cdrom_newpc_intr() of ide-cd)
1964  *     This interface will be removed when such drivers are rewritten.
1965  *     Don't use this interface in other places anymore.
1966  *
1967  * Return:
1968  *     0 - we are done with this request
1969  *     1 - this request is not freed yet.
1970  *         this request still has pending buffers or
1971  *         the driver doesn't want to finish this request yet.
1972  **/
1973 int blk_end_request_callback(struct request *rq, int error,
1974                              unsigned int nr_bytes,
1975                              int (drv_callback)(struct request *))
1976 {
1977         return blk_end_io(rq, error, nr_bytes, 0, drv_callback);
1978 }
1979 EXPORT_SYMBOL_GPL(blk_end_request_callback);
1980
1981 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
1982                      struct bio *bio)
1983 {
1984         /* first two bits are identical in rq->cmd_flags and bio->bi_rw */
1985         rq->cmd_flags |= (bio->bi_rw & 3);
1986
1987         rq->nr_phys_segments = bio_phys_segments(q, bio);
1988         rq->nr_hw_segments = bio_hw_segments(q, bio);
1989         rq->current_nr_sectors = bio_cur_sectors(bio);
1990         rq->hard_cur_sectors = rq->current_nr_sectors;
1991         rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
1992         rq->buffer = bio_data(bio);
1993         rq->data_len = bio->bi_size;
1994
1995         rq->bio = rq->biotail = bio;
1996
1997         if (bio->bi_bdev)
1998                 rq->rq_disk = bio->bi_bdev->bd_disk;
1999 }
2000
2001 int kblockd_schedule_work(struct work_struct *work)
2002 {
2003         return queue_work(kblockd_workqueue, work);
2004 }
2005
2006 EXPORT_SYMBOL(kblockd_schedule_work);
2007
2008 void kblockd_flush_work(struct work_struct *work)
2009 {
2010         cancel_work_sync(work);
2011 }
2012 EXPORT_SYMBOL(kblockd_flush_work);
2013
2014 int __init blk_dev_init(void)
2015 {
2016         int i;
2017
2018         kblockd_workqueue = create_workqueue("kblockd");
2019         if (!kblockd_workqueue)
2020                 panic("Failed to create kblockd\n");
2021
2022         request_cachep = kmem_cache_create("blkdev_requests",
2023                         sizeof(struct request), 0, SLAB_PANIC, NULL);
2024
2025         blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2026                         sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2027
2028         for_each_possible_cpu(i)
2029                 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
2030
2031         open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
2032         register_hotcpu_notifier(&blk_cpu_notifier);
2033
2034         return 0;
2035 }
2036