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