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