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