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