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>
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
12 * This handles all read/write requests to block devices
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/highmem.h>
21 #include <linux/kernel_stat.h>
22 #include <linux/string.h>
23 #include <linux/init.h>
24 #include <linux/completion.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/task_io_accounting_ops.h>
29 #include <linux/blktrace_api.h>
30 #include <linux/fault-inject.h>
32 #define CREATE_TRACE_POINTS
33 #include <trace/events/block.h>
37 EXPORT_TRACEPOINT_SYMBOL_GPL(block_remap);
38 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
40 static int __make_request(struct request_queue *q, struct bio *bio);
43 * For the allocated request tables
45 static struct kmem_cache *request_cachep;
48 * For queue allocation
50 struct kmem_cache *blk_requestq_cachep;
53 * Controlling structure to kblockd
55 static struct workqueue_struct *kblockd_workqueue;
57 static void drive_stat_acct(struct request *rq, int new_io)
59 struct hd_struct *part;
60 int rw = rq_data_dir(rq);
63 if (!blk_do_io_stat(rq))
66 cpu = part_stat_lock();
67 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
70 part_stat_inc(cpu, part, merges[rw]);
72 part_round_stats(cpu, part);
73 part_inc_in_flight(part);
79 void blk_queue_congestion_threshold(struct request_queue *q)
83 nr = q->nr_requests - (q->nr_requests / 8) + 1;
84 if (nr > q->nr_requests)
86 q->nr_congestion_on = nr;
88 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
91 q->nr_congestion_off = nr;
95 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
98 * Locates the passed device's request queue and returns the address of its
101 * Will return NULL if the request queue cannot be located.
103 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
105 struct backing_dev_info *ret = NULL;
106 struct request_queue *q = bdev_get_queue(bdev);
109 ret = &q->backing_dev_info;
112 EXPORT_SYMBOL(blk_get_backing_dev_info);
114 void blk_rq_init(struct request_queue *q, struct request *rq)
116 memset(rq, 0, sizeof(*rq));
118 INIT_LIST_HEAD(&rq->queuelist);
119 INIT_LIST_HEAD(&rq->timeout_list);
122 rq->__sector = (sector_t) -1;
123 INIT_HLIST_NODE(&rq->hash);
124 RB_CLEAR_NODE(&rq->rb_node);
126 rq->cmd_len = BLK_MAX_CDB;
129 rq->start_time = jiffies;
131 EXPORT_SYMBOL(blk_rq_init);
133 static void req_bio_endio(struct request *rq, struct bio *bio,
134 unsigned int nbytes, int error)
136 struct request_queue *q = rq->q;
138 if (&q->bar_rq != rq) {
140 clear_bit(BIO_UPTODATE, &bio->bi_flags);
141 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
144 if (unlikely(nbytes > bio->bi_size)) {
145 printk(KERN_ERR "%s: want %u bytes done, %u left\n",
146 __func__, nbytes, bio->bi_size);
147 nbytes = bio->bi_size;
150 if (unlikely(rq->cmd_flags & REQ_QUIET))
151 set_bit(BIO_QUIET, &bio->bi_flags);
153 bio->bi_size -= nbytes;
154 bio->bi_sector += (nbytes >> 9);
156 if (bio_integrity(bio))
157 bio_integrity_advance(bio, nbytes);
159 if (bio->bi_size == 0)
160 bio_endio(bio, error);
164 * Okay, this is the barrier request in progress, just
167 if (error && !q->orderr)
172 void blk_dump_rq_flags(struct request *rq, char *msg)
176 printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
177 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
180 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
181 (unsigned long long)blk_rq_pos(rq),
182 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
183 printk(KERN_INFO " bio %p, biotail %p, buffer %p, len %u\n",
184 rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
186 if (blk_pc_request(rq)) {
187 printk(KERN_INFO " cdb: ");
188 for (bit = 0; bit < BLK_MAX_CDB; bit++)
189 printk("%02x ", rq->cmd[bit]);
193 EXPORT_SYMBOL(blk_dump_rq_flags);
196 * "plug" the device if there are no outstanding requests: this will
197 * force the transfer to start only after we have put all the requests
200 * This is called with interrupts off and no requests on the queue and
201 * with the queue lock held.
203 void blk_plug_device(struct request_queue *q)
205 WARN_ON(!irqs_disabled());
208 * don't plug a stopped queue, it must be paired with blk_start_queue()
209 * which will restart the queueing
211 if (blk_queue_stopped(q))
214 if (!queue_flag_test_and_set(QUEUE_FLAG_PLUGGED, q)) {
215 mod_timer(&q->unplug_timer, jiffies + q->unplug_delay);
219 EXPORT_SYMBOL(blk_plug_device);
222 * blk_plug_device_unlocked - plug a device without queue lock held
223 * @q: The &struct request_queue to plug
226 * Like @blk_plug_device(), but grabs the queue lock and disables
229 void blk_plug_device_unlocked(struct request_queue *q)
233 spin_lock_irqsave(q->queue_lock, flags);
235 spin_unlock_irqrestore(q->queue_lock, flags);
237 EXPORT_SYMBOL(blk_plug_device_unlocked);
240 * remove the queue from the plugged list, if present. called with
241 * queue lock held and interrupts disabled.
243 int blk_remove_plug(struct request_queue *q)
245 WARN_ON(!irqs_disabled());
247 if (!queue_flag_test_and_clear(QUEUE_FLAG_PLUGGED, q))
250 del_timer(&q->unplug_timer);
253 EXPORT_SYMBOL(blk_remove_plug);
256 * remove the plug and let it rip..
258 void __generic_unplug_device(struct request_queue *q)
260 if (unlikely(blk_queue_stopped(q)))
262 if (!blk_remove_plug(q) && !blk_queue_nonrot(q))
269 * generic_unplug_device - fire a request queue
270 * @q: The &struct request_queue in question
273 * Linux uses plugging to build bigger requests queues before letting
274 * the device have at them. If a queue is plugged, the I/O scheduler
275 * is still adding and merging requests on the queue. Once the queue
276 * gets unplugged, the request_fn defined for the queue is invoked and
279 void generic_unplug_device(struct request_queue *q)
281 if (blk_queue_plugged(q)) {
282 spin_lock_irq(q->queue_lock);
283 __generic_unplug_device(q);
284 spin_unlock_irq(q->queue_lock);
287 EXPORT_SYMBOL(generic_unplug_device);
289 static void blk_backing_dev_unplug(struct backing_dev_info *bdi,
292 struct request_queue *q = bdi->unplug_io_data;
297 void blk_unplug_work(struct work_struct *work)
299 struct request_queue *q =
300 container_of(work, struct request_queue, unplug_work);
302 trace_block_unplug_io(q);
306 void blk_unplug_timeout(unsigned long data)
308 struct request_queue *q = (struct request_queue *)data;
310 trace_block_unplug_timer(q);
311 kblockd_schedule_work(q, &q->unplug_work);
314 void blk_unplug(struct request_queue *q)
317 * devices don't necessarily have an ->unplug_fn defined
320 trace_block_unplug_io(q);
324 EXPORT_SYMBOL(blk_unplug);
327 * blk_start_queue - restart a previously stopped queue
328 * @q: The &struct request_queue in question
331 * blk_start_queue() will clear the stop flag on the queue, and call
332 * the request_fn for the queue if it was in a stopped state when
333 * entered. Also see blk_stop_queue(). Queue lock must be held.
335 void blk_start_queue(struct request_queue *q)
337 WARN_ON(!irqs_disabled());
339 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
342 EXPORT_SYMBOL(blk_start_queue);
345 * blk_stop_queue - stop a queue
346 * @q: The &struct request_queue in question
349 * The Linux block layer assumes that a block driver will consume all
350 * entries on the request queue when the request_fn strategy is called.
351 * Often this will not happen, because of hardware limitations (queue
352 * depth settings). If a device driver gets a 'queue full' response,
353 * or if it simply chooses not to queue more I/O at one point, it can
354 * call this function to prevent the request_fn from being called until
355 * the driver has signalled it's ready to go again. This happens by calling
356 * blk_start_queue() to restart queue operations. Queue lock must be held.
358 void blk_stop_queue(struct request_queue *q)
361 queue_flag_set(QUEUE_FLAG_STOPPED, q);
363 EXPORT_SYMBOL(blk_stop_queue);
366 * blk_sync_queue - cancel any pending callbacks on a queue
370 * The block layer may perform asynchronous callback activity
371 * on a queue, such as calling the unplug function after a timeout.
372 * A block device may call blk_sync_queue to ensure that any
373 * such activity is cancelled, thus allowing it to release resources
374 * that the callbacks might use. The caller must already have made sure
375 * that its ->make_request_fn will not re-add plugging prior to calling
379 void blk_sync_queue(struct request_queue *q)
381 del_timer_sync(&q->unplug_timer);
382 del_timer_sync(&q->timeout);
383 cancel_work_sync(&q->unplug_work);
385 EXPORT_SYMBOL(blk_sync_queue);
388 * __blk_run_queue - run a single device queue
389 * @q: The queue to run
392 * See @blk_run_queue. This variant must be called with the queue lock
393 * held and interrupts disabled.
396 void __blk_run_queue(struct request_queue *q)
400 if (unlikely(blk_queue_stopped(q)))
403 if (elv_queue_empty(q))
407 * Only recurse once to avoid overrunning the stack, let the unplug
408 * handling reinvoke the handler shortly if we already got there.
410 if (!queue_flag_test_and_set(QUEUE_FLAG_REENTER, q)) {
412 queue_flag_clear(QUEUE_FLAG_REENTER, q);
414 queue_flag_set(QUEUE_FLAG_PLUGGED, q);
415 kblockd_schedule_work(q, &q->unplug_work);
418 EXPORT_SYMBOL(__blk_run_queue);
421 * blk_run_queue - run a single device queue
422 * @q: The queue to run
425 * Invoke request handling on this queue, if it has pending work to do.
426 * May be used to restart queueing when a request has completed.
428 void blk_run_queue(struct request_queue *q)
432 spin_lock_irqsave(q->queue_lock, flags);
434 spin_unlock_irqrestore(q->queue_lock, flags);
436 EXPORT_SYMBOL(blk_run_queue);
438 void blk_put_queue(struct request_queue *q)
440 kobject_put(&q->kobj);
443 void blk_cleanup_queue(struct request_queue *q)
446 * We know we have process context here, so we can be a little
447 * cautious and ensure that pending block actions on this device
448 * are done before moving on. Going into this function, we should
449 * not have processes doing IO to this device.
453 mutex_lock(&q->sysfs_lock);
454 queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);
455 mutex_unlock(&q->sysfs_lock);
458 elevator_exit(q->elevator);
462 EXPORT_SYMBOL(blk_cleanup_queue);
464 static int blk_init_free_list(struct request_queue *q)
466 struct request_list *rl = &q->rq;
468 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
469 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
471 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
472 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
474 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
475 mempool_free_slab, request_cachep, q->node);
483 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
485 return blk_alloc_queue_node(gfp_mask, -1);
487 EXPORT_SYMBOL(blk_alloc_queue);
489 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
491 struct request_queue *q;
494 q = kmem_cache_alloc_node(blk_requestq_cachep,
495 gfp_mask | __GFP_ZERO, node_id);
499 q->backing_dev_info.unplug_io_fn = blk_backing_dev_unplug;
500 q->backing_dev_info.unplug_io_data = q;
501 q->backing_dev_info.ra_pages =
502 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
503 q->backing_dev_info.state = 0;
504 q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
506 err = bdi_init(&q->backing_dev_info);
508 kmem_cache_free(blk_requestq_cachep, q);
512 init_timer(&q->unplug_timer);
513 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
514 INIT_LIST_HEAD(&q->timeout_list);
515 INIT_WORK(&q->unplug_work, blk_unplug_work);
517 kobject_init(&q->kobj, &blk_queue_ktype);
519 mutex_init(&q->sysfs_lock);
520 spin_lock_init(&q->__queue_lock);
524 EXPORT_SYMBOL(blk_alloc_queue_node);
527 * blk_init_queue - prepare a request queue for use with a block device
528 * @rfn: The function to be called to process requests that have been
529 * placed on the queue.
530 * @lock: Request queue spin lock
533 * If a block device wishes to use the standard request handling procedures,
534 * which sorts requests and coalesces adjacent requests, then it must
535 * call blk_init_queue(). The function @rfn will be called when there
536 * are requests on the queue that need to be processed. If the device
537 * supports plugging, then @rfn may not be called immediately when requests
538 * are available on the queue, but may be called at some time later instead.
539 * Plugged queues are generally unplugged when a buffer belonging to one
540 * of the requests on the queue is needed, or due to memory pressure.
542 * @rfn is not required, or even expected, to remove all requests off the
543 * queue, but only as many as it can handle at a time. If it does leave
544 * requests on the queue, it is responsible for arranging that the requests
545 * get dealt with eventually.
547 * The queue spin lock must be held while manipulating the requests on the
548 * request queue; this lock will be taken also from interrupt context, so irq
549 * disabling is needed for it.
551 * Function returns a pointer to the initialized request queue, or %NULL if
555 * blk_init_queue() must be paired with a blk_cleanup_queue() call
556 * when the block device is deactivated (such as at module unload).
559 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
561 return blk_init_queue_node(rfn, lock, -1);
563 EXPORT_SYMBOL(blk_init_queue);
565 struct request_queue *
566 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
568 struct request_queue *q = blk_alloc_queue_node(GFP_KERNEL, node_id);
574 if (blk_init_free_list(q)) {
575 kmem_cache_free(blk_requestq_cachep, q);
580 * if caller didn't supply a lock, they get per-queue locking with
584 lock = &q->__queue_lock;
587 q->prep_rq_fn = NULL;
588 q->unplug_fn = generic_unplug_device;
589 q->queue_flags = QUEUE_FLAG_DEFAULT;
590 q->queue_lock = lock;
593 * This also sets hw/phys segments, boundary and size
595 blk_queue_make_request(q, __make_request);
597 q->sg_reserved_size = INT_MAX;
599 blk_set_cmd_filter_defaults(&q->cmd_filter);
604 if (!elevator_init(q, NULL)) {
605 blk_queue_congestion_threshold(q);
612 EXPORT_SYMBOL(blk_init_queue_node);
614 int blk_get_queue(struct request_queue *q)
616 if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
617 kobject_get(&q->kobj);
624 static inline void blk_free_request(struct request_queue *q, struct request *rq)
626 if (rq->cmd_flags & REQ_ELVPRIV)
627 elv_put_request(q, rq);
628 mempool_free(rq, q->rq.rq_pool);
631 static struct request *
632 blk_alloc_request(struct request_queue *q, int flags, int priv, gfp_t gfp_mask)
634 struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
641 rq->cmd_flags = flags | REQ_ALLOCED;
644 if (unlikely(elv_set_request(q, rq, gfp_mask))) {
645 mempool_free(rq, q->rq.rq_pool);
648 rq->cmd_flags |= REQ_ELVPRIV;
655 * ioc_batching returns true if the ioc is a valid batching request and
656 * should be given priority access to a request.
658 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
664 * Make sure the process is able to allocate at least 1 request
665 * even if the batch times out, otherwise we could theoretically
668 return ioc->nr_batch_requests == q->nr_batching ||
669 (ioc->nr_batch_requests > 0
670 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
674 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
675 * will cause the process to be a "batcher" on all queues in the system. This
676 * is the behaviour we want though - once it gets a wakeup it should be given
679 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
681 if (!ioc || ioc_batching(q, ioc))
684 ioc->nr_batch_requests = q->nr_batching;
685 ioc->last_waited = jiffies;
688 static void __freed_request(struct request_queue *q, int sync)
690 struct request_list *rl = &q->rq;
692 if (rl->count[sync] < queue_congestion_off_threshold(q))
693 blk_clear_queue_congested(q, sync);
695 if (rl->count[sync] + 1 <= q->nr_requests) {
696 if (waitqueue_active(&rl->wait[sync]))
697 wake_up(&rl->wait[sync]);
699 blk_clear_queue_full(q, sync);
704 * A request has just been released. Account for it, update the full and
705 * congestion status, wake up any waiters. Called under q->queue_lock.
707 static void freed_request(struct request_queue *q, int sync, int priv)
709 struct request_list *rl = &q->rq;
715 __freed_request(q, sync);
717 if (unlikely(rl->starved[sync ^ 1]))
718 __freed_request(q, sync ^ 1);
722 * Get a free request, queue_lock must be held.
723 * Returns NULL on failure, with queue_lock held.
724 * Returns !NULL on success, with queue_lock *not held*.
726 static struct request *get_request(struct request_queue *q, int rw_flags,
727 struct bio *bio, gfp_t gfp_mask)
729 struct request *rq = NULL;
730 struct request_list *rl = &q->rq;
731 struct io_context *ioc = NULL;
732 const bool is_sync = rw_is_sync(rw_flags) != 0;
735 may_queue = elv_may_queue(q, rw_flags);
736 if (may_queue == ELV_MQUEUE_NO)
739 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
740 if (rl->count[is_sync]+1 >= q->nr_requests) {
741 ioc = current_io_context(GFP_ATOMIC, q->node);
743 * The queue will fill after this allocation, so set
744 * it as full, and mark this process as "batching".
745 * This process will be allowed to complete a batch of
746 * requests, others will be blocked.
748 if (!blk_queue_full(q, is_sync)) {
749 ioc_set_batching(q, ioc);
750 blk_set_queue_full(q, is_sync);
752 if (may_queue != ELV_MQUEUE_MUST
753 && !ioc_batching(q, ioc)) {
755 * The queue is full and the allocating
756 * process is not a "batcher", and not
757 * exempted by the IO scheduler
763 blk_set_queue_congested(q, is_sync);
767 * Only allow batching queuers to allocate up to 50% over the defined
768 * limit of requests, otherwise we could have thousands of requests
769 * allocated with any setting of ->nr_requests
771 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
774 rl->count[is_sync]++;
775 rl->starved[is_sync] = 0;
777 priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);
781 if (blk_queue_io_stat(q))
782 rw_flags |= REQ_IO_STAT;
783 spin_unlock_irq(q->queue_lock);
785 rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);
788 * Allocation failed presumably due to memory. Undo anything
789 * we might have messed up.
791 * Allocating task should really be put onto the front of the
792 * wait queue, but this is pretty rare.
794 spin_lock_irq(q->queue_lock);
795 freed_request(q, is_sync, priv);
798 * in the very unlikely event that allocation failed and no
799 * requests for this direction was pending, mark us starved
800 * so that freeing of a request in the other direction will
801 * notice us. another possible fix would be to split the
802 * rq mempool into READ and WRITE
805 if (unlikely(rl->count[is_sync] == 0))
806 rl->starved[is_sync] = 1;
812 * ioc may be NULL here, and ioc_batching will be false. That's
813 * OK, if the queue is under the request limit then requests need
814 * not count toward the nr_batch_requests limit. There will always
815 * be some limit enforced by BLK_BATCH_TIME.
817 if (ioc_batching(q, ioc))
818 ioc->nr_batch_requests--;
820 trace_block_getrq(q, bio, rw_flags & 1);
826 * No available requests for this queue, unplug the device and wait for some
827 * requests to become available.
829 * Called with q->queue_lock held, and returns with it unlocked.
831 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
834 const bool is_sync = rw_is_sync(rw_flags) != 0;
837 rq = get_request(q, rw_flags, bio, GFP_NOIO);
840 struct io_context *ioc;
841 struct request_list *rl = &q->rq;
843 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
844 TASK_UNINTERRUPTIBLE);
846 trace_block_sleeprq(q, bio, rw_flags & 1);
848 __generic_unplug_device(q);
849 spin_unlock_irq(q->queue_lock);
853 * After sleeping, we become a "batching" process and
854 * will be able to allocate at least one request, and
855 * up to a big batch of them for a small period time.
856 * See ioc_batching, ioc_set_batching
858 ioc = current_io_context(GFP_NOIO, q->node);
859 ioc_set_batching(q, ioc);
861 spin_lock_irq(q->queue_lock);
862 finish_wait(&rl->wait[is_sync], &wait);
864 rq = get_request(q, rw_flags, bio, GFP_NOIO);
870 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
874 BUG_ON(rw != READ && rw != WRITE);
876 spin_lock_irq(q->queue_lock);
877 if (gfp_mask & __GFP_WAIT) {
878 rq = get_request_wait(q, rw, NULL);
880 rq = get_request(q, rw, NULL, gfp_mask);
882 spin_unlock_irq(q->queue_lock);
884 /* q->queue_lock is unlocked at this point */
888 EXPORT_SYMBOL(blk_get_request);
891 * blk_make_request - given a bio, allocate a corresponding struct request.
892 * @q: target request queue
893 * @bio: The bio describing the memory mappings that will be submitted for IO.
894 * It may be a chained-bio properly constructed by block/bio layer.
895 * @gfp_mask: gfp flags to be used for memory allocation
897 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
898 * type commands. Where the struct request needs to be farther initialized by
899 * the caller. It is passed a &struct bio, which describes the memory info of
902 * The caller of blk_make_request must make sure that bi_io_vec
903 * are set to describe the memory buffers. That bio_data_dir() will return
904 * the needed direction of the request. (And all bio's in the passed bio-chain
905 * are properly set accordingly)
907 * If called under none-sleepable conditions, mapped bio buffers must not
908 * need bouncing, by calling the appropriate masked or flagged allocator,
909 * suitable for the target device. Otherwise the call to blk_queue_bounce will
912 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
913 * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
914 * anything but the first bio in the chain. Otherwise you risk waiting for IO
915 * completion of a bio that hasn't been submitted yet, thus resulting in a
916 * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
917 * of bio_alloc(), as that avoids the mempool deadlock.
918 * If possible a big IO should be split into smaller parts when allocation
919 * fails. Partial allocation should not be an error, or you risk a live-lock.
921 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
924 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
927 return ERR_PTR(-ENOMEM);
930 struct bio *bounce_bio = bio;
933 blk_queue_bounce(q, &bounce_bio);
934 ret = blk_rq_append_bio(q, rq, bounce_bio);
943 EXPORT_SYMBOL(blk_make_request);
946 * blk_requeue_request - put a request back on queue
947 * @q: request queue where request should be inserted
948 * @rq: request to be inserted
951 * Drivers often keep queueing requests until the hardware cannot accept
952 * more, when that condition happens we need to put the request back
953 * on the queue. Must be called with queue lock held.
955 void blk_requeue_request(struct request_queue *q, struct request *rq)
957 blk_delete_timer(rq);
958 blk_clear_rq_complete(rq);
959 trace_block_rq_requeue(q, rq);
961 if (blk_rq_tagged(rq))
962 blk_queue_end_tag(q, rq);
964 BUG_ON(blk_queued_rq(rq));
966 elv_requeue_request(q, rq);
968 EXPORT_SYMBOL(blk_requeue_request);
971 * blk_insert_request - insert a special request into a request queue
972 * @q: request queue where request should be inserted
973 * @rq: request to be inserted
974 * @at_head: insert request at head or tail of queue
975 * @data: private data
978 * Many block devices need to execute commands asynchronously, so they don't
979 * block the whole kernel from preemption during request execution. This is
980 * accomplished normally by inserting aritficial requests tagged as
981 * REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them
982 * be scheduled for actual execution by the request queue.
984 * We have the option of inserting the head or the tail of the queue.
985 * Typically we use the tail for new ioctls and so forth. We use the head
986 * of the queue for things like a QUEUE_FULL message from a device, or a
987 * host that is unable to accept a particular command.
989 void blk_insert_request(struct request_queue *q, struct request *rq,
990 int at_head, void *data)
992 int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
996 * tell I/O scheduler that this isn't a regular read/write (ie it
997 * must not attempt merges on this) and that it acts as a soft
1000 rq->cmd_type = REQ_TYPE_SPECIAL;
1004 spin_lock_irqsave(q->queue_lock, flags);
1007 * If command is tagged, release the tag
1009 if (blk_rq_tagged(rq))
1010 blk_queue_end_tag(q, rq);
1012 drive_stat_acct(rq, 1);
1013 __elv_add_request(q, rq, where, 0);
1015 spin_unlock_irqrestore(q->queue_lock, flags);
1017 EXPORT_SYMBOL(blk_insert_request);
1020 * add-request adds a request to the linked list.
1021 * queue lock is held and interrupts disabled, as we muck with the
1022 * request queue list.
1024 static inline void add_request(struct request_queue *q, struct request *req)
1026 drive_stat_acct(req, 1);
1029 * elevator indicated where it wants this request to be
1030 * inserted at elevator_merge time
1032 __elv_add_request(q, req, ELEVATOR_INSERT_SORT, 0);
1035 static void part_round_stats_single(int cpu, struct hd_struct *part,
1038 if (now == part->stamp)
1041 if (part->in_flight) {
1042 __part_stat_add(cpu, part, time_in_queue,
1043 part->in_flight * (now - part->stamp));
1044 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1050 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1051 * @cpu: cpu number for stats access
1052 * @part: target partition
1054 * The average IO queue length and utilisation statistics are maintained
1055 * by observing the current state of the queue length and the amount of
1056 * time it has been in this state for.
1058 * Normally, that accounting is done on IO completion, but that can result
1059 * in more than a second's worth of IO being accounted for within any one
1060 * second, leading to >100% utilisation. To deal with that, we call this
1061 * function to do a round-off before returning the results when reading
1062 * /proc/diskstats. This accounts immediately for all queue usage up to
1063 * the current jiffies and restarts the counters again.
1065 void part_round_stats(int cpu, struct hd_struct *part)
1067 unsigned long now = jiffies;
1070 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1071 part_round_stats_single(cpu, part, now);
1073 EXPORT_SYMBOL_GPL(part_round_stats);
1076 * queue lock must be held
1078 void __blk_put_request(struct request_queue *q, struct request *req)
1082 if (unlikely(--req->ref_count))
1085 elv_completed_request(q, req);
1087 /* this is a bio leak */
1088 WARN_ON(req->bio != NULL);
1091 * Request may not have originated from ll_rw_blk. if not,
1092 * it didn't come out of our reserved rq pools
1094 if (req->cmd_flags & REQ_ALLOCED) {
1095 int is_sync = rq_is_sync(req) != 0;
1096 int priv = req->cmd_flags & REQ_ELVPRIV;
1098 BUG_ON(!list_empty(&req->queuelist));
1099 BUG_ON(!hlist_unhashed(&req->hash));
1101 blk_free_request(q, req);
1102 freed_request(q, is_sync, priv);
1105 EXPORT_SYMBOL_GPL(__blk_put_request);
1107 void blk_put_request(struct request *req)
1109 unsigned long flags;
1110 struct request_queue *q = req->q;
1112 spin_lock_irqsave(q->queue_lock, flags);
1113 __blk_put_request(q, req);
1114 spin_unlock_irqrestore(q->queue_lock, flags);
1116 EXPORT_SYMBOL(blk_put_request);
1118 void init_request_from_bio(struct request *req, struct bio *bio)
1120 req->cpu = bio->bi_comp_cpu;
1121 req->cmd_type = REQ_TYPE_FS;
1124 * inherit FAILFAST from bio (for read-ahead, and explicit FAILFAST)
1126 if (bio_rw_ahead(bio))
1127 req->cmd_flags |= (REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT |
1128 REQ_FAILFAST_DRIVER);
1129 if (bio_failfast_dev(bio))
1130 req->cmd_flags |= REQ_FAILFAST_DEV;
1131 if (bio_failfast_transport(bio))
1132 req->cmd_flags |= REQ_FAILFAST_TRANSPORT;
1133 if (bio_failfast_driver(bio))
1134 req->cmd_flags |= REQ_FAILFAST_DRIVER;
1136 if (unlikely(bio_discard(bio))) {
1137 req->cmd_flags |= REQ_DISCARD;
1138 if (bio_barrier(bio))
1139 req->cmd_flags |= REQ_SOFTBARRIER;
1140 req->q->prepare_discard_fn(req->q, req);
1141 } else if (unlikely(bio_barrier(bio)))
1142 req->cmd_flags |= REQ_HARDBARRIER;
1145 req->cmd_flags |= REQ_RW_SYNC;
1146 if (bio_rw_meta(bio))
1147 req->cmd_flags |= REQ_RW_META;
1148 if (bio_noidle(bio))
1149 req->cmd_flags |= REQ_NOIDLE;
1152 req->__sector = bio->bi_sector;
1153 req->ioprio = bio_prio(bio);
1154 blk_rq_bio_prep(req->q, req, bio);
1158 * Only disabling plugging for non-rotational devices if it does tagging
1159 * as well, otherwise we do need the proper merging
1161 static inline bool queue_should_plug(struct request_queue *q)
1163 return !(blk_queue_nonrot(q) && blk_queue_tagged(q));
1166 static int __make_request(struct request_queue *q, struct bio *bio)
1168 struct request *req;
1170 unsigned int bytes = bio->bi_size;
1171 const unsigned short prio = bio_prio(bio);
1172 const int sync = bio_sync(bio);
1173 const int unplug = bio_unplug(bio);
1177 * low level driver can indicate that it wants pages above a
1178 * certain limit bounced to low memory (ie for highmem, or even
1179 * ISA dma in theory)
1181 blk_queue_bounce(q, &bio);
1183 spin_lock_irq(q->queue_lock);
1185 if (unlikely(bio_barrier(bio)) || elv_queue_empty(q))
1188 el_ret = elv_merge(q, &req, bio);
1190 case ELEVATOR_BACK_MERGE:
1191 BUG_ON(!rq_mergeable(req));
1193 if (!ll_back_merge_fn(q, req, bio))
1196 trace_block_bio_backmerge(q, bio);
1198 req->biotail->bi_next = bio;
1200 req->__data_len += bytes;
1201 req->ioprio = ioprio_best(req->ioprio, prio);
1202 if (!blk_rq_cpu_valid(req))
1203 req->cpu = bio->bi_comp_cpu;
1204 drive_stat_acct(req, 0);
1205 if (!attempt_back_merge(q, req))
1206 elv_merged_request(q, req, el_ret);
1209 case ELEVATOR_FRONT_MERGE:
1210 BUG_ON(!rq_mergeable(req));
1212 if (!ll_front_merge_fn(q, req, bio))
1215 trace_block_bio_frontmerge(q, bio);
1217 bio->bi_next = req->bio;
1221 * may not be valid. if the low level driver said
1222 * it didn't need a bounce buffer then it better
1223 * not touch req->buffer either...
1225 req->buffer = bio_data(bio);
1226 req->__sector = bio->bi_sector;
1227 req->__data_len += bytes;
1228 req->ioprio = ioprio_best(req->ioprio, prio);
1229 if (!blk_rq_cpu_valid(req))
1230 req->cpu = bio->bi_comp_cpu;
1231 drive_stat_acct(req, 0);
1232 if (!attempt_front_merge(q, req))
1233 elv_merged_request(q, req, el_ret);
1236 /* ELV_NO_MERGE: elevator says don't/can't merge. */
1243 * This sync check and mask will be re-done in init_request_from_bio(),
1244 * but we need to set it earlier to expose the sync flag to the
1245 * rq allocator and io schedulers.
1247 rw_flags = bio_data_dir(bio);
1249 rw_flags |= REQ_RW_SYNC;
1252 * Grab a free request. This is might sleep but can not fail.
1253 * Returns with the queue unlocked.
1255 req = get_request_wait(q, rw_flags, bio);
1258 * After dropping the lock and possibly sleeping here, our request
1259 * may now be mergeable after it had proven unmergeable (above).
1260 * We don't worry about that case for efficiency. It won't happen
1261 * often, and the elevators are able to handle it.
1263 init_request_from_bio(req, bio);
1265 spin_lock_irq(q->queue_lock);
1266 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags) ||
1267 bio_flagged(bio, BIO_CPU_AFFINE))
1268 req->cpu = blk_cpu_to_group(smp_processor_id());
1269 if (queue_should_plug(q) && elv_queue_empty(q))
1271 add_request(q, req);
1273 if (unplug || !queue_should_plug(q))
1274 __generic_unplug_device(q);
1275 spin_unlock_irq(q->queue_lock);
1280 * If bio->bi_dev is a partition, remap the location
1282 static inline void blk_partition_remap(struct bio *bio)
1284 struct block_device *bdev = bio->bi_bdev;
1286 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1287 struct hd_struct *p = bdev->bd_part;
1289 bio->bi_sector += p->start_sect;
1290 bio->bi_bdev = bdev->bd_contains;
1292 trace_block_remap(bdev_get_queue(bio->bi_bdev), bio,
1294 bio->bi_sector - p->start_sect);
1298 static void handle_bad_sector(struct bio *bio)
1300 char b[BDEVNAME_SIZE];
1302 printk(KERN_INFO "attempt to access beyond end of device\n");
1303 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1304 bdevname(bio->bi_bdev, b),
1306 (unsigned long long)bio->bi_sector + bio_sectors(bio),
1307 (long long)(bio->bi_bdev->bd_inode->i_size >> 9));
1309 set_bit(BIO_EOF, &bio->bi_flags);
1312 #ifdef CONFIG_FAIL_MAKE_REQUEST
1314 static DECLARE_FAULT_ATTR(fail_make_request);
1316 static int __init setup_fail_make_request(char *str)
1318 return setup_fault_attr(&fail_make_request, str);
1320 __setup("fail_make_request=", setup_fail_make_request);
1322 static int should_fail_request(struct bio *bio)
1324 struct hd_struct *part = bio->bi_bdev->bd_part;
1326 if (part_to_disk(part)->part0.make_it_fail || part->make_it_fail)
1327 return should_fail(&fail_make_request, bio->bi_size);
1332 static int __init fail_make_request_debugfs(void)
1334 return init_fault_attr_dentries(&fail_make_request,
1335 "fail_make_request");
1338 late_initcall(fail_make_request_debugfs);
1340 #else /* CONFIG_FAIL_MAKE_REQUEST */
1342 static inline int should_fail_request(struct bio *bio)
1347 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1350 * Check whether this bio extends beyond the end of the device.
1352 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1359 /* Test device or partition size, when known. */
1360 maxsector = bio->bi_bdev->bd_inode->i_size >> 9;
1362 sector_t sector = bio->bi_sector;
1364 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1366 * This may well happen - the kernel calls bread()
1367 * without checking the size of the device, e.g., when
1368 * mounting a device.
1370 handle_bad_sector(bio);
1379 * generic_make_request - hand a buffer to its device driver for I/O
1380 * @bio: The bio describing the location in memory and on the device.
1382 * generic_make_request() is used to make I/O requests of block
1383 * devices. It is passed a &struct bio, which describes the I/O that needs
1386 * generic_make_request() does not return any status. The
1387 * success/failure status of the request, along with notification of
1388 * completion, is delivered asynchronously through the bio->bi_end_io
1389 * function described (one day) else where.
1391 * The caller of generic_make_request must make sure that bi_io_vec
1392 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1393 * set to describe the device address, and the
1394 * bi_end_io and optionally bi_private are set to describe how
1395 * completion notification should be signaled.
1397 * generic_make_request and the drivers it calls may use bi_next if this
1398 * bio happens to be merged with someone else, and may change bi_dev and
1399 * bi_sector for remaps as it sees fit. So the values of these fields
1400 * should NOT be depended on after the call to generic_make_request.
1402 static inline void __generic_make_request(struct bio *bio)
1404 struct request_queue *q;
1405 sector_t old_sector;
1406 int ret, nr_sectors = bio_sectors(bio);
1412 if (bio_check_eod(bio, nr_sectors))
1416 * Resolve the mapping until finished. (drivers are
1417 * still free to implement/resolve their own stacking
1418 * by explicitly returning 0)
1420 * NOTE: we don't repeat the blk_size check for each new device.
1421 * Stacking drivers are expected to know what they are doing.
1426 char b[BDEVNAME_SIZE];
1428 q = bdev_get_queue(bio->bi_bdev);
1431 "generic_make_request: Trying to access "
1432 "nonexistent block-device %s (%Lu)\n",
1433 bdevname(bio->bi_bdev, b),
1434 (long long) bio->bi_sector);
1438 if (unlikely(nr_sectors > queue_max_hw_sectors(q))) {
1439 printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1440 bdevname(bio->bi_bdev, b),
1442 queue_max_hw_sectors(q));
1446 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
1449 if (should_fail_request(bio))
1453 * If this device has partitions, remap block n
1454 * of partition p to block n+start(p) of the disk.
1456 blk_partition_remap(bio);
1458 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
1461 if (old_sector != -1)
1462 trace_block_remap(q, bio, old_dev, old_sector);
1464 trace_block_bio_queue(q, bio);
1466 old_sector = bio->bi_sector;
1467 old_dev = bio->bi_bdev->bd_dev;
1469 if (bio_check_eod(bio, nr_sectors))
1472 if (bio_discard(bio) && !q->prepare_discard_fn) {
1476 if (bio_barrier(bio) && bio_has_data(bio) &&
1477 (q->next_ordered == QUEUE_ORDERED_NONE)) {
1482 ret = q->make_request_fn(q, bio);
1488 bio_endio(bio, err);
1492 * We only want one ->make_request_fn to be active at a time,
1493 * else stack usage with stacked devices could be a problem.
1494 * So use current->bio_{list,tail} to keep a list of requests
1495 * submited by a make_request_fn function.
1496 * current->bio_tail is also used as a flag to say if
1497 * generic_make_request is currently active in this task or not.
1498 * If it is NULL, then no make_request is active. If it is non-NULL,
1499 * then a make_request is active, and new requests should be added
1502 void generic_make_request(struct bio *bio)
1504 if (current->bio_tail) {
1505 /* make_request is active */
1506 *(current->bio_tail) = bio;
1507 bio->bi_next = NULL;
1508 current->bio_tail = &bio->bi_next;
1511 /* following loop may be a bit non-obvious, and so deserves some
1513 * Before entering the loop, bio->bi_next is NULL (as all callers
1514 * ensure that) so we have a list with a single bio.
1515 * We pretend that we have just taken it off a longer list, so
1516 * we assign bio_list to the next (which is NULL) and bio_tail
1517 * to &bio_list, thus initialising the bio_list of new bios to be
1518 * added. __generic_make_request may indeed add some more bios
1519 * through a recursive call to generic_make_request. If it
1520 * did, we find a non-NULL value in bio_list and re-enter the loop
1521 * from the top. In this case we really did just take the bio
1522 * of the top of the list (no pretending) and so fixup bio_list and
1523 * bio_tail or bi_next, and call into __generic_make_request again.
1525 * The loop was structured like this to make only one call to
1526 * __generic_make_request (which is important as it is large and
1527 * inlined) and to keep the structure simple.
1529 BUG_ON(bio->bi_next);
1531 current->bio_list = bio->bi_next;
1532 if (bio->bi_next == NULL)
1533 current->bio_tail = ¤t->bio_list;
1535 bio->bi_next = NULL;
1536 __generic_make_request(bio);
1537 bio = current->bio_list;
1539 current->bio_tail = NULL; /* deactivate */
1541 EXPORT_SYMBOL(generic_make_request);
1544 * submit_bio - submit a bio to the block device layer for I/O
1545 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1546 * @bio: The &struct bio which describes the I/O
1548 * submit_bio() is very similar in purpose to generic_make_request(), and
1549 * uses that function to do most of the work. Both are fairly rough
1550 * interfaces; @bio must be presetup and ready for I/O.
1553 void submit_bio(int rw, struct bio *bio)
1555 int count = bio_sectors(bio);
1560 * If it's a regular read/write or a barrier with data attached,
1561 * go through the normal accounting stuff before submission.
1563 if (bio_has_data(bio)) {
1565 count_vm_events(PGPGOUT, count);
1567 task_io_account_read(bio->bi_size);
1568 count_vm_events(PGPGIN, count);
1571 if (unlikely(block_dump)) {
1572 char b[BDEVNAME_SIZE];
1573 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
1574 current->comm, task_pid_nr(current),
1575 (rw & WRITE) ? "WRITE" : "READ",
1576 (unsigned long long)bio->bi_sector,
1577 bdevname(bio->bi_bdev, b));
1581 generic_make_request(bio);
1583 EXPORT_SYMBOL(submit_bio);
1586 * blk_rq_check_limits - Helper function to check a request for the queue limit
1588 * @rq: the request being checked
1591 * @rq may have been made based on weaker limitations of upper-level queues
1592 * in request stacking drivers, and it may violate the limitation of @q.
1593 * Since the block layer and the underlying device driver trust @rq
1594 * after it is inserted to @q, it should be checked against @q before
1595 * the insertion using this generic function.
1597 * This function should also be useful for request stacking drivers
1598 * in some cases below, so export this fuction.
1599 * Request stacking drivers like request-based dm may change the queue
1600 * limits while requests are in the queue (e.g. dm's table swapping).
1601 * Such request stacking drivers should check those requests agaist
1602 * the new queue limits again when they dispatch those requests,
1603 * although such checkings are also done against the old queue limits
1604 * when submitting requests.
1606 int blk_rq_check_limits(struct request_queue *q, struct request *rq)
1608 if (blk_rq_sectors(rq) > queue_max_sectors(q) ||
1609 blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {
1610 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1615 * queue's settings related to segment counting like q->bounce_pfn
1616 * may differ from that of other stacking queues.
1617 * Recalculate it to check the request correctly on this queue's
1620 blk_recalc_rq_segments(rq);
1621 if (rq->nr_phys_segments > queue_max_phys_segments(q) ||
1622 rq->nr_phys_segments > queue_max_hw_segments(q)) {
1623 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1629 EXPORT_SYMBOL_GPL(blk_rq_check_limits);
1632 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1633 * @q: the queue to submit the request
1634 * @rq: the request being queued
1636 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1638 unsigned long flags;
1640 if (blk_rq_check_limits(q, rq))
1643 #ifdef CONFIG_FAIL_MAKE_REQUEST
1644 if (rq->rq_disk && rq->rq_disk->part0.make_it_fail &&
1645 should_fail(&fail_make_request, blk_rq_bytes(rq)))
1649 spin_lock_irqsave(q->queue_lock, flags);
1652 * Submitting request must be dequeued before calling this function
1653 * because it will be linked to another request_queue
1655 BUG_ON(blk_queued_rq(rq));
1657 drive_stat_acct(rq, 1);
1658 __elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 0);
1660 spin_unlock_irqrestore(q->queue_lock, flags);
1664 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1666 static void blk_account_io_completion(struct request *req, unsigned int bytes)
1668 if (blk_do_io_stat(req)) {
1669 const int rw = rq_data_dir(req);
1670 struct hd_struct *part;
1673 cpu = part_stat_lock();
1674 part = disk_map_sector_rcu(req->rq_disk, blk_rq_pos(req));
1675 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
1680 static void blk_account_io_done(struct request *req)
1683 * Account IO completion. bar_rq isn't accounted as a normal
1684 * IO on queueing nor completion. Accounting the containing
1685 * request is enough.
1687 if (blk_do_io_stat(req) && req != &req->q->bar_rq) {
1688 unsigned long duration = jiffies - req->start_time;
1689 const int rw = rq_data_dir(req);
1690 struct hd_struct *part;
1693 cpu = part_stat_lock();
1694 part = disk_map_sector_rcu(req->rq_disk, blk_rq_pos(req));
1696 part_stat_inc(cpu, part, ios[rw]);
1697 part_stat_add(cpu, part, ticks[rw], duration);
1698 part_round_stats(cpu, part);
1699 part_dec_in_flight(part);
1706 * blk_peek_request - peek at the top of a request queue
1707 * @q: request queue to peek at
1710 * Return the request at the top of @q. The returned request
1711 * should be started using blk_start_request() before LLD starts
1715 * Pointer to the request at the top of @q if available. Null
1719 * queue_lock must be held.
1721 struct request *blk_peek_request(struct request_queue *q)
1726 while ((rq = __elv_next_request(q)) != NULL) {
1727 if (!(rq->cmd_flags & REQ_STARTED)) {
1729 * This is the first time the device driver
1730 * sees this request (possibly after
1731 * requeueing). Notify IO scheduler.
1733 if (blk_sorted_rq(rq))
1734 elv_activate_rq(q, rq);
1737 * just mark as started even if we don't start
1738 * it, a request that has been delayed should
1739 * not be passed by new incoming requests
1741 rq->cmd_flags |= REQ_STARTED;
1742 trace_block_rq_issue(q, rq);
1745 if (!q->boundary_rq || q->boundary_rq == rq) {
1746 q->end_sector = rq_end_sector(rq);
1747 q->boundary_rq = NULL;
1750 if (rq->cmd_flags & REQ_DONTPREP)
1753 if (q->dma_drain_size && blk_rq_bytes(rq)) {
1755 * make sure space for the drain appears we
1756 * know we can do this because max_hw_segments
1757 * has been adjusted to be one fewer than the
1760 rq->nr_phys_segments++;
1766 ret = q->prep_rq_fn(q, rq);
1767 if (ret == BLKPREP_OK) {
1769 } else if (ret == BLKPREP_DEFER) {
1771 * the request may have been (partially) prepped.
1772 * we need to keep this request in the front to
1773 * avoid resource deadlock. REQ_STARTED will
1774 * prevent other fs requests from passing this one.
1776 if (q->dma_drain_size && blk_rq_bytes(rq) &&
1777 !(rq->cmd_flags & REQ_DONTPREP)) {
1779 * remove the space for the drain we added
1780 * so that we don't add it again
1782 --rq->nr_phys_segments;
1787 } else if (ret == BLKPREP_KILL) {
1788 rq->cmd_flags |= REQ_QUIET;
1790 * Mark this request as started so we don't trigger
1791 * any debug logic in the end I/O path.
1793 blk_start_request(rq);
1794 __blk_end_request_all(rq, -EIO);
1796 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
1803 EXPORT_SYMBOL(blk_peek_request);
1805 void blk_dequeue_request(struct request *rq)
1807 struct request_queue *q = rq->q;
1809 BUG_ON(list_empty(&rq->queuelist));
1810 BUG_ON(ELV_ON_HASH(rq));
1812 list_del_init(&rq->queuelist);
1815 * the time frame between a request being removed from the lists
1816 * and to it is freed is accounted as io that is in progress at
1819 if (blk_account_rq(rq))
1820 q->in_flight[rq_is_sync(rq)]++;
1824 * blk_start_request - start request processing on the driver
1825 * @req: request to dequeue
1828 * Dequeue @req and start timeout timer on it. This hands off the
1829 * request to the driver.
1831 * Block internal functions which don't want to start timer should
1832 * call blk_dequeue_request().
1835 * queue_lock must be held.
1837 void blk_start_request(struct request *req)
1839 blk_dequeue_request(req);
1842 * We are now handing the request to the hardware, initialize
1843 * resid_len to full count and add the timeout handler.
1845 req->resid_len = blk_rq_bytes(req);
1846 if (unlikely(blk_bidi_rq(req)))
1847 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
1851 EXPORT_SYMBOL(blk_start_request);
1854 * blk_fetch_request - fetch a request from a request queue
1855 * @q: request queue to fetch a request from
1858 * Return the request at the top of @q. The request is started on
1859 * return and LLD can start processing it immediately.
1862 * Pointer to the request at the top of @q if available. Null
1866 * queue_lock must be held.
1868 struct request *blk_fetch_request(struct request_queue *q)
1872 rq = blk_peek_request(q);
1874 blk_start_request(rq);
1877 EXPORT_SYMBOL(blk_fetch_request);
1880 * blk_update_request - Special helper function for request stacking drivers
1881 * @req: the request being processed
1882 * @error: %0 for success, < %0 for error
1883 * @nr_bytes: number of bytes to complete @req
1886 * Ends I/O on a number of bytes attached to @req, but doesn't complete
1887 * the request structure even if @req doesn't have leftover.
1888 * If @req has leftover, sets it up for the next range of segments.
1890 * This special helper function is only for request stacking drivers
1891 * (e.g. request-based dm) so that they can handle partial completion.
1892 * Actual device drivers should use blk_end_request instead.
1894 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
1895 * %false return from this function.
1898 * %false - this request doesn't have any more data
1899 * %true - this request has more data
1901 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
1903 int total_bytes, bio_nbytes, next_idx = 0;
1909 trace_block_rq_complete(req->q, req);
1912 * For fs requests, rq is just carrier of independent bio's
1913 * and each partial completion should be handled separately.
1914 * Reset per-request error on each partial completion.
1916 * TODO: tj: This is too subtle. It would be better to let
1917 * low level drivers do what they see fit.
1919 if (blk_fs_request(req))
1922 if (error && (blk_fs_request(req) && !(req->cmd_flags & REQ_QUIET))) {
1923 printk(KERN_ERR "end_request: I/O error, dev %s, sector %llu\n",
1924 req->rq_disk ? req->rq_disk->disk_name : "?",
1925 (unsigned long long)blk_rq_pos(req));
1928 blk_account_io_completion(req, nr_bytes);
1930 total_bytes = bio_nbytes = 0;
1931 while ((bio = req->bio) != NULL) {
1934 if (nr_bytes >= bio->bi_size) {
1935 req->bio = bio->bi_next;
1936 nbytes = bio->bi_size;
1937 req_bio_endio(req, bio, nbytes, error);
1941 int idx = bio->bi_idx + next_idx;
1943 if (unlikely(idx >= bio->bi_vcnt)) {
1944 blk_dump_rq_flags(req, "__end_that");
1945 printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
1946 __func__, idx, bio->bi_vcnt);
1950 nbytes = bio_iovec_idx(bio, idx)->bv_len;
1951 BIO_BUG_ON(nbytes > bio->bi_size);
1954 * not a complete bvec done
1956 if (unlikely(nbytes > nr_bytes)) {
1957 bio_nbytes += nr_bytes;
1958 total_bytes += nr_bytes;
1963 * advance to the next vector
1966 bio_nbytes += nbytes;
1969 total_bytes += nbytes;
1975 * end more in this run, or just return 'not-done'
1977 if (unlikely(nr_bytes <= 0))
1987 * Reset counters so that the request stacking driver
1988 * can find how many bytes remain in the request
1991 req->__data_len = 0;
1996 * if the request wasn't completed, update state
1999 req_bio_endio(req, bio, bio_nbytes, error);
2000 bio->bi_idx += next_idx;
2001 bio_iovec(bio)->bv_offset += nr_bytes;
2002 bio_iovec(bio)->bv_len -= nr_bytes;
2005 req->__data_len -= total_bytes;
2006 req->buffer = bio_data(req->bio);
2008 /* update sector only for requests with clear definition of sector */
2009 if (blk_fs_request(req) || blk_discard_rq(req))
2010 req->__sector += total_bytes >> 9;
2013 * If total number of sectors is less than the first segment
2014 * size, something has gone terribly wrong.
2016 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2017 printk(KERN_ERR "blk: request botched\n");
2018 req->__data_len = blk_rq_cur_bytes(req);
2021 /* recalculate the number of segments */
2022 blk_recalc_rq_segments(req);
2026 EXPORT_SYMBOL_GPL(blk_update_request);
2028 static bool blk_update_bidi_request(struct request *rq, int error,
2029 unsigned int nr_bytes,
2030 unsigned int bidi_bytes)
2032 if (blk_update_request(rq, error, nr_bytes))
2035 /* Bidi request must be completed as a whole */
2036 if (unlikely(blk_bidi_rq(rq)) &&
2037 blk_update_request(rq->next_rq, error, bidi_bytes))
2040 add_disk_randomness(rq->rq_disk);
2046 * queue lock must be held
2048 static void blk_finish_request(struct request *req, int error)
2050 if (blk_rq_tagged(req))
2051 blk_queue_end_tag(req->q, req);
2053 BUG_ON(blk_queued_rq(req));
2055 if (unlikely(laptop_mode) && blk_fs_request(req))
2056 laptop_io_completion();
2058 blk_delete_timer(req);
2060 blk_account_io_done(req);
2063 req->end_io(req, error);
2065 if (blk_bidi_rq(req))
2066 __blk_put_request(req->next_rq->q, req->next_rq);
2068 __blk_put_request(req->q, req);
2073 * blk_end_bidi_request - Complete a bidi request
2074 * @rq: the request to complete
2075 * @error: %0 for success, < %0 for error
2076 * @nr_bytes: number of bytes to complete @rq
2077 * @bidi_bytes: number of bytes to complete @rq->next_rq
2080 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2081 * Drivers that supports bidi can safely call this member for any
2082 * type of request, bidi or uni. In the later case @bidi_bytes is
2086 * %false - we are done with this request
2087 * %true - still buffers pending for this request
2089 static bool blk_end_bidi_request(struct request *rq, int error,
2090 unsigned int nr_bytes, unsigned int bidi_bytes)
2092 struct request_queue *q = rq->q;
2093 unsigned long flags;
2095 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2098 spin_lock_irqsave(q->queue_lock, flags);
2099 blk_finish_request(rq, error);
2100 spin_unlock_irqrestore(q->queue_lock, flags);
2106 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2107 * @rq: the request to complete
2108 * @error: %0 for success, < %0 for error
2109 * @nr_bytes: number of bytes to complete @rq
2110 * @bidi_bytes: number of bytes to complete @rq->next_rq
2113 * Identical to blk_end_bidi_request() except that queue lock is
2114 * assumed to be locked on entry and remains so on return.
2117 * %false - we are done with this request
2118 * %true - still buffers pending for this request
2120 static bool __blk_end_bidi_request(struct request *rq, int error,
2121 unsigned int nr_bytes, unsigned int bidi_bytes)
2123 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2126 blk_finish_request(rq, error);
2132 * blk_end_request - Helper function for drivers to complete the request.
2133 * @rq: the request being processed
2134 * @error: %0 for success, < %0 for error
2135 * @nr_bytes: number of bytes to complete
2138 * Ends I/O on a number of bytes attached to @rq.
2139 * If @rq has leftover, sets it up for the next range of segments.
2142 * %false - we are done with this request
2143 * %true - still buffers pending for this request
2145 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2147 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2149 EXPORT_SYMBOL_GPL(blk_end_request);
2152 * blk_end_request_all - Helper function for drives to finish the request.
2153 * @rq: the request to finish
2154 * @error: %0 for success, < %0 for error
2157 * Completely finish @rq.
2159 void blk_end_request_all(struct request *rq, int error)
2162 unsigned int bidi_bytes = 0;
2164 if (unlikely(blk_bidi_rq(rq)))
2165 bidi_bytes = blk_rq_bytes(rq->next_rq);
2167 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2170 EXPORT_SYMBOL_GPL(blk_end_request_all);
2173 * blk_end_request_cur - Helper function to finish the current request chunk.
2174 * @rq: the request to finish the current chunk for
2175 * @error: %0 for success, < %0 for error
2178 * Complete the current consecutively mapped chunk from @rq.
2181 * %false - we are done with this request
2182 * %true - still buffers pending for this request
2184 bool blk_end_request_cur(struct request *rq, int error)
2186 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2188 EXPORT_SYMBOL_GPL(blk_end_request_cur);
2191 * __blk_end_request - Helper function for drivers to complete the request.
2192 * @rq: the request being processed
2193 * @error: %0 for success, < %0 for error
2194 * @nr_bytes: number of bytes to complete
2197 * Must be called with queue lock held unlike blk_end_request().
2200 * %false - we are done with this request
2201 * %true - still buffers pending for this request
2203 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2205 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2207 EXPORT_SYMBOL_GPL(__blk_end_request);
2210 * __blk_end_request_all - Helper function for drives to finish the request.
2211 * @rq: the request to finish
2212 * @error: %0 for success, < %0 for error
2215 * Completely finish @rq. Must be called with queue lock held.
2217 void __blk_end_request_all(struct request *rq, int error)
2220 unsigned int bidi_bytes = 0;
2222 if (unlikely(blk_bidi_rq(rq)))
2223 bidi_bytes = blk_rq_bytes(rq->next_rq);
2225 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2228 EXPORT_SYMBOL_GPL(__blk_end_request_all);
2231 * __blk_end_request_cur - Helper function to finish the current request chunk.
2232 * @rq: the request to finish the current chunk for
2233 * @error: %0 for success, < %0 for error
2236 * Complete the current consecutively mapped chunk from @rq. Must
2237 * be called with queue lock held.
2240 * %false - we are done with this request
2241 * %true - still buffers pending for this request
2243 bool __blk_end_request_cur(struct request *rq, int error)
2245 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2247 EXPORT_SYMBOL_GPL(__blk_end_request_cur);
2249 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2252 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw, and
2253 we want BIO_RW_AHEAD (bit 1) to imply REQ_FAILFAST (bit 1). */
2254 rq->cmd_flags |= (bio->bi_rw & 3);
2256 if (bio_has_data(bio)) {
2257 rq->nr_phys_segments = bio_phys_segments(q, bio);
2258 rq->buffer = bio_data(bio);
2260 rq->__data_len = bio->bi_size;
2261 rq->bio = rq->biotail = bio;
2264 rq->rq_disk = bio->bi_bdev->bd_disk;
2268 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2269 * @q : the queue of the device being checked
2272 * Check if underlying low-level drivers of a device are busy.
2273 * If the drivers want to export their busy state, they must set own
2274 * exporting function using blk_queue_lld_busy() first.
2276 * Basically, this function is used only by request stacking drivers
2277 * to stop dispatching requests to underlying devices when underlying
2278 * devices are busy. This behavior helps more I/O merging on the queue
2279 * of the request stacking driver and prevents I/O throughput regression
2280 * on burst I/O load.
2283 * 0 - Not busy (The request stacking driver should dispatch request)
2284 * 1 - Busy (The request stacking driver should stop dispatching request)
2286 int blk_lld_busy(struct request_queue *q)
2289 return q->lld_busy_fn(q);
2293 EXPORT_SYMBOL_GPL(blk_lld_busy);
2296 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2297 * @rq: the clone request to be cleaned up
2300 * Free all bios in @rq for a cloned request.
2302 void blk_rq_unprep_clone(struct request *rq)
2306 while ((bio = rq->bio) != NULL) {
2307 rq->bio = bio->bi_next;
2312 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2315 * Copy attributes of the original request to the clone request.
2316 * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2318 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2320 dst->cpu = src->cpu;
2321 dst->cmd_flags = (rq_data_dir(src) | REQ_NOMERGE);
2322 dst->cmd_type = src->cmd_type;
2323 dst->__sector = blk_rq_pos(src);
2324 dst->__data_len = blk_rq_bytes(src);
2325 dst->nr_phys_segments = src->nr_phys_segments;
2326 dst->ioprio = src->ioprio;
2327 dst->extra_len = src->extra_len;
2331 * blk_rq_prep_clone - Helper function to setup clone request
2332 * @rq: the request to be setup
2333 * @rq_src: original request to be cloned
2334 * @bs: bio_set that bios for clone are allocated from
2335 * @gfp_mask: memory allocation mask for bio
2336 * @bio_ctr: setup function to be called for each clone bio.
2337 * Returns %0 for success, non %0 for failure.
2338 * @data: private data to be passed to @bio_ctr
2341 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2342 * The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2343 * are not copied, and copying such parts is the caller's responsibility.
2344 * Also, pages which the original bios are pointing to are not copied
2345 * and the cloned bios just point same pages.
2346 * So cloned bios must be completed before original bios, which means
2347 * the caller must complete @rq before @rq_src.
2349 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2350 struct bio_set *bs, gfp_t gfp_mask,
2351 int (*bio_ctr)(struct bio *, struct bio *, void *),
2354 struct bio *bio, *bio_src;
2359 blk_rq_init(NULL, rq);
2361 __rq_for_each_bio(bio_src, rq_src) {
2362 bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);
2366 __bio_clone(bio, bio_src);
2368 if (bio_integrity(bio_src) &&
2369 bio_integrity_clone(bio, bio_src, gfp_mask))
2372 if (bio_ctr && bio_ctr(bio, bio_src, data))
2376 rq->biotail->bi_next = bio;
2379 rq->bio = rq->biotail = bio;
2382 __blk_rq_prep_clone(rq, rq_src);
2389 blk_rq_unprep_clone(rq);
2393 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
2395 int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
2397 return queue_work(kblockd_workqueue, work);
2399 EXPORT_SYMBOL(kblockd_schedule_work);
2401 int __init blk_dev_init(void)
2403 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
2404 sizeof(((struct request *)0)->cmd_flags));
2406 kblockd_workqueue = create_workqueue("kblockd");
2407 if (!kblockd_workqueue)
2408 panic("Failed to create kblockd\n");
2410 request_cachep = kmem_cache_create("blkdev_requests",
2411 sizeof(struct request), 0, SLAB_PANIC, NULL);
2413 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2414 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);