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