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