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