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/fault-inject.h>
30 #include <linux/list_sort.h>
31 #include <linux/delay.h>
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/block.h>
37 #include "blk-cgroup.h"
39 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap
);
40 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap
);
41 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete
);
43 DEFINE_IDA(blk_queue_ida
);
46 * For the allocated request tables
48 static struct kmem_cache
*request_cachep
;
51 * For queue allocation
53 struct kmem_cache
*blk_requestq_cachep
;
56 * Controlling structure to kblockd
58 static struct workqueue_struct
*kblockd_workqueue
;
60 static void drive_stat_acct(struct request
*rq
, int new_io
)
62 struct hd_struct
*part
;
63 int rw
= rq_data_dir(rq
);
66 if (!blk_do_io_stat(rq
))
69 cpu
= part_stat_lock();
73 part_stat_inc(cpu
, part
, merges
[rw
]);
75 part
= disk_map_sector_rcu(rq
->rq_disk
, blk_rq_pos(rq
));
76 if (!hd_struct_try_get(part
)) {
78 * The partition is already being removed,
79 * the request will be accounted on the disk only
81 * We take a reference on disk->part0 although that
82 * partition will never be deleted, so we can treat
83 * it as any other partition.
85 part
= &rq
->rq_disk
->part0
;
88 part_round_stats(cpu
, part
);
89 part_inc_in_flight(part
, rw
);
96 void blk_queue_congestion_threshold(struct request_queue
*q
)
100 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) + 1;
101 if (nr
> q
->nr_requests
)
103 q
->nr_congestion_on
= nr
;
105 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) - (q
->nr_requests
/ 16) - 1;
108 q
->nr_congestion_off
= nr
;
112 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
115 * Locates the passed device's request queue and returns the address of its
118 * Will return NULL if the request queue cannot be located.
120 struct backing_dev_info
*blk_get_backing_dev_info(struct block_device
*bdev
)
122 struct backing_dev_info
*ret
= NULL
;
123 struct request_queue
*q
= bdev_get_queue(bdev
);
126 ret
= &q
->backing_dev_info
;
129 EXPORT_SYMBOL(blk_get_backing_dev_info
);
131 void blk_rq_init(struct request_queue
*q
, struct request
*rq
)
133 memset(rq
, 0, sizeof(*rq
));
135 INIT_LIST_HEAD(&rq
->queuelist
);
136 INIT_LIST_HEAD(&rq
->timeout_list
);
139 rq
->__sector
= (sector_t
) -1;
140 INIT_HLIST_NODE(&rq
->hash
);
141 RB_CLEAR_NODE(&rq
->rb_node
);
143 rq
->cmd_len
= BLK_MAX_CDB
;
146 rq
->start_time
= jiffies
;
147 set_start_time_ns(rq
);
150 EXPORT_SYMBOL(blk_rq_init
);
152 static void req_bio_endio(struct request
*rq
, struct bio
*bio
,
153 unsigned int nbytes
, int error
)
156 clear_bit(BIO_UPTODATE
, &bio
->bi_flags
);
157 else if (!test_bit(BIO_UPTODATE
, &bio
->bi_flags
))
160 if (unlikely(nbytes
> bio
->bi_size
)) {
161 printk(KERN_ERR
"%s: want %u bytes done, %u left\n",
162 __func__
, nbytes
, bio
->bi_size
);
163 nbytes
= bio
->bi_size
;
166 if (unlikely(rq
->cmd_flags
& REQ_QUIET
))
167 set_bit(BIO_QUIET
, &bio
->bi_flags
);
169 bio
->bi_size
-= nbytes
;
170 bio
->bi_sector
+= (nbytes
>> 9);
172 if (bio_integrity(bio
))
173 bio_integrity_advance(bio
, nbytes
);
175 /* don't actually finish bio if it's part of flush sequence */
176 if (bio
->bi_size
== 0 && !(rq
->cmd_flags
& REQ_FLUSH_SEQ
))
177 bio_endio(bio
, error
);
180 void blk_dump_rq_flags(struct request
*rq
, char *msg
)
184 printk(KERN_INFO
"%s: dev %s: type=%x, flags=%x\n", msg
,
185 rq
->rq_disk
? rq
->rq_disk
->disk_name
: "?", rq
->cmd_type
,
188 printk(KERN_INFO
" sector %llu, nr/cnr %u/%u\n",
189 (unsigned long long)blk_rq_pos(rq
),
190 blk_rq_sectors(rq
), blk_rq_cur_sectors(rq
));
191 printk(KERN_INFO
" bio %p, biotail %p, buffer %p, len %u\n",
192 rq
->bio
, rq
->biotail
, rq
->buffer
, blk_rq_bytes(rq
));
194 if (rq
->cmd_type
== REQ_TYPE_BLOCK_PC
) {
195 printk(KERN_INFO
" cdb: ");
196 for (bit
= 0; bit
< BLK_MAX_CDB
; bit
++)
197 printk("%02x ", rq
->cmd
[bit
]);
201 EXPORT_SYMBOL(blk_dump_rq_flags
);
203 static void blk_delay_work(struct work_struct
*work
)
205 struct request_queue
*q
;
207 q
= container_of(work
, struct request_queue
, delay_work
.work
);
208 spin_lock_irq(q
->queue_lock
);
210 spin_unlock_irq(q
->queue_lock
);
214 * blk_delay_queue - restart queueing after defined interval
215 * @q: The &struct request_queue in question
216 * @msecs: Delay in msecs
219 * Sometimes queueing needs to be postponed for a little while, to allow
220 * resources to come back. This function will make sure that queueing is
221 * restarted around the specified time.
223 void blk_delay_queue(struct request_queue
*q
, unsigned long msecs
)
225 queue_delayed_work(kblockd_workqueue
, &q
->delay_work
,
226 msecs_to_jiffies(msecs
));
228 EXPORT_SYMBOL(blk_delay_queue
);
231 * blk_start_queue - restart a previously stopped queue
232 * @q: The &struct request_queue in question
235 * blk_start_queue() will clear the stop flag on the queue, and call
236 * the request_fn for the queue if it was in a stopped state when
237 * entered. Also see blk_stop_queue(). Queue lock must be held.
239 void blk_start_queue(struct request_queue
*q
)
241 WARN_ON(!irqs_disabled());
243 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
246 EXPORT_SYMBOL(blk_start_queue
);
249 * blk_stop_queue - stop a queue
250 * @q: The &struct request_queue in question
253 * The Linux block layer assumes that a block driver will consume all
254 * entries on the request queue when the request_fn strategy is called.
255 * Often this will not happen, because of hardware limitations (queue
256 * depth settings). If a device driver gets a 'queue full' response,
257 * or if it simply chooses not to queue more I/O at one point, it can
258 * call this function to prevent the request_fn from being called until
259 * the driver has signalled it's ready to go again. This happens by calling
260 * blk_start_queue() to restart queue operations. Queue lock must be held.
262 void blk_stop_queue(struct request_queue
*q
)
264 __cancel_delayed_work(&q
->delay_work
);
265 queue_flag_set(QUEUE_FLAG_STOPPED
, q
);
267 EXPORT_SYMBOL(blk_stop_queue
);
270 * blk_sync_queue - cancel any pending callbacks on a queue
274 * The block layer may perform asynchronous callback activity
275 * on a queue, such as calling the unplug function after a timeout.
276 * A block device may call blk_sync_queue to ensure that any
277 * such activity is cancelled, thus allowing it to release resources
278 * that the callbacks might use. The caller must already have made sure
279 * that its ->make_request_fn will not re-add plugging prior to calling
282 * This function does not cancel any asynchronous activity arising
283 * out of elevator or throttling code. That would require elevaotor_exit()
284 * and blkcg_exit_queue() to be called with queue lock initialized.
287 void blk_sync_queue(struct request_queue
*q
)
289 del_timer_sync(&q
->timeout
);
290 cancel_delayed_work_sync(&q
->delay_work
);
292 EXPORT_SYMBOL(blk_sync_queue
);
295 * __blk_run_queue - run a single device queue
296 * @q: The queue to run
299 * See @blk_run_queue. This variant must be called with the queue lock
300 * held and interrupts disabled.
302 void __blk_run_queue(struct request_queue
*q
)
304 if (unlikely(blk_queue_stopped(q
)))
309 EXPORT_SYMBOL(__blk_run_queue
);
312 * blk_run_queue_async - run a single device queue in workqueue context
313 * @q: The queue to run
316 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
319 void blk_run_queue_async(struct request_queue
*q
)
321 if (likely(!blk_queue_stopped(q
))) {
322 __cancel_delayed_work(&q
->delay_work
);
323 queue_delayed_work(kblockd_workqueue
, &q
->delay_work
, 0);
326 EXPORT_SYMBOL(blk_run_queue_async
);
329 * blk_run_queue - run a single device queue
330 * @q: The queue to run
333 * Invoke request handling on this queue, if it has pending work to do.
334 * May be used to restart queueing when a request has completed.
336 void blk_run_queue(struct request_queue
*q
)
340 spin_lock_irqsave(q
->queue_lock
, flags
);
342 spin_unlock_irqrestore(q
->queue_lock
, flags
);
344 EXPORT_SYMBOL(blk_run_queue
);
346 void blk_put_queue(struct request_queue
*q
)
348 kobject_put(&q
->kobj
);
350 EXPORT_SYMBOL(blk_put_queue
);
353 * blk_drain_queue - drain requests from request_queue
355 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
357 * Drain requests from @q. If @drain_all is set, all requests are drained.
358 * If not, only ELVPRIV requests are drained. The caller is responsible
359 * for ensuring that no new requests which need to be drained are queued.
361 void blk_drain_queue(struct request_queue
*q
, bool drain_all
)
367 spin_lock_irq(q
->queue_lock
);
370 * The caller might be trying to drain @q before its
371 * elevator is initialized.
374 elv_drain_elevator(q
);
376 blkcg_drain_queue(q
);
379 * This function might be called on a queue which failed
380 * driver init after queue creation or is not yet fully
381 * active yet. Some drivers (e.g. fd and loop) get unhappy
382 * in such cases. Kick queue iff dispatch queue has
383 * something on it and @q has request_fn set.
385 if (!list_empty(&q
->queue_head
) && q
->request_fn
)
388 drain
|= q
->rq
.elvpriv
;
391 * Unfortunately, requests are queued at and tracked from
392 * multiple places and there's no single counter which can
393 * be drained. Check all the queues and counters.
396 drain
|= !list_empty(&q
->queue_head
);
397 for (i
= 0; i
< 2; i
++) {
398 drain
|= q
->rq
.count
[i
];
399 drain
|= q
->in_flight
[i
];
400 drain
|= !list_empty(&q
->flush_queue
[i
]);
404 spin_unlock_irq(q
->queue_lock
);
413 * blk_queue_bypass_start - enter queue bypass mode
414 * @q: queue of interest
416 * In bypass mode, only the dispatch FIFO queue of @q is used. This
417 * function makes @q enter bypass mode and drains all requests which were
418 * throttled or issued before. On return, it's guaranteed that no request
419 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
420 * inside queue or RCU read lock.
422 void blk_queue_bypass_start(struct request_queue
*q
)
424 spin_lock_irq(q
->queue_lock
);
426 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
427 spin_unlock_irq(q
->queue_lock
);
429 blk_drain_queue(q
, false);
430 /* ensure blk_queue_bypass() is %true inside RCU read lock */
433 EXPORT_SYMBOL_GPL(blk_queue_bypass_start
);
436 * blk_queue_bypass_end - leave queue bypass mode
437 * @q: queue of interest
439 * Leave bypass mode and restore the normal queueing behavior.
441 void blk_queue_bypass_end(struct request_queue
*q
)
443 spin_lock_irq(q
->queue_lock
);
444 if (!--q
->bypass_depth
)
445 queue_flag_clear(QUEUE_FLAG_BYPASS
, q
);
446 WARN_ON_ONCE(q
->bypass_depth
< 0);
447 spin_unlock_irq(q
->queue_lock
);
449 EXPORT_SYMBOL_GPL(blk_queue_bypass_end
);
452 * blk_cleanup_queue - shutdown a request queue
453 * @q: request queue to shutdown
455 * Mark @q DEAD, drain all pending requests, destroy and put it. All
456 * future requests will be failed immediately with -ENODEV.
458 void blk_cleanup_queue(struct request_queue
*q
)
460 spinlock_t
*lock
= q
->queue_lock
;
462 /* mark @q DEAD, no new request or merges will be allowed afterwards */
463 mutex_lock(&q
->sysfs_lock
);
464 queue_flag_set_unlocked(QUEUE_FLAG_DEAD
, q
);
469 * Dead queue is permanently in bypass mode till released. Note
470 * that, unlike blk_queue_bypass_start(), we aren't performing
471 * synchronize_rcu() after entering bypass mode to avoid the delay
472 * as some drivers create and destroy a lot of queues while
473 * probing. This is still safe because blk_release_queue() will be
474 * called only after the queue refcnt drops to zero and nothing,
475 * RCU or not, would be traversing the queue by then.
478 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
480 queue_flag_set(QUEUE_FLAG_NOMERGES
, q
);
481 queue_flag_set(QUEUE_FLAG_NOXMERGES
, q
);
482 queue_flag_set(QUEUE_FLAG_DEAD
, q
);
484 if (q
->queue_lock
!= &q
->__queue_lock
)
485 q
->queue_lock
= &q
->__queue_lock
;
487 spin_unlock_irq(lock
);
488 mutex_unlock(&q
->sysfs_lock
);
490 /* drain all requests queued before DEAD marking */
491 blk_drain_queue(q
, true);
493 /* @q won't process any more request, flush async actions */
494 del_timer_sync(&q
->backing_dev_info
.laptop_mode_wb_timer
);
497 /* @q is and will stay empty, shutdown and put */
500 EXPORT_SYMBOL(blk_cleanup_queue
);
502 static int blk_init_free_list(struct request_queue
*q
)
504 struct request_list
*rl
= &q
->rq
;
506 if (unlikely(rl
->rq_pool
))
509 rl
->count
[BLK_RW_SYNC
] = rl
->count
[BLK_RW_ASYNC
] = 0;
510 rl
->starved
[BLK_RW_SYNC
] = rl
->starved
[BLK_RW_ASYNC
] = 0;
512 init_waitqueue_head(&rl
->wait
[BLK_RW_SYNC
]);
513 init_waitqueue_head(&rl
->wait
[BLK_RW_ASYNC
]);
515 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
, mempool_alloc_slab
,
516 mempool_free_slab
, request_cachep
, q
->node
);
524 struct request_queue
*blk_alloc_queue(gfp_t gfp_mask
)
526 return blk_alloc_queue_node(gfp_mask
, -1);
528 EXPORT_SYMBOL(blk_alloc_queue
);
530 struct request_queue
*blk_alloc_queue_node(gfp_t gfp_mask
, int node_id
)
532 struct request_queue
*q
;
535 q
= kmem_cache_alloc_node(blk_requestq_cachep
,
536 gfp_mask
| __GFP_ZERO
, node_id
);
540 q
->id
= ida_simple_get(&blk_queue_ida
, 0, 0, GFP_KERNEL
);
544 q
->backing_dev_info
.ra_pages
=
545 (VM_MAX_READAHEAD
* 1024) / PAGE_CACHE_SIZE
;
546 q
->backing_dev_info
.state
= 0;
547 q
->backing_dev_info
.capabilities
= BDI_CAP_MAP_COPY
;
548 q
->backing_dev_info
.name
= "block";
551 err
= bdi_init(&q
->backing_dev_info
);
555 setup_timer(&q
->backing_dev_info
.laptop_mode_wb_timer
,
556 laptop_mode_timer_fn
, (unsigned long) q
);
557 setup_timer(&q
->timeout
, blk_rq_timed_out_timer
, (unsigned long) q
);
558 INIT_LIST_HEAD(&q
->queue_head
);
559 INIT_LIST_HEAD(&q
->timeout_list
);
560 INIT_LIST_HEAD(&q
->icq_list
);
561 #ifdef CONFIG_BLK_CGROUP
562 INIT_LIST_HEAD(&q
->blkg_list
);
564 INIT_LIST_HEAD(&q
->flush_queue
[0]);
565 INIT_LIST_HEAD(&q
->flush_queue
[1]);
566 INIT_LIST_HEAD(&q
->flush_data_in_flight
);
567 INIT_DELAYED_WORK(&q
->delay_work
, blk_delay_work
);
569 kobject_init(&q
->kobj
, &blk_queue_ktype
);
571 mutex_init(&q
->sysfs_lock
);
572 spin_lock_init(&q
->__queue_lock
);
575 * By default initialize queue_lock to internal lock and driver can
576 * override it later if need be.
578 q
->queue_lock
= &q
->__queue_lock
;
580 if (blkcg_init_queue(q
))
586 ida_simple_remove(&blk_queue_ida
, q
->id
);
588 kmem_cache_free(blk_requestq_cachep
, q
);
591 EXPORT_SYMBOL(blk_alloc_queue_node
);
594 * blk_init_queue - prepare a request queue for use with a block device
595 * @rfn: The function to be called to process requests that have been
596 * placed on the queue.
597 * @lock: Request queue spin lock
600 * If a block device wishes to use the standard request handling procedures,
601 * which sorts requests and coalesces adjacent requests, then it must
602 * call blk_init_queue(). The function @rfn will be called when there
603 * are requests on the queue that need to be processed. If the device
604 * supports plugging, then @rfn may not be called immediately when requests
605 * are available on the queue, but may be called at some time later instead.
606 * Plugged queues are generally unplugged when a buffer belonging to one
607 * of the requests on the queue is needed, or due to memory pressure.
609 * @rfn is not required, or even expected, to remove all requests off the
610 * queue, but only as many as it can handle at a time. If it does leave
611 * requests on the queue, it is responsible for arranging that the requests
612 * get dealt with eventually.
614 * The queue spin lock must be held while manipulating the requests on the
615 * request queue; this lock will be taken also from interrupt context, so irq
616 * disabling is needed for it.
618 * Function returns a pointer to the initialized request queue, or %NULL if
622 * blk_init_queue() must be paired with a blk_cleanup_queue() call
623 * when the block device is deactivated (such as at module unload).
626 struct request_queue
*blk_init_queue(request_fn_proc
*rfn
, spinlock_t
*lock
)
628 return blk_init_queue_node(rfn
, lock
, -1);
630 EXPORT_SYMBOL(blk_init_queue
);
632 struct request_queue
*
633 blk_init_queue_node(request_fn_proc
*rfn
, spinlock_t
*lock
, int node_id
)
635 struct request_queue
*uninit_q
, *q
;
637 uninit_q
= blk_alloc_queue_node(GFP_KERNEL
, node_id
);
641 q
= blk_init_allocated_queue(uninit_q
, rfn
, lock
);
643 blk_cleanup_queue(uninit_q
);
647 EXPORT_SYMBOL(blk_init_queue_node
);
649 struct request_queue
*
650 blk_init_allocated_queue(struct request_queue
*q
, request_fn_proc
*rfn
,
656 if (blk_init_free_list(q
))
660 q
->prep_rq_fn
= NULL
;
661 q
->unprep_rq_fn
= NULL
;
662 q
->queue_flags
= QUEUE_FLAG_DEFAULT
;
664 /* Override internal queue lock with supplied lock pointer */
666 q
->queue_lock
= lock
;
669 * This also sets hw/phys segments, boundary and size
671 blk_queue_make_request(q
, blk_queue_bio
);
673 q
->sg_reserved_size
= INT_MAX
;
678 if (!elevator_init(q
, NULL
)) {
679 blk_queue_congestion_threshold(q
);
685 EXPORT_SYMBOL(blk_init_allocated_queue
);
687 bool blk_get_queue(struct request_queue
*q
)
689 if (likely(!blk_queue_dead(q
))) {
696 EXPORT_SYMBOL(blk_get_queue
);
698 static inline void blk_free_request(struct request_queue
*q
, struct request
*rq
)
700 if (rq
->cmd_flags
& REQ_ELVPRIV
) {
701 elv_put_request(q
, rq
);
703 put_io_context(rq
->elv
.icq
->ioc
);
706 mempool_free(rq
, q
->rq
.rq_pool
);
709 static struct request
*
710 blk_alloc_request(struct request_queue
*q
, struct bio
*bio
, struct io_cq
*icq
,
711 unsigned int flags
, gfp_t gfp_mask
)
713 struct request
*rq
= mempool_alloc(q
->rq
.rq_pool
, gfp_mask
);
720 rq
->cmd_flags
= flags
| REQ_ALLOCED
;
722 if (flags
& REQ_ELVPRIV
) {
724 if (unlikely(elv_set_request(q
, rq
, bio
, gfp_mask
))) {
725 mempool_free(rq
, q
->rq
.rq_pool
);
728 /* @rq->elv.icq holds on to io_context until @rq is freed */
730 get_io_context(icq
->ioc
);
737 * ioc_batching returns true if the ioc is a valid batching request and
738 * should be given priority access to a request.
740 static inline int ioc_batching(struct request_queue
*q
, struct io_context
*ioc
)
746 * Make sure the process is able to allocate at least 1 request
747 * even if the batch times out, otherwise we could theoretically
750 return ioc
->nr_batch_requests
== q
->nr_batching
||
751 (ioc
->nr_batch_requests
> 0
752 && time_before(jiffies
, ioc
->last_waited
+ BLK_BATCH_TIME
));
756 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
757 * will cause the process to be a "batcher" on all queues in the system. This
758 * is the behaviour we want though - once it gets a wakeup it should be given
761 static void ioc_set_batching(struct request_queue
*q
, struct io_context
*ioc
)
763 if (!ioc
|| ioc_batching(q
, ioc
))
766 ioc
->nr_batch_requests
= q
->nr_batching
;
767 ioc
->last_waited
= jiffies
;
770 static void __freed_request(struct request_queue
*q
, int sync
)
772 struct request_list
*rl
= &q
->rq
;
774 if (rl
->count
[sync
] < queue_congestion_off_threshold(q
))
775 blk_clear_queue_congested(q
, sync
);
777 if (rl
->count
[sync
] + 1 <= q
->nr_requests
) {
778 if (waitqueue_active(&rl
->wait
[sync
]))
779 wake_up(&rl
->wait
[sync
]);
781 blk_clear_queue_full(q
, sync
);
786 * A request has just been released. Account for it, update the full and
787 * congestion status, wake up any waiters. Called under q->queue_lock.
789 static void freed_request(struct request_queue
*q
, unsigned int flags
)
791 struct request_list
*rl
= &q
->rq
;
792 int sync
= rw_is_sync(flags
);
795 if (flags
& REQ_ELVPRIV
)
798 __freed_request(q
, sync
);
800 if (unlikely(rl
->starved
[sync
^ 1]))
801 __freed_request(q
, sync
^ 1);
805 * Determine if elevator data should be initialized when allocating the
806 * request associated with @bio.
808 static bool blk_rq_should_init_elevator(struct bio
*bio
)
814 * Flush requests do not use the elevator so skip initialization.
815 * This allows a request to share the flush and elevator data.
817 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
))
824 * rq_ioc - determine io_context for request allocation
825 * @bio: request being allocated is for this bio (can be %NULL)
827 * Determine io_context to use for request allocation for @bio. May return
828 * %NULL if %current->io_context doesn't exist.
830 static struct io_context
*rq_ioc(struct bio
*bio
)
832 #ifdef CONFIG_BLK_CGROUP
833 if (bio
&& bio
->bi_ioc
)
836 return current
->io_context
;
840 * get_request - get a free request
841 * @q: request_queue to allocate request from
842 * @rw_flags: RW and SYNC flags
843 * @bio: bio to allocate request for (can be %NULL)
844 * @gfp_mask: allocation mask
846 * Get a free request from @q. This function may fail under memory
847 * pressure or if @q is dead.
849 * Must be callled with @q->queue_lock held and,
850 * Returns %NULL on failure, with @q->queue_lock held.
851 * Returns !%NULL on success, with @q->queue_lock *not held*.
853 static struct request
*get_request(struct request_queue
*q
, int rw_flags
,
854 struct bio
*bio
, gfp_t gfp_mask
)
857 struct request_list
*rl
= &q
->rq
;
858 struct elevator_type
*et
;
859 struct io_context
*ioc
;
860 struct io_cq
*icq
= NULL
;
861 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
862 bool retried
= false;
865 et
= q
->elevator
->type
;
868 if (unlikely(blk_queue_dead(q
)))
871 may_queue
= elv_may_queue(q
, rw_flags
);
872 if (may_queue
== ELV_MQUEUE_NO
)
875 if (rl
->count
[is_sync
]+1 >= queue_congestion_on_threshold(q
)) {
876 if (rl
->count
[is_sync
]+1 >= q
->nr_requests
) {
878 * We want ioc to record batching state. If it's
879 * not already there, creating a new one requires
880 * dropping queue_lock, which in turn requires
881 * retesting conditions to avoid queue hang.
883 if (!ioc
&& !retried
) {
884 spin_unlock_irq(q
->queue_lock
);
885 create_io_context(gfp_mask
, q
->node
);
886 spin_lock_irq(q
->queue_lock
);
892 * The queue will fill after this allocation, so set
893 * it as full, and mark this process as "batching".
894 * This process will be allowed to complete a batch of
895 * requests, others will be blocked.
897 if (!blk_queue_full(q
, is_sync
)) {
898 ioc_set_batching(q
, ioc
);
899 blk_set_queue_full(q
, is_sync
);
901 if (may_queue
!= ELV_MQUEUE_MUST
902 && !ioc_batching(q
, ioc
)) {
904 * The queue is full and the allocating
905 * process is not a "batcher", and not
906 * exempted by the IO scheduler
912 blk_set_queue_congested(q
, is_sync
);
916 * Only allow batching queuers to allocate up to 50% over the defined
917 * limit of requests, otherwise we could have thousands of requests
918 * allocated with any setting of ->nr_requests
920 if (rl
->count
[is_sync
] >= (3 * q
->nr_requests
/ 2))
923 rl
->count
[is_sync
]++;
924 rl
->starved
[is_sync
] = 0;
927 * Decide whether the new request will be managed by elevator. If
928 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
929 * prevent the current elevator from being destroyed until the new
930 * request is freed. This guarantees icq's won't be destroyed and
931 * makes creating new ones safe.
933 * Also, lookup icq while holding queue_lock. If it doesn't exist,
934 * it will be created after releasing queue_lock.
936 if (blk_rq_should_init_elevator(bio
) && !blk_queue_bypass(q
)) {
937 rw_flags
|= REQ_ELVPRIV
;
939 if (et
->icq_cache
&& ioc
)
940 icq
= ioc_lookup_icq(ioc
, q
);
943 if (blk_queue_io_stat(q
))
944 rw_flags
|= REQ_IO_STAT
;
945 spin_unlock_irq(q
->queue_lock
);
947 /* create icq if missing */
948 if ((rw_flags
& REQ_ELVPRIV
) && unlikely(et
->icq_cache
&& !icq
)) {
949 create_io_context(gfp_mask
, q
->node
);
953 icq
= ioc_create_icq(ioc
, q
, gfp_mask
);
958 rq
= blk_alloc_request(q
, bio
, icq
, rw_flags
, gfp_mask
);
963 * ioc may be NULL here, and ioc_batching will be false. That's
964 * OK, if the queue is under the request limit then requests need
965 * not count toward the nr_batch_requests limit. There will always
966 * be some limit enforced by BLK_BATCH_TIME.
968 if (ioc_batching(q
, ioc
))
969 ioc
->nr_batch_requests
--;
971 trace_block_getrq(q
, bio
, rw_flags
& 1);
976 * Allocation failed presumably due to memory. Undo anything we
977 * might have messed up.
979 * Allocating task should really be put onto the front of the wait
980 * queue, but this is pretty rare.
982 spin_lock_irq(q
->queue_lock
);
983 freed_request(q
, rw_flags
);
986 * in the very unlikely event that allocation failed and no
987 * requests for this direction was pending, mark us starved so that
988 * freeing of a request in the other direction will notice
989 * us. another possible fix would be to split the rq mempool into
993 if (unlikely(rl
->count
[is_sync
] == 0))
994 rl
->starved
[is_sync
] = 1;
999 * get_request_wait - get a free request with retry
1000 * @q: request_queue to allocate request from
1001 * @rw_flags: RW and SYNC flags
1002 * @bio: bio to allocate request for (can be %NULL)
1004 * Get a free request from @q. This function keeps retrying under memory
1005 * pressure and fails iff @q is dead.
1007 * Must be callled with @q->queue_lock held and,
1008 * Returns %NULL on failure, with @q->queue_lock held.
1009 * Returns !%NULL on success, with @q->queue_lock *not held*.
1011 static struct request
*get_request_wait(struct request_queue
*q
, int rw_flags
,
1014 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
1017 rq
= get_request(q
, rw_flags
, bio
, GFP_NOIO
);
1020 struct request_list
*rl
= &q
->rq
;
1022 if (unlikely(blk_queue_dead(q
)))
1025 prepare_to_wait_exclusive(&rl
->wait
[is_sync
], &wait
,
1026 TASK_UNINTERRUPTIBLE
);
1028 trace_block_sleeprq(q
, bio
, rw_flags
& 1);
1030 spin_unlock_irq(q
->queue_lock
);
1034 * After sleeping, we become a "batching" process and
1035 * will be able to allocate at least one request, and
1036 * up to a big batch of them for a small period time.
1037 * See ioc_batching, ioc_set_batching
1039 create_io_context(GFP_NOIO
, q
->node
);
1040 ioc_set_batching(q
, current
->io_context
);
1042 spin_lock_irq(q
->queue_lock
);
1043 finish_wait(&rl
->wait
[is_sync
], &wait
);
1045 rq
= get_request(q
, rw_flags
, bio
, GFP_NOIO
);
1051 struct request
*blk_get_request(struct request_queue
*q
, int rw
, gfp_t gfp_mask
)
1055 BUG_ON(rw
!= READ
&& rw
!= WRITE
);
1057 spin_lock_irq(q
->queue_lock
);
1058 if (gfp_mask
& __GFP_WAIT
)
1059 rq
= get_request_wait(q
, rw
, NULL
);
1061 rq
= get_request(q
, rw
, NULL
, gfp_mask
);
1063 spin_unlock_irq(q
->queue_lock
);
1064 /* q->queue_lock is unlocked at this point */
1068 EXPORT_SYMBOL(blk_get_request
);
1071 * blk_make_request - given a bio, allocate a corresponding struct request.
1072 * @q: target request queue
1073 * @bio: The bio describing the memory mappings that will be submitted for IO.
1074 * It may be a chained-bio properly constructed by block/bio layer.
1075 * @gfp_mask: gfp flags to be used for memory allocation
1077 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1078 * type commands. Where the struct request needs to be farther initialized by
1079 * the caller. It is passed a &struct bio, which describes the memory info of
1082 * The caller of blk_make_request must make sure that bi_io_vec
1083 * are set to describe the memory buffers. That bio_data_dir() will return
1084 * the needed direction of the request. (And all bio's in the passed bio-chain
1085 * are properly set accordingly)
1087 * If called under none-sleepable conditions, mapped bio buffers must not
1088 * need bouncing, by calling the appropriate masked or flagged allocator,
1089 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1092 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1093 * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
1094 * anything but the first bio in the chain. Otherwise you risk waiting for IO
1095 * completion of a bio that hasn't been submitted yet, thus resulting in a
1096 * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
1097 * of bio_alloc(), as that avoids the mempool deadlock.
1098 * If possible a big IO should be split into smaller parts when allocation
1099 * fails. Partial allocation should not be an error, or you risk a live-lock.
1101 struct request
*blk_make_request(struct request_queue
*q
, struct bio
*bio
,
1104 struct request
*rq
= blk_get_request(q
, bio_data_dir(bio
), gfp_mask
);
1107 return ERR_PTR(-ENOMEM
);
1110 struct bio
*bounce_bio
= bio
;
1113 blk_queue_bounce(q
, &bounce_bio
);
1114 ret
= blk_rq_append_bio(q
, rq
, bounce_bio
);
1115 if (unlikely(ret
)) {
1116 blk_put_request(rq
);
1117 return ERR_PTR(ret
);
1123 EXPORT_SYMBOL(blk_make_request
);
1126 * blk_requeue_request - put a request back on queue
1127 * @q: request queue where request should be inserted
1128 * @rq: request to be inserted
1131 * Drivers often keep queueing requests until the hardware cannot accept
1132 * more, when that condition happens we need to put the request back
1133 * on the queue. Must be called with queue lock held.
1135 void blk_requeue_request(struct request_queue
*q
, struct request
*rq
)
1137 blk_delete_timer(rq
);
1138 blk_clear_rq_complete(rq
);
1139 trace_block_rq_requeue(q
, rq
);
1141 if (blk_rq_tagged(rq
))
1142 blk_queue_end_tag(q
, rq
);
1144 BUG_ON(blk_queued_rq(rq
));
1146 elv_requeue_request(q
, rq
);
1148 EXPORT_SYMBOL(blk_requeue_request
);
1150 static void add_acct_request(struct request_queue
*q
, struct request
*rq
,
1153 drive_stat_acct(rq
, 1);
1154 __elv_add_request(q
, rq
, where
);
1157 static void part_round_stats_single(int cpu
, struct hd_struct
*part
,
1160 if (now
== part
->stamp
)
1163 if (part_in_flight(part
)) {
1164 __part_stat_add(cpu
, part
, time_in_queue
,
1165 part_in_flight(part
) * (now
- part
->stamp
));
1166 __part_stat_add(cpu
, part
, io_ticks
, (now
- part
->stamp
));
1172 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1173 * @cpu: cpu number for stats access
1174 * @part: target partition
1176 * The average IO queue length and utilisation statistics are maintained
1177 * by observing the current state of the queue length and the amount of
1178 * time it has been in this state for.
1180 * Normally, that accounting is done on IO completion, but that can result
1181 * in more than a second's worth of IO being accounted for within any one
1182 * second, leading to >100% utilisation. To deal with that, we call this
1183 * function to do a round-off before returning the results when reading
1184 * /proc/diskstats. This accounts immediately for all queue usage up to
1185 * the current jiffies and restarts the counters again.
1187 void part_round_stats(int cpu
, struct hd_struct
*part
)
1189 unsigned long now
= jiffies
;
1192 part_round_stats_single(cpu
, &part_to_disk(part
)->part0
, now
);
1193 part_round_stats_single(cpu
, part
, now
);
1195 EXPORT_SYMBOL_GPL(part_round_stats
);
1198 * queue lock must be held
1200 void __blk_put_request(struct request_queue
*q
, struct request
*req
)
1204 if (unlikely(--req
->ref_count
))
1207 elv_completed_request(q
, req
);
1209 /* this is a bio leak */
1210 WARN_ON(req
->bio
!= NULL
);
1213 * Request may not have originated from ll_rw_blk. if not,
1214 * it didn't come out of our reserved rq pools
1216 if (req
->cmd_flags
& REQ_ALLOCED
) {
1217 unsigned int flags
= req
->cmd_flags
;
1219 BUG_ON(!list_empty(&req
->queuelist
));
1220 BUG_ON(!hlist_unhashed(&req
->hash
));
1222 blk_free_request(q
, req
);
1223 freed_request(q
, flags
);
1226 EXPORT_SYMBOL_GPL(__blk_put_request
);
1228 void blk_put_request(struct request
*req
)
1230 unsigned long flags
;
1231 struct request_queue
*q
= req
->q
;
1233 spin_lock_irqsave(q
->queue_lock
, flags
);
1234 __blk_put_request(q
, req
);
1235 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1237 EXPORT_SYMBOL(blk_put_request
);
1240 * blk_add_request_payload - add a payload to a request
1241 * @rq: request to update
1242 * @page: page backing the payload
1243 * @len: length of the payload.
1245 * This allows to later add a payload to an already submitted request by
1246 * a block driver. The driver needs to take care of freeing the payload
1249 * Note that this is a quite horrible hack and nothing but handling of
1250 * discard requests should ever use it.
1252 void blk_add_request_payload(struct request
*rq
, struct page
*page
,
1255 struct bio
*bio
= rq
->bio
;
1257 bio
->bi_io_vec
->bv_page
= page
;
1258 bio
->bi_io_vec
->bv_offset
= 0;
1259 bio
->bi_io_vec
->bv_len
= len
;
1263 bio
->bi_phys_segments
= 1;
1265 rq
->__data_len
= rq
->resid_len
= len
;
1266 rq
->nr_phys_segments
= 1;
1267 rq
->buffer
= bio_data(bio
);
1269 EXPORT_SYMBOL_GPL(blk_add_request_payload
);
1271 static bool bio_attempt_back_merge(struct request_queue
*q
, struct request
*req
,
1274 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1276 if (!ll_back_merge_fn(q
, req
, bio
))
1279 trace_block_bio_backmerge(q
, bio
);
1281 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1282 blk_rq_set_mixed_merge(req
);
1284 req
->biotail
->bi_next
= bio
;
1286 req
->__data_len
+= bio
->bi_size
;
1287 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1289 drive_stat_acct(req
, 0);
1293 static bool bio_attempt_front_merge(struct request_queue
*q
,
1294 struct request
*req
, struct bio
*bio
)
1296 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1298 if (!ll_front_merge_fn(q
, req
, bio
))
1301 trace_block_bio_frontmerge(q
, bio
);
1303 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1304 blk_rq_set_mixed_merge(req
);
1306 bio
->bi_next
= req
->bio
;
1310 * may not be valid. if the low level driver said
1311 * it didn't need a bounce buffer then it better
1312 * not touch req->buffer either...
1314 req
->buffer
= bio_data(bio
);
1315 req
->__sector
= bio
->bi_sector
;
1316 req
->__data_len
+= bio
->bi_size
;
1317 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1319 drive_stat_acct(req
, 0);
1324 * attempt_plug_merge - try to merge with %current's plugged list
1325 * @q: request_queue new bio is being queued at
1326 * @bio: new bio being queued
1327 * @request_count: out parameter for number of traversed plugged requests
1329 * Determine whether @bio being queued on @q can be merged with a request
1330 * on %current's plugged list. Returns %true if merge was successful,
1333 * Plugging coalesces IOs from the same issuer for the same purpose without
1334 * going through @q->queue_lock. As such it's more of an issuing mechanism
1335 * than scheduling, and the request, while may have elvpriv data, is not
1336 * added on the elevator at this point. In addition, we don't have
1337 * reliable access to the elevator outside queue lock. Only check basic
1338 * merging parameters without querying the elevator.
1340 static bool attempt_plug_merge(struct request_queue
*q
, struct bio
*bio
,
1341 unsigned int *request_count
)
1343 struct blk_plug
*plug
;
1347 plug
= current
->plug
;
1352 list_for_each_entry_reverse(rq
, &plug
->list
, queuelist
) {
1357 if (rq
->q
!= q
|| !blk_rq_merge_ok(rq
, bio
))
1360 el_ret
= blk_try_merge(rq
, bio
);
1361 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1362 ret
= bio_attempt_back_merge(q
, rq
, bio
);
1365 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1366 ret
= bio_attempt_front_merge(q
, rq
, bio
);
1375 void init_request_from_bio(struct request
*req
, struct bio
*bio
)
1377 req
->cmd_type
= REQ_TYPE_FS
;
1379 req
->cmd_flags
|= bio
->bi_rw
& REQ_COMMON_MASK
;
1380 if (bio
->bi_rw
& REQ_RAHEAD
)
1381 req
->cmd_flags
|= REQ_FAILFAST_MASK
;
1384 req
->__sector
= bio
->bi_sector
;
1385 req
->ioprio
= bio_prio(bio
);
1386 blk_rq_bio_prep(req
->q
, req
, bio
);
1389 void blk_queue_bio(struct request_queue
*q
, struct bio
*bio
)
1391 const bool sync
= !!(bio
->bi_rw
& REQ_SYNC
);
1392 struct blk_plug
*plug
;
1393 int el_ret
, rw_flags
, where
= ELEVATOR_INSERT_SORT
;
1394 struct request
*req
;
1395 unsigned int request_count
= 0;
1398 * low level driver can indicate that it wants pages above a
1399 * certain limit bounced to low memory (ie for highmem, or even
1400 * ISA dma in theory)
1402 blk_queue_bounce(q
, &bio
);
1404 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) {
1405 spin_lock_irq(q
->queue_lock
);
1406 where
= ELEVATOR_INSERT_FLUSH
;
1411 * Check if we can merge with the plugged list before grabbing
1414 if (attempt_plug_merge(q
, bio
, &request_count
))
1417 spin_lock_irq(q
->queue_lock
);
1419 el_ret
= elv_merge(q
, &req
, bio
);
1420 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1421 if (bio_attempt_back_merge(q
, req
, bio
)) {
1422 elv_bio_merged(q
, req
, bio
);
1423 if (!attempt_back_merge(q
, req
))
1424 elv_merged_request(q
, req
, el_ret
);
1427 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1428 if (bio_attempt_front_merge(q
, req
, bio
)) {
1429 elv_bio_merged(q
, req
, bio
);
1430 if (!attempt_front_merge(q
, req
))
1431 elv_merged_request(q
, req
, el_ret
);
1438 * This sync check and mask will be re-done in init_request_from_bio(),
1439 * but we need to set it earlier to expose the sync flag to the
1440 * rq allocator and io schedulers.
1442 rw_flags
= bio_data_dir(bio
);
1444 rw_flags
|= REQ_SYNC
;
1447 * Grab a free request. This is might sleep but can not fail.
1448 * Returns with the queue unlocked.
1450 req
= get_request_wait(q
, rw_flags
, bio
);
1451 if (unlikely(!req
)) {
1452 bio_endio(bio
, -ENODEV
); /* @q is dead */
1457 * After dropping the lock and possibly sleeping here, our request
1458 * may now be mergeable after it had proven unmergeable (above).
1459 * We don't worry about that case for efficiency. It won't happen
1460 * often, and the elevators are able to handle it.
1462 init_request_from_bio(req
, bio
);
1464 if (test_bit(QUEUE_FLAG_SAME_COMP
, &q
->queue_flags
))
1465 req
->cpu
= raw_smp_processor_id();
1467 plug
= current
->plug
;
1470 * If this is the first request added after a plug, fire
1471 * of a plug trace. If others have been added before, check
1472 * if we have multiple devices in this plug. If so, make a
1473 * note to sort the list before dispatch.
1475 if (list_empty(&plug
->list
))
1476 trace_block_plug(q
);
1478 if (!plug
->should_sort
) {
1479 struct request
*__rq
;
1481 __rq
= list_entry_rq(plug
->list
.prev
);
1483 plug
->should_sort
= 1;
1485 if (request_count
>= BLK_MAX_REQUEST_COUNT
) {
1486 blk_flush_plug_list(plug
, false);
1487 trace_block_plug(q
);
1490 list_add_tail(&req
->queuelist
, &plug
->list
);
1491 drive_stat_acct(req
, 1);
1493 spin_lock_irq(q
->queue_lock
);
1494 add_acct_request(q
, req
, where
);
1497 spin_unlock_irq(q
->queue_lock
);
1500 EXPORT_SYMBOL_GPL(blk_queue_bio
); /* for device mapper only */
1503 * If bio->bi_dev is a partition, remap the location
1505 static inline void blk_partition_remap(struct bio
*bio
)
1507 struct block_device
*bdev
= bio
->bi_bdev
;
1509 if (bio_sectors(bio
) && bdev
!= bdev
->bd_contains
) {
1510 struct hd_struct
*p
= bdev
->bd_part
;
1512 bio
->bi_sector
+= p
->start_sect
;
1513 bio
->bi_bdev
= bdev
->bd_contains
;
1515 trace_block_bio_remap(bdev_get_queue(bio
->bi_bdev
), bio
,
1517 bio
->bi_sector
- p
->start_sect
);
1521 static void handle_bad_sector(struct bio
*bio
)
1523 char b
[BDEVNAME_SIZE
];
1525 printk(KERN_INFO
"attempt to access beyond end of device\n");
1526 printk(KERN_INFO
"%s: rw=%ld, want=%Lu, limit=%Lu\n",
1527 bdevname(bio
->bi_bdev
, b
),
1529 (unsigned long long)bio
->bi_sector
+ bio_sectors(bio
),
1530 (long long)(i_size_read(bio
->bi_bdev
->bd_inode
) >> 9));
1532 set_bit(BIO_EOF
, &bio
->bi_flags
);
1535 #ifdef CONFIG_FAIL_MAKE_REQUEST
1537 static DECLARE_FAULT_ATTR(fail_make_request
);
1539 static int __init
setup_fail_make_request(char *str
)
1541 return setup_fault_attr(&fail_make_request
, str
);
1543 __setup("fail_make_request=", setup_fail_make_request
);
1545 static bool should_fail_request(struct hd_struct
*part
, unsigned int bytes
)
1547 return part
->make_it_fail
&& should_fail(&fail_make_request
, bytes
);
1550 static int __init
fail_make_request_debugfs(void)
1552 struct dentry
*dir
= fault_create_debugfs_attr("fail_make_request",
1553 NULL
, &fail_make_request
);
1555 return IS_ERR(dir
) ? PTR_ERR(dir
) : 0;
1558 late_initcall(fail_make_request_debugfs
);
1560 #else /* CONFIG_FAIL_MAKE_REQUEST */
1562 static inline bool should_fail_request(struct hd_struct
*part
,
1568 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1571 * Check whether this bio extends beyond the end of the device.
1573 static inline int bio_check_eod(struct bio
*bio
, unsigned int nr_sectors
)
1580 /* Test device or partition size, when known. */
1581 maxsector
= i_size_read(bio
->bi_bdev
->bd_inode
) >> 9;
1583 sector_t sector
= bio
->bi_sector
;
1585 if (maxsector
< nr_sectors
|| maxsector
- nr_sectors
< sector
) {
1587 * This may well happen - the kernel calls bread()
1588 * without checking the size of the device, e.g., when
1589 * mounting a device.
1591 handle_bad_sector(bio
);
1599 static noinline_for_stack
bool
1600 generic_make_request_checks(struct bio
*bio
)
1602 struct request_queue
*q
;
1603 int nr_sectors
= bio_sectors(bio
);
1605 char b
[BDEVNAME_SIZE
];
1606 struct hd_struct
*part
;
1610 if (bio_check_eod(bio
, nr_sectors
))
1613 q
= bdev_get_queue(bio
->bi_bdev
);
1616 "generic_make_request: Trying to access "
1617 "nonexistent block-device %s (%Lu)\n",
1618 bdevname(bio
->bi_bdev
, b
),
1619 (long long) bio
->bi_sector
);
1623 if (unlikely(!(bio
->bi_rw
& REQ_DISCARD
) &&
1624 nr_sectors
> queue_max_hw_sectors(q
))) {
1625 printk(KERN_ERR
"bio too big device %s (%u > %u)\n",
1626 bdevname(bio
->bi_bdev
, b
),
1628 queue_max_hw_sectors(q
));
1632 part
= bio
->bi_bdev
->bd_part
;
1633 if (should_fail_request(part
, bio
->bi_size
) ||
1634 should_fail_request(&part_to_disk(part
)->part0
,
1639 * If this device has partitions, remap block n
1640 * of partition p to block n+start(p) of the disk.
1642 blk_partition_remap(bio
);
1644 if (bio_integrity_enabled(bio
) && bio_integrity_prep(bio
))
1647 if (bio_check_eod(bio
, nr_sectors
))
1651 * Filter flush bio's early so that make_request based
1652 * drivers without flush support don't have to worry
1655 if ((bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) && !q
->flush_flags
) {
1656 bio
->bi_rw
&= ~(REQ_FLUSH
| REQ_FUA
);
1663 if ((bio
->bi_rw
& REQ_DISCARD
) &&
1664 (!blk_queue_discard(q
) ||
1665 ((bio
->bi_rw
& REQ_SECURE
) &&
1666 !blk_queue_secdiscard(q
)))) {
1671 if (blk_throtl_bio(q
, bio
))
1672 return false; /* throttled, will be resubmitted later */
1674 trace_block_bio_queue(q
, bio
);
1678 bio_endio(bio
, err
);
1683 * generic_make_request - hand a buffer to its device driver for I/O
1684 * @bio: The bio describing the location in memory and on the device.
1686 * generic_make_request() is used to make I/O requests of block
1687 * devices. It is passed a &struct bio, which describes the I/O that needs
1690 * generic_make_request() does not return any status. The
1691 * success/failure status of the request, along with notification of
1692 * completion, is delivered asynchronously through the bio->bi_end_io
1693 * function described (one day) else where.
1695 * The caller of generic_make_request must make sure that bi_io_vec
1696 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1697 * set to describe the device address, and the
1698 * bi_end_io and optionally bi_private are set to describe how
1699 * completion notification should be signaled.
1701 * generic_make_request and the drivers it calls may use bi_next if this
1702 * bio happens to be merged with someone else, and may resubmit the bio to
1703 * a lower device by calling into generic_make_request recursively, which
1704 * means the bio should NOT be touched after the call to ->make_request_fn.
1706 void generic_make_request(struct bio
*bio
)
1708 struct bio_list bio_list_on_stack
;
1710 if (!generic_make_request_checks(bio
))
1714 * We only want one ->make_request_fn to be active at a time, else
1715 * stack usage with stacked devices could be a problem. So use
1716 * current->bio_list to keep a list of requests submited by a
1717 * make_request_fn function. current->bio_list is also used as a
1718 * flag to say if generic_make_request is currently active in this
1719 * task or not. If it is NULL, then no make_request is active. If
1720 * it is non-NULL, then a make_request is active, and new requests
1721 * should be added at the tail
1723 if (current
->bio_list
) {
1724 bio_list_add(current
->bio_list
, bio
);
1728 /* following loop may be a bit non-obvious, and so deserves some
1730 * Before entering the loop, bio->bi_next is NULL (as all callers
1731 * ensure that) so we have a list with a single bio.
1732 * We pretend that we have just taken it off a longer list, so
1733 * we assign bio_list to a pointer to the bio_list_on_stack,
1734 * thus initialising the bio_list of new bios to be
1735 * added. ->make_request() may indeed add some more bios
1736 * through a recursive call to generic_make_request. If it
1737 * did, we find a non-NULL value in bio_list and re-enter the loop
1738 * from the top. In this case we really did just take the bio
1739 * of the top of the list (no pretending) and so remove it from
1740 * bio_list, and call into ->make_request() again.
1742 BUG_ON(bio
->bi_next
);
1743 bio_list_init(&bio_list_on_stack
);
1744 current
->bio_list
= &bio_list_on_stack
;
1746 struct request_queue
*q
= bdev_get_queue(bio
->bi_bdev
);
1748 q
->make_request_fn(q
, bio
);
1750 bio
= bio_list_pop(current
->bio_list
);
1752 current
->bio_list
= NULL
; /* deactivate */
1754 EXPORT_SYMBOL(generic_make_request
);
1757 * submit_bio - submit a bio to the block device layer for I/O
1758 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1759 * @bio: The &struct bio which describes the I/O
1761 * submit_bio() is very similar in purpose to generic_make_request(), and
1762 * uses that function to do most of the work. Both are fairly rough
1763 * interfaces; @bio must be presetup and ready for I/O.
1766 void submit_bio(int rw
, struct bio
*bio
)
1768 int count
= bio_sectors(bio
);
1773 * If it's a regular read/write or a barrier with data attached,
1774 * go through the normal accounting stuff before submission.
1776 if (bio_has_data(bio
) && !(rw
& REQ_DISCARD
)) {
1778 count_vm_events(PGPGOUT
, count
);
1780 task_io_account_read(bio
->bi_size
);
1781 count_vm_events(PGPGIN
, count
);
1784 if (unlikely(block_dump
)) {
1785 char b
[BDEVNAME_SIZE
];
1786 printk(KERN_DEBUG
"%s(%d): %s block %Lu on %s (%u sectors)\n",
1787 current
->comm
, task_pid_nr(current
),
1788 (rw
& WRITE
) ? "WRITE" : "READ",
1789 (unsigned long long)bio
->bi_sector
,
1790 bdevname(bio
->bi_bdev
, b
),
1795 generic_make_request(bio
);
1797 EXPORT_SYMBOL(submit_bio
);
1800 * blk_rq_check_limits - Helper function to check a request for the queue limit
1802 * @rq: the request being checked
1805 * @rq may have been made based on weaker limitations of upper-level queues
1806 * in request stacking drivers, and it may violate the limitation of @q.
1807 * Since the block layer and the underlying device driver trust @rq
1808 * after it is inserted to @q, it should be checked against @q before
1809 * the insertion using this generic function.
1811 * This function should also be useful for request stacking drivers
1812 * in some cases below, so export this function.
1813 * Request stacking drivers like request-based dm may change the queue
1814 * limits while requests are in the queue (e.g. dm's table swapping).
1815 * Such request stacking drivers should check those requests agaist
1816 * the new queue limits again when they dispatch those requests,
1817 * although such checkings are also done against the old queue limits
1818 * when submitting requests.
1820 int blk_rq_check_limits(struct request_queue
*q
, struct request
*rq
)
1822 if (rq
->cmd_flags
& REQ_DISCARD
)
1825 if (blk_rq_sectors(rq
) > queue_max_sectors(q
) ||
1826 blk_rq_bytes(rq
) > queue_max_hw_sectors(q
) << 9) {
1827 printk(KERN_ERR
"%s: over max size limit.\n", __func__
);
1832 * queue's settings related to segment counting like q->bounce_pfn
1833 * may differ from that of other stacking queues.
1834 * Recalculate it to check the request correctly on this queue's
1837 blk_recalc_rq_segments(rq
);
1838 if (rq
->nr_phys_segments
> queue_max_segments(q
)) {
1839 printk(KERN_ERR
"%s: over max segments limit.\n", __func__
);
1845 EXPORT_SYMBOL_GPL(blk_rq_check_limits
);
1848 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1849 * @q: the queue to submit the request
1850 * @rq: the request being queued
1852 int blk_insert_cloned_request(struct request_queue
*q
, struct request
*rq
)
1854 unsigned long flags
;
1855 int where
= ELEVATOR_INSERT_BACK
;
1857 if (blk_rq_check_limits(q
, rq
))
1861 should_fail_request(&rq
->rq_disk
->part0
, blk_rq_bytes(rq
)))
1864 spin_lock_irqsave(q
->queue_lock
, flags
);
1865 if (unlikely(blk_queue_dead(q
))) {
1866 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1871 * Submitting request must be dequeued before calling this function
1872 * because it will be linked to another request_queue
1874 BUG_ON(blk_queued_rq(rq
));
1876 if (rq
->cmd_flags
& (REQ_FLUSH
|REQ_FUA
))
1877 where
= ELEVATOR_INSERT_FLUSH
;
1879 add_acct_request(q
, rq
, where
);
1880 if (where
== ELEVATOR_INSERT_FLUSH
)
1882 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1886 EXPORT_SYMBOL_GPL(blk_insert_cloned_request
);
1889 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1890 * @rq: request to examine
1893 * A request could be merge of IOs which require different failure
1894 * handling. This function determines the number of bytes which
1895 * can be failed from the beginning of the request without
1896 * crossing into area which need to be retried further.
1899 * The number of bytes to fail.
1902 * queue_lock must be held.
1904 unsigned int blk_rq_err_bytes(const struct request
*rq
)
1906 unsigned int ff
= rq
->cmd_flags
& REQ_FAILFAST_MASK
;
1907 unsigned int bytes
= 0;
1910 if (!(rq
->cmd_flags
& REQ_MIXED_MERGE
))
1911 return blk_rq_bytes(rq
);
1914 * Currently the only 'mixing' which can happen is between
1915 * different fastfail types. We can safely fail portions
1916 * which have all the failfast bits that the first one has -
1917 * the ones which are at least as eager to fail as the first
1920 for (bio
= rq
->bio
; bio
; bio
= bio
->bi_next
) {
1921 if ((bio
->bi_rw
& ff
) != ff
)
1923 bytes
+= bio
->bi_size
;
1926 /* this could lead to infinite loop */
1927 BUG_ON(blk_rq_bytes(rq
) && !bytes
);
1930 EXPORT_SYMBOL_GPL(blk_rq_err_bytes
);
1932 static void blk_account_io_completion(struct request
*req
, unsigned int bytes
)
1934 if (blk_do_io_stat(req
)) {
1935 const int rw
= rq_data_dir(req
);
1936 struct hd_struct
*part
;
1939 cpu
= part_stat_lock();
1941 part_stat_add(cpu
, part
, sectors
[rw
], bytes
>> 9);
1946 static void blk_account_io_done(struct request
*req
)
1949 * Account IO completion. flush_rq isn't accounted as a
1950 * normal IO on queueing nor completion. Accounting the
1951 * containing request is enough.
1953 if (blk_do_io_stat(req
) && !(req
->cmd_flags
& REQ_FLUSH_SEQ
)) {
1954 unsigned long duration
= jiffies
- req
->start_time
;
1955 const int rw
= rq_data_dir(req
);
1956 struct hd_struct
*part
;
1959 cpu
= part_stat_lock();
1962 part_stat_inc(cpu
, part
, ios
[rw
]);
1963 part_stat_add(cpu
, part
, ticks
[rw
], duration
);
1964 part_round_stats(cpu
, part
);
1965 part_dec_in_flight(part
, rw
);
1967 hd_struct_put(part
);
1973 * blk_peek_request - peek at the top of a request queue
1974 * @q: request queue to peek at
1977 * Return the request at the top of @q. The returned request
1978 * should be started using blk_start_request() before LLD starts
1982 * Pointer to the request at the top of @q if available. Null
1986 * queue_lock must be held.
1988 struct request
*blk_peek_request(struct request_queue
*q
)
1993 while ((rq
= __elv_next_request(q
)) != NULL
) {
1994 if (!(rq
->cmd_flags
& REQ_STARTED
)) {
1996 * This is the first time the device driver
1997 * sees this request (possibly after
1998 * requeueing). Notify IO scheduler.
2000 if (rq
->cmd_flags
& REQ_SORTED
)
2001 elv_activate_rq(q
, rq
);
2004 * just mark as started even if we don't start
2005 * it, a request that has been delayed should
2006 * not be passed by new incoming requests
2008 rq
->cmd_flags
|= REQ_STARTED
;
2009 trace_block_rq_issue(q
, rq
);
2012 if (!q
->boundary_rq
|| q
->boundary_rq
== rq
) {
2013 q
->end_sector
= rq_end_sector(rq
);
2014 q
->boundary_rq
= NULL
;
2017 if (rq
->cmd_flags
& REQ_DONTPREP
)
2020 if (q
->dma_drain_size
&& blk_rq_bytes(rq
)) {
2022 * make sure space for the drain appears we
2023 * know we can do this because max_hw_segments
2024 * has been adjusted to be one fewer than the
2027 rq
->nr_phys_segments
++;
2033 ret
= q
->prep_rq_fn(q
, rq
);
2034 if (ret
== BLKPREP_OK
) {
2036 } else if (ret
== BLKPREP_DEFER
) {
2038 * the request may have been (partially) prepped.
2039 * we need to keep this request in the front to
2040 * avoid resource deadlock. REQ_STARTED will
2041 * prevent other fs requests from passing this one.
2043 if (q
->dma_drain_size
&& blk_rq_bytes(rq
) &&
2044 !(rq
->cmd_flags
& REQ_DONTPREP
)) {
2046 * remove the space for the drain we added
2047 * so that we don't add it again
2049 --rq
->nr_phys_segments
;
2054 } else if (ret
== BLKPREP_KILL
) {
2055 rq
->cmd_flags
|= REQ_QUIET
;
2057 * Mark this request as started so we don't trigger
2058 * any debug logic in the end I/O path.
2060 blk_start_request(rq
);
2061 __blk_end_request_all(rq
, -EIO
);
2063 printk(KERN_ERR
"%s: bad return=%d\n", __func__
, ret
);
2070 EXPORT_SYMBOL(blk_peek_request
);
2072 void blk_dequeue_request(struct request
*rq
)
2074 struct request_queue
*q
= rq
->q
;
2076 BUG_ON(list_empty(&rq
->queuelist
));
2077 BUG_ON(ELV_ON_HASH(rq
));
2079 list_del_init(&rq
->queuelist
);
2082 * the time frame between a request being removed from the lists
2083 * and to it is freed is accounted as io that is in progress at
2086 if (blk_account_rq(rq
)) {
2087 q
->in_flight
[rq_is_sync(rq
)]++;
2088 set_io_start_time_ns(rq
);
2093 * blk_start_request - start request processing on the driver
2094 * @req: request to dequeue
2097 * Dequeue @req and start timeout timer on it. This hands off the
2098 * request to the driver.
2100 * Block internal functions which don't want to start timer should
2101 * call blk_dequeue_request().
2104 * queue_lock must be held.
2106 void blk_start_request(struct request
*req
)
2108 blk_dequeue_request(req
);
2111 * We are now handing the request to the hardware, initialize
2112 * resid_len to full count and add the timeout handler.
2114 req
->resid_len
= blk_rq_bytes(req
);
2115 if (unlikely(blk_bidi_rq(req
)))
2116 req
->next_rq
->resid_len
= blk_rq_bytes(req
->next_rq
);
2120 EXPORT_SYMBOL(blk_start_request
);
2123 * blk_fetch_request - fetch a request from a request queue
2124 * @q: request queue to fetch a request from
2127 * Return the request at the top of @q. The request is started on
2128 * return and LLD can start processing it immediately.
2131 * Pointer to the request at the top of @q if available. Null
2135 * queue_lock must be held.
2137 struct request
*blk_fetch_request(struct request_queue
*q
)
2141 rq
= blk_peek_request(q
);
2143 blk_start_request(rq
);
2146 EXPORT_SYMBOL(blk_fetch_request
);
2149 * blk_update_request - Special helper function for request stacking drivers
2150 * @req: the request being processed
2151 * @error: %0 for success, < %0 for error
2152 * @nr_bytes: number of bytes to complete @req
2155 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2156 * the request structure even if @req doesn't have leftover.
2157 * If @req has leftover, sets it up for the next range of segments.
2159 * This special helper function is only for request stacking drivers
2160 * (e.g. request-based dm) so that they can handle partial completion.
2161 * Actual device drivers should use blk_end_request instead.
2163 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2164 * %false return from this function.
2167 * %false - this request doesn't have any more data
2168 * %true - this request has more data
2170 bool blk_update_request(struct request
*req
, int error
, unsigned int nr_bytes
)
2172 int total_bytes
, bio_nbytes
, next_idx
= 0;
2178 trace_block_rq_complete(req
->q
, req
);
2181 * For fs requests, rq is just carrier of independent bio's
2182 * and each partial completion should be handled separately.
2183 * Reset per-request error on each partial completion.
2185 * TODO: tj: This is too subtle. It would be better to let
2186 * low level drivers do what they see fit.
2188 if (req
->cmd_type
== REQ_TYPE_FS
)
2191 if (error
&& req
->cmd_type
== REQ_TYPE_FS
&&
2192 !(req
->cmd_flags
& REQ_QUIET
)) {
2197 error_type
= "recoverable transport";
2200 error_type
= "critical target";
2203 error_type
= "critical nexus";
2210 printk(KERN_ERR
"end_request: %s error, dev %s, sector %llu\n",
2211 error_type
, req
->rq_disk
? req
->rq_disk
->disk_name
: "?",
2212 (unsigned long long)blk_rq_pos(req
));
2215 blk_account_io_completion(req
, nr_bytes
);
2217 total_bytes
= bio_nbytes
= 0;
2218 while ((bio
= req
->bio
) != NULL
) {
2221 if (nr_bytes
>= bio
->bi_size
) {
2222 req
->bio
= bio
->bi_next
;
2223 nbytes
= bio
->bi_size
;
2224 req_bio_endio(req
, bio
, nbytes
, error
);
2228 int idx
= bio
->bi_idx
+ next_idx
;
2230 if (unlikely(idx
>= bio
->bi_vcnt
)) {
2231 blk_dump_rq_flags(req
, "__end_that");
2232 printk(KERN_ERR
"%s: bio idx %d >= vcnt %d\n",
2233 __func__
, idx
, bio
->bi_vcnt
);
2237 nbytes
= bio_iovec_idx(bio
, idx
)->bv_len
;
2238 BIO_BUG_ON(nbytes
> bio
->bi_size
);
2241 * not a complete bvec done
2243 if (unlikely(nbytes
> nr_bytes
)) {
2244 bio_nbytes
+= nr_bytes
;
2245 total_bytes
+= nr_bytes
;
2250 * advance to the next vector
2253 bio_nbytes
+= nbytes
;
2256 total_bytes
+= nbytes
;
2262 * end more in this run, or just return 'not-done'
2264 if (unlikely(nr_bytes
<= 0))
2274 * Reset counters so that the request stacking driver
2275 * can find how many bytes remain in the request
2278 req
->__data_len
= 0;
2283 * if the request wasn't completed, update state
2286 req_bio_endio(req
, bio
, bio_nbytes
, error
);
2287 bio
->bi_idx
+= next_idx
;
2288 bio_iovec(bio
)->bv_offset
+= nr_bytes
;
2289 bio_iovec(bio
)->bv_len
-= nr_bytes
;
2292 req
->__data_len
-= total_bytes
;
2293 req
->buffer
= bio_data(req
->bio
);
2295 /* update sector only for requests with clear definition of sector */
2296 if (req
->cmd_type
== REQ_TYPE_FS
|| (req
->cmd_flags
& REQ_DISCARD
))
2297 req
->__sector
+= total_bytes
>> 9;
2299 /* mixed attributes always follow the first bio */
2300 if (req
->cmd_flags
& REQ_MIXED_MERGE
) {
2301 req
->cmd_flags
&= ~REQ_FAILFAST_MASK
;
2302 req
->cmd_flags
|= req
->bio
->bi_rw
& REQ_FAILFAST_MASK
;
2306 * If total number of sectors is less than the first segment
2307 * size, something has gone terribly wrong.
2309 if (blk_rq_bytes(req
) < blk_rq_cur_bytes(req
)) {
2310 blk_dump_rq_flags(req
, "request botched");
2311 req
->__data_len
= blk_rq_cur_bytes(req
);
2314 /* recalculate the number of segments */
2315 blk_recalc_rq_segments(req
);
2319 EXPORT_SYMBOL_GPL(blk_update_request
);
2321 static bool blk_update_bidi_request(struct request
*rq
, int error
,
2322 unsigned int nr_bytes
,
2323 unsigned int bidi_bytes
)
2325 if (blk_update_request(rq
, error
, nr_bytes
))
2328 /* Bidi request must be completed as a whole */
2329 if (unlikely(blk_bidi_rq(rq
)) &&
2330 blk_update_request(rq
->next_rq
, error
, bidi_bytes
))
2333 if (blk_queue_add_random(rq
->q
))
2334 add_disk_randomness(rq
->rq_disk
);
2340 * blk_unprep_request - unprepare a request
2343 * This function makes a request ready for complete resubmission (or
2344 * completion). It happens only after all error handling is complete,
2345 * so represents the appropriate moment to deallocate any resources
2346 * that were allocated to the request in the prep_rq_fn. The queue
2347 * lock is held when calling this.
2349 void blk_unprep_request(struct request
*req
)
2351 struct request_queue
*q
= req
->q
;
2353 req
->cmd_flags
&= ~REQ_DONTPREP
;
2354 if (q
->unprep_rq_fn
)
2355 q
->unprep_rq_fn(q
, req
);
2357 EXPORT_SYMBOL_GPL(blk_unprep_request
);
2360 * queue lock must be held
2362 static void blk_finish_request(struct request
*req
, int error
)
2364 if (blk_rq_tagged(req
))
2365 blk_queue_end_tag(req
->q
, req
);
2367 BUG_ON(blk_queued_rq(req
));
2369 if (unlikely(laptop_mode
) && req
->cmd_type
== REQ_TYPE_FS
)
2370 laptop_io_completion(&req
->q
->backing_dev_info
);
2372 blk_delete_timer(req
);
2374 if (req
->cmd_flags
& REQ_DONTPREP
)
2375 blk_unprep_request(req
);
2378 blk_account_io_done(req
);
2381 req
->end_io(req
, error
);
2383 if (blk_bidi_rq(req
))
2384 __blk_put_request(req
->next_rq
->q
, req
->next_rq
);
2386 __blk_put_request(req
->q
, req
);
2391 * blk_end_bidi_request - Complete a bidi request
2392 * @rq: the request to complete
2393 * @error: %0 for success, < %0 for error
2394 * @nr_bytes: number of bytes to complete @rq
2395 * @bidi_bytes: number of bytes to complete @rq->next_rq
2398 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2399 * Drivers that supports bidi can safely call this member for any
2400 * type of request, bidi or uni. In the later case @bidi_bytes is
2404 * %false - we are done with this request
2405 * %true - still buffers pending for this request
2407 static bool blk_end_bidi_request(struct request
*rq
, int error
,
2408 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2410 struct request_queue
*q
= rq
->q
;
2411 unsigned long flags
;
2413 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2416 spin_lock_irqsave(q
->queue_lock
, flags
);
2417 blk_finish_request(rq
, error
);
2418 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2424 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2425 * @rq: the request to complete
2426 * @error: %0 for success, < %0 for error
2427 * @nr_bytes: number of bytes to complete @rq
2428 * @bidi_bytes: number of bytes to complete @rq->next_rq
2431 * Identical to blk_end_bidi_request() except that queue lock is
2432 * assumed to be locked on entry and remains so on return.
2435 * %false - we are done with this request
2436 * %true - still buffers pending for this request
2438 bool __blk_end_bidi_request(struct request
*rq
, int error
,
2439 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2441 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2444 blk_finish_request(rq
, error
);
2450 * blk_end_request - Helper function for drivers to complete the request.
2451 * @rq: the request being processed
2452 * @error: %0 for success, < %0 for error
2453 * @nr_bytes: number of bytes to complete
2456 * Ends I/O on a number of bytes attached to @rq.
2457 * If @rq has leftover, sets it up for the next range of segments.
2460 * %false - we are done with this request
2461 * %true - still buffers pending for this request
2463 bool blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2465 return blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2467 EXPORT_SYMBOL(blk_end_request
);
2470 * blk_end_request_all - Helper function for drives to finish the request.
2471 * @rq: the request to finish
2472 * @error: %0 for success, < %0 for error
2475 * Completely finish @rq.
2477 void blk_end_request_all(struct request
*rq
, int error
)
2480 unsigned int bidi_bytes
= 0;
2482 if (unlikely(blk_bidi_rq(rq
)))
2483 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2485 pending
= blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2488 EXPORT_SYMBOL(blk_end_request_all
);
2491 * blk_end_request_cur - Helper function to finish the current request chunk.
2492 * @rq: the request to finish the current chunk for
2493 * @error: %0 for success, < %0 for error
2496 * Complete the current consecutively mapped chunk from @rq.
2499 * %false - we are done with this request
2500 * %true - still buffers pending for this request
2502 bool blk_end_request_cur(struct request
*rq
, int error
)
2504 return blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2506 EXPORT_SYMBOL(blk_end_request_cur
);
2509 * blk_end_request_err - Finish a request till the next failure boundary.
2510 * @rq: the request to finish till the next failure boundary for
2511 * @error: must be negative errno
2514 * Complete @rq till the next failure boundary.
2517 * %false - we are done with this request
2518 * %true - still buffers pending for this request
2520 bool blk_end_request_err(struct request
*rq
, int error
)
2522 WARN_ON(error
>= 0);
2523 return blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2525 EXPORT_SYMBOL_GPL(blk_end_request_err
);
2528 * __blk_end_request - Helper function for drivers to complete the request.
2529 * @rq: the request being processed
2530 * @error: %0 for success, < %0 for error
2531 * @nr_bytes: number of bytes to complete
2534 * Must be called with queue lock held unlike blk_end_request().
2537 * %false - we are done with this request
2538 * %true - still buffers pending for this request
2540 bool __blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2542 return __blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2544 EXPORT_SYMBOL(__blk_end_request
);
2547 * __blk_end_request_all - Helper function for drives to finish the request.
2548 * @rq: the request to finish
2549 * @error: %0 for success, < %0 for error
2552 * Completely finish @rq. Must be called with queue lock held.
2554 void __blk_end_request_all(struct request
*rq
, int error
)
2557 unsigned int bidi_bytes
= 0;
2559 if (unlikely(blk_bidi_rq(rq
)))
2560 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2562 pending
= __blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2565 EXPORT_SYMBOL(__blk_end_request_all
);
2568 * __blk_end_request_cur - Helper function to finish the current request chunk.
2569 * @rq: the request to finish the current chunk for
2570 * @error: %0 for success, < %0 for error
2573 * Complete the current consecutively mapped chunk from @rq. Must
2574 * be called with queue lock held.
2577 * %false - we are done with this request
2578 * %true - still buffers pending for this request
2580 bool __blk_end_request_cur(struct request
*rq
, int error
)
2582 return __blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2584 EXPORT_SYMBOL(__blk_end_request_cur
);
2587 * __blk_end_request_err - Finish a request till the next failure boundary.
2588 * @rq: the request to finish till the next failure boundary for
2589 * @error: must be negative errno
2592 * Complete @rq till the next failure boundary. Must be called
2593 * with queue lock held.
2596 * %false - we are done with this request
2597 * %true - still buffers pending for this request
2599 bool __blk_end_request_err(struct request
*rq
, int error
)
2601 WARN_ON(error
>= 0);
2602 return __blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2604 EXPORT_SYMBOL_GPL(__blk_end_request_err
);
2606 void blk_rq_bio_prep(struct request_queue
*q
, struct request
*rq
,
2609 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2610 rq
->cmd_flags
|= bio
->bi_rw
& REQ_WRITE
;
2612 if (bio_has_data(bio
)) {
2613 rq
->nr_phys_segments
= bio_phys_segments(q
, bio
);
2614 rq
->buffer
= bio_data(bio
);
2616 rq
->__data_len
= bio
->bi_size
;
2617 rq
->bio
= rq
->biotail
= bio
;
2620 rq
->rq_disk
= bio
->bi_bdev
->bd_disk
;
2623 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2625 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2626 * @rq: the request to be flushed
2629 * Flush all pages in @rq.
2631 void rq_flush_dcache_pages(struct request
*rq
)
2633 struct req_iterator iter
;
2634 struct bio_vec
*bvec
;
2636 rq_for_each_segment(bvec
, rq
, iter
)
2637 flush_dcache_page(bvec
->bv_page
);
2639 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages
);
2643 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2644 * @q : the queue of the device being checked
2647 * Check if underlying low-level drivers of a device are busy.
2648 * If the drivers want to export their busy state, they must set own
2649 * exporting function using blk_queue_lld_busy() first.
2651 * Basically, this function is used only by request stacking drivers
2652 * to stop dispatching requests to underlying devices when underlying
2653 * devices are busy. This behavior helps more I/O merging on the queue
2654 * of the request stacking driver and prevents I/O throughput regression
2655 * on burst I/O load.
2658 * 0 - Not busy (The request stacking driver should dispatch request)
2659 * 1 - Busy (The request stacking driver should stop dispatching request)
2661 int blk_lld_busy(struct request_queue
*q
)
2664 return q
->lld_busy_fn(q
);
2668 EXPORT_SYMBOL_GPL(blk_lld_busy
);
2671 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2672 * @rq: the clone request to be cleaned up
2675 * Free all bios in @rq for a cloned request.
2677 void blk_rq_unprep_clone(struct request
*rq
)
2681 while ((bio
= rq
->bio
) != NULL
) {
2682 rq
->bio
= bio
->bi_next
;
2687 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone
);
2690 * Copy attributes of the original request to the clone request.
2691 * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2693 static void __blk_rq_prep_clone(struct request
*dst
, struct request
*src
)
2695 dst
->cpu
= src
->cpu
;
2696 dst
->cmd_flags
= (src
->cmd_flags
& REQ_CLONE_MASK
) | REQ_NOMERGE
;
2697 dst
->cmd_type
= src
->cmd_type
;
2698 dst
->__sector
= blk_rq_pos(src
);
2699 dst
->__data_len
= blk_rq_bytes(src
);
2700 dst
->nr_phys_segments
= src
->nr_phys_segments
;
2701 dst
->ioprio
= src
->ioprio
;
2702 dst
->extra_len
= src
->extra_len
;
2706 * blk_rq_prep_clone - Helper function to setup clone request
2707 * @rq: the request to be setup
2708 * @rq_src: original request to be cloned
2709 * @bs: bio_set that bios for clone are allocated from
2710 * @gfp_mask: memory allocation mask for bio
2711 * @bio_ctr: setup function to be called for each clone bio.
2712 * Returns %0 for success, non %0 for failure.
2713 * @data: private data to be passed to @bio_ctr
2716 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2717 * The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2718 * are not copied, and copying such parts is the caller's responsibility.
2719 * Also, pages which the original bios are pointing to are not copied
2720 * and the cloned bios just point same pages.
2721 * So cloned bios must be completed before original bios, which means
2722 * the caller must complete @rq before @rq_src.
2724 int blk_rq_prep_clone(struct request
*rq
, struct request
*rq_src
,
2725 struct bio_set
*bs
, gfp_t gfp_mask
,
2726 int (*bio_ctr
)(struct bio
*, struct bio
*, void *),
2729 struct bio
*bio
, *bio_src
;
2734 blk_rq_init(NULL
, rq
);
2736 __rq_for_each_bio(bio_src
, rq_src
) {
2737 bio
= bio_alloc_bioset(gfp_mask
, bio_src
->bi_max_vecs
, bs
);
2741 __bio_clone(bio
, bio_src
);
2743 if (bio_integrity(bio_src
) &&
2744 bio_integrity_clone(bio
, bio_src
, gfp_mask
, bs
))
2747 if (bio_ctr
&& bio_ctr(bio
, bio_src
, data
))
2751 rq
->biotail
->bi_next
= bio
;
2754 rq
->bio
= rq
->biotail
= bio
;
2757 __blk_rq_prep_clone(rq
, rq_src
);
2764 blk_rq_unprep_clone(rq
);
2768 EXPORT_SYMBOL_GPL(blk_rq_prep_clone
);
2770 int kblockd_schedule_work(struct request_queue
*q
, struct work_struct
*work
)
2772 return queue_work(kblockd_workqueue
, work
);
2774 EXPORT_SYMBOL(kblockd_schedule_work
);
2776 int kblockd_schedule_delayed_work(struct request_queue
*q
,
2777 struct delayed_work
*dwork
, unsigned long delay
)
2779 return queue_delayed_work(kblockd_workqueue
, dwork
, delay
);
2781 EXPORT_SYMBOL(kblockd_schedule_delayed_work
);
2783 #define PLUG_MAGIC 0x91827364
2786 * blk_start_plug - initialize blk_plug and track it inside the task_struct
2787 * @plug: The &struct blk_plug that needs to be initialized
2790 * Tracking blk_plug inside the task_struct will help with auto-flushing the
2791 * pending I/O should the task end up blocking between blk_start_plug() and
2792 * blk_finish_plug(). This is important from a performance perspective, but
2793 * also ensures that we don't deadlock. For instance, if the task is blocking
2794 * for a memory allocation, memory reclaim could end up wanting to free a
2795 * page belonging to that request that is currently residing in our private
2796 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
2797 * this kind of deadlock.
2799 void blk_start_plug(struct blk_plug
*plug
)
2801 struct task_struct
*tsk
= current
;
2803 plug
->magic
= PLUG_MAGIC
;
2804 INIT_LIST_HEAD(&plug
->list
);
2805 INIT_LIST_HEAD(&plug
->cb_list
);
2806 plug
->should_sort
= 0;
2809 * If this is a nested plug, don't actually assign it. It will be
2810 * flushed on its own.
2814 * Store ordering should not be needed here, since a potential
2815 * preempt will imply a full memory barrier
2820 EXPORT_SYMBOL(blk_start_plug
);
2822 static int plug_rq_cmp(void *priv
, struct list_head
*a
, struct list_head
*b
)
2824 struct request
*rqa
= container_of(a
, struct request
, queuelist
);
2825 struct request
*rqb
= container_of(b
, struct request
, queuelist
);
2827 return !(rqa
->q
<= rqb
->q
);
2831 * If 'from_schedule' is true, then postpone the dispatch of requests
2832 * until a safe kblockd context. We due this to avoid accidental big
2833 * additional stack usage in driver dispatch, in places where the originally
2834 * plugger did not intend it.
2836 static void queue_unplugged(struct request_queue
*q
, unsigned int depth
,
2838 __releases(q
->queue_lock
)
2840 trace_block_unplug(q
, depth
, !from_schedule
);
2843 * Don't mess with dead queue.
2845 if (unlikely(blk_queue_dead(q
))) {
2846 spin_unlock(q
->queue_lock
);
2851 * If we are punting this to kblockd, then we can safely drop
2852 * the queue_lock before waking kblockd (which needs to take
2855 if (from_schedule
) {
2856 spin_unlock(q
->queue_lock
);
2857 blk_run_queue_async(q
);
2860 spin_unlock(q
->queue_lock
);
2865 static void flush_plug_callbacks(struct blk_plug
*plug
)
2867 LIST_HEAD(callbacks
);
2869 if (list_empty(&plug
->cb_list
))
2872 list_splice_init(&plug
->cb_list
, &callbacks
);
2874 while (!list_empty(&callbacks
)) {
2875 struct blk_plug_cb
*cb
= list_first_entry(&callbacks
,
2878 list_del(&cb
->list
);
2883 void blk_flush_plug_list(struct blk_plug
*plug
, bool from_schedule
)
2885 struct request_queue
*q
;
2886 unsigned long flags
;
2891 BUG_ON(plug
->magic
!= PLUG_MAGIC
);
2893 flush_plug_callbacks(plug
);
2894 if (list_empty(&plug
->list
))
2897 list_splice_init(&plug
->list
, &list
);
2899 if (plug
->should_sort
) {
2900 list_sort(NULL
, &list
, plug_rq_cmp
);
2901 plug
->should_sort
= 0;
2908 * Save and disable interrupts here, to avoid doing it for every
2909 * queue lock we have to take.
2911 local_irq_save(flags
);
2912 while (!list_empty(&list
)) {
2913 rq
= list_entry_rq(list
.next
);
2914 list_del_init(&rq
->queuelist
);
2918 * This drops the queue lock
2921 queue_unplugged(q
, depth
, from_schedule
);
2924 spin_lock(q
->queue_lock
);
2928 * Short-circuit if @q is dead
2930 if (unlikely(blk_queue_dead(q
))) {
2931 __blk_end_request_all(rq
, -ENODEV
);
2936 * rq is already accounted, so use raw insert
2938 if (rq
->cmd_flags
& (REQ_FLUSH
| REQ_FUA
))
2939 __elv_add_request(q
, rq
, ELEVATOR_INSERT_FLUSH
);
2941 __elv_add_request(q
, rq
, ELEVATOR_INSERT_SORT_MERGE
);
2947 * This drops the queue lock
2950 queue_unplugged(q
, depth
, from_schedule
);
2952 local_irq_restore(flags
);
2955 void blk_finish_plug(struct blk_plug
*plug
)
2957 blk_flush_plug_list(plug
, false);
2959 if (plug
== current
->plug
)
2960 current
->plug
= NULL
;
2962 EXPORT_SYMBOL(blk_finish_plug
);
2964 int __init
blk_dev_init(void)
2966 BUILD_BUG_ON(__REQ_NR_BITS
> 8 *
2967 sizeof(((struct request
*)0)->cmd_flags
));
2969 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
2970 kblockd_workqueue
= alloc_workqueue("kblockd",
2971 WQ_MEM_RECLAIM
| WQ_HIGHPRI
, 0);
2972 if (!kblockd_workqueue
)
2973 panic("Failed to create kblockd\n");
2975 request_cachep
= kmem_cache_create("blkdev_requests",
2976 sizeof(struct request
), 0, SLAB_PANIC
, NULL
);
2978 blk_requestq_cachep
= kmem_cache_create("blkdev_queue",
2979 sizeof(struct request_queue
), 0, SLAB_PANIC
, NULL
);