blkio: Core implementation of throttle policy
[linux-flexiantxendom0-natty.git] / 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/fault-inject.h>
30
31 #define CREATE_TRACE_POINTS
32 #include <trace/events/block.h>
33
34 #include "blk.h"
35
36 EXPORT_TRACEPOINT_SYMBOL_GPL(block_remap);
37 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
38 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
39
40 static int __make_request(struct request_queue *q, struct bio *bio);
41
42 /*
43  * For the allocated request tables
44  */
45 static struct kmem_cache *request_cachep;
46
47 /*
48  * For queue allocation
49  */
50 struct kmem_cache *blk_requestq_cachep;
51
52 /*
53  * Controlling structure to kblockd
54  */
55 static struct workqueue_struct *kblockd_workqueue;
56
57 static void drive_stat_acct(struct request *rq, int new_io)
58 {
59         struct hd_struct *part;
60         int rw = rq_data_dir(rq);
61         int cpu;
62
63         if (!blk_do_io_stat(rq))
64                 return;
65
66         cpu = part_stat_lock();
67         part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
68
69         if (!new_io)
70                 part_stat_inc(cpu, part, merges[rw]);
71         else {
72                 part_round_stats(cpu, part);
73                 part_inc_in_flight(part, rw);
74         }
75
76         part_stat_unlock();
77 }
78
79 void blk_queue_congestion_threshold(struct request_queue *q)
80 {
81         int nr;
82
83         nr = q->nr_requests - (q->nr_requests / 8) + 1;
84         if (nr > q->nr_requests)
85                 nr = q->nr_requests;
86         q->nr_congestion_on = nr;
87
88         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
89         if (nr < 1)
90                 nr = 1;
91         q->nr_congestion_off = nr;
92 }
93
94 /**
95  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
96  * @bdev:       device
97  *
98  * Locates the passed device's request queue and returns the address of its
99  * backing_dev_info
100  *
101  * Will return NULL if the request queue cannot be located.
102  */
103 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
104 {
105         struct backing_dev_info *ret = NULL;
106         struct request_queue *q = bdev_get_queue(bdev);
107
108         if (q)
109                 ret = &q->backing_dev_info;
110         return ret;
111 }
112 EXPORT_SYMBOL(blk_get_backing_dev_info);
113
114 void blk_rq_init(struct request_queue *q, struct request *rq)
115 {
116         memset(rq, 0, sizeof(*rq));
117
118         INIT_LIST_HEAD(&rq->queuelist);
119         INIT_LIST_HEAD(&rq->timeout_list);
120         rq->cpu = -1;
121         rq->q = q;
122         rq->__sector = (sector_t) -1;
123         INIT_HLIST_NODE(&rq->hash);
124         RB_CLEAR_NODE(&rq->rb_node);
125         rq->cmd = rq->__cmd;
126         rq->cmd_len = BLK_MAX_CDB;
127         rq->tag = -1;
128         rq->ref_count = 1;
129         rq->start_time = jiffies;
130         set_start_time_ns(rq);
131 }
132 EXPORT_SYMBOL(blk_rq_init);
133
134 static void req_bio_endio(struct request *rq, struct bio *bio,
135                           unsigned int nbytes, int error)
136 {
137         struct request_queue *q = rq->q;
138
139         if (&q->bar_rq != rq) {
140                 if (error)
141                         clear_bit(BIO_UPTODATE, &bio->bi_flags);
142                 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
143                         error = -EIO;
144
145                 if (unlikely(nbytes > bio->bi_size)) {
146                         printk(KERN_ERR "%s: want %u bytes done, %u left\n",
147                                __func__, nbytes, bio->bi_size);
148                         nbytes = bio->bi_size;
149                 }
150
151                 if (unlikely(rq->cmd_flags & REQ_QUIET))
152                         set_bit(BIO_QUIET, &bio->bi_flags);
153
154                 bio->bi_size -= nbytes;
155                 bio->bi_sector += (nbytes >> 9);
156
157                 if (bio_integrity(bio))
158                         bio_integrity_advance(bio, nbytes);
159
160                 if (bio->bi_size == 0)
161                         bio_endio(bio, error);
162         } else {
163
164                 /*
165                  * Okay, this is the barrier request in progress, just
166                  * record the error;
167                  */
168                 if (error && !q->orderr)
169                         q->orderr = error;
170         }
171 }
172
173 void blk_dump_rq_flags(struct request *rq, char *msg)
174 {
175         int bit;
176
177         printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
178                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
179                 rq->cmd_flags);
180
181         printk(KERN_INFO "  sector %llu, nr/cnr %u/%u\n",
182                (unsigned long long)blk_rq_pos(rq),
183                blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
184         printk(KERN_INFO "  bio %p, biotail %p, buffer %p, len %u\n",
185                rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
186
187         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
188                 printk(KERN_INFO "  cdb: ");
189                 for (bit = 0; bit < BLK_MAX_CDB; bit++)
190                         printk("%02x ", rq->cmd[bit]);
191                 printk("\n");
192         }
193 }
194 EXPORT_SYMBOL(blk_dump_rq_flags);
195
196 /*
197  * "plug" the device if there are no outstanding requests: this will
198  * force the transfer to start only after we have put all the requests
199  * on the list.
200  *
201  * This is called with interrupts off and no requests on the queue and
202  * with the queue lock held.
203  */
204 void blk_plug_device(struct request_queue *q)
205 {
206         WARN_ON(!irqs_disabled());
207
208         /*
209          * don't plug a stopped queue, it must be paired with blk_start_queue()
210          * which will restart the queueing
211          */
212         if (blk_queue_stopped(q))
213                 return;
214
215         if (!queue_flag_test_and_set(QUEUE_FLAG_PLUGGED, q)) {
216                 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
217                 trace_block_plug(q);
218         }
219 }
220 EXPORT_SYMBOL(blk_plug_device);
221
222 /**
223  * blk_plug_device_unlocked - plug a device without queue lock held
224  * @q:    The &struct request_queue to plug
225  *
226  * Description:
227  *   Like @blk_plug_device(), but grabs the queue lock and disables
228  *   interrupts.
229  **/
230 void blk_plug_device_unlocked(struct request_queue *q)
231 {
232         unsigned long flags;
233
234         spin_lock_irqsave(q->queue_lock, flags);
235         blk_plug_device(q);
236         spin_unlock_irqrestore(q->queue_lock, flags);
237 }
238 EXPORT_SYMBOL(blk_plug_device_unlocked);
239
240 /*
241  * remove the queue from the plugged list, if present. called with
242  * queue lock held and interrupts disabled.
243  */
244 int blk_remove_plug(struct request_queue *q)
245 {
246         WARN_ON(!irqs_disabled());
247
248         if (!queue_flag_test_and_clear(QUEUE_FLAG_PLUGGED, q))
249                 return 0;
250
251         del_timer(&q->unplug_timer);
252         return 1;
253 }
254 EXPORT_SYMBOL(blk_remove_plug);
255
256 /*
257  * remove the plug and let it rip..
258  */
259 void __generic_unplug_device(struct request_queue *q)
260 {
261         if (unlikely(blk_queue_stopped(q)))
262                 return;
263         if (!blk_remove_plug(q) && !blk_queue_nonrot(q))
264                 return;
265
266         q->request_fn(q);
267 }
268
269 /**
270  * generic_unplug_device - fire a request queue
271  * @q:    The &struct request_queue in question
272  *
273  * Description:
274  *   Linux uses plugging to build bigger requests queues before letting
275  *   the device have at them. If a queue is plugged, the I/O scheduler
276  *   is still adding and merging requests on the queue. Once the queue
277  *   gets unplugged, the request_fn defined for the queue is invoked and
278  *   transfers started.
279  **/
280 void generic_unplug_device(struct request_queue *q)
281 {
282         if (blk_queue_plugged(q)) {
283                 spin_lock_irq(q->queue_lock);
284                 __generic_unplug_device(q);
285                 spin_unlock_irq(q->queue_lock);
286         }
287 }
288 EXPORT_SYMBOL(generic_unplug_device);
289
290 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
291                                    struct page *page)
292 {
293         struct request_queue *q = bdi->unplug_io_data;
294
295         blk_unplug(q);
296 }
297
298 void blk_unplug_work(struct work_struct *work)
299 {
300         struct request_queue *q =
301                 container_of(work, struct request_queue, unplug_work);
302
303         trace_block_unplug_io(q);
304         q->unplug_fn(q);
305 }
306
307 void blk_unplug_timeout(unsigned long data)
308 {
309         struct request_queue *q = (struct request_queue *)data;
310
311         trace_block_unplug_timer(q);
312         kblockd_schedule_work(q, &q->unplug_work);
313 }
314
315 void blk_unplug(struct request_queue *q)
316 {
317         /*
318          * devices don't necessarily have an ->unplug_fn defined
319          */
320         if (q->unplug_fn) {
321                 trace_block_unplug_io(q);
322                 q->unplug_fn(q);
323         }
324 }
325 EXPORT_SYMBOL(blk_unplug);
326
327 /**
328  * blk_start_queue - restart a previously stopped queue
329  * @q:    The &struct request_queue in question
330  *
331  * Description:
332  *   blk_start_queue() will clear the stop flag on the queue, and call
333  *   the request_fn for the queue if it was in a stopped state when
334  *   entered. Also see blk_stop_queue(). Queue lock must be held.
335  **/
336 void blk_start_queue(struct request_queue *q)
337 {
338         WARN_ON(!irqs_disabled());
339
340         queue_flag_clear(QUEUE_FLAG_STOPPED, q);
341         __blk_run_queue(q);
342 }
343 EXPORT_SYMBOL(blk_start_queue);
344
345 /**
346  * blk_stop_queue - stop a queue
347  * @q:    The &struct request_queue in question
348  *
349  * Description:
350  *   The Linux block layer assumes that a block driver will consume all
351  *   entries on the request queue when the request_fn strategy is called.
352  *   Often this will not happen, because of hardware limitations (queue
353  *   depth settings). If a device driver gets a 'queue full' response,
354  *   or if it simply chooses not to queue more I/O at one point, it can
355  *   call this function to prevent the request_fn from being called until
356  *   the driver has signalled it's ready to go again. This happens by calling
357  *   blk_start_queue() to restart queue operations. Queue lock must be held.
358  **/
359 void blk_stop_queue(struct request_queue *q)
360 {
361         blk_remove_plug(q);
362         queue_flag_set(QUEUE_FLAG_STOPPED, q);
363 }
364 EXPORT_SYMBOL(blk_stop_queue);
365
366 /**
367  * blk_sync_queue - cancel any pending callbacks on a queue
368  * @q: the queue
369  *
370  * Description:
371  *     The block layer may perform asynchronous callback activity
372  *     on a queue, such as calling the unplug function after a timeout.
373  *     A block device may call blk_sync_queue to ensure that any
374  *     such activity is cancelled, thus allowing it to release resources
375  *     that the callbacks might use. The caller must already have made sure
376  *     that its ->make_request_fn will not re-add plugging prior to calling
377  *     this function.
378  *
379  */
380 void blk_sync_queue(struct request_queue *q)
381 {
382         del_timer_sync(&q->unplug_timer);
383         del_timer_sync(&q->timeout);
384         cancel_work_sync(&q->unplug_work);
385         throtl_shutdown_timer_wq(q);
386 }
387 EXPORT_SYMBOL(blk_sync_queue);
388
389 /**
390  * __blk_run_queue - run a single device queue
391  * @q:  The queue to run
392  *
393  * Description:
394  *    See @blk_run_queue. This variant must be called with the queue lock
395  *    held and interrupts disabled.
396  *
397  */
398 void __blk_run_queue(struct request_queue *q)
399 {
400         blk_remove_plug(q);
401
402         if (unlikely(blk_queue_stopped(q)))
403                 return;
404
405         if (elv_queue_empty(q))
406                 return;
407
408         /*
409          * Only recurse once to avoid overrunning the stack, let the unplug
410          * handling reinvoke the handler shortly if we already got there.
411          */
412         if (!queue_flag_test_and_set(QUEUE_FLAG_REENTER, q)) {
413                 q->request_fn(q);
414                 queue_flag_clear(QUEUE_FLAG_REENTER, q);
415         } else {
416                 queue_flag_set(QUEUE_FLAG_PLUGGED, q);
417                 kblockd_schedule_work(q, &q->unplug_work);
418         }
419 }
420 EXPORT_SYMBOL(__blk_run_queue);
421
422 /**
423  * blk_run_queue - run a single device queue
424  * @q: The queue to run
425  *
426  * Description:
427  *    Invoke request handling on this queue, if it has pending work to do.
428  *    May be used to restart queueing when a request has completed.
429  */
430 void blk_run_queue(struct request_queue *q)
431 {
432         unsigned long flags;
433
434         spin_lock_irqsave(q->queue_lock, flags);
435         __blk_run_queue(q);
436         spin_unlock_irqrestore(q->queue_lock, flags);
437 }
438 EXPORT_SYMBOL(blk_run_queue);
439
440 void blk_put_queue(struct request_queue *q)
441 {
442         kobject_put(&q->kobj);
443 }
444
445 void blk_cleanup_queue(struct request_queue *q)
446 {
447         /*
448          * We know we have process context here, so we can be a little
449          * cautious and ensure that pending block actions on this device
450          * are done before moving on. Going into this function, we should
451          * not have processes doing IO to this device.
452          */
453         blk_sync_queue(q);
454
455         del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
456         mutex_lock(&q->sysfs_lock);
457         queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);
458         mutex_unlock(&q->sysfs_lock);
459
460         if (q->elevator)
461                 elevator_exit(q->elevator);
462
463         blk_throtl_exit(q);
464
465         blk_put_queue(q);
466 }
467 EXPORT_SYMBOL(blk_cleanup_queue);
468
469 static int blk_init_free_list(struct request_queue *q)
470 {
471         struct request_list *rl = &q->rq;
472
473         if (unlikely(rl->rq_pool))
474                 return 0;
475
476         rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
477         rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
478         rl->elvpriv = 0;
479         init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
480         init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
481
482         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
483                                 mempool_free_slab, request_cachep, q->node);
484
485         if (!rl->rq_pool)
486                 return -ENOMEM;
487
488         return 0;
489 }
490
491 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
492 {
493         return blk_alloc_queue_node(gfp_mask, -1);
494 }
495 EXPORT_SYMBOL(blk_alloc_queue);
496
497 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
498 {
499         struct request_queue *q;
500         int err;
501
502         q = kmem_cache_alloc_node(blk_requestq_cachep,
503                                 gfp_mask | __GFP_ZERO, node_id);
504         if (!q)
505                 return NULL;
506
507         q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
508         q->backing_dev_info.unplug_io_data = q;
509         q->backing_dev_info.ra_pages =
510                         (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
511         q->backing_dev_info.state = 0;
512         q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
513         q->backing_dev_info.name = "block";
514
515         err = bdi_init(&q->backing_dev_info);
516         if (err) {
517                 kmem_cache_free(blk_requestq_cachep, q);
518                 return NULL;
519         }
520
521         if (blk_throtl_init(q)) {
522                 kmem_cache_free(blk_requestq_cachep, q);
523                 return NULL;
524         }
525
526         setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
527                     laptop_mode_timer_fn, (unsigned long) q);
528         init_timer(&q->unplug_timer);
529         setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
530         INIT_LIST_HEAD(&q->timeout_list);
531         INIT_WORK(&q->unplug_work, blk_unplug_work);
532
533         kobject_init(&q->kobj, &blk_queue_ktype);
534
535         mutex_init(&q->sysfs_lock);
536         spin_lock_init(&q->__queue_lock);
537
538         return q;
539 }
540 EXPORT_SYMBOL(blk_alloc_queue_node);
541
542 /**
543  * blk_init_queue  - prepare a request queue for use with a block device
544  * @rfn:  The function to be called to process requests that have been
545  *        placed on the queue.
546  * @lock: Request queue spin lock
547  *
548  * Description:
549  *    If a block device wishes to use the standard request handling procedures,
550  *    which sorts requests and coalesces adjacent requests, then it must
551  *    call blk_init_queue().  The function @rfn will be called when there
552  *    are requests on the queue that need to be processed.  If the device
553  *    supports plugging, then @rfn may not be called immediately when requests
554  *    are available on the queue, but may be called at some time later instead.
555  *    Plugged queues are generally unplugged when a buffer belonging to one
556  *    of the requests on the queue is needed, or due to memory pressure.
557  *
558  *    @rfn is not required, or even expected, to remove all requests off the
559  *    queue, but only as many as it can handle at a time.  If it does leave
560  *    requests on the queue, it is responsible for arranging that the requests
561  *    get dealt with eventually.
562  *
563  *    The queue spin lock must be held while manipulating the requests on the
564  *    request queue; this lock will be taken also from interrupt context, so irq
565  *    disabling is needed for it.
566  *
567  *    Function returns a pointer to the initialized request queue, or %NULL if
568  *    it didn't succeed.
569  *
570  * Note:
571  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
572  *    when the block device is deactivated (such as at module unload).
573  **/
574
575 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
576 {
577         return blk_init_queue_node(rfn, lock, -1);
578 }
579 EXPORT_SYMBOL(blk_init_queue);
580
581 struct request_queue *
582 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
583 {
584         struct request_queue *uninit_q, *q;
585
586         uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
587         if (!uninit_q)
588                 return NULL;
589
590         q = blk_init_allocated_queue_node(uninit_q, rfn, lock, node_id);
591         if (!q)
592                 blk_cleanup_queue(uninit_q);
593
594         return q;
595 }
596 EXPORT_SYMBOL(blk_init_queue_node);
597
598 struct request_queue *
599 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
600                          spinlock_t *lock)
601 {
602         return blk_init_allocated_queue_node(q, rfn, lock, -1);
603 }
604 EXPORT_SYMBOL(blk_init_allocated_queue);
605
606 struct request_queue *
607 blk_init_allocated_queue_node(struct request_queue *q, request_fn_proc *rfn,
608                               spinlock_t *lock, int node_id)
609 {
610         if (!q)
611                 return NULL;
612
613         q->node = node_id;
614         if (blk_init_free_list(q))
615                 return NULL;
616
617         q->request_fn           = rfn;
618         q->prep_rq_fn           = NULL;
619         q->unprep_rq_fn         = NULL;
620         q->unplug_fn            = generic_unplug_device;
621         q->queue_flags          = QUEUE_FLAG_DEFAULT;
622         q->queue_lock           = lock;
623
624         /*
625          * This also sets hw/phys segments, boundary and size
626          */
627         blk_queue_make_request(q, __make_request);
628
629         q->sg_reserved_size = INT_MAX;
630
631         /*
632          * all done
633          */
634         if (!elevator_init(q, NULL)) {
635                 blk_queue_congestion_threshold(q);
636                 return q;
637         }
638
639         return NULL;
640 }
641 EXPORT_SYMBOL(blk_init_allocated_queue_node);
642
643 int blk_get_queue(struct request_queue *q)
644 {
645         if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
646                 kobject_get(&q->kobj);
647                 return 0;
648         }
649
650         return 1;
651 }
652
653 static inline void blk_free_request(struct request_queue *q, struct request *rq)
654 {
655         if (rq->cmd_flags & REQ_ELVPRIV)
656                 elv_put_request(q, rq);
657         mempool_free(rq, q->rq.rq_pool);
658 }
659
660 static struct request *
661 blk_alloc_request(struct request_queue *q, int flags, int priv, gfp_t gfp_mask)
662 {
663         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
664
665         if (!rq)
666                 return NULL;
667
668         blk_rq_init(q, rq);
669
670         rq->cmd_flags = flags | REQ_ALLOCED;
671
672         if (priv) {
673                 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
674                         mempool_free(rq, q->rq.rq_pool);
675                         return NULL;
676                 }
677                 rq->cmd_flags |= REQ_ELVPRIV;
678         }
679
680         return rq;
681 }
682
683 /*
684  * ioc_batching returns true if the ioc is a valid batching request and
685  * should be given priority access to a request.
686  */
687 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
688 {
689         if (!ioc)
690                 return 0;
691
692         /*
693          * Make sure the process is able to allocate at least 1 request
694          * even if the batch times out, otherwise we could theoretically
695          * lose wakeups.
696          */
697         return ioc->nr_batch_requests == q->nr_batching ||
698                 (ioc->nr_batch_requests > 0
699                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
700 }
701
702 /*
703  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
704  * will cause the process to be a "batcher" on all queues in the system. This
705  * is the behaviour we want though - once it gets a wakeup it should be given
706  * a nice run.
707  */
708 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
709 {
710         if (!ioc || ioc_batching(q, ioc))
711                 return;
712
713         ioc->nr_batch_requests = q->nr_batching;
714         ioc->last_waited = jiffies;
715 }
716
717 static void __freed_request(struct request_queue *q, int sync)
718 {
719         struct request_list *rl = &q->rq;
720
721         if (rl->count[sync] < queue_congestion_off_threshold(q))
722                 blk_clear_queue_congested(q, sync);
723
724         if (rl->count[sync] + 1 <= q->nr_requests) {
725                 if (waitqueue_active(&rl->wait[sync]))
726                         wake_up(&rl->wait[sync]);
727
728                 blk_clear_queue_full(q, sync);
729         }
730 }
731
732 /*
733  * A request has just been released.  Account for it, update the full and
734  * congestion status, wake up any waiters.   Called under q->queue_lock.
735  */
736 static void freed_request(struct request_queue *q, int sync, int priv)
737 {
738         struct request_list *rl = &q->rq;
739
740         rl->count[sync]--;
741         if (priv)
742                 rl->elvpriv--;
743
744         __freed_request(q, sync);
745
746         if (unlikely(rl->starved[sync ^ 1]))
747                 __freed_request(q, sync ^ 1);
748 }
749
750 /*
751  * Get a free request, queue_lock must be held.
752  * Returns NULL on failure, with queue_lock held.
753  * Returns !NULL on success, with queue_lock *not held*.
754  */
755 static struct request *get_request(struct request_queue *q, int rw_flags,
756                                    struct bio *bio, gfp_t gfp_mask)
757 {
758         struct request *rq = NULL;
759         struct request_list *rl = &q->rq;
760         struct io_context *ioc = NULL;
761         const bool is_sync = rw_is_sync(rw_flags) != 0;
762         int may_queue, priv;
763
764         may_queue = elv_may_queue(q, rw_flags);
765         if (may_queue == ELV_MQUEUE_NO)
766                 goto rq_starved;
767
768         if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
769                 if (rl->count[is_sync]+1 >= q->nr_requests) {
770                         ioc = current_io_context(GFP_ATOMIC, q->node);
771                         /*
772                          * The queue will fill after this allocation, so set
773                          * it as full, and mark this process as "batching".
774                          * This process will be allowed to complete a batch of
775                          * requests, others will be blocked.
776                          */
777                         if (!blk_queue_full(q, is_sync)) {
778                                 ioc_set_batching(q, ioc);
779                                 blk_set_queue_full(q, is_sync);
780                         } else {
781                                 if (may_queue != ELV_MQUEUE_MUST
782                                                 && !ioc_batching(q, ioc)) {
783                                         /*
784                                          * The queue is full and the allocating
785                                          * process is not a "batcher", and not
786                                          * exempted by the IO scheduler
787                                          */
788                                         goto out;
789                                 }
790                         }
791                 }
792                 blk_set_queue_congested(q, is_sync);
793         }
794
795         /*
796          * Only allow batching queuers to allocate up to 50% over the defined
797          * limit of requests, otherwise we could have thousands of requests
798          * allocated with any setting of ->nr_requests
799          */
800         if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
801                 goto out;
802
803         rl->count[is_sync]++;
804         rl->starved[is_sync] = 0;
805
806         priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
807         if (priv)
808                 rl->elvpriv++;
809
810         if (blk_queue_io_stat(q))
811                 rw_flags |= REQ_IO_STAT;
812         spin_unlock_irq(q->queue_lock);
813
814         rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
815         if (unlikely(!rq)) {
816                 /*
817                  * Allocation failed presumably due to memory. Undo anything
818                  * we might have messed up.
819                  *
820                  * Allocating task should really be put onto the front of the
821                  * wait queue, but this is pretty rare.
822                  */
823                 spin_lock_irq(q->queue_lock);
824                 freed_request(q, is_sync, priv);
825
826                 /*
827                  * in the very unlikely event that allocation failed and no
828                  * requests for this direction was pending, mark us starved
829                  * so that freeing of a request in the other direction will
830                  * notice us. another possible fix would be to split the
831                  * rq mempool into READ and WRITE
832                  */
833 rq_starved:
834                 if (unlikely(rl->count[is_sync] == 0))
835                         rl->starved[is_sync] = 1;
836
837                 goto out;
838         }
839
840         /*
841          * ioc may be NULL here, and ioc_batching will be false. That's
842          * OK, if the queue is under the request limit then requests need
843          * not count toward the nr_batch_requests limit. There will always
844          * be some limit enforced by BLK_BATCH_TIME.
845          */
846         if (ioc_batching(q, ioc))
847                 ioc->nr_batch_requests--;
848
849         trace_block_getrq(q, bio, rw_flags & 1);
850 out:
851         return rq;
852 }
853
854 /*
855  * No available requests for this queue, unplug the device and wait for some
856  * requests to become available.
857  *
858  * Called with q->queue_lock held, and returns with it unlocked.
859  */
860 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
861                                         struct bio *bio)
862 {
863         const bool is_sync = rw_is_sync(rw_flags) != 0;
864         struct request *rq;
865
866         rq = get_request(q, rw_flags, bio, GFP_NOIO);
867         while (!rq) {
868                 DEFINE_WAIT(wait);
869                 struct io_context *ioc;
870                 struct request_list *rl = &q->rq;
871
872                 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
873                                 TASK_UNINTERRUPTIBLE);
874
875                 trace_block_sleeprq(q, bio, rw_flags & 1);
876
877                 __generic_unplug_device(q);
878                 spin_unlock_irq(q->queue_lock);
879                 io_schedule();
880
881                 /*
882                  * After sleeping, we become a "batching" process and
883                  * will be able to allocate at least one request, and
884                  * up to a big batch of them for a small period time.
885                  * See ioc_batching, ioc_set_batching
886                  */
887                 ioc = current_io_context(GFP_NOIO, q->node);
888                 ioc_set_batching(q, ioc);
889
890                 spin_lock_irq(q->queue_lock);
891                 finish_wait(&rl->wait[is_sync], &wait);
892
893                 rq = get_request(q, rw_flags, bio, GFP_NOIO);
894         };
895
896         return rq;
897 }
898
899 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
900 {
901         struct request *rq;
902
903         BUG_ON(rw != READ && rw != WRITE);
904
905         spin_lock_irq(q->queue_lock);
906         if (gfp_mask & __GFP_WAIT) {
907                 rq = get_request_wait(q, rw, NULL);
908         } else {
909                 rq = get_request(q, rw, NULL, gfp_mask);
910                 if (!rq)
911                         spin_unlock_irq(q->queue_lock);
912         }
913         /* q->queue_lock is unlocked at this point */
914
915         return rq;
916 }
917 EXPORT_SYMBOL(blk_get_request);
918
919 /**
920  * blk_make_request - given a bio, allocate a corresponding struct request.
921  * @q: target request queue
922  * @bio:  The bio describing the memory mappings that will be submitted for IO.
923  *        It may be a chained-bio properly constructed by block/bio layer.
924  * @gfp_mask: gfp flags to be used for memory allocation
925  *
926  * blk_make_request is the parallel of generic_make_request for BLOCK_PC
927  * type commands. Where the struct request needs to be farther initialized by
928  * the caller. It is passed a &struct bio, which describes the memory info of
929  * the I/O transfer.
930  *
931  * The caller of blk_make_request must make sure that bi_io_vec
932  * are set to describe the memory buffers. That bio_data_dir() will return
933  * the needed direction of the request. (And all bio's in the passed bio-chain
934  * are properly set accordingly)
935  *
936  * If called under none-sleepable conditions, mapped bio buffers must not
937  * need bouncing, by calling the appropriate masked or flagged allocator,
938  * suitable for the target device. Otherwise the call to blk_queue_bounce will
939  * BUG.
940  *
941  * WARNING: When allocating/cloning a bio-chain, careful consideration should be
942  * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
943  * anything but the first bio in the chain. Otherwise you risk waiting for IO
944  * completion of a bio that hasn't been submitted yet, thus resulting in a
945  * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
946  * of bio_alloc(), as that avoids the mempool deadlock.
947  * If possible a big IO should be split into smaller parts when allocation
948  * fails. Partial allocation should not be an error, or you risk a live-lock.
949  */
950 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
951                                  gfp_t gfp_mask)
952 {
953         struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
954
955         if (unlikely(!rq))
956                 return ERR_PTR(-ENOMEM);
957
958         for_each_bio(bio) {
959                 struct bio *bounce_bio = bio;
960                 int ret;
961
962                 blk_queue_bounce(q, &bounce_bio);
963                 ret = blk_rq_append_bio(q, rq, bounce_bio);
964                 if (unlikely(ret)) {
965                         blk_put_request(rq);
966                         return ERR_PTR(ret);
967                 }
968         }
969
970         return rq;
971 }
972 EXPORT_SYMBOL(blk_make_request);
973
974 /**
975  * blk_requeue_request - put a request back on queue
976  * @q:          request queue where request should be inserted
977  * @rq:         request to be inserted
978  *
979  * Description:
980  *    Drivers often keep queueing requests until the hardware cannot accept
981  *    more, when that condition happens we need to put the request back
982  *    on the queue. Must be called with queue lock held.
983  */
984 void blk_requeue_request(struct request_queue *q, struct request *rq)
985 {
986         blk_delete_timer(rq);
987         blk_clear_rq_complete(rq);
988         trace_block_rq_requeue(q, rq);
989
990         if (blk_rq_tagged(rq))
991                 blk_queue_end_tag(q, rq);
992
993         BUG_ON(blk_queued_rq(rq));
994
995         elv_requeue_request(q, rq);
996 }
997 EXPORT_SYMBOL(blk_requeue_request);
998
999 /**
1000  * blk_insert_request - insert a special request into a request queue
1001  * @q:          request queue where request should be inserted
1002  * @rq:         request to be inserted
1003  * @at_head:    insert request at head or tail of queue
1004  * @data:       private data
1005  *
1006  * Description:
1007  *    Many block devices need to execute commands asynchronously, so they don't
1008  *    block the whole kernel from preemption during request execution.  This is
1009  *    accomplished normally by inserting aritficial requests tagged as
1010  *    REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them
1011  *    be scheduled for actual execution by the request queue.
1012  *
1013  *    We have the option of inserting the head or the tail of the queue.
1014  *    Typically we use the tail for new ioctls and so forth.  We use the head
1015  *    of the queue for things like a QUEUE_FULL message from a device, or a
1016  *    host that is unable to accept a particular command.
1017  */
1018 void blk_insert_request(struct request_queue *q, struct request *rq,
1019                         int at_head, void *data)
1020 {
1021         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
1022         unsigned long flags;
1023
1024         /*
1025          * tell I/O scheduler that this isn't a regular read/write (ie it
1026          * must not attempt merges on this) and that it acts as a soft
1027          * barrier
1028          */
1029         rq->cmd_type = REQ_TYPE_SPECIAL;
1030
1031         rq->special = data;
1032
1033         spin_lock_irqsave(q->queue_lock, flags);
1034
1035         /*
1036          * If command is tagged, release the tag
1037          */
1038         if (blk_rq_tagged(rq))
1039                 blk_queue_end_tag(q, rq);
1040
1041         drive_stat_acct(rq, 1);
1042         __elv_add_request(q, rq, where, 0);
1043         __blk_run_queue(q);
1044         spin_unlock_irqrestore(q->queue_lock, flags);
1045 }
1046 EXPORT_SYMBOL(blk_insert_request);
1047
1048 /*
1049  * add-request adds a request to the linked list.
1050  * queue lock is held and interrupts disabled, as we muck with the
1051  * request queue list.
1052  */
1053 static inline void add_request(struct request_queue *q, struct request *req)
1054 {
1055         drive_stat_acct(req, 1);
1056
1057         /*
1058          * elevator indicated where it wants this request to be
1059          * inserted at elevator_merge time
1060          */
1061         __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1062 }
1063
1064 static void part_round_stats_single(int cpu, struct hd_struct *part,
1065                                     unsigned long now)
1066 {
1067         if (now == part->stamp)
1068                 return;
1069
1070         if (part_in_flight(part)) {
1071                 __part_stat_add(cpu, part, time_in_queue,
1072                                 part_in_flight(part) * (now - part->stamp));
1073                 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1074         }
1075         part->stamp = now;
1076 }
1077
1078 /**
1079  * part_round_stats() - Round off the performance stats on a struct disk_stats.
1080  * @cpu: cpu number for stats access
1081  * @part: target partition
1082  *
1083  * The average IO queue length and utilisation statistics are maintained
1084  * by observing the current state of the queue length and the amount of
1085  * time it has been in this state for.
1086  *
1087  * Normally, that accounting is done on IO completion, but that can result
1088  * in more than a second's worth of IO being accounted for within any one
1089  * second, leading to >100% utilisation.  To deal with that, we call this
1090  * function to do a round-off before returning the results when reading
1091  * /proc/diskstats.  This accounts immediately for all queue usage up to
1092  * the current jiffies and restarts the counters again.
1093  */
1094 void part_round_stats(int cpu, struct hd_struct *part)
1095 {
1096         unsigned long now = jiffies;
1097
1098         if (part->partno)
1099                 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1100         part_round_stats_single(cpu, part, now);
1101 }
1102 EXPORT_SYMBOL_GPL(part_round_stats);
1103
1104 /*
1105  * queue lock must be held
1106  */
1107 void __blk_put_request(struct request_queue *q, struct request *req)
1108 {
1109         if (unlikely(!q))
1110                 return;
1111         if (unlikely(--req->ref_count))
1112                 return;
1113
1114         elv_completed_request(q, req);
1115
1116         /* this is a bio leak */
1117         WARN_ON(req->bio != NULL);
1118
1119         /*
1120          * Request may not have originated from ll_rw_blk. if not,
1121          * it didn't come out of our reserved rq pools
1122          */
1123         if (req->cmd_flags & REQ_ALLOCED) {
1124                 int is_sync = rq_is_sync(req) != 0;
1125                 int priv = req->cmd_flags & REQ_ELVPRIV;
1126
1127                 BUG_ON(!list_empty(&req->queuelist));
1128                 BUG_ON(!hlist_unhashed(&req->hash));
1129
1130                 blk_free_request(q, req);
1131                 freed_request(q, is_sync, priv);
1132         }
1133 }
1134 EXPORT_SYMBOL_GPL(__blk_put_request);
1135
1136 void blk_put_request(struct request *req)
1137 {
1138         unsigned long flags;
1139         struct request_queue *q = req->q;
1140
1141         spin_lock_irqsave(q->queue_lock, flags);
1142         __blk_put_request(q, req);
1143         spin_unlock_irqrestore(q->queue_lock, flags);
1144 }
1145 EXPORT_SYMBOL(blk_put_request);
1146
1147 /**
1148  * blk_add_request_payload - add a payload to a request
1149  * @rq: request to update
1150  * @page: page backing the payload
1151  * @len: length of the payload.
1152  *
1153  * This allows to later add a payload to an already submitted request by
1154  * a block driver.  The driver needs to take care of freeing the payload
1155  * itself.
1156  *
1157  * Note that this is a quite horrible hack and nothing but handling of
1158  * discard requests should ever use it.
1159  */
1160 void blk_add_request_payload(struct request *rq, struct page *page,
1161                 unsigned int len)
1162 {
1163         struct bio *bio = rq->bio;
1164
1165         bio->bi_io_vec->bv_page = page;
1166         bio->bi_io_vec->bv_offset = 0;
1167         bio->bi_io_vec->bv_len = len;
1168
1169         bio->bi_size = len;
1170         bio->bi_vcnt = 1;
1171         bio->bi_phys_segments = 1;
1172
1173         rq->__data_len = rq->resid_len = len;
1174         rq->nr_phys_segments = 1;
1175         rq->buffer = bio_data(bio);
1176 }
1177 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1178
1179 void init_request_from_bio(struct request *req, struct bio *bio)
1180 {
1181         req->cpu = bio->bi_comp_cpu;
1182         req->cmd_type = REQ_TYPE_FS;
1183
1184         req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1185         if (bio->bi_rw & REQ_RAHEAD)
1186                 req->cmd_flags |= REQ_FAILFAST_MASK;
1187
1188         req->errors = 0;
1189         req->__sector = bio->bi_sector;
1190         req->ioprio = bio_prio(bio);
1191         blk_rq_bio_prep(req->q, req, bio);
1192 }
1193
1194 /*
1195  * Only disabling plugging for non-rotational devices if it does tagging
1196  * as well, otherwise we do need the proper merging
1197  */
1198 static inline bool queue_should_plug(struct request_queue *q)
1199 {
1200         return !(blk_queue_nonrot(q) && blk_queue_tagged(q));
1201 }
1202
1203 static int __make_request(struct request_queue *q, struct bio *bio)
1204 {
1205         struct request *req;
1206         int el_ret;
1207         unsigned int bytes = bio->bi_size;
1208         const unsigned short prio = bio_prio(bio);
1209         const bool sync = (bio->bi_rw & REQ_SYNC);
1210         const bool unplug = (bio->bi_rw & REQ_UNPLUG);
1211         const unsigned int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1212         int rw_flags;
1213
1214         if ((bio->bi_rw & REQ_HARDBARRIER) &&
1215             (q->next_ordered == QUEUE_ORDERED_NONE)) {
1216                 bio_endio(bio, -EOPNOTSUPP);
1217                 return 0;
1218         }
1219         /*
1220          * low level driver can indicate that it wants pages above a
1221          * certain limit bounced to low memory (ie for highmem, or even
1222          * ISA dma in theory)
1223          */
1224         blk_queue_bounce(q, &bio);
1225
1226         spin_lock_irq(q->queue_lock);
1227
1228         if (unlikely((bio->bi_rw & REQ_HARDBARRIER)) || elv_queue_empty(q))
1229                 goto get_rq;
1230
1231         el_ret = elv_merge(q, &req, bio);
1232         switch (el_ret) {
1233         case ELEVATOR_BACK_MERGE:
1234                 BUG_ON(!rq_mergeable(req));
1235
1236                 if (!ll_back_merge_fn(q, req, bio))
1237                         break;
1238
1239                 trace_block_bio_backmerge(q, bio);
1240
1241                 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1242                         blk_rq_set_mixed_merge(req);
1243
1244                 req->biotail->bi_next = bio;
1245                 req->biotail = bio;
1246                 req->__data_len += bytes;
1247                 req->ioprio = ioprio_best(req->ioprio, prio);
1248                 if (!blk_rq_cpu_valid(req))
1249                         req->cpu = bio->bi_comp_cpu;
1250                 drive_stat_acct(req, 0);
1251                 elv_bio_merged(q, req, bio);
1252                 if (!attempt_back_merge(q, req))
1253                         elv_merged_request(q, req, el_ret);
1254                 goto out;
1255
1256         case ELEVATOR_FRONT_MERGE:
1257                 BUG_ON(!rq_mergeable(req));
1258
1259                 if (!ll_front_merge_fn(q, req, bio))
1260                         break;
1261
1262                 trace_block_bio_frontmerge(q, bio);
1263
1264                 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff) {
1265                         blk_rq_set_mixed_merge(req);
1266                         req->cmd_flags &= ~REQ_FAILFAST_MASK;
1267                         req->cmd_flags |= ff;
1268                 }
1269
1270                 bio->bi_next = req->bio;
1271                 req->bio = bio;
1272
1273                 /*
1274                  * may not be valid. if the low level driver said
1275                  * it didn't need a bounce buffer then it better
1276                  * not touch req->buffer either...
1277                  */
1278                 req->buffer = bio_data(bio);
1279                 req->__sector = bio->bi_sector;
1280                 req->__data_len += bytes;
1281                 req->ioprio = ioprio_best(req->ioprio, prio);
1282                 if (!blk_rq_cpu_valid(req))
1283                         req->cpu = bio->bi_comp_cpu;
1284                 drive_stat_acct(req, 0);
1285                 elv_bio_merged(q, req, bio);
1286                 if (!attempt_front_merge(q, req))
1287                         elv_merged_request(q, req, el_ret);
1288                 goto out;
1289
1290         /* ELV_NO_MERGE: elevator says don't/can't merge. */
1291         default:
1292                 ;
1293         }
1294
1295 get_rq:
1296         /*
1297          * This sync check and mask will be re-done in init_request_from_bio(),
1298          * but we need to set it earlier to expose the sync flag to the
1299          * rq allocator and io schedulers.
1300          */
1301         rw_flags = bio_data_dir(bio);
1302         if (sync)
1303                 rw_flags |= REQ_SYNC;
1304
1305         /*
1306          * Grab a free request. This is might sleep but can not fail.
1307          * Returns with the queue unlocked.
1308          */
1309         req = get_request_wait(q, rw_flags, bio);
1310
1311         /*
1312          * After dropping the lock and possibly sleeping here, our request
1313          * may now be mergeable after it had proven unmergeable (above).
1314          * We don't worry about that case for efficiency. It won't happen
1315          * often, and the elevators are able to handle it.
1316          */
1317         init_request_from_bio(req, bio);
1318
1319         spin_lock_irq(q->queue_lock);
1320         if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags) ||
1321             bio_flagged(bio, BIO_CPU_AFFINE))
1322                 req->cpu = blk_cpu_to_group(smp_processor_id());
1323         if (queue_should_plug(q) && elv_queue_empty(q))
1324                 blk_plug_device(q);
1325         add_request(q, req);
1326 out:
1327         if (unplug || !queue_should_plug(q))
1328                 __generic_unplug_device(q);
1329         spin_unlock_irq(q->queue_lock);
1330         return 0;
1331 }
1332
1333 /*
1334  * If bio->bi_dev is a partition, remap the location
1335  */
1336 static inline void blk_partition_remap(struct bio *bio)
1337 {
1338         struct block_device *bdev = bio->bi_bdev;
1339
1340         if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1341                 struct hd_struct *p = bdev->bd_part;
1342
1343                 bio->bi_sector += p->start_sect;
1344                 bio->bi_bdev = bdev->bd_contains;
1345
1346                 trace_block_remap(bdev_get_queue(bio->bi_bdev), bio,
1347                                     bdev->bd_dev,
1348                                     bio->bi_sector - p->start_sect);
1349         }
1350 }
1351
1352 static void handle_bad_sector(struct bio *bio)
1353 {
1354         char b[BDEVNAME_SIZE];
1355
1356         printk(KERN_INFO "attempt to access beyond end of device\n");
1357         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1358                         bdevname(bio->bi_bdev, b),
1359                         bio->bi_rw,
1360                         (unsigned long long)bio->bi_sector + bio_sectors(bio),
1361                         (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1362
1363         set_bit(BIO_EOF, &bio->bi_flags);
1364 }
1365
1366 #ifdef CONFIG_FAIL_MAKE_REQUEST
1367
1368 static DECLARE_FAULT_ATTR(fail_make_request);
1369
1370 static int __init setup_fail_make_request(char *str)
1371 {
1372         return setup_fault_attr(&fail_make_request, str);
1373 }
1374 __setup("fail_make_request=", setup_fail_make_request);
1375
1376 static int should_fail_request(struct bio *bio)
1377 {
1378         struct hd_struct *part = bio->bi_bdev->bd_part;
1379
1380         if (part_to_disk(part)->part0.make_it_fail || part->make_it_fail)
1381                 return should_fail(&fail_make_request, bio->bi_size);
1382
1383         return 0;
1384 }
1385
1386 static int __init fail_make_request_debugfs(void)
1387 {
1388         return init_fault_attr_dentries(&fail_make_request,
1389                                         "fail_make_request");
1390 }
1391
1392 late_initcall(fail_make_request_debugfs);
1393
1394 #else /* CONFIG_FAIL_MAKE_REQUEST */
1395
1396 static inline int should_fail_request(struct bio *bio)
1397 {
1398         return 0;
1399 }
1400
1401 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1402
1403 /*
1404  * Check whether this bio extends beyond the end of the device.
1405  */
1406 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1407 {
1408         sector_t maxsector;
1409
1410         if (!nr_sectors)
1411                 return 0;
1412
1413         /* Test device or partition size, when known. */
1414         maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1415         if (maxsector) {
1416                 sector_t sector = bio->bi_sector;
1417
1418                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1419                         /*
1420                          * This may well happen - the kernel calls bread()
1421                          * without checking the size of the device, e.g., when
1422                          * mounting a device.
1423                          */
1424                         handle_bad_sector(bio);
1425                         return 1;
1426                 }
1427         }
1428
1429         return 0;
1430 }
1431
1432 /**
1433  * generic_make_request - hand a buffer to its device driver for I/O
1434  * @bio:  The bio describing the location in memory and on the device.
1435  *
1436  * generic_make_request() is used to make I/O requests of block
1437  * devices. It is passed a &struct bio, which describes the I/O that needs
1438  * to be done.
1439  *
1440  * generic_make_request() does not return any status.  The
1441  * success/failure status of the request, along with notification of
1442  * completion, is delivered asynchronously through the bio->bi_end_io
1443  * function described (one day) else where.
1444  *
1445  * The caller of generic_make_request must make sure that bi_io_vec
1446  * are set to describe the memory buffer, and that bi_dev and bi_sector are
1447  * set to describe the device address, and the
1448  * bi_end_io and optionally bi_private are set to describe how
1449  * completion notification should be signaled.
1450  *
1451  * generic_make_request and the drivers it calls may use bi_next if this
1452  * bio happens to be merged with someone else, and may change bi_dev and
1453  * bi_sector for remaps as it sees fit.  So the values of these fields
1454  * should NOT be depended on after the call to generic_make_request.
1455  */
1456 static inline void __generic_make_request(struct bio *bio)
1457 {
1458         struct request_queue *q;
1459         sector_t old_sector;
1460         int ret, nr_sectors = bio_sectors(bio);
1461         dev_t old_dev;
1462         int err = -EIO;
1463
1464         might_sleep();
1465
1466         if (bio_check_eod(bio, nr_sectors))
1467                 goto end_io;
1468
1469         /*
1470          * Resolve the mapping until finished. (drivers are
1471          * still free to implement/resolve their own stacking
1472          * by explicitly returning 0)
1473          *
1474          * NOTE: we don't repeat the blk_size check for each new device.
1475          * Stacking drivers are expected to know what they are doing.
1476          */
1477         old_sector = -1;
1478         old_dev = 0;
1479         do {
1480                 char b[BDEVNAME_SIZE];
1481
1482                 q = bdev_get_queue(bio->bi_bdev);
1483                 if (unlikely(!q)) {
1484                         printk(KERN_ERR
1485                                "generic_make_request: Trying to access "
1486                                 "nonexistent block-device %s (%Lu)\n",
1487                                 bdevname(bio->bi_bdev, b),
1488                                 (long long) bio->bi_sector);
1489                         goto end_io;
1490                 }
1491
1492                 if (unlikely(!(bio->bi_rw & REQ_DISCARD) &&
1493                              nr_sectors > queue_max_hw_sectors(q))) {
1494                         printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1495                                bdevname(bio->bi_bdev, b),
1496                                bio_sectors(bio),
1497                                queue_max_hw_sectors(q));
1498                         goto end_io;
1499                 }
1500
1501                 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1502                         goto end_io;
1503
1504                 if (should_fail_request(bio))
1505                         goto end_io;
1506
1507                 /*
1508                  * If this device has partitions, remap block n
1509                  * of partition p to block n+start(p) of the disk.
1510                  */
1511                 blk_partition_remap(bio);
1512
1513                 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
1514                         goto end_io;
1515
1516                 if (old_sector != -1)
1517                         trace_block_remap(q, bio, old_dev, old_sector);
1518
1519                 old_sector = bio->bi_sector;
1520                 old_dev = bio->bi_bdev->bd_dev;
1521
1522                 if (bio_check_eod(bio, nr_sectors))
1523                         goto end_io;
1524
1525                 if ((bio->bi_rw & REQ_DISCARD) &&
1526                     (!blk_queue_discard(q) ||
1527                      ((bio->bi_rw & REQ_SECURE) &&
1528                       !blk_queue_secdiscard(q)))) {
1529                         err = -EOPNOTSUPP;
1530                         goto end_io;
1531                 }
1532
1533                 blk_throtl_bio(q, &bio);
1534
1535                 /*
1536                  * If bio = NULL, bio has been throttled and will be submitted
1537                  * later.
1538                  */
1539                 if (!bio)
1540                         break;
1541
1542                 trace_block_bio_queue(q, bio);
1543
1544                 ret = q->make_request_fn(q, bio);
1545         } while (ret);
1546
1547         return;
1548
1549 end_io:
1550         bio_endio(bio, err);
1551 }
1552
1553 /*
1554  * We only want one ->make_request_fn to be active at a time,
1555  * else stack usage with stacked devices could be a problem.
1556  * So use current->bio_list to keep a list of requests
1557  * submited by a make_request_fn function.
1558  * current->bio_list is also used as a flag to say if
1559  * generic_make_request is currently active in this task or not.
1560  * If it is NULL, then no make_request is active.  If it is non-NULL,
1561  * then a make_request is active, and new requests should be added
1562  * at the tail
1563  */
1564 void generic_make_request(struct bio *bio)
1565 {
1566         struct bio_list bio_list_on_stack;
1567
1568         if (current->bio_list) {
1569                 /* make_request is active */
1570                 bio_list_add(current->bio_list, bio);
1571                 return;
1572         }
1573         /* following loop may be a bit non-obvious, and so deserves some
1574          * explanation.
1575          * Before entering the loop, bio->bi_next is NULL (as all callers
1576          * ensure that) so we have a list with a single bio.
1577          * We pretend that we have just taken it off a longer list, so
1578          * we assign bio_list to a pointer to the bio_list_on_stack,
1579          * thus initialising the bio_list of new bios to be
1580          * added.  __generic_make_request may indeed add some more bios
1581          * through a recursive call to generic_make_request.  If it
1582          * did, we find a non-NULL value in bio_list and re-enter the loop
1583          * from the top.  In this case we really did just take the bio
1584          * of the top of the list (no pretending) and so remove it from
1585          * bio_list, and call into __generic_make_request again.
1586          *
1587          * The loop was structured like this to make only one call to
1588          * __generic_make_request (which is important as it is large and
1589          * inlined) and to keep the structure simple.
1590          */
1591         BUG_ON(bio->bi_next);
1592         bio_list_init(&bio_list_on_stack);
1593         current->bio_list = &bio_list_on_stack;
1594         do {
1595                 __generic_make_request(bio);
1596                 bio = bio_list_pop(current->bio_list);
1597         } while (bio);
1598         current->bio_list = NULL; /* deactivate */
1599 }
1600 EXPORT_SYMBOL(generic_make_request);
1601
1602 /**
1603  * submit_bio - submit a bio to the block device layer for I/O
1604  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1605  * @bio: The &struct bio which describes the I/O
1606  *
1607  * submit_bio() is very similar in purpose to generic_make_request(), and
1608  * uses that function to do most of the work. Both are fairly rough
1609  * interfaces; @bio must be presetup and ready for I/O.
1610  *
1611  */
1612 void submit_bio(int rw, struct bio *bio)
1613 {
1614         int count = bio_sectors(bio);
1615
1616         bio->bi_rw |= rw;
1617
1618         /*
1619          * If it's a regular read/write or a barrier with data attached,
1620          * go through the normal accounting stuff before submission.
1621          */
1622         if (bio_has_data(bio) && !(rw & REQ_DISCARD)) {
1623                 if (rw & WRITE) {
1624                         count_vm_events(PGPGOUT, count);
1625                 } else {
1626                         task_io_account_read(bio->bi_size);
1627                         count_vm_events(PGPGIN, count);
1628                 }
1629
1630                 if (unlikely(block_dump)) {
1631                         char b[BDEVNAME_SIZE];
1632                         printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
1633                         current->comm, task_pid_nr(current),
1634                                 (rw & WRITE) ? "WRITE" : "READ",
1635                                 (unsigned long long)bio->bi_sector,
1636                                 bdevname(bio->bi_bdev, b),
1637                                 count);
1638                 }
1639         }
1640
1641         generic_make_request(bio);
1642 }
1643 EXPORT_SYMBOL(submit_bio);
1644
1645 /**
1646  * blk_rq_check_limits - Helper function to check a request for the queue limit
1647  * @q:  the queue
1648  * @rq: the request being checked
1649  *
1650  * Description:
1651  *    @rq may have been made based on weaker limitations of upper-level queues
1652  *    in request stacking drivers, and it may violate the limitation of @q.
1653  *    Since the block layer and the underlying device driver trust @rq
1654  *    after it is inserted to @q, it should be checked against @q before
1655  *    the insertion using this generic function.
1656  *
1657  *    This function should also be useful for request stacking drivers
1658  *    in some cases below, so export this fuction.
1659  *    Request stacking drivers like request-based dm may change the queue
1660  *    limits while requests are in the queue (e.g. dm's table swapping).
1661  *    Such request stacking drivers should check those requests agaist
1662  *    the new queue limits again when they dispatch those requests,
1663  *    although such checkings are also done against the old queue limits
1664  *    when submitting requests.
1665  */
1666 int blk_rq_check_limits(struct request_queue *q, struct request *rq)
1667 {
1668         if (rq->cmd_flags & REQ_DISCARD)
1669                 return 0;
1670
1671         if (blk_rq_sectors(rq) > queue_max_sectors(q) ||
1672             blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {
1673                 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1674                 return -EIO;
1675         }
1676
1677         /*
1678          * queue's settings related to segment counting like q->bounce_pfn
1679          * may differ from that of other stacking queues.
1680          * Recalculate it to check the request correctly on this queue's
1681          * limitation.
1682          */
1683         blk_recalc_rq_segments(rq);
1684         if (rq->nr_phys_segments > queue_max_segments(q)) {
1685                 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1686                 return -EIO;
1687         }
1688
1689         return 0;
1690 }
1691 EXPORT_SYMBOL_GPL(blk_rq_check_limits);
1692
1693 /**
1694  * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1695  * @q:  the queue to submit the request
1696  * @rq: the request being queued
1697  */
1698 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1699 {
1700         unsigned long flags;
1701
1702         if (blk_rq_check_limits(q, rq))
1703                 return -EIO;
1704
1705 #ifdef CONFIG_FAIL_MAKE_REQUEST
1706         if (rq->rq_disk && rq->rq_disk->part0.make_it_fail &&
1707             should_fail(&fail_make_request, blk_rq_bytes(rq)))
1708                 return -EIO;
1709 #endif
1710
1711         spin_lock_irqsave(q->queue_lock, flags);
1712
1713         /*
1714          * Submitting request must be dequeued before calling this function
1715          * because it will be linked to another request_queue
1716          */
1717         BUG_ON(blk_queued_rq(rq));
1718
1719         drive_stat_acct(rq, 1);
1720         __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
1721
1722         spin_unlock_irqrestore(q->queue_lock, flags);
1723
1724         return 0;
1725 }
1726 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1727
1728 /**
1729  * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1730  * @rq: request to examine
1731  *
1732  * Description:
1733  *     A request could be merge of IOs which require different failure
1734  *     handling.  This function determines the number of bytes which
1735  *     can be failed from the beginning of the request without
1736  *     crossing into area which need to be retried further.
1737  *
1738  * Return:
1739  *     The number of bytes to fail.
1740  *
1741  * Context:
1742  *     queue_lock must be held.
1743  */
1744 unsigned int blk_rq_err_bytes(const struct request *rq)
1745 {
1746         unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
1747         unsigned int bytes = 0;
1748         struct bio *bio;
1749
1750         if (!(rq->cmd_flags & REQ_MIXED_MERGE))
1751                 return blk_rq_bytes(rq);
1752
1753         /*
1754          * Currently the only 'mixing' which can happen is between
1755          * different fastfail types.  We can safely fail portions
1756          * which have all the failfast bits that the first one has -
1757          * the ones which are at least as eager to fail as the first
1758          * one.
1759          */
1760         for (bio = rq->bio; bio; bio = bio->bi_next) {
1761                 if ((bio->bi_rw & ff) != ff)
1762                         break;
1763                 bytes += bio->bi_size;
1764         }
1765
1766         /* this could lead to infinite loop */
1767         BUG_ON(blk_rq_bytes(rq) && !bytes);
1768         return bytes;
1769 }
1770 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
1771
1772 static void blk_account_io_completion(struct request *req, unsigned int bytes)
1773 {
1774         if (blk_do_io_stat(req)) {
1775                 const int rw = rq_data_dir(req);
1776                 struct hd_struct *part;
1777                 int cpu;
1778
1779                 cpu = part_stat_lock();
1780                 part = disk_map_sector_rcu(req->rq_disk, blk_rq_pos(req));
1781                 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
1782                 part_stat_unlock();
1783         }
1784 }
1785
1786 static void blk_account_io_done(struct request *req)
1787 {
1788         /*
1789          * Account IO completion.  bar_rq isn't accounted as a normal
1790          * IO on queueing nor completion.  Accounting the containing
1791          * request is enough.
1792          */
1793         if (blk_do_io_stat(req) && req != &req->q->bar_rq) {
1794                 unsigned long duration = jiffies - req->start_time;
1795                 const int rw = rq_data_dir(req);
1796                 struct hd_struct *part;
1797                 int cpu;
1798
1799                 cpu = part_stat_lock();
1800                 part = disk_map_sector_rcu(req->rq_disk, blk_rq_pos(req));
1801
1802                 part_stat_inc(cpu, part, ios[rw]);
1803                 part_stat_add(cpu, part, ticks[rw], duration);
1804                 part_round_stats(cpu, part);
1805                 part_dec_in_flight(part, rw);
1806
1807                 part_stat_unlock();
1808         }
1809 }
1810
1811 /**
1812  * blk_peek_request - peek at the top of a request queue
1813  * @q: request queue to peek at
1814  *
1815  * Description:
1816  *     Return the request at the top of @q.  The returned request
1817  *     should be started using blk_start_request() before LLD starts
1818  *     processing it.
1819  *
1820  * Return:
1821  *     Pointer to the request at the top of @q if available.  Null
1822  *     otherwise.
1823  *
1824  * Context:
1825  *     queue_lock must be held.
1826  */
1827 struct request *blk_peek_request(struct request_queue *q)
1828 {
1829         struct request *rq;
1830         int ret;
1831
1832         while ((rq = __elv_next_request(q)) != NULL) {
1833                 if (!(rq->cmd_flags & REQ_STARTED)) {
1834                         /*
1835                          * This is the first time the device driver
1836                          * sees this request (possibly after
1837                          * requeueing).  Notify IO scheduler.
1838                          */
1839                         if (rq->cmd_flags & REQ_SORTED)
1840                                 elv_activate_rq(q, rq);
1841
1842                         /*
1843                          * just mark as started even if we don't start
1844                          * it, a request that has been delayed should
1845                          * not be passed by new incoming requests
1846                          */
1847                         rq->cmd_flags |= REQ_STARTED;
1848                         trace_block_rq_issue(q, rq);
1849                 }
1850
1851                 if (!q->boundary_rq || q->boundary_rq == rq) {
1852                         q->end_sector = rq_end_sector(rq);
1853                         q->boundary_rq = NULL;
1854                 }
1855
1856                 if (rq->cmd_flags & REQ_DONTPREP)
1857                         break;
1858
1859                 if (q->dma_drain_size && blk_rq_bytes(rq)) {
1860                         /*
1861                          * make sure space for the drain appears we
1862                          * know we can do this because max_hw_segments
1863                          * has been adjusted to be one fewer than the
1864                          * device can handle
1865                          */
1866                         rq->nr_phys_segments++;
1867                 }
1868
1869                 if (!q->prep_rq_fn)
1870                         break;
1871
1872                 ret = q->prep_rq_fn(q, rq);
1873                 if (ret == BLKPREP_OK) {
1874                         break;
1875                 } else if (ret == BLKPREP_DEFER) {
1876                         /*
1877                          * the request may have been (partially) prepped.
1878                          * we need to keep this request in the front to
1879                          * avoid resource deadlock.  REQ_STARTED will
1880                          * prevent other fs requests from passing this one.
1881                          */
1882                         if (q->dma_drain_size && blk_rq_bytes(rq) &&
1883                             !(rq->cmd_flags & REQ_DONTPREP)) {
1884                                 /*
1885                                  * remove the space for the drain we added
1886                                  * so that we don't add it again
1887                                  */
1888                                 --rq->nr_phys_segments;
1889                         }
1890
1891                         rq = NULL;
1892                         break;
1893                 } else if (ret == BLKPREP_KILL) {
1894                         rq->cmd_flags |= REQ_QUIET;
1895                         /*
1896                          * Mark this request as started so we don't trigger
1897                          * any debug logic in the end I/O path.
1898                          */
1899                         blk_start_request(rq);
1900                         __blk_end_request_all(rq, -EIO);
1901                 } else {
1902                         printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
1903                         break;
1904                 }
1905         }
1906
1907         return rq;
1908 }
1909 EXPORT_SYMBOL(blk_peek_request);
1910
1911 void blk_dequeue_request(struct request *rq)
1912 {
1913         struct request_queue *q = rq->q;
1914
1915         BUG_ON(list_empty(&rq->queuelist));
1916         BUG_ON(ELV_ON_HASH(rq));
1917
1918         list_del_init(&rq->queuelist);
1919
1920         /*
1921          * the time frame between a request being removed from the lists
1922          * and to it is freed is accounted as io that is in progress at
1923          * the driver side.
1924          */
1925         if (blk_account_rq(rq)) {
1926                 q->in_flight[rq_is_sync(rq)]++;
1927                 set_io_start_time_ns(rq);
1928         }
1929 }
1930
1931 /**
1932  * blk_start_request - start request processing on the driver
1933  * @req: request to dequeue
1934  *
1935  * Description:
1936  *     Dequeue @req and start timeout timer on it.  This hands off the
1937  *     request to the driver.
1938  *
1939  *     Block internal functions which don't want to start timer should
1940  *     call blk_dequeue_request().
1941  *
1942  * Context:
1943  *     queue_lock must be held.
1944  */
1945 void blk_start_request(struct request *req)
1946 {
1947         blk_dequeue_request(req);
1948
1949         /*
1950          * We are now handing the request to the hardware, initialize
1951          * resid_len to full count and add the timeout handler.
1952          */
1953         req->resid_len = blk_rq_bytes(req);
1954         if (unlikely(blk_bidi_rq(req)))
1955                 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
1956
1957         blk_add_timer(req);
1958 }
1959 EXPORT_SYMBOL(blk_start_request);
1960
1961 /**
1962  * blk_fetch_request - fetch a request from a request queue
1963  * @q: request queue to fetch a request from
1964  *
1965  * Description:
1966  *     Return the request at the top of @q.  The request is started on
1967  *     return and LLD can start processing it immediately.
1968  *
1969  * Return:
1970  *     Pointer to the request at the top of @q if available.  Null
1971  *     otherwise.
1972  *
1973  * Context:
1974  *     queue_lock must be held.
1975  */
1976 struct request *blk_fetch_request(struct request_queue *q)
1977 {
1978         struct request *rq;
1979
1980         rq = blk_peek_request(q);
1981         if (rq)
1982                 blk_start_request(rq);
1983         return rq;
1984 }
1985 EXPORT_SYMBOL(blk_fetch_request);
1986
1987 /**
1988  * blk_update_request - Special helper function for request stacking drivers
1989  * @req:      the request being processed
1990  * @error:    %0 for success, < %0 for error
1991  * @nr_bytes: number of bytes to complete @req
1992  *
1993  * Description:
1994  *     Ends I/O on a number of bytes attached to @req, but doesn't complete
1995  *     the request structure even if @req doesn't have leftover.
1996  *     If @req has leftover, sets it up for the next range of segments.
1997  *
1998  *     This special helper function is only for request stacking drivers
1999  *     (e.g. request-based dm) so that they can handle partial completion.
2000  *     Actual device drivers should use blk_end_request instead.
2001  *
2002  *     Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2003  *     %false return from this function.
2004  *
2005  * Return:
2006  *     %false - this request doesn't have any more data
2007  *     %true  - this request has more data
2008  **/
2009 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2010 {
2011         int total_bytes, bio_nbytes, next_idx = 0;
2012         struct bio *bio;
2013
2014         if (!req->bio)
2015                 return false;
2016
2017         trace_block_rq_complete(req->q, req);
2018
2019         /*
2020          * For fs requests, rq is just carrier of independent bio's
2021          * and each partial completion should be handled separately.
2022          * Reset per-request error on each partial completion.
2023          *
2024          * TODO: tj: This is too subtle.  It would be better to let
2025          * low level drivers do what they see fit.
2026          */
2027         if (req->cmd_type == REQ_TYPE_FS)
2028                 req->errors = 0;
2029
2030         if (error && req->cmd_type == REQ_TYPE_FS &&
2031             !(req->cmd_flags & REQ_QUIET)) {
2032                 printk(KERN_ERR "end_request: I/O error, dev %s, sector %llu\n",
2033                                 req->rq_disk ? req->rq_disk->disk_name : "?",
2034                                 (unsigned long long)blk_rq_pos(req));
2035         }
2036
2037         blk_account_io_completion(req, nr_bytes);
2038
2039         total_bytes = bio_nbytes = 0;
2040         while ((bio = req->bio) != NULL) {
2041                 int nbytes;
2042
2043                 if (nr_bytes >= bio->bi_size) {
2044                         req->bio = bio->bi_next;
2045                         nbytes = bio->bi_size;
2046                         req_bio_endio(req, bio, nbytes, error);
2047                         next_idx = 0;
2048                         bio_nbytes = 0;
2049                 } else {
2050                         int idx = bio->bi_idx + next_idx;
2051
2052                         if (unlikely(idx >= bio->bi_vcnt)) {
2053                                 blk_dump_rq_flags(req, "__end_that");
2054                                 printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
2055                                        __func__, idx, bio->bi_vcnt);
2056                                 break;
2057                         }
2058
2059                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
2060                         BIO_BUG_ON(nbytes > bio->bi_size);
2061
2062                         /*
2063                          * not a complete bvec done
2064                          */
2065                         if (unlikely(nbytes > nr_bytes)) {
2066                                 bio_nbytes += nr_bytes;
2067                                 total_bytes += nr_bytes;
2068                                 break;
2069                         }
2070
2071                         /*
2072                          * advance to the next vector
2073                          */
2074                         next_idx++;
2075                         bio_nbytes += nbytes;
2076                 }
2077
2078                 total_bytes += nbytes;
2079                 nr_bytes -= nbytes;
2080
2081                 bio = req->bio;
2082                 if (bio) {
2083                         /*
2084                          * end more in this run, or just return 'not-done'
2085                          */
2086                         if (unlikely(nr_bytes <= 0))
2087                                 break;
2088                 }
2089         }
2090
2091         /*
2092          * completely done
2093          */
2094         if (!req->bio) {
2095                 /*
2096                  * Reset counters so that the request stacking driver
2097                  * can find how many bytes remain in the request
2098                  * later.
2099                  */
2100                 req->__data_len = 0;
2101                 return false;
2102         }
2103
2104         /*
2105          * if the request wasn't completed, update state
2106          */
2107         if (bio_nbytes) {
2108                 req_bio_endio(req, bio, bio_nbytes, error);
2109                 bio->bi_idx += next_idx;
2110                 bio_iovec(bio)->bv_offset += nr_bytes;
2111                 bio_iovec(bio)->bv_len -= nr_bytes;
2112         }
2113
2114         req->__data_len -= total_bytes;
2115         req->buffer = bio_data(req->bio);
2116
2117         /* update sector only for requests with clear definition of sector */
2118         if (req->cmd_type == REQ_TYPE_FS || (req->cmd_flags & REQ_DISCARD))
2119                 req->__sector += total_bytes >> 9;
2120
2121         /* mixed attributes always follow the first bio */
2122         if (req->cmd_flags & REQ_MIXED_MERGE) {
2123                 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2124                 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2125         }
2126
2127         /*
2128          * If total number of sectors is less than the first segment
2129          * size, something has gone terribly wrong.
2130          */
2131         if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2132                 printk(KERN_ERR "blk: request botched\n");
2133                 req->__data_len = blk_rq_cur_bytes(req);
2134         }
2135
2136         /* recalculate the number of segments */
2137         blk_recalc_rq_segments(req);
2138
2139         return true;
2140 }
2141 EXPORT_SYMBOL_GPL(blk_update_request);
2142
2143 static bool blk_update_bidi_request(struct request *rq, int error,
2144                                     unsigned int nr_bytes,
2145                                     unsigned int bidi_bytes)
2146 {
2147         if (blk_update_request(rq, error, nr_bytes))
2148                 return true;
2149
2150         /* Bidi request must be completed as a whole */
2151         if (unlikely(blk_bidi_rq(rq)) &&
2152             blk_update_request(rq->next_rq, error, bidi_bytes))
2153                 return true;
2154
2155         if (blk_queue_add_random(rq->q))
2156                 add_disk_randomness(rq->rq_disk);
2157
2158         return false;
2159 }
2160
2161 /**
2162  * blk_unprep_request - unprepare a request
2163  * @req:        the request
2164  *
2165  * This function makes a request ready for complete resubmission (or
2166  * completion).  It happens only after all error handling is complete,
2167  * so represents the appropriate moment to deallocate any resources
2168  * that were allocated to the request in the prep_rq_fn.  The queue
2169  * lock is held when calling this.
2170  */
2171 void blk_unprep_request(struct request *req)
2172 {
2173         struct request_queue *q = req->q;
2174
2175         req->cmd_flags &= ~REQ_DONTPREP;
2176         if (q->unprep_rq_fn)
2177                 q->unprep_rq_fn(q, req);
2178 }
2179 EXPORT_SYMBOL_GPL(blk_unprep_request);
2180
2181 /*
2182  * queue lock must be held
2183  */
2184 static void blk_finish_request(struct request *req, int error)
2185 {
2186         if (blk_rq_tagged(req))
2187                 blk_queue_end_tag(req->q, req);
2188
2189         BUG_ON(blk_queued_rq(req));
2190
2191         if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2192                 laptop_io_completion(&req->q->backing_dev_info);
2193
2194         blk_delete_timer(req);
2195
2196         if (req->cmd_flags & REQ_DONTPREP)
2197                 blk_unprep_request(req);
2198
2199
2200         blk_account_io_done(req);
2201
2202         if (req->end_io)
2203                 req->end_io(req, error);
2204         else {
2205                 if (blk_bidi_rq(req))
2206                         __blk_put_request(req->next_rq->q, req->next_rq);
2207
2208                 __blk_put_request(req->q, req);
2209         }
2210 }
2211
2212 /**
2213  * blk_end_bidi_request - Complete a bidi request
2214  * @rq:         the request to complete
2215  * @error:      %0 for success, < %0 for error
2216  * @nr_bytes:   number of bytes to complete @rq
2217  * @bidi_bytes: number of bytes to complete @rq->next_rq
2218  *
2219  * Description:
2220  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2221  *     Drivers that supports bidi can safely call this member for any
2222  *     type of request, bidi or uni.  In the later case @bidi_bytes is
2223  *     just ignored.
2224  *
2225  * Return:
2226  *     %false - we are done with this request
2227  *     %true  - still buffers pending for this request
2228  **/
2229 static bool blk_end_bidi_request(struct request *rq, int error,
2230                                  unsigned int nr_bytes, unsigned int bidi_bytes)
2231 {
2232         struct request_queue *q = rq->q;
2233         unsigned long flags;
2234
2235         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2236                 return true;
2237
2238         spin_lock_irqsave(q->queue_lock, flags);
2239         blk_finish_request(rq, error);
2240         spin_unlock_irqrestore(q->queue_lock, flags);
2241
2242         return false;
2243 }
2244
2245 /**
2246  * __blk_end_bidi_request - Complete a bidi request with queue lock held
2247  * @rq:         the request to complete
2248  * @error:      %0 for success, < %0 for error
2249  * @nr_bytes:   number of bytes to complete @rq
2250  * @bidi_bytes: number of bytes to complete @rq->next_rq
2251  *
2252  * Description:
2253  *     Identical to blk_end_bidi_request() except that queue lock is
2254  *     assumed to be locked on entry and remains so on return.
2255  *
2256  * Return:
2257  *     %false - we are done with this request
2258  *     %true  - still buffers pending for this request
2259  **/
2260 static bool __blk_end_bidi_request(struct request *rq, int error,
2261                                    unsigned int nr_bytes, unsigned int bidi_bytes)
2262 {
2263         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2264                 return true;
2265
2266         blk_finish_request(rq, error);
2267
2268         return false;
2269 }
2270
2271 /**
2272  * blk_end_request - Helper function for drivers to complete the request.
2273  * @rq:       the request being processed
2274  * @error:    %0 for success, < %0 for error
2275  * @nr_bytes: number of bytes to complete
2276  *
2277  * Description:
2278  *     Ends I/O on a number of bytes attached to @rq.
2279  *     If @rq has leftover, sets it up for the next range of segments.
2280  *
2281  * Return:
2282  *     %false - we are done with this request
2283  *     %true  - still buffers pending for this request
2284  **/
2285 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2286 {
2287         return blk_end_bidi_request(rq, error, nr_bytes, 0);
2288 }
2289 EXPORT_SYMBOL(blk_end_request);
2290
2291 /**
2292  * blk_end_request_all - Helper function for drives to finish the request.
2293  * @rq: the request to finish
2294  * @error: %0 for success, < %0 for error
2295  *
2296  * Description:
2297  *     Completely finish @rq.
2298  */
2299 void blk_end_request_all(struct request *rq, int error)
2300 {
2301         bool pending;
2302         unsigned int bidi_bytes = 0;
2303
2304         if (unlikely(blk_bidi_rq(rq)))
2305                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2306
2307         pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2308         BUG_ON(pending);
2309 }
2310 EXPORT_SYMBOL(blk_end_request_all);
2311
2312 /**
2313  * blk_end_request_cur - Helper function to finish the current request chunk.
2314  * @rq: the request to finish the current chunk for
2315  * @error: %0 for success, < %0 for error
2316  *
2317  * Description:
2318  *     Complete the current consecutively mapped chunk from @rq.
2319  *
2320  * Return:
2321  *     %false - we are done with this request
2322  *     %true  - still buffers pending for this request
2323  */
2324 bool blk_end_request_cur(struct request *rq, int error)
2325 {
2326         return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2327 }
2328 EXPORT_SYMBOL(blk_end_request_cur);
2329
2330 /**
2331  * blk_end_request_err - Finish a request till the next failure boundary.
2332  * @rq: the request to finish till the next failure boundary for
2333  * @error: must be negative errno
2334  *
2335  * Description:
2336  *     Complete @rq till the next failure boundary.
2337  *
2338  * Return:
2339  *     %false - we are done with this request
2340  *     %true  - still buffers pending for this request
2341  */
2342 bool blk_end_request_err(struct request *rq, int error)
2343 {
2344         WARN_ON(error >= 0);
2345         return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2346 }
2347 EXPORT_SYMBOL_GPL(blk_end_request_err);
2348
2349 /**
2350  * __blk_end_request - Helper function for drivers to complete the request.
2351  * @rq:       the request being processed
2352  * @error:    %0 for success, < %0 for error
2353  * @nr_bytes: number of bytes to complete
2354  *
2355  * Description:
2356  *     Must be called with queue lock held unlike blk_end_request().
2357  *
2358  * Return:
2359  *     %false - we are done with this request
2360  *     %true  - still buffers pending for this request
2361  **/
2362 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2363 {
2364         return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2365 }
2366 EXPORT_SYMBOL(__blk_end_request);
2367
2368 /**
2369  * __blk_end_request_all - Helper function for drives to finish the request.
2370  * @rq: the request to finish
2371  * @error: %0 for success, < %0 for error
2372  *
2373  * Description:
2374  *     Completely finish @rq.  Must be called with queue lock held.
2375  */
2376 void __blk_end_request_all(struct request *rq, int error)
2377 {
2378         bool pending;
2379         unsigned int bidi_bytes = 0;
2380
2381         if (unlikely(blk_bidi_rq(rq)))
2382                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2383
2384         pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2385         BUG_ON(pending);
2386 }
2387 EXPORT_SYMBOL(__blk_end_request_all);
2388
2389 /**
2390  * __blk_end_request_cur - Helper function to finish the current request chunk.
2391  * @rq: the request to finish the current chunk for
2392  * @error: %0 for success, < %0 for error
2393  *
2394  * Description:
2395  *     Complete the current consecutively mapped chunk from @rq.  Must
2396  *     be called with queue lock held.
2397  *
2398  * Return:
2399  *     %false - we are done with this request
2400  *     %true  - still buffers pending for this request
2401  */
2402 bool __blk_end_request_cur(struct request *rq, int error)
2403 {
2404         return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2405 }
2406 EXPORT_SYMBOL(__blk_end_request_cur);
2407
2408 /**
2409  * __blk_end_request_err - Finish a request till the next failure boundary.
2410  * @rq: the request to finish till the next failure boundary for
2411  * @error: must be negative errno
2412  *
2413  * Description:
2414  *     Complete @rq till the next failure boundary.  Must be called
2415  *     with queue lock held.
2416  *
2417  * Return:
2418  *     %false - we are done with this request
2419  *     %true  - still buffers pending for this request
2420  */
2421 bool __blk_end_request_err(struct request *rq, int error)
2422 {
2423         WARN_ON(error >= 0);
2424         return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2425 }
2426 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2427
2428 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2429                      struct bio *bio)
2430 {
2431         /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2432         rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
2433
2434         if (bio_has_data(bio)) {
2435                 rq->nr_phys_segments = bio_phys_segments(q, bio);
2436                 rq->buffer = bio_data(bio);
2437         }
2438         rq->__data_len = bio->bi_size;
2439         rq->bio = rq->biotail = bio;
2440
2441         if (bio->bi_bdev)
2442                 rq->rq_disk = bio->bi_bdev->bd_disk;
2443 }
2444
2445 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2446 /**
2447  * rq_flush_dcache_pages - Helper function to flush all pages in a request
2448  * @rq: the request to be flushed
2449  *
2450  * Description:
2451  *     Flush all pages in @rq.
2452  */
2453 void rq_flush_dcache_pages(struct request *rq)
2454 {
2455         struct req_iterator iter;
2456         struct bio_vec *bvec;
2457
2458         rq_for_each_segment(bvec, rq, iter)
2459                 flush_dcache_page(bvec->bv_page);
2460 }
2461 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2462 #endif
2463
2464 /**
2465  * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2466  * @q : the queue of the device being checked
2467  *
2468  * Description:
2469  *    Check if underlying low-level drivers of a device are busy.
2470  *    If the drivers want to export their busy state, they must set own
2471  *    exporting function using blk_queue_lld_busy() first.
2472  *
2473  *    Basically, this function is used only by request stacking drivers
2474  *    to stop dispatching requests to underlying devices when underlying
2475  *    devices are busy.  This behavior helps more I/O merging on the queue
2476  *    of the request stacking driver and prevents I/O throughput regression
2477  *    on burst I/O load.
2478  *
2479  * Return:
2480  *    0 - Not busy (The request stacking driver should dispatch request)
2481  *    1 - Busy (The request stacking driver should stop dispatching request)
2482  */
2483 int blk_lld_busy(struct request_queue *q)
2484 {
2485         if (q->lld_busy_fn)
2486                 return q->lld_busy_fn(q);
2487
2488         return 0;
2489 }
2490 EXPORT_SYMBOL_GPL(blk_lld_busy);
2491
2492 /**
2493  * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2494  * @rq: the clone request to be cleaned up
2495  *
2496  * Description:
2497  *     Free all bios in @rq for a cloned request.
2498  */
2499 void blk_rq_unprep_clone(struct request *rq)
2500 {
2501         struct bio *bio;
2502
2503         while ((bio = rq->bio) != NULL) {
2504                 rq->bio = bio->bi_next;
2505
2506                 bio_put(bio);
2507         }
2508 }
2509 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2510
2511 /*
2512  * Copy attributes of the original request to the clone request.
2513  * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2514  */
2515 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2516 {
2517         dst->cpu = src->cpu;
2518         dst->cmd_flags = (rq_data_dir(src) | REQ_NOMERGE);
2519         if (src->cmd_flags & REQ_DISCARD)
2520                 dst->cmd_flags |= REQ_DISCARD;
2521         dst->cmd_type = src->cmd_type;
2522         dst->__sector = blk_rq_pos(src);
2523         dst->__data_len = blk_rq_bytes(src);
2524         dst->nr_phys_segments = src->nr_phys_segments;
2525         dst->ioprio = src->ioprio;
2526         dst->extra_len = src->extra_len;
2527 }
2528
2529 /**
2530  * blk_rq_prep_clone - Helper function to setup clone request
2531  * @rq: the request to be setup
2532  * @rq_src: original request to be cloned
2533  * @bs: bio_set that bios for clone are allocated from
2534  * @gfp_mask: memory allocation mask for bio
2535  * @bio_ctr: setup function to be called for each clone bio.
2536  *           Returns %0 for success, non %0 for failure.
2537  * @data: private data to be passed to @bio_ctr
2538  *
2539  * Description:
2540  *     Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2541  *     The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2542  *     are not copied, and copying such parts is the caller's responsibility.
2543  *     Also, pages which the original bios are pointing to are not copied
2544  *     and the cloned bios just point same pages.
2545  *     So cloned bios must be completed before original bios, which means
2546  *     the caller must complete @rq before @rq_src.
2547  */
2548 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2549                       struct bio_set *bs, gfp_t gfp_mask,
2550                       int (*bio_ctr)(struct bio *, struct bio *, void *),
2551                       void *data)
2552 {
2553         struct bio *bio, *bio_src;
2554
2555         if (!bs)
2556                 bs = fs_bio_set;
2557
2558         blk_rq_init(NULL, rq);
2559
2560         __rq_for_each_bio(bio_src, rq_src) {
2561                 bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);
2562                 if (!bio)
2563                         goto free_and_out;
2564
2565                 __bio_clone(bio, bio_src);
2566
2567                 if (bio_integrity(bio_src) &&
2568                     bio_integrity_clone(bio, bio_src, gfp_mask, bs))
2569                         goto free_and_out;
2570
2571                 if (bio_ctr && bio_ctr(bio, bio_src, data))
2572                         goto free_and_out;
2573
2574                 if (rq->bio) {
2575                         rq->biotail->bi_next = bio;
2576                         rq->biotail = bio;
2577                 } else
2578                         rq->bio = rq->biotail = bio;
2579         }
2580
2581         __blk_rq_prep_clone(rq, rq_src);
2582
2583         return 0;
2584
2585 free_and_out:
2586         if (bio)
2587                 bio_free(bio, bs);
2588         blk_rq_unprep_clone(rq);
2589
2590         return -ENOMEM;
2591 }
2592 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
2593
2594 int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
2595 {
2596         return queue_work(kblockd_workqueue, work);
2597 }
2598 EXPORT_SYMBOL(kblockd_schedule_work);
2599
2600 int kblockd_schedule_delayed_work(struct request_queue *q,
2601                         struct delayed_work *dwork, unsigned long delay)
2602 {
2603         return queue_delayed_work(kblockd_workqueue, dwork, delay);
2604 }
2605 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
2606
2607 int __init blk_dev_init(void)
2608 {
2609         BUILD_BUG_ON(__REQ_NR_BITS > 8 *
2610                         sizeof(((struct request *)0)->cmd_flags));
2611
2612         kblockd_workqueue = create_workqueue("kblockd");
2613         if (!kblockd_workqueue)
2614                 panic("Failed to create kblockd\n");
2615
2616         request_cachep = kmem_cache_create("blkdev_requests",
2617                         sizeof(struct request), 0, SLAB_PANIC, NULL);
2618
2619         blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2620                         sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2621
2622         return 0;
2623 }