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);
385 * the standard queue merge functions, can be overridden with device
386 * specific ones if so desired
389 static inline int ll_new_mergeable(struct request_queue *q,
393 int nr_phys_segs = bio_phys_segments(q, bio);
395 if (req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
396 req->cmd_flags |= REQ_NOMERGE;
397 if (req == q->last_merge)
398 q->last_merge = NULL;
403 * A hw segment is just getting larger, bump just the phys
406 req->nr_phys_segments += nr_phys_segs;
410 static inline int ll_new_hw_segment(struct request_queue *q,
414 int nr_hw_segs = bio_hw_segments(q, bio);
415 int nr_phys_segs = bio_phys_segments(q, bio);
417 if (req->nr_hw_segments + nr_hw_segs > q->max_hw_segments
418 || req->nr_phys_segments + nr_phys_segs > q->max_phys_segments) {
419 req->cmd_flags |= REQ_NOMERGE;
420 if (req == q->last_merge)
421 q->last_merge = NULL;
426 * This will form the start of a new hw segment. Bump both
429 req->nr_hw_segments += nr_hw_segs;
430 req->nr_phys_segments += nr_phys_segs;
434 int ll_back_merge_fn(struct request_queue *q, struct request *req,
437 unsigned short max_sectors;
440 if (unlikely(blk_pc_request(req)))
441 max_sectors = q->max_hw_sectors;
443 max_sectors = q->max_sectors;
445 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
446 req->cmd_flags |= REQ_NOMERGE;
447 if (req == q->last_merge)
448 q->last_merge = NULL;
451 if (unlikely(!bio_flagged(req->biotail, BIO_SEG_VALID)))
452 blk_recount_segments(q, req->biotail);
453 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
454 blk_recount_segments(q, bio);
455 len = req->biotail->bi_hw_back_size + bio->bi_hw_front_size;
456 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(req->biotail), __BVEC_START(bio)) &&
457 !BIOVEC_VIRT_OVERSIZE(len)) {
458 int mergeable = ll_new_mergeable(q, req, bio);
461 if (req->nr_hw_segments == 1)
462 req->bio->bi_hw_front_size = len;
463 if (bio->bi_hw_segments == 1)
464 bio->bi_hw_back_size = len;
469 return ll_new_hw_segment(q, req, bio);
472 static int ll_front_merge_fn(struct request_queue *q, struct request *req,
475 unsigned short max_sectors;
478 if (unlikely(blk_pc_request(req)))
479 max_sectors = q->max_hw_sectors;
481 max_sectors = q->max_sectors;
484 if (req->nr_sectors + bio_sectors(bio) > max_sectors) {
485 req->cmd_flags |= REQ_NOMERGE;
486 if (req == q->last_merge)
487 q->last_merge = NULL;
490 len = bio->bi_hw_back_size + req->bio->bi_hw_front_size;
491 if (unlikely(!bio_flagged(bio, BIO_SEG_VALID)))
492 blk_recount_segments(q, bio);
493 if (unlikely(!bio_flagged(req->bio, BIO_SEG_VALID)))
494 blk_recount_segments(q, req->bio);
495 if (BIOVEC_VIRT_MERGEABLE(__BVEC_END(bio), __BVEC_START(req->bio)) &&
496 !BIOVEC_VIRT_OVERSIZE(len)) {
497 int mergeable = ll_new_mergeable(q, req, bio);
500 if (bio->bi_hw_segments == 1)
501 bio->bi_hw_front_size = len;
502 if (req->nr_hw_segments == 1)
503 req->biotail->bi_hw_back_size = len;
508 return ll_new_hw_segment(q, req, bio);
511 static int ll_merge_requests_fn(struct request_queue *q, struct request *req,
512 struct request *next)
514 int total_phys_segments;
515 int total_hw_segments;
518 * First check if the either of the requests are re-queued
519 * requests. Can't merge them if they are.
521 if (req->special || next->special)
525 * Will it become too large?
527 if ((req->nr_sectors + next->nr_sectors) > q->max_sectors)
530 total_phys_segments = req->nr_phys_segments + next->nr_phys_segments;
531 if (blk_phys_contig_segment(q, req->biotail, next->bio))
532 total_phys_segments--;
534 if (total_phys_segments > q->max_phys_segments)
537 total_hw_segments = req->nr_hw_segments + next->nr_hw_segments;
538 if (blk_hw_contig_segment(q, req->biotail, next->bio)) {
539 int len = req->biotail->bi_hw_back_size + next->bio->bi_hw_front_size;
541 * propagate the combined length to the end of the requests
543 if (req->nr_hw_segments == 1)
544 req->bio->bi_hw_front_size = len;
545 if (next->nr_hw_segments == 1)
546 next->biotail->bi_hw_back_size = len;
550 if (total_hw_segments > q->max_hw_segments)
554 req->nr_phys_segments = total_phys_segments;
555 req->nr_hw_segments = total_hw_segments;
560 * "plug" the device if there are no outstanding requests: this will
561 * force the transfer to start only after we have put all the requests
564 * This is called with interrupts off and no requests on the queue and
565 * with the queue lock held.
567 void blk_plug_device(struct request_queue *q)
569 WARN_ON(!irqs_disabled());
572 * don't plug a stopped queue, it must be paired with blk_start_queue()
573 * which will restart the queueing
575 if (blk_queue_stopped(q))
578 if (!test_and_set_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags)) {
579 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
580 blk_add_trace_generic(q, NULL, 0, BLK_TA_PLUG);
584 EXPORT_SYMBOL(blk_plug_device);
587 * remove the queue from the plugged list, if present. called with
588 * queue lock held and interrupts disabled.
590 int blk_remove_plug(struct request_queue *q)
592 WARN_ON(!irqs_disabled());
594 if (!test_and_clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags))
597 del_timer(&q->unplug_timer);
601 EXPORT_SYMBOL(blk_remove_plug);
604 * remove the plug and let it rip..
606 void __generic_unplug_device(struct request_queue *q)
608 if (unlikely(blk_queue_stopped(q)))
611 if (!blk_remove_plug(q))
616 EXPORT_SYMBOL(__generic_unplug_device);
619 * generic_unplug_device - fire a request queue
620 * @q: The &struct request_queue in question
623 * Linux uses plugging to build bigger requests queues before letting
624 * the device have at them. If a queue is plugged, the I/O scheduler
625 * is still adding and merging requests on the queue. Once the queue
626 * gets unplugged, the request_fn defined for the queue is invoked and
629 void generic_unplug_device(struct request_queue *q)
631 spin_lock_irq(q->queue_lock);
632 __generic_unplug_device(q);
633 spin_unlock_irq(q->queue_lock);
635 EXPORT_SYMBOL(generic_unplug_device);
637 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
640 struct request_queue *q = bdi->unplug_io_data;
645 void blk_unplug_work(struct work_struct *work)
647 struct request_queue *q =
648 container_of(work, struct request_queue, unplug_work);
650 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
651 q->rq.count[READ] + q->rq.count[WRITE]);
656 void blk_unplug_timeout(unsigned long data)
658 struct request_queue *q = (struct request_queue *)data;
660 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_TIMER, NULL,
661 q->rq.count[READ] + q->rq.count[WRITE]);
663 kblockd_schedule_work(&q->unplug_work);
666 void blk_unplug(struct request_queue *q)
669 * devices don't necessarily have an ->unplug_fn defined
672 blk_add_trace_pdu_int(q, BLK_TA_UNPLUG_IO, NULL,
673 q->rq.count[READ] + q->rq.count[WRITE]);
678 EXPORT_SYMBOL(blk_unplug);
681 * blk_start_queue - restart a previously stopped queue
682 * @q: The &struct request_queue in question
685 * blk_start_queue() will clear the stop flag on the queue, and call
686 * the request_fn for the queue if it was in a stopped state when
687 * entered. Also see blk_stop_queue(). Queue lock must be held.
689 void blk_start_queue(struct request_queue *q)
691 WARN_ON(!irqs_disabled());
693 clear_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
696 * one level of recursion is ok and is much faster than kicking
697 * the unplug handling
699 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
701 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
704 kblockd_schedule_work(&q->unplug_work);
708 EXPORT_SYMBOL(blk_start_queue);
711 * blk_stop_queue - stop a queue
712 * @q: The &struct request_queue in question
715 * The Linux block layer assumes that a block driver will consume all
716 * entries on the request queue when the request_fn strategy is called.
717 * Often this will not happen, because of hardware limitations (queue
718 * depth settings). If a device driver gets a 'queue full' response,
719 * or if it simply chooses not to queue more I/O at one point, it can
720 * call this function to prevent the request_fn from being called until
721 * the driver has signalled it's ready to go again. This happens by calling
722 * blk_start_queue() to restart queue operations. Queue lock must be held.
724 void blk_stop_queue(struct request_queue *q)
727 set_bit(QUEUE_FLAG_STOPPED, &q->queue_flags);
729 EXPORT_SYMBOL(blk_stop_queue);
732 * blk_sync_queue - cancel any pending callbacks on a queue
736 * The block layer may perform asynchronous callback activity
737 * on a queue, such as calling the unplug function after a timeout.
738 * A block device may call blk_sync_queue to ensure that any
739 * such activity is cancelled, thus allowing it to release resources
740 * that the callbacks might use. The caller must already have made sure
741 * that its ->make_request_fn will not re-add plugging prior to calling
745 void blk_sync_queue(struct request_queue *q)
747 del_timer_sync(&q->unplug_timer);
748 kblockd_flush_work(&q->unplug_work);
750 EXPORT_SYMBOL(blk_sync_queue);
753 * blk_run_queue - run a single device queue
754 * @q: The queue to run
756 void blk_run_queue(struct request_queue *q)
760 spin_lock_irqsave(q->queue_lock, flags);
764 * Only recurse once to avoid overrunning the stack, let the unplug
765 * handling reinvoke the handler shortly if we already got there.
767 if (!elv_queue_empty(q)) {
768 if (!test_and_set_bit(QUEUE_FLAG_REENTER, &q->queue_flags)) {
770 clear_bit(QUEUE_FLAG_REENTER, &q->queue_flags);
773 kblockd_schedule_work(&q->unplug_work);
777 spin_unlock_irqrestore(q->queue_lock, flags);
779 EXPORT_SYMBOL(blk_run_queue);
781 void blk_put_queue(struct request_queue *q)
783 kobject_put(&q->kobj);
785 EXPORT_SYMBOL(blk_put_queue);
787 void blk_cleanup_queue(struct request_queue * q)
789 mutex_lock(&q->sysfs_lock);
790 set_bit(QUEUE_FLAG_DEAD, &q->queue_flags);
791 mutex_unlock(&q->sysfs_lock);
794 elevator_exit(q->elevator);
799 EXPORT_SYMBOL(blk_cleanup_queue);
801 static int blk_init_free_list(struct request_queue *q)
803 struct request_list *rl = &q->rq;
805 rl->count[READ] = rl->count[WRITE] = 0;
806 rl->starved[READ] = rl->starved[WRITE] = 0;
808 init_waitqueue_head(&rl->wait[READ]);
809 init_waitqueue_head(&rl->wait[WRITE]);
811 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
812 mempool_free_slab, request_cachep, q->node);
820 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
822 return blk_alloc_queue_node(gfp_mask, -1);
824 EXPORT_SYMBOL(blk_alloc_queue);
826 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
828 struct request_queue *q;
831 q = kmem_cache_alloc_node(blk_requestq_cachep,
832 gfp_mask | __GFP_ZERO, node_id);
836 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
837 q->backing_dev_info.unplug_io_data = q;
838 err = bdi_init(&q->backing_dev_info);
840 kmem_cache_free(blk_requestq_cachep, q);
844 init_timer(&q->unplug_timer);
846 kobject_init(&q->kobj, &blk_queue_ktype);
848 mutex_init(&q->sysfs_lock);
852 EXPORT_SYMBOL(blk_alloc_queue_node);
855 * blk_init_queue - prepare a request queue for use with a block device
856 * @rfn: The function to be called to process requests that have been
857 * placed on the queue.
858 * @lock: Request queue spin lock
861 * If a block device wishes to use the standard request handling procedures,
862 * which sorts requests and coalesces adjacent requests, then it must
863 * call blk_init_queue(). The function @rfn will be called when there
864 * are requests on the queue that need to be processed. If the device
865 * supports plugging, then @rfn may not be called immediately when requests
866 * are available on the queue, but may be called at some time later instead.
867 * Plugged queues are generally unplugged when a buffer belonging to one
868 * of the requests on the queue is needed, or due to memory pressure.
870 * @rfn is not required, or even expected, to remove all requests off the
871 * queue, but only as many as it can handle at a time. If it does leave
872 * requests on the queue, it is responsible for arranging that the requests
873 * get dealt with eventually.
875 * The queue spin lock must be held while manipulating the requests on the
876 * request queue; this lock will be taken also from interrupt context, so irq
877 * disabling is needed for it.
879 * Function returns a pointer to the initialized request queue, or NULL if
883 * blk_init_queue() must be paired with a blk_cleanup_queue() call
884 * when the block device is deactivated (such as at module unload).
887 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
889 return blk_init_queue_node(rfn, lock, -1);
891 EXPORT_SYMBOL(blk_init_queue);
893 struct request_queue *
894 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
896 struct request_queue *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
902 if (blk_init_free_list(q)) {
903 kmem_cache_free(blk_requestq_cachep, q);
908 * if caller didn't supply a lock, they get per-queue locking with
912 spin_lock_init(&q->__queue_lock);
913 lock = &q->__queue_lock;
917 q->prep_rq_fn = NULL;
918 q->unplug_fn = generic_unplug_device;
919 q->queue_flags = (1 << QUEUE_FLAG_CLUSTER);
920 q->queue_lock = lock;
922 blk_queue_segment_boundary(q, 0xffffffff);
924 blk_queue_make_request(q, __make_request);
925 blk_queue_max_segment_size(q, MAX_SEGMENT_SIZE);
927 blk_queue_max_hw_segments(q, MAX_HW_SEGMENTS);
928 blk_queue_max_phys_segments(q, MAX_PHYS_SEGMENTS);
930 q->sg_reserved_size = INT_MAX;
935 if (!elevator_init(q, NULL)) {
936 blk_queue_congestion_threshold(q);
943 EXPORT_SYMBOL(blk_init_queue_node);
945 int blk_get_queue(struct request_queue *q)
947 if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
948 kobject_get(&q->kobj);
955 EXPORT_SYMBOL(blk_get_queue);
957 static inline void blk_free_request(struct request_queue *q, struct request *rq)
959 if (rq->cmd_flags & REQ_ELVPRIV)
960 elv_put_request(q, rq);
961 mempool_free(rq, q->rq.rq_pool);
964 static struct request *
965 blk_alloc_request(struct request_queue *q, int rw, int priv, gfp_t gfp_mask)
967 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
973 * first three bits are identical in rq->cmd_flags and bio->bi_rw,
974 * see bio.h and blkdev.h
976 rq->cmd_flags = rw | REQ_ALLOCED;
979 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
980 mempool_free(rq, q->rq.rq_pool);
983 rq->cmd_flags |= REQ_ELVPRIV;
990 * ioc_batching returns true if the ioc is a valid batching request and
991 * should be given priority access to a request.
993 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
999 * Make sure the process is able to allocate at least 1 request
1000 * even if the batch times out, otherwise we could theoretically
1003 return ioc->nr_batch_requests == q->nr_batching ||
1004 (ioc->nr_batch_requests > 0
1005 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
1009 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1010 * will cause the process to be a "batcher" on all queues in the system. This
1011 * is the behaviour we want though - once it gets a wakeup it should be given
1014 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1016 if (!ioc || ioc_batching(q, ioc))
1019 ioc->nr_batch_requests = q->nr_batching;
1020 ioc->last_waited = jiffies;
1023 static void __freed_request(struct request_queue *q, int rw)
1025 struct request_list *rl = &q->rq;
1027 if (rl->count[rw] < queue_congestion_off_threshold(q))
1028 blk_clear_queue_congested(q, rw);
1030 if (rl->count[rw] + 1 <= q->nr_requests) {
1031 if (waitqueue_active(&rl->wait[rw]))
1032 wake_up(&rl->wait[rw]);
1034 blk_clear_queue_full(q, rw);
1039 * A request has just been released. Account for it, update the full and
1040 * congestion status, wake up any waiters. Called under q->queue_lock.
1042 static void freed_request(struct request_queue *q, int rw, int priv)
1044 struct request_list *rl = &q->rq;
1050 __freed_request(q, rw);
1052 if (unlikely(rl->starved[rw ^ 1]))
1053 __freed_request(q, rw ^ 1);
1056 #define blkdev_free_rq(list) list_entry((list)->next, struct request, queuelist)
1058 * Get a free request, queue_lock must be held.
1059 * Returns NULL on failure, with queue_lock held.
1060 * Returns !NULL on success, with queue_lock *not held*.
1062 static struct request *get_request(struct request_queue *q, int rw_flags,
1063 struct bio *bio, gfp_t gfp_mask)
1065 struct request *rq = NULL;
1066 struct request_list *rl = &q->rq;
1067 struct io_context *ioc = NULL;
1068 const int rw = rw_flags & 0x01;
1069 int may_queue, priv;
1071 may_queue = elv_may_queue(q, rw_flags);
1072 if (may_queue == ELV_MQUEUE_NO)
1075 if (rl->count[rw]+1 >= queue_congestion_on_threshold(q)) {
1076 if (rl->count[rw]+1 >= q->nr_requests) {
1077 ioc = current_io_context(GFP_ATOMIC, q->node);
1079 * The queue will fill after this allocation, so set
1080 * it as full, and mark this process as "batching".
1081 * This process will be allowed to complete a batch of
1082 * requests, others will be blocked.
1084 if (!blk_queue_full(q, rw)) {
1085 ioc_set_batching(q, ioc);
1086 blk_set_queue_full(q, rw);
1088 if (may_queue != ELV_MQUEUE_MUST
1089 && !ioc_batching(q, ioc)) {
1091 * The queue is full and the allocating
1092 * process is not a "batcher", and not
1093 * exempted by the IO scheduler
1099 blk_set_queue_congested(q, rw);
1103 * Only allow batching queuers to allocate up to 50% over the defined
1104 * limit of requests, otherwise we could have thousands of requests
1105 * allocated with any setting of ->nr_requests
1107 if (rl->count[rw] >= (3 * q->nr_requests / 2))
1111 rl->starved[rw] = 0;
1113 priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
1117 spin_unlock_irq(q->queue_lock);
1119 rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
1120 if (unlikely(!rq)) {
1122 * Allocation failed presumably due to memory. Undo anything
1123 * we might have messed up.
1125 * Allocating task should really be put onto the front of the
1126 * wait queue, but this is pretty rare.
1128 spin_lock_irq(q->queue_lock);
1129 freed_request(q, rw, priv);
1132 * in the very unlikely event that allocation failed and no
1133 * requests for this direction was pending, mark us starved
1134 * so that freeing of a request in the other direction will
1135 * notice us. another possible fix would be to split the
1136 * rq mempool into READ and WRITE
1139 if (unlikely(rl->count[rw] == 0))
1140 rl->starved[rw] = 1;
1146 * ioc may be NULL here, and ioc_batching will be false. That's
1147 * OK, if the queue is under the request limit then requests need
1148 * not count toward the nr_batch_requests limit. There will always
1149 * be some limit enforced by BLK_BATCH_TIME.
1151 if (ioc_batching(q, ioc))
1152 ioc->nr_batch_requests--;
1156 blk_add_trace_generic(q, bio, rw, BLK_TA_GETRQ);
1162 * No available requests for this queue, unplug the device and wait for some
1163 * requests to become available.
1165 * Called with q->queue_lock held, and returns with it unlocked.
1167 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
1170 const int rw = rw_flags & 0x01;
1173 rq = get_request(q, rw_flags, bio, GFP_NOIO);
1176 struct request_list *rl = &q->rq;
1178 prepare_to_wait_exclusive(&rl->wait[rw], &wait,
1179 TASK_UNINTERRUPTIBLE);
1181 rq = get_request(q, rw_flags, bio, GFP_NOIO);
1184 struct io_context *ioc;
1186 blk_add_trace_generic(q, bio, rw, BLK_TA_SLEEPRQ);
1188 __generic_unplug_device(q);
1189 spin_unlock_irq(q->queue_lock);
1193 * After sleeping, we become a "batching" process and
1194 * will be able to allocate at least one request, and
1195 * up to a big batch of them for a small period time.
1196 * See ioc_batching, ioc_set_batching
1198 ioc = current_io_context(GFP_NOIO, q->node);
1199 ioc_set_batching(q, ioc);
1201 spin_lock_irq(q->queue_lock);
1203 finish_wait(&rl->wait[rw], &wait);
1209 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1213 BUG_ON(rw != READ && rw != WRITE);
1215 spin_lock_irq(q->queue_lock);
1216 if (gfp_mask & __GFP_WAIT) {
1217 rq = get_request_wait(q, rw, NULL);
1219 rq = get_request(q, rw, NULL, gfp_mask);
1221 spin_unlock_irq(q->queue_lock);
1223 /* q->queue_lock is unlocked at this point */
1227 EXPORT_SYMBOL(blk_get_request);
1230 * blk_start_queueing - initiate dispatch of requests to device
1231 * @q: request queue to kick into gear
1233 * This is basically a helper to remove the need to know whether a queue
1234 * is plugged or not if someone just wants to initiate dispatch of requests
1237 * The queue lock must be held with interrupts disabled.
1239 void blk_start_queueing(struct request_queue *q)
1241 if (!blk_queue_plugged(q))
1244 __generic_unplug_device(q);
1246 EXPORT_SYMBOL(blk_start_queueing);
1249 * blk_requeue_request - put a request back on queue
1250 * @q: request queue where request should be inserted
1251 * @rq: request to be inserted
1254 * Drivers often keep queueing requests until the hardware cannot accept
1255 * more, when that condition happens we need to put the request back
1256 * on the queue. Must be called with queue lock held.
1258 void blk_requeue_request(struct request_queue *q, struct request *rq)
1260 blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
1262 if (blk_rq_tagged(rq))
1263 blk_queue_end_tag(q, rq);
1265 elv_requeue_request(q, rq);
1268 EXPORT_SYMBOL(blk_requeue_request);
1271 * blk_insert_request - insert a special request in to a request queue
1272 * @q: request queue where request should be inserted
1273 * @rq: request to be inserted
1274 * @at_head: insert request at head or tail of queue
1275 * @data: private data
1278 * Many block devices need to execute commands asynchronously, so they don't
1279 * block the whole kernel from preemption during request execution. This is
1280 * accomplished normally by inserting aritficial requests tagged as
1281 * REQ_SPECIAL in to the corresponding request queue, and letting them be
1282 * scheduled for actual execution by the request queue.
1284 * We have the option of inserting the head or the tail of the queue.
1285 * Typically we use the tail for new ioctls and so forth. We use the head
1286 * of the queue for things like a QUEUE_FULL message from a device, or a
1287 * host that is unable to accept a particular command.
1289 void blk_insert_request(struct request_queue *q, struct request *rq,
1290 int at_head, void *data)
1292 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
1293 unsigned long flags;
1296 * tell I/O scheduler that this isn't a regular read/write (ie it
1297 * must not attempt merges on this) and that it acts as a soft
1300 rq->cmd_type = REQ_TYPE_SPECIAL;
1301 rq->cmd_flags |= REQ_SOFTBARRIER;
1305 spin_lock_irqsave(q->queue_lock, flags);
1308 * If command is tagged, release the tag
1310 if (blk_rq_tagged(rq))
1311 blk_queue_end_tag(q, rq);
1313 drive_stat_acct(rq, 1);
1314 __elv_add_request(q, rq, where, 0);
1315 blk_start_queueing(q);
1316 spin_unlock_irqrestore(q->queue_lock, flags);
1319 EXPORT_SYMBOL(blk_insert_request);
1322 * add-request adds a request to the linked list.
1323 * queue lock is held and interrupts disabled, as we muck with the
1324 * request queue list.
1326 static inline void add_request(struct request_queue * q, struct request * req)
1328 drive_stat_acct(req, 1);
1331 * elevator indicated where it wants this request to be
1332 * inserted at elevator_merge time
1334 __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1338 * disk_round_stats() - Round off the performance stats on a struct
1341 * The average IO queue length and utilisation statistics are maintained
1342 * by observing the current state of the queue length and the amount of
1343 * time it has been in this state for.
1345 * Normally, that accounting is done on IO completion, but that can result
1346 * in more than a second's worth of IO being accounted for within any one
1347 * second, leading to >100% utilisation. To deal with that, we call this
1348 * function to do a round-off before returning the results when reading
1349 * /proc/diskstats. This accounts immediately for all queue usage up to
1350 * the current jiffies and restarts the counters again.
1352 void disk_round_stats(struct gendisk *disk)
1354 unsigned long now = jiffies;
1356 if (now == disk->stamp)
1359 if (disk->in_flight) {
1360 __disk_stat_add(disk, time_in_queue,
1361 disk->in_flight * (now - disk->stamp));
1362 __disk_stat_add(disk, io_ticks, (now - disk->stamp));
1367 EXPORT_SYMBOL_GPL(disk_round_stats);
1370 * queue lock must be held
1372 void __blk_put_request(struct request_queue *q, struct request *req)
1376 if (unlikely(--req->ref_count))
1379 elv_completed_request(q, req);
1382 * Request may not have originated from ll_rw_blk. if not,
1383 * it didn't come out of our reserved rq pools
1385 if (req->cmd_flags & REQ_ALLOCED) {
1386 int rw = rq_data_dir(req);
1387 int priv = req->cmd_flags & REQ_ELVPRIV;
1389 BUG_ON(!list_empty(&req->queuelist));
1390 BUG_ON(!hlist_unhashed(&req->hash));
1392 blk_free_request(q, req);
1393 freed_request(q, rw, priv);
1397 EXPORT_SYMBOL_GPL(__blk_put_request);
1399 void blk_put_request(struct request *req)
1401 unsigned long flags;
1402 struct request_queue *q = req->q;
1405 * Gee, IDE calls in w/ NULL q. Fix IDE and remove the
1406 * following if (q) test.
1409 spin_lock_irqsave(q->queue_lock, flags);
1410 __blk_put_request(q, req);
1411 spin_unlock_irqrestore(q->queue_lock, flags);
1415 EXPORT_SYMBOL(blk_put_request);
1418 * Has to be called with the request spinlock acquired
1420 static int attempt_merge(struct request_queue *q, struct request *req,
1421 struct request *next)
1423 if (!rq_mergeable(req) || !rq_mergeable(next))
1429 if (req->sector + req->nr_sectors != next->sector)
1432 if (rq_data_dir(req) != rq_data_dir(next)
1433 || req->rq_disk != next->rq_disk
1438 * If we are allowed to merge, then append bio list
1439 * from next to rq and release next. merge_requests_fn
1440 * will have updated segment counts, update sector
1443 if (!ll_merge_requests_fn(q, req, next))
1447 * At this point we have either done a back merge
1448 * or front merge. We need the smaller start_time of
1449 * the merged requests to be the current request
1450 * for accounting purposes.
1452 if (time_after(req->start_time, next->start_time))
1453 req->start_time = next->start_time;
1455 req->biotail->bi_next = next->bio;
1456 req->biotail = next->biotail;
1458 req->nr_sectors = req->hard_nr_sectors += next->hard_nr_sectors;
1460 elv_merge_requests(q, req, next);
1463 disk_round_stats(req->rq_disk);
1464 req->rq_disk->in_flight--;
1467 req->ioprio = ioprio_best(req->ioprio, next->ioprio);
1469 __blk_put_request(q, next);
1473 static inline int attempt_back_merge(struct request_queue *q,
1476 struct request *next = elv_latter_request(q, rq);
1479 return attempt_merge(q, rq, next);
1484 static inline int attempt_front_merge(struct request_queue *q,
1487 struct request *prev = elv_former_request(q, rq);
1490 return attempt_merge(q, prev, rq);
1495 void init_request_from_bio(struct request *req, struct bio *bio)
1497 req->cmd_type = REQ_TYPE_FS;
1500 * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
1502 if (bio_rw_ahead(bio) || bio_failfast(bio))
1503 req->cmd_flags |= REQ_FAILFAST;
1506 * REQ_BARRIER implies no merging, but lets make it explicit
1508 if (unlikely(bio_barrier(bio)))
1509 req->cmd_flags |= (REQ_HARDBARRIER | REQ_NOMERGE);
1512 req->cmd_flags |= REQ_RW_SYNC;
1513 if (bio_rw_meta(bio))
1514 req->cmd_flags |= REQ_RW_META;
1517 req->hard_sector = req->sector = bio->bi_sector;
1518 req->ioprio = bio_prio(bio);
1519 req->start_time = jiffies;
1520 blk_rq_bio_prep(req->q, req, bio);
1523 static int __make_request(struct request_queue *q, struct bio *bio)
1525 struct request *req;
1526 int el_ret, nr_sectors, barrier, err;
1527 const unsigned short prio = bio_prio(bio);
1528 const int sync = bio_sync(bio);
1531 nr_sectors = bio_sectors(bio);
1534 * low level driver can indicate that it wants pages above a
1535 * certain limit bounced to low memory (ie for highmem, or even
1536 * ISA dma in theory)
1538 blk_queue_bounce(q, &bio);
1540 barrier = bio_barrier(bio);
1541 if (unlikely(barrier) && (q->next_ordered == QUEUE_ORDERED_NONE)) {
1546 spin_lock_irq(q->queue_lock);
1548 if (unlikely(barrier) || elv_queue_empty(q))
1551 el_ret = elv_merge(q, &req, bio);
1553 case ELEVATOR_BACK_MERGE:
1554 BUG_ON(!rq_mergeable(req));
1556 if (!ll_back_merge_fn(q, req, bio))
1559 blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
1561 req->biotail->bi_next = bio;
1563 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1564 req->ioprio = ioprio_best(req->ioprio, prio);
1565 drive_stat_acct(req, 0);
1566 if (!attempt_back_merge(q, req))
1567 elv_merged_request(q, req, el_ret);
1570 case ELEVATOR_FRONT_MERGE:
1571 BUG_ON(!rq_mergeable(req));
1573 if (!ll_front_merge_fn(q, req, bio))
1576 blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
1578 bio->bi_next = req->bio;
1582 * may not be valid. if the low level driver said
1583 * it didn't need a bounce buffer then it better
1584 * not touch req->buffer either...
1586 req->buffer = bio_data(bio);
1587 req->current_nr_sectors = bio_cur_sectors(bio);
1588 req->hard_cur_sectors = req->current_nr_sectors;
1589 req->sector = req->hard_sector = bio->bi_sector;
1590 req->nr_sectors = req->hard_nr_sectors += nr_sectors;
1591 req->ioprio = ioprio_best(req->ioprio, prio);
1592 drive_stat_acct(req, 0);
1593 if (!attempt_front_merge(q, req))
1594 elv_merged_request(q, req, el_ret);
1597 /* ELV_NO_MERGE: elevator says don't/can't merge. */
1604 * This sync check and mask will be re-done in init_request_from_bio(),
1605 * but we need to set it earlier to expose the sync flag to the
1606 * rq allocator and io schedulers.
1608 rw_flags = bio_data_dir(bio);
1610 rw_flags |= REQ_RW_SYNC;
1613 * Grab a free request. This is might sleep but can not fail.
1614 * Returns with the queue unlocked.
1616 req = get_request_wait(q, rw_flags, bio);
1619 * After dropping the lock and possibly sleeping here, our request
1620 * may now be mergeable after it had proven unmergeable (above).
1621 * We don't worry about that case for efficiency. It won't happen
1622 * often, and the elevators are able to handle it.
1624 init_request_from_bio(req, bio);
1626 spin_lock_irq(q->queue_lock);
1627 if (elv_queue_empty(q))
1629 add_request(q, req);
1632 __generic_unplug_device(q);
1634 spin_unlock_irq(q->queue_lock);
1638 bio_endio(bio, err);
1643 * If bio->bi_dev is a partition, remap the location
1645 static inline void blk_partition_remap(struct bio *bio)
1647 struct block_device *bdev = bio->bi_bdev;
1649 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1650 struct hd_struct *p = bdev->bd_part;
1651 const int rw = bio_data_dir(bio);
1653 p->sectors[rw] += bio_sectors(bio);
1656 bio->bi_sector += p->start_sect;
1657 bio->bi_bdev = bdev->bd_contains;
1659 blk_add_trace_remap(bdev_get_queue(bio->bi_bdev), bio,
1660 bdev->bd_dev, bio->bi_sector,
1661 bio->bi_sector - p->start_sect);
1665 static void handle_bad_sector(struct bio *bio)
1667 char b[BDEVNAME_SIZE];
1669 printk(KERN_INFO "attempt to access beyond end of device\n");
1670 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1671 bdevname(bio->bi_bdev, b),
1673 (unsigned long long)bio->bi_sector + bio_sectors(bio),
1674 (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1676 set_bit(BIO_EOF, &bio->bi_flags);
1679 #ifdef CONFIG_FAIL_MAKE_REQUEST
1681 static DECLARE_FAULT_ATTR(fail_make_request);
1683 static int __init setup_fail_make_request(char *str)
1685 return setup_fault_attr(&fail_make_request, str);
1687 __setup("fail_make_request=", setup_fail_make_request);
1689 static int should_fail_request(struct bio *bio)
1691 if ((bio->bi_bdev->bd_disk->flags & GENHD_FL_FAIL) ||
1692 (bio->bi_bdev->bd_part && bio->bi_bdev->bd_part->make_it_fail))
1693 return should_fail(&fail_make_request, bio->bi_size);
1698 static int __init fail_make_request_debugfs(void)
1700 return init_fault_attr_dentries(&fail_make_request,
1701 "fail_make_request");
1704 late_initcall(fail_make_request_debugfs);
1706 #else /* CONFIG_FAIL_MAKE_REQUEST */
1708 static inline int should_fail_request(struct bio *bio)
1713 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1716 * Check whether this bio extends beyond the end of the device.
1718 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1725 /* Test device or partition size, when known. */
1726 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1728 sector_t sector = bio->bi_sector;
1730 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1732 * This may well happen - the kernel calls bread()
1733 * without checking the size of the device, e.g., when
1734 * mounting a device.
1736 handle_bad_sector(bio);
1745 * generic_make_request: hand a buffer to its device driver for I/O
1746 * @bio: The bio describing the location in memory and on the device.
1748 * generic_make_request() is used to make I/O requests of block
1749 * devices. It is passed a &struct bio, which describes the I/O that needs
1752 * generic_make_request() does not return any status. The
1753 * success/failure status of the request, along with notification of
1754 * completion, is delivered asynchronously through the bio->bi_end_io
1755 * function described (one day) else where.
1757 * The caller of generic_make_request must make sure that bi_io_vec
1758 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1759 * set to describe the device address, and the
1760 * bi_end_io and optionally bi_private are set to describe how
1761 * completion notification should be signaled.
1763 * generic_make_request and the drivers it calls may use bi_next if this
1764 * bio happens to be merged with someone else, and may change bi_dev and
1765 * bi_sector for remaps as it sees fit. So the values of these fields
1766 * should NOT be depended on after the call to generic_make_request.
1768 static inline void __generic_make_request(struct bio *bio)
1770 struct request_queue *q;
1771 sector_t old_sector;
1772 int ret, nr_sectors = bio_sectors(bio);
1778 if (bio_check_eod(bio, nr_sectors))
1782 * Resolve the mapping until finished. (drivers are
1783 * still free to implement/resolve their own stacking
1784 * by explicitly returning 0)
1786 * NOTE: we don't repeat the blk_size check for each new device.
1787 * Stacking drivers are expected to know what they are doing.
1792 char b[BDEVNAME_SIZE];
1794 q = bdev_get_queue(bio->bi_bdev);
1797 "generic_make_request: Trying to access "
1798 "nonexistent block-device %s (%Lu)\n",
1799 bdevname(bio->bi_bdev, b),
1800 (long long) bio->bi_sector);
1802 bio_endio(bio, err);
1806 if (unlikely(nr_sectors > q->max_hw_sectors)) {
1807 printk("bio too big device %s (%u > %u)\n",
1808 bdevname(bio->bi_bdev, b),
1814 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1817 if (should_fail_request(bio))
1821 * If this device has partitions, remap block n
1822 * of partition p to block n+start(p) of the disk.
1824 blk_partition_remap(bio);
1826 if (old_sector != -1)
1827 blk_add_trace_remap(q, bio, old_dev, bio->bi_sector,
1830 blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
1832 old_sector = bio->bi_sector;
1833 old_dev = bio->bi_bdev->bd_dev;
1835 if (bio_check_eod(bio, nr_sectors))
1837 if (bio_empty_barrier(bio) && !q->prepare_flush_fn) {
1842 ret = q->make_request_fn(q, bio);
1847 * We only want one ->make_request_fn to be active at a time,
1848 * else stack usage with stacked devices could be a problem.
1849 * So use current->bio_{list,tail} to keep a list of requests
1850 * submited by a make_request_fn function.
1851 * current->bio_tail is also used as a flag to say if
1852 * generic_make_request is currently active in this task or not.
1853 * If it is NULL, then no make_request is active. If it is non-NULL,
1854 * then a make_request is active, and new requests should be added
1857 void generic_make_request(struct bio *bio)
1859 if (current->bio_tail) {
1860 /* make_request is active */
1861 *(current->bio_tail) = bio;
1862 bio->bi_next = NULL;
1863 current->bio_tail = &bio->bi_next;
1866 /* following loop may be a bit non-obvious, and so deserves some
1868 * Before entering the loop, bio->bi_next is NULL (as all callers
1869 * ensure that) so we have a list with a single bio.
1870 * We pretend that we have just taken it off a longer list, so
1871 * we assign bio_list to the next (which is NULL) and bio_tail
1872 * to &bio_list, thus initialising the bio_list of new bios to be
1873 * added. __generic_make_request may indeed add some more bios
1874 * through a recursive call to generic_make_request. If it
1875 * did, we find a non-NULL value in bio_list and re-enter the loop
1876 * from the top. In this case we really did just take the bio
1877 * of the top of the list (no pretending) and so fixup bio_list and
1878 * bio_tail or bi_next, and call into __generic_make_request again.
1880 * The loop was structured like this to make only one call to
1881 * __generic_make_request (which is important as it is large and
1882 * inlined) and to keep the structure simple.
1884 BUG_ON(bio->bi_next);
1886 current->bio_list = bio->bi_next;
1887 if (bio->bi_next == NULL)
1888 current->bio_tail = ¤t->bio_list;
1890 bio->bi_next = NULL;
1891 __generic_make_request(bio);
1892 bio = current->bio_list;
1894 current->bio_tail = NULL; /* deactivate */
1897 EXPORT_SYMBOL(generic_make_request);
1900 * submit_bio: submit a bio to the block device layer for I/O
1901 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1902 * @bio: The &struct bio which describes the I/O
1904 * submit_bio() is very similar in purpose to generic_make_request(), and
1905 * uses that function to do most of the work. Both are fairly rough
1906 * interfaces, @bio must be presetup and ready for I/O.
1909 void submit_bio(int rw, struct bio *bio)
1911 int count = bio_sectors(bio);
1916 * If it's a regular read/write or a barrier with data attached,
1917 * go through the normal accounting stuff before submission.
1919 if (!bio_empty_barrier(bio)) {
1921 BIO_BUG_ON(!bio->bi_size);
1922 BIO_BUG_ON(!bio->bi_io_vec);
1925 count_vm_events(PGPGOUT, count);
1927 task_io_account_read(bio->bi_size);
1928 count_vm_events(PGPGIN, count);
1931 if (unlikely(block_dump)) {
1932 char b[BDEVNAME_SIZE];
1933 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
1934 current->comm, task_pid_nr(current),
1935 (rw & WRITE) ? "WRITE" : "READ",
1936 (unsigned long long)bio->bi_sector,
1937 bdevname(bio->bi_bdev,b));
1941 generic_make_request(bio);
1944 EXPORT_SYMBOL(submit_bio);
1946 static void blk_recalc_rq_sectors(struct request *rq, int nsect)
1948 if (blk_fs_request(rq)) {
1949 rq->hard_sector += nsect;
1950 rq->hard_nr_sectors -= nsect;
1953 * Move the I/O submission pointers ahead if required.
1955 if ((rq->nr_sectors >= rq->hard_nr_sectors) &&
1956 (rq->sector <= rq->hard_sector)) {
1957 rq->sector = rq->hard_sector;
1958 rq->nr_sectors = rq->hard_nr_sectors;
1959 rq->hard_cur_sectors = bio_cur_sectors(rq->bio);
1960 rq->current_nr_sectors = rq->hard_cur_sectors;
1961 rq->buffer = bio_data(rq->bio);
1965 * if total number of sectors is less than the first segment
1966 * size, something has gone terribly wrong
1968 if (rq->nr_sectors < rq->current_nr_sectors) {
1969 printk("blk: request botched\n");
1970 rq->nr_sectors = rq->current_nr_sectors;
1976 * __end_that_request_first - end I/O on a request
1977 * @req: the request being processed
1978 * @error: 0 for success, < 0 for error
1979 * @nr_bytes: number of bytes to complete
1982 * Ends I/O on a number of bytes attached to @req, and sets it up
1983 * for the next range of segments (if any) in the cluster.
1986 * 0 - we are done with this request, call end_that_request_last()
1987 * 1 - still buffers pending for this request
1989 static int __end_that_request_first(struct request *req, int error,
1992 int total_bytes, bio_nbytes, next_idx = 0;
1995 blk_add_trace_rq(req->q, req, BLK_TA_COMPLETE);
1998 * for a REQ_BLOCK_PC request, we want to carry any eventual
1999 * sense key with us all the way through
2001 if (!blk_pc_request(req))
2005 if (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))
2006 printk("end_request: I/O error, dev %s, sector %llu\n",
2007 req->rq_disk ? req->rq_disk->disk_name : "?",
2008 (unsigned long long)req->sector);
2011 if (blk_fs_request(req) && req->rq_disk) {
2012 const int rw = rq_data_dir(req);
2014 disk_stat_add(req->rq_disk, sectors[rw], nr_bytes >> 9);
2017 total_bytes = bio_nbytes = 0;
2018 while ((bio = req->bio) != NULL) {
2022 * For an empty barrier request, the low level driver must
2023 * store a potential error location in ->sector. We pass
2024 * that back up in ->bi_sector.
2026 if (blk_empty_barrier(req))
2027 bio->bi_sector = req->sector;
2029 if (nr_bytes >= bio->bi_size) {
2030 req->bio = bio->bi_next;
2031 nbytes = bio->bi_size;
2032 req_bio_endio(req, bio, nbytes, error);
2036 int idx = bio->bi_idx + next_idx;
2038 if (unlikely(bio->bi_idx >= bio->bi_vcnt)) {
2039 blk_dump_rq_flags(req, "__end_that");
2040 printk("%s: bio idx %d >= vcnt %d\n",
2042 bio->bi_idx, bio->bi_vcnt);
2046 nbytes = bio_iovec_idx(bio, idx)->bv_len;
2047 BIO_BUG_ON(nbytes > bio->bi_size);
2050 * not a complete bvec done
2052 if (unlikely(nbytes > nr_bytes)) {
2053 bio_nbytes += nr_bytes;
2054 total_bytes += nr_bytes;
2059 * advance to the next vector
2062 bio_nbytes += nbytes;
2065 total_bytes += nbytes;
2068 if ((bio = req->bio)) {
2070 * end more in this run, or just return 'not-done'
2072 if (unlikely(nr_bytes <= 0))
2084 * if the request wasn't completed, update state
2087 req_bio_endio(req, bio, bio_nbytes, error);
2088 bio->bi_idx += next_idx;
2089 bio_iovec(bio)->bv_offset += nr_bytes;
2090 bio_iovec(bio)->bv_len -= nr_bytes;
2093 blk_recalc_rq_sectors(req, total_bytes >> 9);
2094 blk_recalc_rq_segments(req);
2099 * splice the completion data to a local structure and hand off to
2100 * process_completion_queue() to complete the requests
2102 static void blk_done_softirq(struct softirq_action *h)
2104 struct list_head *cpu_list, local_list;
2106 local_irq_disable();
2107 cpu_list = &__get_cpu_var(blk_cpu_done);
2108 list_replace_init(cpu_list, &local_list);
2111 while (!list_empty(&local_list)) {
2112 struct request *rq = list_entry(local_list.next, struct request, donelist);
2114 list_del_init(&rq->donelist);
2115 rq->q->softirq_done_fn(rq);
2119 static int __cpuinit blk_cpu_notify(struct notifier_block *self, unsigned long action,
2123 * If a CPU goes away, splice its entries to the current CPU
2124 * and trigger a run of the softirq
2126 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
2127 int cpu = (unsigned long) hcpu;
2129 local_irq_disable();
2130 list_splice_init(&per_cpu(blk_cpu_done, cpu),
2131 &__get_cpu_var(blk_cpu_done));
2132 raise_softirq_irqoff(BLOCK_SOFTIRQ);
2140 static struct notifier_block blk_cpu_notifier __cpuinitdata = {
2141 .notifier_call = blk_cpu_notify,
2145 * blk_complete_request - end I/O on a request
2146 * @req: the request being processed
2149 * Ends all I/O on a request. It does not handle partial completions,
2150 * unless the driver actually implements this in its completion callback
2151 * through requeueing. The actual completion happens out-of-order,
2152 * through a softirq handler. The user must have registered a completion
2153 * callback through blk_queue_softirq_done().
2156 void blk_complete_request(struct request *req)
2158 struct list_head *cpu_list;
2159 unsigned long flags;
2161 BUG_ON(!req->q->softirq_done_fn);
2163 local_irq_save(flags);
2165 cpu_list = &__get_cpu_var(blk_cpu_done);
2166 list_add_tail(&req->donelist, cpu_list);
2167 raise_softirq_irqoff(BLOCK_SOFTIRQ);
2169 local_irq_restore(flags);
2172 EXPORT_SYMBOL(blk_complete_request);
2175 * queue lock must be held
2177 static void end_that_request_last(struct request *req, int error)
2179 struct gendisk *disk = req->rq_disk;
2181 if (blk_rq_tagged(req))
2182 blk_queue_end_tag(req->q, req);
2184 if (blk_queued_rq(req))
2185 blkdev_dequeue_request(req);
2187 if (unlikely(laptop_mode) && blk_fs_request(req))
2188 laptop_io_completion();
2191 * Account IO completion. bar_rq isn't accounted as a normal
2192 * IO on queueing nor completion. Accounting the containing
2193 * request is enough.
2195 if (disk && blk_fs_request(req) && req != &req->q->bar_rq) {
2196 unsigned long duration = jiffies - req->start_time;
2197 const int rw = rq_data_dir(req);
2199 __disk_stat_inc(disk, ios[rw]);
2200 __disk_stat_add(disk, ticks[rw], duration);
2201 disk_round_stats(disk);
2206 req->end_io(req, error);
2208 if (blk_bidi_rq(req))
2209 __blk_put_request(req->next_rq->q, req->next_rq);
2211 __blk_put_request(req->q, req);
2215 static inline void __end_request(struct request *rq, int uptodate,
2216 unsigned int nr_bytes)
2221 error = uptodate ? uptodate : -EIO;
2223 __blk_end_request(rq, error, nr_bytes);
2227 * blk_rq_bytes - Returns bytes left to complete in the entire request
2229 unsigned int blk_rq_bytes(struct request *rq)
2231 if (blk_fs_request(rq))
2232 return rq->hard_nr_sectors << 9;
2234 return rq->data_len;
2236 EXPORT_SYMBOL_GPL(blk_rq_bytes);
2239 * blk_rq_cur_bytes - Returns bytes left to complete in the current segment
2241 unsigned int blk_rq_cur_bytes(struct request *rq)
2243 if (blk_fs_request(rq))
2244 return rq->current_nr_sectors << 9;
2247 return rq->bio->bi_size;
2249 return rq->data_len;
2251 EXPORT_SYMBOL_GPL(blk_rq_cur_bytes);
2254 * end_queued_request - end all I/O on a queued request
2255 * @rq: the request being processed
2256 * @uptodate: error value or 0/1 uptodate flag
2259 * Ends all I/O on a request, and removes it from the block layer queues.
2260 * Not suitable for normal IO completion, unless the driver still has
2261 * the request attached to the block layer.
2264 void end_queued_request(struct request *rq, int uptodate)
2266 __end_request(rq, uptodate, blk_rq_bytes(rq));
2268 EXPORT_SYMBOL(end_queued_request);
2271 * end_dequeued_request - end all I/O on a dequeued request
2272 * @rq: the request being processed
2273 * @uptodate: error value or 0/1 uptodate flag
2276 * Ends all I/O on a request. The request must already have been
2277 * dequeued using blkdev_dequeue_request(), as is normally the case
2281 void end_dequeued_request(struct request *rq, int uptodate)
2283 __end_request(rq, uptodate, blk_rq_bytes(rq));
2285 EXPORT_SYMBOL(end_dequeued_request);
2289 * end_request - end I/O on the current segment of the request
2290 * @req: the request being processed
2291 * @uptodate: error value or 0/1 uptodate flag
2294 * Ends I/O on the current segment of a request. If that is the only
2295 * remaining segment, the request is also completed and freed.
2297 * This is a remnant of how older block drivers handled IO completions.
2298 * Modern drivers typically end IO on the full request in one go, unless
2299 * they have a residual value to account for. For that case this function
2300 * isn't really useful, unless the residual just happens to be the
2301 * full current segment. In other words, don't use this function in new
2302 * code. Either use end_request_completely(), or the
2303 * end_that_request_chunk() (along with end_that_request_last()) for
2304 * partial completions.
2307 void end_request(struct request *req, int uptodate)
2309 __end_request(req, uptodate, req->hard_cur_sectors << 9);
2311 EXPORT_SYMBOL(end_request);
2314 * blk_end_io - Generic end_io function to complete a request.
2315 * @rq: the request being processed
2316 * @error: 0 for success, < 0 for error
2317 * @nr_bytes: number of bytes to complete @rq
2318 * @bidi_bytes: number of bytes to complete @rq->next_rq
2319 * @drv_callback: function called between completion of bios in the request
2320 * and completion of the request.
2321 * If the callback returns non 0, this helper returns without
2322 * completion of the request.
2325 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2326 * If @rq has leftover, sets it up for the next range of segments.
2329 * 0 - we are done with this request
2330 * 1 - this request is not freed yet, it still has pending buffers.
2332 static int blk_end_io(struct request *rq, int error, int nr_bytes,
2333 int bidi_bytes, int (drv_callback)(struct request *))
2335 struct request_queue *q = rq->q;
2336 unsigned long flags = 0UL;
2338 if (blk_fs_request(rq) || blk_pc_request(rq)) {
2339 if (__end_that_request_first(rq, error, nr_bytes))
2342 /* Bidi request must be completed as a whole */
2343 if (blk_bidi_rq(rq) &&
2344 __end_that_request_first(rq->next_rq, error, bidi_bytes))
2348 /* Special feature for tricky drivers */
2349 if (drv_callback && drv_callback(rq))
2352 add_disk_randomness(rq->rq_disk);
2354 spin_lock_irqsave(q->queue_lock, flags);
2355 end_that_request_last(rq, error);
2356 spin_unlock_irqrestore(q->queue_lock, flags);
2362 * blk_end_request - Helper function for drivers to complete the request.
2363 * @rq: the request being processed
2364 * @error: 0 for success, < 0 for error
2365 * @nr_bytes: number of bytes to complete
2368 * Ends I/O on a number of bytes attached to @rq.
2369 * If @rq has leftover, sets it up for the next range of segments.
2372 * 0 - we are done with this request
2373 * 1 - still buffers pending for this request
2375 int blk_end_request(struct request *rq, int error, int nr_bytes)
2377 return blk_end_io(rq, error, nr_bytes, 0, NULL);
2379 EXPORT_SYMBOL_GPL(blk_end_request);
2382 * __blk_end_request - Helper function for drivers to complete the request.
2383 * @rq: the request being processed
2384 * @error: 0 for success, < 0 for error
2385 * @nr_bytes: number of bytes to complete
2388 * Must be called with queue lock held unlike blk_end_request().
2391 * 0 - we are done with this request
2392 * 1 - still buffers pending for this request
2394 int __blk_end_request(struct request *rq, int error, int nr_bytes)
2396 if (blk_fs_request(rq) || blk_pc_request(rq)) {
2397 if (__end_that_request_first(rq, error, nr_bytes))
2401 add_disk_randomness(rq->rq_disk);
2403 end_that_request_last(rq, error);
2407 EXPORT_SYMBOL_GPL(__blk_end_request);
2410 * blk_end_bidi_request - Helper function for drivers to complete bidi request.
2411 * @rq: the bidi request being processed
2412 * @error: 0 for success, < 0 for error
2413 * @nr_bytes: number of bytes to complete @rq
2414 * @bidi_bytes: number of bytes to complete @rq->next_rq
2417 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2420 * 0 - we are done with this request
2421 * 1 - still buffers pending for this request
2423 int blk_end_bidi_request(struct request *rq, int error, int nr_bytes,
2426 return blk_end_io(rq, error, nr_bytes, bidi_bytes, NULL);
2428 EXPORT_SYMBOL_GPL(blk_end_bidi_request);
2431 * blk_end_request_callback - Special helper function for tricky drivers
2432 * @rq: the request being processed
2433 * @error: 0 for success, < 0 for error
2434 * @nr_bytes: number of bytes to complete
2435 * @drv_callback: function called between completion of bios in the request
2436 * and completion of the request.
2437 * If the callback returns non 0, this helper returns without
2438 * completion of the request.
2441 * Ends I/O on a number of bytes attached to @rq.
2442 * If @rq has leftover, sets it up for the next range of segments.
2444 * This special helper function is used only for existing tricky drivers.
2445 * (e.g. cdrom_newpc_intr() of ide-cd)
2446 * This interface will be removed when such drivers are rewritten.
2447 * Don't use this interface in other places anymore.
2450 * 0 - we are done with this request
2451 * 1 - this request is not freed yet.
2452 * this request still has pending buffers or
2453 * the driver doesn't want to finish this request yet.
2455 int blk_end_request_callback(struct request *rq, int error, int nr_bytes,
2456 int (drv_callback)(struct request *))
2458 return blk_end_io(rq, error, nr_bytes, 0, drv_callback);
2460 EXPORT_SYMBOL_GPL(blk_end_request_callback);
2462 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2465 /* first two bits are identical in rq->cmd_flags and bio->bi_rw */
2466 rq->cmd_flags |= (bio->bi_rw & 3);
2468 rq->nr_phys_segments = bio_phys_segments(q, bio);
2469 rq->nr_hw_segments = bio_hw_segments(q, bio);
2470 rq->current_nr_sectors = bio_cur_sectors(bio);
2471 rq->hard_cur_sectors = rq->current_nr_sectors;
2472 rq->hard_nr_sectors = rq->nr_sectors = bio_sectors(bio);
2473 rq->buffer = bio_data(bio);
2474 rq->data_len = bio->bi_size;
2476 rq->bio = rq->biotail = bio;
2479 rq->rq_disk = bio->bi_bdev->bd_disk;
2482 int kblockd_schedule_work(struct work_struct *work)
2484 return queue_work(kblockd_workqueue, work);
2487 EXPORT_SYMBOL(kblockd_schedule_work);
2489 void kblockd_flush_work(struct work_struct *work)
2491 cancel_work_sync(work);
2493 EXPORT_SYMBOL(kblockd_flush_work);
2495 int __init blk_dev_init(void)
2499 kblockd_workqueue = create_workqueue("kblockd");
2500 if (!kblockd_workqueue)
2501 panic("Failed to create kblockd\n");
2503 request_cachep = kmem_cache_create("blkdev_requests",
2504 sizeof(struct request), 0, SLAB_PANIC, NULL);
2506 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2507 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2509 for_each_possible_cpu(i)
2510 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
2512 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq, NULL);
2513 register_hotcpu_notifier(&blk_cpu_notifier);