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