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> - July2000
7 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
11 * This handles all read/write requests to block devices
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/backing-dev.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/highmem.h>
20 #include <linux/kernel_stat.h>
21 #include <linux/string.h>
22 #include <linux/init.h>
23 #include <linux/completion.h>
24 #include <linux/slab.h>
25 #include <linux/swap.h>
26 #include <linux/writeback.h>
27 #include <linux/task_io_accounting_ops.h>
28 #include <linux/interrupt.h>
29 #include <linux/cpu.h>
30 #include <linux/blktrace_api.h>
31 #include <linux/fault-inject.h>
32 #include <linux/scatterlist.h>
36 static int __make_request(struct request_queue *q, struct bio *bio);
39 * For the allocated request tables
41 struct kmem_cache *request_cachep;
44 * For queue allocation
46 struct kmem_cache *blk_requestq_cachep = NULL;
49 * Controlling structure to kblockd
51 static struct workqueue_struct *kblockd_workqueue;
53 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
55 static void drive_stat_acct(struct request *rq, int new_io)
57 int rw = rq_data_dir(rq);
59 if (!blk_fs_request(rq) || !rq->rq_disk)
63 __disk_stat_inc(rq->rq_disk, merges[rw]);
65 disk_round_stats(rq->rq_disk);
66 rq->rq_disk->in_flight++;
70 void blk_queue_congestion_threshold(struct request_queue *q)
74 nr = q->nr_requests - (q->nr_requests / 8) + 1;
75 if (nr > q->nr_requests)
77 q->nr_congestion_on = nr;
79 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
82 q->nr_congestion_off = nr;
86 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
89 * Locates the passed device's request queue and returns the address of its
92 * Will return NULL if the request queue cannot be located.
94 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
96 struct backing_dev_info *ret = NULL;
97 struct request_queue *q = bdev_get_queue(bdev);
100 ret = &q->backing_dev_info;
103 EXPORT_SYMBOL(blk_get_backing_dev_info);
105 void rq_init(struct request_queue *q, struct request *rq)
107 INIT_LIST_HEAD(&rq->queuelist);
108 INIT_LIST_HEAD(&rq->donelist);
111 rq->bio = rq->biotail = NULL;
112 INIT_HLIST_NODE(&rq->hash);
113 RB_CLEAR_NODE(&rq->rb_node);
121 rq->nr_phys_segments = 0;
124 rq->end_io_data = NULL;
125 rq->completion_data = NULL;
129 static void req_bio_endio(struct request *rq, struct bio *bio,
130 unsigned int nbytes, int error)
132 struct request_queue *q = rq->q;
134 if (&q->bar_rq != rq) {
136 clear_bit(BIO_UPTODATE, &bio->bi_flags);
137 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
140 if (unlikely(nbytes > bio->bi_size)) {
141 printk("%s: want %u bytes done, only %u left\n",
142 __FUNCTION__, nbytes, bio->bi_size);
143 nbytes = bio->bi_size;
146 bio->bi_size -= nbytes;
147 bio->bi_sector += (nbytes >> 9);
148 if (bio->bi_size == 0)
149 bio_endio(bio, error);
153 * Okay, this is the barrier request in progress, just
156 if (error && !q->orderr)
161 void blk_dump_rq_flags(struct request *rq, char *msg)
165 printk("%s: dev %s: type=%x, flags=%x\n", msg,
166 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
169 printk("\nsector %llu, nr/cnr %lu/%u\n", (unsigned long long)rq->sector,
171 rq->current_nr_sectors);
172 printk("bio %p, biotail %p, buffer %p, data %p, len %u\n", rq->bio, rq->biotail, rq->buffer, rq->data, rq->data_len);
174 if (blk_pc_request(rq)) {
176 for (bit = 0; bit < sizeof(rq->cmd); bit++)
177 printk("%02x ", rq->cmd[bit]);
182 EXPORT_SYMBOL(blk_dump_rq_flags);
184 static void blk_recalc_rq_segments(struct request *rq)
188 unsigned int phys_size;
189 unsigned int hw_size;
190 struct bio_vec *bv, *bvprv = NULL;
194 struct req_iterator iter;
195 int high, highprv = 1;
196 struct request_queue *q = rq->q;
201 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
202 hw_seg_size = seg_size = 0;
203 phys_size = hw_size = nr_phys_segs = nr_hw_segs = 0;
204 rq_for_each_segment(bv, rq, iter) {
206 * the trick here is making sure that a high page is never
207 * considered part of another segment, since that might
208 * change with the bounce page.
210 high = page_to_pfn(bv->bv_page) > q->bounce_pfn;
214 if (seg_size + bv->bv_len > q->max_segment_size)
216 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bv))
218 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bv))
220 if (BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len))
223 seg_size += bv->bv_len;
224 hw_seg_size += bv->bv_len;
229 if (BIOVEC_VIRT_MERGEABLE(bvprv, bv) &&
230 !BIOVEC_VIRT_OVERSIZE(hw_seg_size + bv->bv_len))
231 hw_seg_size += bv->bv_len;
234 if (nr_hw_segs == 1 &&
235 hw_seg_size > rq->bio->bi_hw_front_size)
236 rq->bio->bi_hw_front_size = hw_seg_size;
237 hw_seg_size = BIOVEC_VIRT_START_SIZE(bv) + bv->bv_len;
243 seg_size = bv->bv_len;
247 if (nr_hw_segs == 1 &&
248 hw_seg_size > rq->bio->bi_hw_front_size)
249 rq->bio->bi_hw_front_size = hw_seg_size;
250 if (hw_seg_size > rq->biotail->bi_hw_back_size)
251 rq->biotail->bi_hw_back_size = hw_seg_size;
252 rq->nr_phys_segments = nr_phys_segs;
253 rq->nr_hw_segments = nr_hw_segs;
256 void blk_recount_segments(struct request_queue *q, struct bio *bio)
259 struct bio *nxt = bio->bi_next;
261 rq.bio = rq.biotail = bio;
263 blk_recalc_rq_segments(&rq);
265 bio->bi_phys_segments = rq.nr_phys_segments;
266 bio->bi_hw_segments = rq.nr_hw_segments;
267 bio->bi_flags |= (1 << BIO_SEG_VALID);
269 EXPORT_SYMBOL(blk_recount_segments);
271 static int blk_phys_contig_segment(struct request_queue *q, struct bio *bio,
274 if (!(q->queue_flags & (1 << QUEUE_FLAG_CLUSTER)))
277 if (!BIOVEC_PHYS_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)))
279 if (bio->bi_size + nxt->bi_size > q->max_segment_size)
283 * bio and nxt are contigous in memory, check if the queue allows
284 * these two to be merged into one
286 if (BIO_SEG_BOUNDARY(q, bio, nxt))
292 static int blk_hw_contig_segment(struct request_queue *q, struct bio *bio,
295 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
296 blk_recount_segments(q, bio);
297 if (unlikely(!bio_flagged(nxt, BIO_SEG_VALID)))
298 blk_recount_segments(q, nxt);
299 if (!BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(nxt)) ||
300 BIOVEC_VIRT_OVERSIZE(bio->bi_hw_back_size + nxt->bi_hw_front_size))
302 if (bio->bi_hw_back_size + nxt->bi_hw_front_size > q->max_segment_size)
309 * map a request to scatterlist, return number of sg entries setup. Caller
310 * must make sure sg can hold rq->nr_phys_segments entries
312 int blk_rq_map_sg(struct request_queue *q, struct request *rq,
313 struct scatterlist *sglist)
315 struct bio_vec *bvec, *bvprv;
316 struct req_iterator iter;
317 struct scatterlist *sg;
321 cluster = q->queue_flags & (1 << QUEUE_FLAG_CLUSTER);
328 rq_for_each_segment(bvec, rq, iter) {
329 int nbytes = bvec->bv_len;
331 if (bvprv && cluster) {
332 if (sg->length + nbytes > q->max_segment_size)
335 if (!BIOVEC_PHYS_MERGEABLE(bvprv, bvec))
337 if (!BIOVEC_SEG_BOUNDARY(q, bvprv, bvec))
340 sg->length += nbytes;
347 * If the driver previously mapped a shorter
348 * list, we could see a termination bit
349 * prematurely unless it fully inits the sg
350 * table on each mapping. We KNOW that there
351 * must be more entries here or the driver
352 * would be buggy, so force clear the
353 * termination bit to avoid doing a full
354 * sg_init_table() in drivers for each command.
356 sg->page_link &= ~0x02;
360 sg_set_page(sg, bvec->bv_page, nbytes, bvec->bv_offset);
364 } /* segments in rq */
366 if (q->dma_drain_size) {
367 sg->page_link &= ~0x02;
369 sg_set_page(sg, virt_to_page(q->dma_drain_buffer),
371 ((unsigned long)q->dma_drain_buffer) &
382 EXPORT_SYMBOL(blk_rq_map_sg);
384 static inline int ll_new_mergeable(struct request_queue *q,
388 int nr_phys_segs = bio_phys_segments(q, bio);
390 if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
391 req->cmd_flags |= REQ_NOMERGE;
392 if (req == q->last_merge)
393 q->last_merge = NULL;
398 * A hw segment is just getting larger, bump just the phys
401 req->nr_phys_segments += nr_phys_segs;
405 static inline int ll_new_hw_segment(struct request_queue *q,
409 int nr_hw_segs = bio_hw_segments(q, bio);
410 int nr_phys_segs = bio_phys_segments(q, bio);
412 if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
413 || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
414 req->cmd_flags |= REQ_NOMERGE;
415 if (req == q->last_merge)
416 q->last_merge = NULL;
421 * This will form the start of a new hw segment. Bump both
424 req->nr_hw_segments += nr_hw_segs;
425 req->nr_phys_segments += nr_phys_segs;
429 int ll_back_merge_fn(struct request_queue *q, struct request *req,
432 unsigned short max_sectors;
435 if (unlikely(blk_pc_request(req)))
436 max_sectors = q->max_hw_sectors;
438 max_sectors = q->max_sectors;
440 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
441 req->cmd_flags |= REQ_NOMERGE;
442 if (req == q->last_merge)
443 q->last_merge = NULL;
446 if (unlikely(!bio_flagged(req->biotail, BIO_SEG_VALID)))
447 blk_recount_segments(q, req->biotail);
448 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
449 blk_recount_segments(q, bio);
450 len = req->biotail->bi_hw_back_size + bio->bi_hw_front_size;
451 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)) &&
452 !BIOVEC_VIRT_OVERSIZE(len)) {
453 int mergeable = ll_new_mergeable(q, req, bio);
456 if (req->nr_hw_segments == 1)
457 req->bio->bi_hw_front_size = len;
458 if (bio->bi_hw_segments == 1)
459 bio->bi_hw_back_size = len;
464 return ll_new_hw_segment(q, req, bio);
467 static int ll_front_merge_fn(struct request_queue *q, struct request *req,
470 unsigned short max_sectors;
473 if (unlikely(blk_pc_request(req)))
474 max_sectors = q->max_hw_sectors;
476 max_sectors = q->max_sectors;
479 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
480 req->cmd_flags |= REQ_NOMERGE;
481 if (req == q->last_merge)
482 q->last_merge = NULL;
485 len = bio->bi_hw_back_size + req->bio->bi_hw_front_size;
486 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
487 blk_recount_segments(q, bio);
488 if (unlikely(!bio_flagged(req->bio, BIO_SEG_VALID)))
489 blk_recount_segments(q, req->bio);
490 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)) &&
491 !BIOVEC_VIRT_OVERSIZE(len)) {
492 int mergeable = ll_new_mergeable(q, req, bio);
495 if (bio->bi_hw_segments == 1)
496 bio->bi_hw_front_size = len;
497 if (req->nr_hw_segments == 1)
498 req->biotail->bi_hw_back_size = len;
503 return ll_new_hw_segment(q, req, bio);
506 static int ll_merge_requests_fn(struct request_queue *q, struct request *req,
507 struct request *next)
509 int total_phys_segments;
510 int total_hw_segments;
513 * First check if the either of the requests are re-queued
514 * requests. Can't merge them if they are.
516 if (req->special || next->special)
520 * Will it become too large?
522 if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
525 total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
526 if (blk_phys_contig_segment(q, req->biotail, next->bio))
527 total_phys_segments--;
529 if (total_phys_segments > q->max_phys_segments)
532 total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
533 if (blk_hw_contig_segment(q, req->biotail, next->bio)) {
534 int len = req->biotail->bi_hw_back_size + next->bio->bi_hw_front_size;
536 * propagate the combined length to the end of the requests
538 if (req->nr_hw_segments == 1)
539 req->bio->bi_hw_front_size = len;
540 if (next->nr_hw_segments == 1)
541 next->biotail->bi_hw_back_size = len;
545 if (total_hw_segments > q->max_hw_segments)
549 req->nr_phys_segments = total_phys_segments;
550 req->nr_hw_segments = total_hw_segments;
555 * "plug" the device if there are no outstanding requests: this will
556 * force the transfer to start only after we have put all the requests
559 * This is called with interrupts off and no requests on the queue and
560 * with the queue lock held.
562 void blk_plug_device(struct request_queue *q)
564 WARN_ON(!irqs_disabled());
567 * don't plug a stopped queue, it must be paired with blk_start_queue()
568 * which will restart the queueing
570 if (blk_queue_stopped(q))
573 if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
574 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
575 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
579 EXPORT_SYMBOL(blk_plug_device);
582 * remove the queue from the plugged list, if present. called with
583 * queue lock held and interrupts disabled.
585 int blk_remove_plug(struct request_queue *q)
587 WARN_ON(!irqs_disabled());
589 if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
592 del_timer(&q->unplug_timer);
596 EXPORT_SYMBOL(blk_remove_plug);
599 * remove the plug and let it rip..
601 void __generic_unplug_device(struct request_queue *q)
603 if (unlikely(blk_queue_stopped(q)))
606 if (!blk_remove_plug(q))
611 EXPORT_SYMBOL(__generic_unplug_device);
614 * generic_unplug_device - fire a request queue
615 * @q: The &struct request_queue in question
618 * Linux uses plugging to build bigger requests queues before letting
619 * the device have at them. If a queue is plugged, the I/O scheduler
620 * is still adding and merging requests on the queue. Once the queue
621 * gets unplugged, the request_fn defined for the queue is invoked and
624 void generic_unplug_device(struct request_queue *q)
626 spin_lock_irq(q->queue_lock);
627 __generic_unplug_device(q);
628 spin_unlock_irq(q->queue_lock);
630 EXPORT_SYMBOL(generic_unplug_device);
632 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
635 struct request_queue *q = bdi->unplug_io_data;
640 void blk_unplug_work(struct work_struct *work)
642 struct request_queue *q =
643 container_of(work, struct request_queue, unplug_work);
645 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
646 q->rq.count[READ] + q->rq.count[WRITE]);
651 void blk_unplug_timeout(unsigned long data)
653 struct request_queue *q = (struct request_queue *)data;
655 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
656 q->rq.count[READ] + q->rq.count[WRITE]);
658 kblockd_schedule_work(&q->unplug_work);
661 void blk_unplug(struct request_queue *q)
664 * devices don't necessarily have an ->unplug_fn defined
667 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
668 q->rq.count[READ] + q->rq.count[WRITE]);
673 EXPORT_SYMBOL(blk_unplug);
676 * blk_start_queue - restart a previously stopped queue
677 * @q: The &struct request_queue in question
680 * blk_start_queue() will clear the stop flag on the queue, and call
681 * the request_fn for the queue if it was in a stopped state when
682 * entered. Also see blk_stop_queue(). Queue lock must be held.
684 void blk_start_queue(struct request_queue *q)
686 WARN_ON(!irqs_disabled());
688 clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
691 * one level of recursion is ok and is much faster than kicking
692 * the unplug handling
694 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
696 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
699 kblockd_schedule_work(&q->unplug_work);
703 EXPORT_SYMBOL(blk_start_queue);
706 * blk_stop_queue - stop a queue
707 * @q: The &struct request_queue in question
710 * The Linux block layer assumes that a block driver will consume all
711 * entries on the request queue when the request_fn strategy is called.
712 * Often this will not happen, because of hardware limitations (queue
713 * depth settings). If a device driver gets a 'queue full' response,
714 * or if it simply chooses not to queue more I/O at one point, it can
715 * call this function to prevent the request_fn from being called until
716 * the driver has signalled it's ready to go again. This happens by calling
717 * blk_start_queue() to restart queue operations. Queue lock must be held.
719 void blk_stop_queue(struct request_queue *q)
722 set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
724 EXPORT_SYMBOL(blk_stop_queue);
727 * blk_sync_queue - cancel any pending callbacks on a queue
731 * The block layer may perform asynchronous callback activity
732 * on a queue, such as calling the unplug function after a timeout.
733 * A block device may call blk_sync_queue to ensure that any
734 * such activity is cancelled, thus allowing it to release resources
735 * that the callbacks might use. The caller must already have made sure
736 * that its ->make_request_fn will not re-add plugging prior to calling
740 void blk_sync_queue(struct request_queue *q)
742 del_timer_sync(&q->unplug_timer);
743 kblockd_flush_work(&q->unplug_work);
745 EXPORT_SYMBOL(blk_sync_queue);
748 * blk_run_queue - run a single device queue
749 * @q: The queue to run
751 void blk_run_queue(struct request_queue *q)
755 spin_lock_irqsave(q->queue_lock, flags);
759 * Only recurse once to avoid overrunning the stack, let the unplug
760 * handling reinvoke the handler shortly if we already got there.
762 if (!elv_queue_empty(q)) {
763 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
765 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
768 kblockd_schedule_work(&q->unplug_work);
772 spin_unlock_irqrestore(q->queue_lock, flags);
774 EXPORT_SYMBOL(blk_run_queue);
776 void blk_put_queue(struct request_queue *q)
778 kobject_put(&q->kobj);
780 EXPORT_SYMBOL(blk_put_queue);
782 void blk_cleanup_queue(struct request_queue * q)
784 mutex_lock(&q->sysfs_lock);
785 set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
786 mutex_unlock(&q->sysfs_lock);
789 elevator_exit(q->elevator);
794 EXPORT_SYMBOL(blk_cleanup_queue);
796 static int blk_init_free_list(struct request_queue *q)
798 struct request_list *rl = &q->rq;
800 rl->count[READ] = rl->count[WRITE] = 0;
801 rl->starved[READ] = rl->starved[WRITE] = 0;
803 init_waitqueue_head(&rl->wait[READ]);
804 init_waitqueue_head(&rl->wait[WRITE]);
806 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
807 mempool_free_slab, request_cachep, q->node);
815 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
817 return blk_alloc_queue_node(gfp_mask, -1);
819 EXPORT_SYMBOL(blk_alloc_queue);
821 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
823 struct request_queue *q;
826 q = kmem_cache_alloc_node(blk_requestq_cachep,
827 gfp_mask | __GFP_ZERO, node_id);
831 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
832 q->backing_dev_info.unplug_io_data = q;
833 err = bdi_init(&q->backing_dev_info);
835 kmem_cache_free(blk_requestq_cachep, q);
839 init_timer(&q->unplug_timer);
841 kobject_init(&q->kobj, &blk_queue_ktype);
843 mutex_init(&q->sysfs_lock);
847 EXPORT_SYMBOL(blk_alloc_queue_node);
850 * blk_init_queue - prepare a request queue for use with a block device
851 * @rfn: The function to be called to process requests that have been
852 * placed on the queue.
853 * @lock: Request queue spin lock
856 * If a block device wishes to use the standard request handling procedures,
857 * which sorts requests and coalesces adjacent requests, then it must
858 * call blk_init_queue(). The function @rfn will be called when there
859 * are requests on the queue that need to be processed. If the device
860 * supports plugging, then @rfn may not be called immediately when requests
861 * are available on the queue, but may be called at some time later instead.
862 * Plugged queues are generally unplugged when a buffer belonging to one
863 * of the requests on the queue is needed, or due to memory pressure.
865 * @rfn is not required, or even expected, to remove all requests off the
866 * queue, but only as many as it can handle at a time. If it does leave
867 * requests on the queue, it is responsible for arranging that the requests
868 * get dealt with eventually.
870 * The queue spin lock must be held while manipulating the requests on the
871 * request queue; this lock will be taken also from interrupt context, so irq
872 * disabling is needed for it.
874 * Function returns a pointer to the initialized request queue, or NULL if
878 * blk_init_queue() must be paired with a blk_cleanup_queue() call
879 * when the block device is deactivated (such as at module unload).
882 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
884 return blk_init_queue_node(rfn, lock, -1);
886 EXPORT_SYMBOL(blk_init_queue);
888 struct request_queue *
889 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
891 struct request_queue *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
897 if (blk_init_free_list(q)) {
898 kmem_cache_free(blk_requestq_cachep, q);
903 * if caller didn't supply a lock, they get per-queue locking with
907 spin_lock_init(&q->__queue_lock);
908 lock = &q->__queue_lock;
912 q->prep_rq_fn = NULL;
913 q->unplug_fn = generic_unplug_device;
914 q->queue_flags = (1 << QUEUE_FLAG_CLUSTER);
915 q->queue_lock = lock;
917 blk_queue_segment_boundary(q, 0xffffffff);
919 blk_queue_make_request(q, __make_request);
920 blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
922 blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
923 blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
925 q->sg_reserved_size = INT_MAX;
930 if (!elevator_init(q, NULL)) {
931 blk_queue_congestion_threshold(q);
938 EXPORT_SYMBOL(blk_init_queue_node);
940 int blk_get_queue(struct request_queue *q)
942 if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
943 kobject_get(&q->kobj);
950 EXPORT_SYMBOL(blk_get_queue);
952 static inline void blk_free_request(struct request_queue *q, struct request *rq)
954 if (rq->cmd_flags & REQ_ELVPRIV)
955 elv_put_request(q, rq);
956 mempool_free(rq, q->rq.rq_pool);
959 static struct request *
960 blk_alloc_request(struct request_queue *q, int rw, int priv, gfp_t gfp_mask)
962 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
968 * first three bits are identical in rq->cmd_flags and bio->bi_rw,
969 * see bio.h and blkdev.h
971 rq->cmd_flags = rw | REQ_ALLOCED;
974 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
975 mempool_free(rq, q->rq.rq_pool);
978 rq->cmd_flags |= REQ_ELVPRIV;
985 * ioc_batching returns true if the ioc is a valid batching request and
986 * should be given priority access to a request.
988 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
994 * Make sure the process is able to allocate at least 1 request
995 * even if the batch times out, otherwise we could theoretically
998 return ioc->nr_batch_requests == q->nr_batching ||
999 (ioc->nr_batch_requests > 0
1000 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
1004 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1005 * will cause the process to be a "batcher" on all queues in the system. This
1006 * is the behaviour we want though - once it gets a wakeup it should be given
1009 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1011 if (!ioc || ioc_batching(q, ioc))
1014 ioc->nr_batch_requests = q->nr_batching;
1015 ioc->last_waited = jiffies;
1018 static void __freed_request(struct request_queue *q, int rw)
1020 struct request_list *rl = &q->rq;
1022 if (rl->count[rw] < queue_congestion_off_threshold(q))
1023 blk_clear_queue_congested(q, rw);
1025 if (rl->count[rw] + 1 <= q->nr_requests) {
1026 if (waitqueue_active(&rl->wait[rw]))
1027 wake_up(&rl->wait[rw]);
1029 blk_clear_queue_full(q, rw);
1034 * A request has just been released. Account for it, update the full and
1035 * congestion status, wake up any waiters. Called under q->queue_lock.
1037 static void freed_request(struct request_queue *q, int rw, int priv)
1039 struct request_list *rl = &q->rq;
1045 __freed_request(q, rw);
1047 if (unlikely(rl->starved[rw ^ 1]))
1048 __freed_request(q, rw ^ 1);
1051 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
1053 * Get a free request, queue_lock must be held.
1054 * Returns NULL on failure, with queue_lock held.
1055 * Returns !NULL on success, with queue_lock *not held*.
1057 static struct request *get_request(struct request_queue *q, int rw_flags,
1058 struct bio *bio, gfp_t gfp_mask)
1060 struct request *rq = NULL;
1061 struct request_list *rl = &q->rq;
1062 struct io_context *ioc = NULL;
1063 const int rw = rw_flags & 0x01;
1064 int may_queue, priv;
1066 may_queue = elv_may_queue(q, rw_flags);
1067 if (may_queue == ELV_MQUEUE_NO)
1070 if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
1071 if (rl->count[rw]+1 >= q->nr_requests) {
1072 ioc = current_io_context(GFP_ATOMIC, q->node);
1074 * The queue will fill after this allocation, so set
1075 * it as full, and mark this process as "batching".
1076 * This process will be allowed to complete a batch of
1077 * requests, others will be blocked.
1079 if (!blk_queue_full(q, rw)) {
1080 ioc_set_batching(q, ioc);
1081 blk_set_queue_full(q, rw);
1083 if (may_queue != ELV_MQUEUE_MUST
1084 && !ioc_batching(q, ioc)) {
1086 * The queue is full and the allocating
1087 * process is not a "batcher", and not
1088 * exempted by the IO scheduler
1094 blk_set_queue_congested(q, rw);
1098 * Only allow batching queuers to allocate up to 50% over the defined
1099 * limit of requests, otherwise we could have thousands of requests
1100 * allocated with any setting of ->nr_requests
1102 if (rl->count[rw] >= (3 * q->nr_requests / 2))
1106 rl->starved[rw] = 0;
1108 priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
1112 spin_unlock_irq(q->queue_lock);
1114 rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
1115 if (unlikely(!rq)) {
1117 * Allocation failed presumably due to memory. Undo anything
1118 * we might have messed up.
1120 * Allocating task should really be put onto the front of the
1121 * wait queue, but this is pretty rare.
1123 spin_lock_irq(q->queue_lock);
1124 freed_request(q, rw, priv);
1127 * in the very unlikely event that allocation failed and no
1128 * requests for this direction was pending, mark us starved
1129 * so that freeing of a request in the other direction will
1130 * notice us. another possible fix would be to split the
1131 * rq mempool into READ and WRITE
1134 if (unlikely(rl->count[rw] == 0))
1135 rl->starved[rw] = 1;
1141 * ioc may be NULL here, and ioc_batching will be false. That's
1142 * OK, if the queue is under the request limit then requests need
1143 * not count toward the nr_batch_requests limit. There will always
1144 * be some limit enforced by BLK_BATCH_TIME.
1146 if (ioc_batching(q, ioc))
1147 ioc->nr_batch_requests--;
1151 blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
1157 * No available requests for this queue, unplug the device and wait for some
1158 * requests to become available.
1160 * Called with q->queue_lock held, and returns with it unlocked.
1162 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
1165 const int rw = rw_flags & 0x01;
1168 rq = get_request(q, rw_flags, bio, GFP_NOIO);
1171 struct request_list *rl = &q->rq;
1173 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
1174 TASK_UNINTERRUPTIBLE);
1176 rq = get_request(q, rw_flags, bio, GFP_NOIO);
1179 struct io_context *ioc;
1181 blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
1183 __generic_unplug_device(q);
1184 spin_unlock_irq(q->queue_lock);
1188 * After sleeping, we become a "batching" process and
1189 * will be able to allocate at least one request, and
1190 * up to a big batch of them for a small period time.
1191 * See ioc_batching, ioc_set_batching
1193 ioc = current_io_context(GFP_NOIO, q->node);
1194 ioc_set_batching(q, ioc);
1196 spin_lock_irq(q->queue_lock);
1198 finish_wait(&rl->wait[rw], &wait);
1204 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1208 BUG_ON(rw != READ && rw != WRITE);
1210 spin_lock_irq(q->queue_lock);
1211 if (gfp_mask & __GFP_WAIT) {
1212 rq = get_request_wait(q, rw, NULL);
1214 rq = get_request(q, rw, NULL, gfp_mask);
1216 spin_unlock_irq(q->queue_lock);
1218 /* q->queue_lock is unlocked at this point */
1222 EXPORT_SYMBOL(blk_get_request);
1225 * blk_start_queueing - initiate dispatch of requests to device
1226 * @q: request queue to kick into gear
1228 * This is basically a helper to remove the need to know whether a queue
1229 * is plugged or not if someone just wants to initiate dispatch of requests
1232 * The queue lock must be held with interrupts disabled.
1234 void blk_start_queueing(struct request_queue *q)
1236 if (!blk_queue_plugged(q))
1239 __generic_unplug_device(q);
1241 EXPORT_SYMBOL(blk_start_queueing);
1244 * blk_requeue_request - put a request back on queue
1245 * @q: request queue where request should be inserted
1246 * @rq: request to be inserted
1249 * Drivers often keep queueing requests until the hardware cannot accept
1250 * more, when that condition happens we need to put the request back
1251 * on the queue. Must be called with queue lock held.
1253 void blk_requeue_request(struct request_queue *q, struct request *rq)
1255 blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
1257 if (blk_rq_tagged(rq))
1258 blk_queue_end_tag(q, rq);
1260 elv_requeue_request(q, rq);
1263 EXPORT_SYMBOL(blk_requeue_request);
1266 * blk_insert_request - insert a special request in to a request queue
1267 * @q: request queue where request should be inserted
1268 * @rq: request to be inserted
1269 * @at_head: insert request at head or tail of queue
1270 * @data: private data
1273 * Many block devices need to execute commands asynchronously, so they don't
1274 * block the whole kernel from preemption during request execution. This is
1275 * accomplished normally by inserting aritficial requests tagged as
1276 * REQ_SPECIAL in to the corresponding request queue, and letting them be
1277 * scheduled for actual execution by the request queue.
1279 * We have the option of inserting the head or the tail of the queue.
1280 * Typically we use the tail for new ioctls and so forth. We use the head
1281 * of the queue for things like a QUEUE_FULL message from a device, or a
1282 * host that is unable to accept a particular command.
1284 void blk_insert_request(struct request_queue *q, struct request *rq,
1285 int at_head, void *data)
1287 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
1288 unsigned long flags;
1291 * tell I/O scheduler that this isn't a regular read/write (ie it
1292 * must not attempt merges on this) and that it acts as a soft
1295 rq->cmd_type = REQ_TYPE_SPECIAL;
1296 rq->cmd_flags |= REQ_SOFTBARRIER;
1300 spin_lock_irqsave(q->queue_lock, flags);
1303 * If command is tagged, release the tag
1305 if (blk_rq_tagged(rq))
1306 blk_queue_end_tag(q, rq);
1308 drive_stat_acct(rq, 1);
1309 __elv_add_request(q, rq, where, 0);
1310 blk_start_queueing(q);
1311 spin_unlock_irqrestore(q->queue_lock, flags);
1314 EXPORT_SYMBOL(blk_insert_request);
1317 * add-request adds a request to the linked list.
1318 * queue lock is held and interrupts disabled, as we muck with the
1319 * request queue list.
1321 static inline void add_request(struct request_queue * q, struct request * req)
1323 drive_stat_acct(req, 1);
1326 * elevator indicated where it wants this request to be
1327 * inserted at elevator_merge time
1329 __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1333 * disk_round_stats() - Round off the performance stats on a struct
1336 * The average IO queue length and utilisation statistics are maintained
1337 * by observing the current state of the queue length and the amount of
1338 * time it has been in this state for.
1340 * Normally, that accounting is done on IO completion, but that can result
1341 * in more than a second's worth of IO being accounted for within any one
1342 * second, leading to >100% utilisation. To deal with that, we call this
1343 * function to do a round-off before returning the results when reading
1344 * /proc/diskstats. This accounts immediately for all queue usage up to
1345 * the current jiffies and restarts the counters again.
1347 void disk_round_stats(struct gendisk *disk)
1349 unsigned long now = jiffies;
1351 if (now == disk->stamp)
1354 if (disk->in_flight) {
1355 __disk_stat_add(disk, time_in_queue,
1356 disk->in_flight * (now - disk->stamp));
1357 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
1362 EXPORT_SYMBOL_GPL(disk_round_stats);
1365 * queue lock must be held
1367 void __blk_put_request(struct request_queue *q, struct request *req)
1371 if (unlikely(--req->ref_count))
1374 elv_completed_request(q, req);
1377 * Request may not have originated from ll_rw_blk. if not,
1378 * it didn't come out of our reserved rq pools
1380 if (req->cmd_flags & REQ_ALLOCED) {
1381 int rw = rq_data_dir(req);
1382 int priv = req->cmd_flags & REQ_ELVPRIV;
1384 BUG_ON(!list_empty(&req->queuelist));
1385 BUG_ON(!hlist_unhashed(&req->hash));
1387 blk_free_request(q, req);
1388 freed_request(q, rw, priv);
1392 EXPORT_SYMBOL_GPL(__blk_put_request);
1394 void blk_put_request(struct request *req)
1396 unsigned long flags;
1397 struct request_queue *q = req->q;
1400 * Gee, IDE calls in w/ NULL q. Fix IDE and remove the
1401 * following if (q) test.
1404 spin_lock_irqsave(q->queue_lock, flags);
1405 __blk_put_request(q, req);
1406 spin_unlock_irqrestore(q->queue_lock, flags);
1410 EXPORT_SYMBOL(blk_put_request);
1413 * Has to be called with the request spinlock acquired
1415 static int attempt_merge(struct request_queue *q, struct request *req,
1416 struct request *next)
1418 if (!rq_mergeable(req) || !rq_mergeable(next))
1424 if (req->sector + req->nr_sectors != next->sector)
1427 if (rq_data_dir(req) != rq_data_dir(next)
1428 || req->rq_disk != next->rq_disk
1433 * If we are allowed to merge, then append bio list
1434 * from next to rq and release next. merge_requests_fn
1435 * will have updated segment counts, update sector
1438 if (!ll_merge_requests_fn(q, req, next))
1442 * At this point we have either done a back merge
1443 * or front merge. We need the smaller start_time of
1444 * the merged requests to be the current request
1445 * for accounting purposes.
1447 if (time_after(req->start_time, next->start_time))
1448 req->start_time = next->start_time;
1450 req->biotail->bi_next = next->bio;
1451 req->biotail = next->biotail;
1453 req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
1455 elv_merge_requests(q, req, next);
1458 disk_round_stats(req->rq_disk);
1459 req->rq_disk->in_flight--;
1462 req->ioprio = ioprio_best(req->ioprio, next->ioprio);
1464 __blk_put_request(q, next);
1468 static inline int attempt_back_merge(struct request_queue *q,
1471 struct request *next = elv_latter_request(q, rq);
1474 return attempt_merge(q, rq, next);
1479 static inline int attempt_front_merge(struct request_queue *q,
1482 struct request *prev = elv_former_request(q, rq);
1485 return attempt_merge(q, prev, rq);
1490 void init_request_from_bio(struct request *req, struct bio *bio)
1492 req->cmd_type = REQ_TYPE_FS;
1495 * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
1497 if (bio_rw_ahead(bio) || bio_failfast(bio))
1498 req->cmd_flags |= REQ_FAILFAST;
1501 * REQ_BARRIER implies no merging, but lets make it explicit
1503 if (unlikely(bio_barrier(bio)))
1504 req->cmd_flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
1507 req->cmd_flags |= REQ_RW_SYNC;
1508 if (bio_rw_meta(bio))
1509 req->cmd_flags |= REQ_RW_META;
1512 req->hard_sector = req->sector = bio->bi_sector;
1513 req->ioprio = bio_prio(bio);
1514 req->start_time = jiffies;
1515 blk_rq_bio_prep(req->q, req, bio);
1518 static int __make_request(struct request_queue *q, struct bio *bio)
1520 struct request *req;
1521 int el_ret, nr_sectors, barrier, err;
1522 const unsigned short prio = bio_prio(bio);
1523 const int sync = bio_sync(bio);
1526 nr_sectors = bio_sectors(bio);
1529 * low level driver can indicate that it wants pages above a
1530 * certain limit bounced to low memory (ie for highmem, or even
1531 * ISA dma in theory)
1533 blk_queue_bounce(q, &bio);
1535 barrier = bio_barrier(bio);
1536 if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
1541 spin_lock_irq(q->queue_lock);
1543 if (unlikely(barrier) || elv_queue_empty(q))
1546 el_ret = elv_merge(q, &req, bio);
1548 case ELEVATOR_BACK_MERGE:
1549 BUG_ON(!rq_mergeable(req));
1551 if (!ll_back_merge_fn(q, req, bio))
1554 blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
1556 req->biotail->bi_next = bio;
1558 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1559 req->ioprio = ioprio_best(req->ioprio, prio);
1560 drive_stat_acct(req, 0);
1561 if (!attempt_back_merge(q, req))
1562 elv_merged_request(q, req, el_ret);
1565 case ELEVATOR_FRONT_MERGE:
1566 BUG_ON(!rq_mergeable(req));
1568 if (!ll_front_merge_fn(q, req, bio))
1571 blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
1573 bio->bi_next = req->bio;
1577 * may not be valid. if the low level driver said
1578 * it didn't need a bounce buffer then it better
1579 * not touch req->buffer either...
1581 req->buffer = bio_data(bio);
1582 req->current_nr_sectors = bio_cur_sectors(bio);
1583 req->hard_cur_sectors = req->current_nr_sectors;
1584 req->sector = req->hard_sector = bio->bi_sector;
1585 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1586 req->ioprio = ioprio_best(req->ioprio, prio);
1587 drive_stat_acct(req, 0);
1588 if (!attempt_front_merge(q, req))
1589 elv_merged_request(q, req, el_ret);
1592 /* ELV_NO_MERGE: elevator says don't/can't merge. */
1599 * This sync check and mask will be re-done in init_request_from_bio(),
1600 * but we need to set it earlier to expose the sync flag to the
1601 * rq allocator and io schedulers.
1603 rw_flags = bio_data_dir(bio);
1605 rw_flags |= REQ_RW_SYNC;
1608 * Grab a free request. This is might sleep but can not fail.
1609 * Returns with the queue unlocked.
1611 req = get_request_wait(q, rw_flags, bio);
1614 * After dropping the lock and possibly sleeping here, our request
1615 * may now be mergeable after it had proven unmergeable (above).
1616 * We don't worry about that case for efficiency. It won't happen
1617 * often, and the elevators are able to handle it.
1619 init_request_from_bio(req, bio);
1621 spin_lock_irq(q->queue_lock);
1622 if (elv_queue_empty(q))
1624 add_request(q, req);
1627 __generic_unplug_device(q);
1629 spin_unlock_irq(q->queue_lock);
1633 bio_endio(bio, err);
1638 * If bio->bi_dev is a partition, remap the location
1640 static inline void blk_partition_remap(struct bio *bio)
1642 struct block_device *bdev = bio->bi_bdev;
1644 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1645 struct hd_struct *p = bdev->bd_part;
1646 const int rw = bio_data_dir(bio);
1648 p->sectors[rw] += bio_sectors(bio);
1651 bio->bi_sector += p->start_sect;
1652 bio->bi_bdev = bdev->bd_contains;
1654 blk_add_trace_remap(bdev_get_queue(bio->bi_bdev), bio,
1655 bdev->bd_dev, bio->bi_sector,
1656 bio->bi_sector - p->start_sect);
1660 static void handle_bad_sector(struct bio *bio)
1662 char b[BDEVNAME_SIZE];
1664 printk(KERN_INFO "attempt to access beyond end of device\n");
1665 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1666 bdevname(bio->bi_bdev, b),
1668 (unsigned long long)bio->bi_sector + bio_sectors(bio),
1669 (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1671 set_bit(BIO_EOF, &bio->bi_flags);
1674 #ifdef CONFIG_FAIL_MAKE_REQUEST
1676 static DECLARE_FAULT_ATTR(fail_make_request);
1678 static int __init setup_fail_make_request(char *str)
1680 return setup_fault_attr(&fail_make_request, str);
1682 __setup("fail_make_request=", setup_fail_make_request);
1684 static int should_fail_request(struct bio *bio)
1686 if ((bio->bi_bdev->bd_disk->flags & GENHD_FL_FAIL) ||
1687 (bio->bi_bdev->bd_part && bio->bi_bdev->bd_part->make_it_fail))
1688 return should_fail(&fail_make_request, bio->bi_size);
1693 static int __init fail_make_request_debugfs(void)
1695 return init_fault_attr_dentries(&fail_make_request,
1696 "fail_make_request");
1699 late_initcall(fail_make_request_debugfs);
1701 #else /* CONFIG_FAIL_MAKE_REQUEST */
1703 static inline int should_fail_request(struct bio *bio)
1708 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1711 * Check whether this bio extends beyond the end of the device.
1713 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1720 /* Test device or partition size, when known. */
1721 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1723 sector_t sector = bio->bi_sector;
1725 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1727 * This may well happen - the kernel calls bread()
1728 * without checking the size of the device, e.g., when
1729 * mounting a device.
1731 handle_bad_sector(bio);
1740 * generic_make_request: hand a buffer to its device driver for I/O
1741 * @bio: The bio describing the location in memory and on the device.
1743 * generic_make_request() is used to make I/O requests of block
1744 * devices. It is passed a &struct bio, which describes the I/O that needs
1747 * generic_make_request() does not return any status. The
1748 * success/failure status of the request, along with notification of
1749 * completion, is delivered asynchronously through the bio->bi_end_io
1750 * function described (one day) else where.
1752 * The caller of generic_make_request must make sure that bi_io_vec
1753 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1754 * set to describe the device address, and the
1755 * bi_end_io and optionally bi_private are set to describe how
1756 * completion notification should be signaled.
1758 * generic_make_request and the drivers it calls may use bi_next if this
1759 * bio happens to be merged with someone else, and may change bi_dev and
1760 * bi_sector for remaps as it sees fit. So the values of these fields
1761 * should NOT be depended on after the call to generic_make_request.
1763 static inline void __generic_make_request(struct bio *bio)
1765 struct request_queue *q;
1766 sector_t old_sector;
1767 int ret, nr_sectors = bio_sectors(bio);
1773 if (bio_check_eod(bio, nr_sectors))
1777 * Resolve the mapping until finished. (drivers are
1778 * still free to implement/resolve their own stacking
1779 * by explicitly returning 0)
1781 * NOTE: we don't repeat the blk_size check for each new device.
1782 * Stacking drivers are expected to know what they are doing.
1787 char b[BDEVNAME_SIZE];
1789 q = bdev_get_queue(bio->bi_bdev);
1792 "generic_make_request: Trying to access "
1793 "nonexistent block-device %s (%Lu)\n",
1794 bdevname(bio->bi_bdev, b),
1795 (long long) bio->bi_sector);
1797 bio_endio(bio, err);
1801 if (unlikely(nr_sectors > q->max_hw_sectors)) {
1802 printk("bio too big device %s (%u > %u)\n",
1803 bdevname(bio->bi_bdev, b),
1809 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1812 if (should_fail_request(bio))
1816 * If this device has partitions, remap block n
1817 * of partition p to block n+start(p) of the disk.
1819 blk_partition_remap(bio);
1821 if (old_sector != -1)
1822 blk_add_trace_remap(q, bio, old_dev, bio->bi_sector,
1825 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
1827 old_sector = bio->bi_sector;
1828 old_dev = bio->bi_bdev->bd_dev;
1830 if (bio_check_eod(bio, nr_sectors))
1832 if (bio_empty_barrier(bio) && !q->prepare_flush_fn) {
1837 ret = q->make_request_fn(q, bio);
1842 * We only want one ->make_request_fn to be active at a time,
1843 * else stack usage with stacked devices could be a problem.
1844 * So use current->bio_{list,tail} to keep a list of requests
1845 * submited by a make_request_fn function.
1846 * current->bio_tail is also used as a flag to say if
1847 * generic_make_request is currently active in this task or not.
1848 * If it is NULL, then no make_request is active. If it is non-NULL,
1849 * then a make_request is active, and new requests should be added
1852 void generic_make_request(struct bio *bio)
1854 if (current->bio_tail) {
1855 /* make_request is active */
1856 *(current->bio_tail) = bio;
1857 bio->bi_next = NULL;
1858 current->bio_tail = &bio->bi_next;
1861 /* following loop may be a bit non-obvious, and so deserves some
1863 * Before entering the loop, bio->bi_next is NULL (as all callers
1864 * ensure that) so we have a list with a single bio.
1865 * We pretend that we have just taken it off a longer list, so
1866 * we assign bio_list to the next (which is NULL) and bio_tail
1867 * to &bio_list, thus initialising the bio_list of new bios to be
1868 * added. __generic_make_request may indeed add some more bios
1869 * through a recursive call to generic_make_request. If it
1870 * did, we find a non-NULL value in bio_list and re-enter the loop
1871 * from the top. In this case we really did just take the bio
1872 * of the top of the list (no pretending) and so fixup bio_list and
1873 * bio_tail or bi_next, and call into __generic_make_request again.
1875 * The loop was structured like this to make only one call to
1876 * __generic_make_request (which is important as it is large and
1877 * inlined) and to keep the structure simple.
1879 BUG_ON(bio->bi_next);
1881 current->bio_list = bio->bi_next;
1882 if (bio->bi_next == NULL)
1883 current->bio_tail = ¤t->bio_list;
1885 bio->bi_next = NULL;
1886 __generic_make_request(bio);
1887 bio = current->bio_list;
1889 current->bio_tail = NULL; /* deactivate */
1892 EXPORT_SYMBOL(generic_make_request);
1895 * submit_bio: submit a bio to the block device layer for I/O
1896 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1897 * @bio: The &struct bio which describes the I/O
1899 * submit_bio() is very similar in purpose to generic_make_request(), and
1900 * uses that function to do most of the work. Both are fairly rough
1901 * interfaces, @bio must be presetup and ready for I/O.
1904 void submit_bio(int rw, struct bio *bio)
1906 int count = bio_sectors(bio);
1911 * If it's a regular read/write or a barrier with data attached,
1912 * go through the normal accounting stuff before submission.
1914 if (!bio_empty_barrier(bio)) {
1916 BIO_BUG_ON(!bio->bi_size);
1917 BIO_BUG_ON(!bio->bi_io_vec);
1920 count_vm_events(PGPGOUT, count);
1922 task_io_account_read(bio->bi_size);
1923 count_vm_events(PGPGIN, count);
1926 if (unlikely(block_dump)) {
1927 char b[BDEVNAME_SIZE];
1928 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
1929 current->comm, task_pid_nr(current),
1930 (rw & WRITE) ? "WRITE" : "READ",
1931 (unsigned long long)bio->bi_sector,
1932 bdevname(bio->bi_bdev,b));
1936 generic_make_request(bio);
1939 EXPORT_SYMBOL(submit_bio);
1941 static void blk_recalc_rq_sectors(struct request *rq, int nsect)
1943 if (blk_fs_request(rq)) {
1944 rq->hard_sector += nsect;
1945 rq->hard_nr_sectors -= nsect;
1948 * Move the I/O submission pointers ahead if required.
1950 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
1951 (rq->sector <= rq->hard_sector)) {
1952 rq->sector = rq->hard_sector;
1953 rq->nr_sectors = rq->hard_nr_sectors;
1954 rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
1955 rq->current_nr_sectors = rq->hard_cur_sectors;
1956 rq->buffer = bio_data(rq->bio);
1960 * if total number of sectors is less than the first segment
1961 * size, something has gone terribly wrong
1963 if (rq->nr_sectors < rq->current_nr_sectors) {
1964 printk("blk: request botched\n");
1965 rq->nr_sectors = rq->current_nr_sectors;
1971 * __end_that_request_first - end I/O on a request
1972 * @req: the request being processed
1973 * @error: 0 for success, < 0 for error
1974 * @nr_bytes: number of bytes to complete
1977 * Ends I/O on a number of bytes attached to @req, and sets it up
1978 * for the next range of segments (if any) in the cluster.
1981 * 0 - we are done with this request, call end_that_request_last()
1982 * 1 - still buffers pending for this request
1984 static int __end_that_request_first(struct request *req, int error,
1987 int total_bytes, bio_nbytes, next_idx = 0;
1990 blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
1993 * for a REQ_BLOCK_PC request, we want to carry any eventual
1994 * sense key with us all the way through
1996 if (!blk_pc_request(req))
2000 if (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))
2001 printk("end_request: I/O error, dev %s, sector %llu\n",
2002 req->rq_disk ? req->rq_disk->disk_name : "?",
2003 (unsigned long long)req->sector);
2006 if (blk_fs_request(req) && req->rq_disk) {
2007 const int rw = rq_data_dir(req);
2009 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
2012 total_bytes = bio_nbytes = 0;
2013 while ((bio = req->bio) != NULL) {
2017 * For an empty barrier request, the low level driver must
2018 * store a potential error location in ->sector. We pass
2019 * that back up in ->bi_sector.
2021 if (blk_empty_barrier(req))
2022 bio->bi_sector = req->sector;
2024 if (nr_bytes >= bio->bi_size) {
2025 req->bio = bio->bi_next;
2026 nbytes = bio->bi_size;
2027 req_bio_endio(req, bio, nbytes, error);
2031 int idx = bio->bi_idx + next_idx;
2033 if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
2034 blk_dump_rq_flags(req, "__end_that");
2035 printk("%s: bio idx %d >= vcnt %d\n",
2037 bio->bi_idx, bio->bi_vcnt);
2041 nbytes = bio_iovec_idx(bio, idx)->bv_len;
2042 BIO_BUG_ON(nbytes > bio->bi_size);
2045 * not a complete bvec done
2047 if (unlikely(nbytes > nr_bytes)) {
2048 bio_nbytes += nr_bytes;
2049 total_bytes += nr_bytes;
2054 * advance to the next vector
2057 bio_nbytes += nbytes;
2060 total_bytes += nbytes;
2063 if ((bio = req->bio)) {
2065 * end more in this run, or just return 'not-done'
2067 if (unlikely(nr_bytes <= 0))
2079 * if the request wasn't completed, update state
2082 req_bio_endio(req, bio, bio_nbytes, error);
2083 bio->bi_idx += next_idx;
2084 bio_iovec(bio)->bv_offset += nr_bytes;
2085 bio_iovec(bio)->bv_len -= nr_bytes;
2088 blk_recalc_rq_sectors(req, total_bytes >> 9);
2089 blk_recalc_rq_segments(req);
2094 * splice the completion data to a local structure and hand off to
2095 * process_completion_queue() to complete the requests
2097 static void blk_done_softirq(struct softirq_action *h)
2099 struct list_head *cpu_list, local_list;
2101 local_irq_disable();
2102 cpu_list = &__get_cpu_var(blk_cpu_done);
2103 list_replace_init(cpu_list, &local_list);
2106 while (!list_empty(&local_list)) {
2107 struct request *rq = list_entry(local_list.next, struct request, donelist);
2109 list_del_init(&rq->donelist);
2110 rq->q->softirq_done_fn(rq);
2114 static int __cpuinit blk_cpu_notify(struct notifier_block *self, unsigned long action,
2118 * If a CPU goes away, splice its entries to the current CPU
2119 * and trigger a run of the softirq
2121 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
2122 int cpu = (unsigned long) hcpu;
2124 local_irq_disable();
2125 list_splice_init(&per_cpu(blk_cpu_done, cpu),
2126 &__get_cpu_var(blk_cpu_done));
2127 raise_softirq_irqoff(BLOCK_SOFTIRQ);
2135 static struct notifier_block blk_cpu_notifier __cpuinitdata = {
2136 .notifier_call = blk_cpu_notify,
2140 * blk_complete_request - end I/O on a request
2141 * @req: the request being processed
2144 * Ends all I/O on a request. It does not handle partial completions,
2145 * unless the driver actually implements this in its completion callback
2146 * through requeueing. The actual completion happens out-of-order,
2147 * through a softirq handler. The user must have registered a completion
2148 * callback through blk_queue_softirq_done().
2151 void blk_complete_request(struct request *req)
2153 struct list_head *cpu_list;
2154 unsigned long flags;
2156 BUG_ON(!req->q->softirq_done_fn);
2158 local_irq_save(flags);
2160 cpu_list = &__get_cpu_var(blk_cpu_done);
2161 list_add_tail(&req->donelist, cpu_list);
2162 raise_softirq_irqoff(BLOCK_SOFTIRQ);
2164 local_irq_restore(flags);
2167 EXPORT_SYMBOL(blk_complete_request);
2170 * queue lock must be held
2172 static void end_that_request_last(struct request *req, int error)
2174 struct gendisk *disk = req->rq_disk;
2176 if (blk_rq_tagged(req))
2177 blk_queue_end_tag(req->q, req);
2179 if (blk_queued_rq(req))
2180 blkdev_dequeue_request(req);
2182 if (unlikely(laptop_mode) && blk_fs_request(req))
2183 laptop_io_completion();
2186 * Account IO completion. bar_rq isn't accounted as a normal
2187 * IO on queueing nor completion. Accounting the containing
2188 * request is enough.
2190 if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
2191 unsigned long duration = jiffies - req->start_time;
2192 const int rw = rq_data_dir(req);
2194 __disk_stat_inc(disk, ios[rw]);
2195 __disk_stat_add(disk, ticks[rw], duration);
2196 disk_round_stats(disk);
2201 req->end_io(req, error);
2203 if (blk_bidi_rq(req))
2204 __blk_put_request(req->next_rq->q, req->next_rq);
2206 __blk_put_request(req->q, req);
2210 static inline void __end_request(struct request *rq, int uptodate,
2211 unsigned int nr_bytes)
2216 error = uptodate ? uptodate : -EIO;
2218 __blk_end_request(rq, error, nr_bytes);
2222 * blk_rq_bytes - Returns bytes left to complete in the entire request
2224 unsigned int blk_rq_bytes(struct request *rq)
2226 if (blk_fs_request(rq))
2227 return rq->hard_nr_sectors << 9;
2229 return rq->data_len;
2231 EXPORT_SYMBOL_GPL(blk_rq_bytes);
2234 * blk_rq_cur_bytes - Returns bytes left to complete in the current segment
2236 unsigned int blk_rq_cur_bytes(struct request *rq)
2238 if (blk_fs_request(rq))
2239 return rq->current_nr_sectors << 9;
2242 return rq->bio->bi_size;
2244 return rq->data_len;
2246 EXPORT_SYMBOL_GPL(blk_rq_cur_bytes);
2249 * end_queued_request - end all I/O on a queued request
2250 * @rq: the request being processed
2251 * @uptodate: error value or 0/1 uptodate flag
2254 * Ends all I/O on a request, and removes it from the block layer queues.
2255 * Not suitable for normal IO completion, unless the driver still has
2256 * the request attached to the block layer.
2259 void end_queued_request(struct request *rq, int uptodate)
2261 __end_request(rq, uptodate, blk_rq_bytes(rq));
2263 EXPORT_SYMBOL(end_queued_request);
2266 * end_dequeued_request - end all I/O on a dequeued request
2267 * @rq: the request being processed
2268 * @uptodate: error value or 0/1 uptodate flag
2271 * Ends all I/O on a request. The request must already have been
2272 * dequeued using blkdev_dequeue_request(), as is normally the case
2276 void end_dequeued_request(struct request *rq, int uptodate)
2278 __end_request(rq, uptodate, blk_rq_bytes(rq));
2280 EXPORT_SYMBOL(end_dequeued_request);
2284 * end_request - end I/O on the current segment of the request
2285 * @req: the request being processed
2286 * @uptodate: error value or 0/1 uptodate flag
2289 * Ends I/O on the current segment of a request. If that is the only
2290 * remaining segment, the request is also completed and freed.
2292 * This is a remnant of how older block drivers handled IO completions.
2293 * Modern drivers typically end IO on the full request in one go, unless
2294 * they have a residual value to account for. For that case this function
2295 * isn't really useful, unless the residual just happens to be the
2296 * full current segment. In other words, don't use this function in new
2297 * code. Either use end_request_completely(), or the
2298 * end_that_request_chunk() (along with end_that_request_last()) for
2299 * partial completions.
2302 void end_request(struct request *req, int uptodate)
2304 __end_request(req, uptodate, req->hard_cur_sectors << 9);
2306 EXPORT_SYMBOL(end_request);
2309 * blk_end_io - Generic end_io function to complete a request.
2310 * @rq: the request being processed
2311 * @error: 0 for success, < 0 for error
2312 * @nr_bytes: number of bytes to complete @rq
2313 * @bidi_bytes: number of bytes to complete @rq->next_rq
2314 * @drv_callback: function called between completion of bios in the request
2315 * and completion of the request.
2316 * If the callback returns non 0, this helper returns without
2317 * completion of the request.
2320 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2321 * If @rq has leftover, sets it up for the next range of segments.
2324 * 0 - we are done with this request
2325 * 1 - this request is not freed yet, it still has pending buffers.
2327 static int blk_end_io(struct request *rq, int error, int nr_bytes,
2328 int bidi_bytes, int (drv_callback)(struct request *))
2330 struct request_queue *q = rq->q;
2331 unsigned long flags = 0UL;
2333 if (blk_fs_request(rq) || blk_pc_request(rq)) {
2334 if (__end_that_request_first(rq, error, nr_bytes))
2337 /* Bidi request must be completed as a whole */
2338 if (blk_bidi_rq(rq) &&
2339 __end_that_request_first(rq->next_rq, error, bidi_bytes))
2343 /* Special feature for tricky drivers */
2344 if (drv_callback && drv_callback(rq))
2347 add_disk_randomness(rq->rq_disk);
2349 spin_lock_irqsave(q->queue_lock, flags);
2350 end_that_request_last(rq, error);
2351 spin_unlock_irqrestore(q->queue_lock, flags);
2357 * blk_end_request - Helper function for drivers to complete the request.
2358 * @rq: the request being processed
2359 * @error: 0 for success, < 0 for error
2360 * @nr_bytes: number of bytes to complete
2363 * Ends I/O on a number of bytes attached to @rq.
2364 * If @rq has leftover, sets it up for the next range of segments.
2367 * 0 - we are done with this request
2368 * 1 - still buffers pending for this request
2370 int blk_end_request(struct request *rq, int error, int nr_bytes)
2372 return blk_end_io(rq, error, nr_bytes, 0, NULL);
2374 EXPORT_SYMBOL_GPL(blk_end_request);
2377 * __blk_end_request - Helper function for drivers to complete the request.
2378 * @rq: the request being processed
2379 * @error: 0 for success, < 0 for error
2380 * @nr_bytes: number of bytes to complete
2383 * Must be called with queue lock held unlike blk_end_request().
2386 * 0 - we are done with this request
2387 * 1 - still buffers pending for this request
2389 int __blk_end_request(struct request *rq, int error, int nr_bytes)
2391 if (blk_fs_request(rq) || blk_pc_request(rq)) {
2392 if (__end_that_request_first(rq, error, nr_bytes))
2396 add_disk_randomness(rq->rq_disk);
2398 end_that_request_last(rq, error);
2402 EXPORT_SYMBOL_GPL(__blk_end_request);
2405 * blk_end_bidi_request - Helper function for drivers to complete bidi request.
2406 * @rq: the bidi request being processed
2407 * @error: 0 for success, < 0 for error
2408 * @nr_bytes: number of bytes to complete @rq
2409 * @bidi_bytes: number of bytes to complete @rq->next_rq
2412 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2415 * 0 - we are done with this request
2416 * 1 - still buffers pending for this request
2418 int blk_end_bidi_request(struct request *rq, int error, int nr_bytes,
2421 return blk_end_io(rq, error, nr_bytes, bidi_bytes, NULL);
2423 EXPORT_SYMBOL_GPL(blk_end_bidi_request);
2426 * blk_end_request_callback - Special helper function for tricky drivers
2427 * @rq: the request being processed
2428 * @error: 0 for success, < 0 for error
2429 * @nr_bytes: number of bytes to complete
2430 * @drv_callback: function called between completion of bios in the request
2431 * and completion of the request.
2432 * If the callback returns non 0, this helper returns without
2433 * completion of the request.
2436 * Ends I/O on a number of bytes attached to @rq.
2437 * If @rq has leftover, sets it up for the next range of segments.
2439 * This special helper function is used only for existing tricky drivers.
2440 * (e.g. cdrom_newpc_intr() of ide-cd)
2441 * This interface will be removed when such drivers are rewritten.
2442 * Don't use this interface in other places anymore.
2445 * 0 - we are done with this request
2446 * 1 - this request is not freed yet.
2447 * this request still has pending buffers or
2448 * the driver doesn't want to finish this request yet.
2450 int blk_end_request_callback(struct request *rq, int error, int nr_bytes,
2451 int (drv_callback)(struct request *))
2453 return blk_end_io(rq, error, nr_bytes, 0, drv_callback);
2455 EXPORT_SYMBOL_GPL(blk_end_request_callback);
2457 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2460 /* first two bits are identical in rq->cmd_flags and bio->bi_rw */
2461 rq->cmd_flags |= (bio->bi_rw & 3);
2463 rq->nr_phys_segments = bio_phys_segments(q, bio);
2464 rq->nr_hw_segments = bio_hw_segments(q, bio);
2465 rq->current_nr_sectors = bio_cur_sectors(bio);
2466 rq->hard_cur_sectors = rq->current_nr_sectors;
2467 rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
2468 rq->buffer = bio_data(bio);
2469 rq->data_len = bio->bi_size;
2471 rq->bio = rq->biotail = bio;
2474 rq->rq_disk = bio->bi_bdev->bd_disk;
2477 int kblockd_schedule_work(struct work_struct *work)
2479 return queue_work(kblockd_workqueue, work);
2482 EXPORT_SYMBOL(kblockd_schedule_work);
2484 void kblockd_flush_work(struct work_struct *work)
2486 cancel_work_sync(work);
2488 EXPORT_SYMBOL(kblockd_flush_work);
2490 int __init blk_dev_init(void)
2494 kblockd_workqueue = create_workqueue("kblockd");
2495 if (!kblockd_workqueue)
2496 panic("Failed to create kblockd\n");
2498 request_cachep = kmem_cache_create("blkdev_requests",
2499 sizeof(struct request), 0, SLAB_PANIC, NULL);
2501 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2502 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2504 for_each_possible_cpu(i)
2505 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
2507 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
2508 register_hotcpu_notifier(&blk_cpu_notifier);