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