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
)
426 spin_lock_irq(q
->queue_lock
);
427 drain
= !q
->bypass_depth
++;
428 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
429 spin_unlock_irq(q
->queue_lock
);
432 blk_drain_queue(q
, false);
433 /* ensure blk_queue_bypass() is %true inside RCU read lock */
437 EXPORT_SYMBOL_GPL(blk_queue_bypass_start
);
440 * blk_queue_bypass_end - leave queue bypass mode
441 * @q: queue of interest
443 * Leave bypass mode and restore the normal queueing behavior.
445 void blk_queue_bypass_end(struct request_queue
*q
)
447 spin_lock_irq(q
->queue_lock
);
448 if (!--q
->bypass_depth
)
449 queue_flag_clear(QUEUE_FLAG_BYPASS
, q
);
450 WARN_ON_ONCE(q
->bypass_depth
< 0);
451 spin_unlock_irq(q
->queue_lock
);
453 EXPORT_SYMBOL_GPL(blk_queue_bypass_end
);
456 * blk_cleanup_queue - shutdown a request queue
457 * @q: request queue to shutdown
459 * Mark @q DEAD, drain all pending requests, destroy and put it. All
460 * future requests will be failed immediately with -ENODEV.
462 void blk_cleanup_queue(struct request_queue
*q
)
464 spinlock_t
*lock
= q
->queue_lock
;
466 /* mark @q DEAD, no new request or merges will be allowed afterwards */
467 mutex_lock(&q
->sysfs_lock
);
468 queue_flag_set_unlocked(QUEUE_FLAG_DEAD
, q
);
473 * Dead queue is permanently in bypass mode till released. Note
474 * that, unlike blk_queue_bypass_start(), we aren't performing
475 * synchronize_rcu() after entering bypass mode to avoid the delay
476 * as some drivers create and destroy a lot of queues while
477 * probing. This is still safe because blk_release_queue() will be
478 * called only after the queue refcnt drops to zero and nothing,
479 * RCU or not, would be traversing the queue by then.
482 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
484 queue_flag_set(QUEUE_FLAG_NOMERGES
, q
);
485 queue_flag_set(QUEUE_FLAG_NOXMERGES
, q
);
486 queue_flag_set(QUEUE_FLAG_DEAD
, q
);
488 if (q
->queue_lock
!= &q
->__queue_lock
)
489 q
->queue_lock
= &q
->__queue_lock
;
491 spin_unlock_irq(lock
);
492 mutex_unlock(&q
->sysfs_lock
);
494 /* drain all requests queued before DEAD marking */
495 blk_drain_queue(q
, true);
497 /* @q won't process any more request, flush async actions */
498 del_timer_sync(&q
->backing_dev_info
.laptop_mode_wb_timer
);
501 /* @q is and will stay empty, shutdown and put */
504 EXPORT_SYMBOL(blk_cleanup_queue
);
506 static int blk_init_free_list(struct request_queue
*q
)
508 struct request_list
*rl
= &q
->rq
;
510 if (unlikely(rl
->rq_pool
))
513 rl
->count
[BLK_RW_SYNC
] = rl
->count
[BLK_RW_ASYNC
] = 0;
514 rl
->starved
[BLK_RW_SYNC
] = rl
->starved
[BLK_RW_ASYNC
] = 0;
516 init_waitqueue_head(&rl
->wait
[BLK_RW_SYNC
]);
517 init_waitqueue_head(&rl
->wait
[BLK_RW_ASYNC
]);
519 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
, mempool_alloc_slab
,
520 mempool_free_slab
, request_cachep
, q
->node
);
528 struct request_queue
*blk_alloc_queue(gfp_t gfp_mask
)
530 return blk_alloc_queue_node(gfp_mask
, -1);
532 EXPORT_SYMBOL(blk_alloc_queue
);
534 struct request_queue
*blk_alloc_queue_node(gfp_t gfp_mask
, int node_id
)
536 struct request_queue
*q
;
539 q
= kmem_cache_alloc_node(blk_requestq_cachep
,
540 gfp_mask
| __GFP_ZERO
, node_id
);
544 q
->id
= ida_simple_get(&blk_queue_ida
, 0, 0, GFP_KERNEL
);
548 q
->backing_dev_info
.ra_pages
=
549 (VM_MAX_READAHEAD
* 1024) / PAGE_CACHE_SIZE
;
550 q
->backing_dev_info
.state
= 0;
551 q
->backing_dev_info
.capabilities
= BDI_CAP_MAP_COPY
;
552 q
->backing_dev_info
.name
= "block";
555 err
= bdi_init(&q
->backing_dev_info
);
559 setup_timer(&q
->backing_dev_info
.laptop_mode_wb_timer
,
560 laptop_mode_timer_fn
, (unsigned long) q
);
561 setup_timer(&q
->timeout
, blk_rq_timed_out_timer
, (unsigned long) q
);
562 INIT_LIST_HEAD(&q
->queue_head
);
563 INIT_LIST_HEAD(&q
->timeout_list
);
564 INIT_LIST_HEAD(&q
->icq_list
);
565 #ifdef CONFIG_BLK_CGROUP
566 INIT_LIST_HEAD(&q
->blkg_list
);
568 INIT_LIST_HEAD(&q
->flush_queue
[0]);
569 INIT_LIST_HEAD(&q
->flush_queue
[1]);
570 INIT_LIST_HEAD(&q
->flush_data_in_flight
);
571 INIT_DELAYED_WORK(&q
->delay_work
, blk_delay_work
);
573 kobject_init(&q
->kobj
, &blk_queue_ktype
);
575 mutex_init(&q
->sysfs_lock
);
576 spin_lock_init(&q
->__queue_lock
);
579 * By default initialize queue_lock to internal lock and driver can
580 * override it later if need be.
582 q
->queue_lock
= &q
->__queue_lock
;
585 * A queue starts its life with bypass turned on to avoid
586 * unnecessary bypass on/off overhead and nasty surprises during
587 * init. The initial bypass will be finished at the end of
588 * blk_init_allocated_queue().
591 __set_bit(QUEUE_FLAG_BYPASS
, &q
->queue_flags
);
593 if (blkcg_init_queue(q
))
599 ida_simple_remove(&blk_queue_ida
, q
->id
);
601 kmem_cache_free(blk_requestq_cachep
, q
);
604 EXPORT_SYMBOL(blk_alloc_queue_node
);
607 * blk_init_queue - prepare a request queue for use with a block device
608 * @rfn: The function to be called to process requests that have been
609 * placed on the queue.
610 * @lock: Request queue spin lock
613 * If a block device wishes to use the standard request handling procedures,
614 * which sorts requests and coalesces adjacent requests, then it must
615 * call blk_init_queue(). The function @rfn will be called when there
616 * are requests on the queue that need to be processed. If the device
617 * supports plugging, then @rfn may not be called immediately when requests
618 * are available on the queue, but may be called at some time later instead.
619 * Plugged queues are generally unplugged when a buffer belonging to one
620 * of the requests on the queue is needed, or due to memory pressure.
622 * @rfn is not required, or even expected, to remove all requests off the
623 * queue, but only as many as it can handle at a time. If it does leave
624 * requests on the queue, it is responsible for arranging that the requests
625 * get dealt with eventually.
627 * The queue spin lock must be held while manipulating the requests on the
628 * request queue; this lock will be taken also from interrupt context, so irq
629 * disabling is needed for it.
631 * Function returns a pointer to the initialized request queue, or %NULL if
635 * blk_init_queue() must be paired with a blk_cleanup_queue() call
636 * when the block device is deactivated (such as at module unload).
639 struct request_queue
*blk_init_queue(request_fn_proc
*rfn
, spinlock_t
*lock
)
641 return blk_init_queue_node(rfn
, lock
, -1);
643 EXPORT_SYMBOL(blk_init_queue
);
645 struct request_queue
*
646 blk_init_queue_node(request_fn_proc
*rfn
, spinlock_t
*lock
, int node_id
)
648 struct request_queue
*uninit_q
, *q
;
650 uninit_q
= blk_alloc_queue_node(GFP_KERNEL
, node_id
);
654 q
= blk_init_allocated_queue(uninit_q
, rfn
, lock
);
656 blk_cleanup_queue(uninit_q
);
660 EXPORT_SYMBOL(blk_init_queue_node
);
662 struct request_queue
*
663 blk_init_allocated_queue(struct request_queue
*q
, request_fn_proc
*rfn
,
669 if (blk_init_free_list(q
))
673 q
->prep_rq_fn
= NULL
;
674 q
->unprep_rq_fn
= NULL
;
675 q
->queue_flags
= QUEUE_FLAG_DEFAULT
;
677 /* Override internal queue lock with supplied lock pointer */
679 q
->queue_lock
= lock
;
682 * This also sets hw/phys segments, boundary and size
684 blk_queue_make_request(q
, blk_queue_bio
);
686 q
->sg_reserved_size
= INT_MAX
;
689 if (elevator_init(q
, NULL
))
692 blk_queue_congestion_threshold(q
);
694 /* all done, end the initial bypass */
695 blk_queue_bypass_end(q
);
698 EXPORT_SYMBOL(blk_init_allocated_queue
);
700 bool blk_get_queue(struct request_queue
*q
)
702 if (likely(!blk_queue_dead(q
))) {
709 EXPORT_SYMBOL(blk_get_queue
);
711 static inline void blk_free_request(struct request_queue
*q
, struct request
*rq
)
713 if (rq
->cmd_flags
& REQ_ELVPRIV
) {
714 elv_put_request(q
, rq
);
716 put_io_context(rq
->elv
.icq
->ioc
);
719 mempool_free(rq
, q
->rq
.rq_pool
);
722 static struct request
*
723 blk_alloc_request(struct request_queue
*q
, struct bio
*bio
, struct io_cq
*icq
,
724 unsigned int flags
, gfp_t gfp_mask
)
726 struct request
*rq
= mempool_alloc(q
->rq
.rq_pool
, gfp_mask
);
733 rq
->cmd_flags
= flags
| REQ_ALLOCED
;
735 if (flags
& REQ_ELVPRIV
) {
737 if (unlikely(elv_set_request(q
, rq
, bio
, gfp_mask
))) {
738 mempool_free(rq
, q
->rq
.rq_pool
);
741 /* @rq->elv.icq holds on to io_context until @rq is freed */
743 get_io_context(icq
->ioc
);
750 * ioc_batching returns true if the ioc is a valid batching request and
751 * should be given priority access to a request.
753 static inline int ioc_batching(struct request_queue
*q
, struct io_context
*ioc
)
759 * Make sure the process is able to allocate at least 1 request
760 * even if the batch times out, otherwise we could theoretically
763 return ioc
->nr_batch_requests
== q
->nr_batching
||
764 (ioc
->nr_batch_requests
> 0
765 && time_before(jiffies
, ioc
->last_waited
+ BLK_BATCH_TIME
));
769 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
770 * will cause the process to be a "batcher" on all queues in the system. This
771 * is the behaviour we want though - once it gets a wakeup it should be given
774 static void ioc_set_batching(struct request_queue
*q
, struct io_context
*ioc
)
776 if (!ioc
|| ioc_batching(q
, ioc
))
779 ioc
->nr_batch_requests
= q
->nr_batching
;
780 ioc
->last_waited
= jiffies
;
783 static void __freed_request(struct request_queue
*q
, int sync
)
785 struct request_list
*rl
= &q
->rq
;
787 if (rl
->count
[sync
] < queue_congestion_off_threshold(q
))
788 blk_clear_queue_congested(q
, sync
);
790 if (rl
->count
[sync
] + 1 <= q
->nr_requests
) {
791 if (waitqueue_active(&rl
->wait
[sync
]))
792 wake_up(&rl
->wait
[sync
]);
794 blk_clear_queue_full(q
, sync
);
799 * A request has just been released. Account for it, update the full and
800 * congestion status, wake up any waiters. Called under q->queue_lock.
802 static void freed_request(struct request_queue
*q
, unsigned int flags
)
804 struct request_list
*rl
= &q
->rq
;
805 int sync
= rw_is_sync(flags
);
808 if (flags
& REQ_ELVPRIV
)
811 __freed_request(q
, sync
);
813 if (unlikely(rl
->starved
[sync
^ 1]))
814 __freed_request(q
, sync
^ 1);
818 * Determine if elevator data should be initialized when allocating the
819 * request associated with @bio.
821 static bool blk_rq_should_init_elevator(struct bio
*bio
)
827 * Flush requests do not use the elevator so skip initialization.
828 * This allows a request to share the flush and elevator data.
830 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
))
837 * rq_ioc - determine io_context for request allocation
838 * @bio: request being allocated is for this bio (can be %NULL)
840 * Determine io_context to use for request allocation for @bio. May return
841 * %NULL if %current->io_context doesn't exist.
843 static struct io_context
*rq_ioc(struct bio
*bio
)
845 #ifdef CONFIG_BLK_CGROUP
846 if (bio
&& bio
->bi_ioc
)
849 return current
->io_context
;
853 * get_request - get a free request
854 * @q: request_queue to allocate request from
855 * @rw_flags: RW and SYNC flags
856 * @bio: bio to allocate request for (can be %NULL)
857 * @gfp_mask: allocation mask
859 * Get a free request from @q. This function may fail under memory
860 * pressure or if @q is dead.
862 * Must be callled with @q->queue_lock held and,
863 * Returns %NULL on failure, with @q->queue_lock held.
864 * Returns !%NULL on success, with @q->queue_lock *not held*.
866 static struct request
*get_request(struct request_queue
*q
, int rw_flags
,
867 struct bio
*bio
, gfp_t gfp_mask
)
870 struct request_list
*rl
= &q
->rq
;
871 struct elevator_type
*et
;
872 struct io_context
*ioc
;
873 struct io_cq
*icq
= NULL
;
874 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
875 bool retried
= false;
878 et
= q
->elevator
->type
;
881 if (unlikely(blk_queue_dead(q
)))
884 may_queue
= elv_may_queue(q
, rw_flags
);
885 if (may_queue
== ELV_MQUEUE_NO
)
888 if (rl
->count
[is_sync
]+1 >= queue_congestion_on_threshold(q
)) {
889 if (rl
->count
[is_sync
]+1 >= q
->nr_requests
) {
891 * We want ioc to record batching state. If it's
892 * not already there, creating a new one requires
893 * dropping queue_lock, which in turn requires
894 * retesting conditions to avoid queue hang.
896 if (!ioc
&& !retried
) {
897 spin_unlock_irq(q
->queue_lock
);
898 create_io_context(gfp_mask
, q
->node
);
899 spin_lock_irq(q
->queue_lock
);
905 * The queue will fill after this allocation, so set
906 * it as full, and mark this process as "batching".
907 * This process will be allowed to complete a batch of
908 * requests, others will be blocked.
910 if (!blk_queue_full(q
, is_sync
)) {
911 ioc_set_batching(q
, ioc
);
912 blk_set_queue_full(q
, is_sync
);
914 if (may_queue
!= ELV_MQUEUE_MUST
915 && !ioc_batching(q
, ioc
)) {
917 * The queue is full and the allocating
918 * process is not a "batcher", and not
919 * exempted by the IO scheduler
925 blk_set_queue_congested(q
, is_sync
);
929 * Only allow batching queuers to allocate up to 50% over the defined
930 * limit of requests, otherwise we could have thousands of requests
931 * allocated with any setting of ->nr_requests
933 if (rl
->count
[is_sync
] >= (3 * q
->nr_requests
/ 2))
936 rl
->count
[is_sync
]++;
937 rl
->starved
[is_sync
] = 0;
940 * Decide whether the new request will be managed by elevator. If
941 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
942 * prevent the current elevator from being destroyed until the new
943 * request is freed. This guarantees icq's won't be destroyed and
944 * makes creating new ones safe.
946 * Also, lookup icq while holding queue_lock. If it doesn't exist,
947 * it will be created after releasing queue_lock.
949 if (blk_rq_should_init_elevator(bio
) && !blk_queue_bypass(q
)) {
950 rw_flags
|= REQ_ELVPRIV
;
952 if (et
->icq_cache
&& ioc
)
953 icq
= ioc_lookup_icq(ioc
, q
);
956 if (blk_queue_io_stat(q
))
957 rw_flags
|= REQ_IO_STAT
;
958 spin_unlock_irq(q
->queue_lock
);
960 /* create icq if missing */
961 if ((rw_flags
& REQ_ELVPRIV
) && unlikely(et
->icq_cache
&& !icq
)) {
962 create_io_context(gfp_mask
, q
->node
);
966 icq
= ioc_create_icq(ioc
, q
, gfp_mask
);
971 rq
= blk_alloc_request(q
, bio
, icq
, rw_flags
, gfp_mask
);
976 * ioc may be NULL here, and ioc_batching will be false. That's
977 * OK, if the queue is under the request limit then requests need
978 * not count toward the nr_batch_requests limit. There will always
979 * be some limit enforced by BLK_BATCH_TIME.
981 if (ioc_batching(q
, ioc
))
982 ioc
->nr_batch_requests
--;
984 trace_block_getrq(q
, bio
, rw_flags
& 1);
989 * Allocation failed presumably due to memory. Undo anything we
990 * might have messed up.
992 * Allocating task should really be put onto the front of the wait
993 * queue, but this is pretty rare.
995 spin_lock_irq(q
->queue_lock
);
996 freed_request(q
, rw_flags
);
999 * in the very unlikely event that allocation failed and no
1000 * requests for this direction was pending, mark us starved so that
1001 * freeing of a request in the other direction will notice
1002 * us. another possible fix would be to split the rq mempool into
1006 if (unlikely(rl
->count
[is_sync
] == 0))
1007 rl
->starved
[is_sync
] = 1;
1012 * get_request_wait - get a free request with retry
1013 * @q: request_queue to allocate request from
1014 * @rw_flags: RW and SYNC flags
1015 * @bio: bio to allocate request for (can be %NULL)
1017 * Get a free request from @q. This function keeps retrying under memory
1018 * pressure and fails iff @q is dead.
1020 * Must be callled with @q->queue_lock held and,
1021 * Returns %NULL on failure, with @q->queue_lock held.
1022 * Returns !%NULL on success, with @q->queue_lock *not held*.
1024 static struct request
*get_request_wait(struct request_queue
*q
, int rw_flags
,
1027 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
1030 rq
= get_request(q
, rw_flags
, bio
, GFP_NOIO
);
1033 struct request_list
*rl
= &q
->rq
;
1035 if (unlikely(blk_queue_dead(q
)))
1038 prepare_to_wait_exclusive(&rl
->wait
[is_sync
], &wait
,
1039 TASK_UNINTERRUPTIBLE
);
1041 trace_block_sleeprq(q
, bio
, rw_flags
& 1);
1043 spin_unlock_irq(q
->queue_lock
);
1047 * After sleeping, we become a "batching" process and
1048 * will be able to allocate at least one request, and
1049 * up to a big batch of them for a small period time.
1050 * See ioc_batching, ioc_set_batching
1052 create_io_context(GFP_NOIO
, q
->node
);
1053 ioc_set_batching(q
, current
->io_context
);
1055 spin_lock_irq(q
->queue_lock
);
1056 finish_wait(&rl
->wait
[is_sync
], &wait
);
1058 rq
= get_request(q
, rw_flags
, bio
, GFP_NOIO
);
1064 struct request
*blk_get_request(struct request_queue
*q
, int rw
, gfp_t gfp_mask
)
1068 BUG_ON(rw
!= READ
&& rw
!= WRITE
);
1070 spin_lock_irq(q
->queue_lock
);
1071 if (gfp_mask
& __GFP_WAIT
)
1072 rq
= get_request_wait(q
, rw
, NULL
);
1074 rq
= get_request(q
, rw
, NULL
, gfp_mask
);
1076 spin_unlock_irq(q
->queue_lock
);
1077 /* q->queue_lock is unlocked at this point */
1081 EXPORT_SYMBOL(blk_get_request
);
1084 * blk_make_request - given a bio, allocate a corresponding struct request.
1085 * @q: target request queue
1086 * @bio: The bio describing the memory mappings that will be submitted for IO.
1087 * It may be a chained-bio properly constructed by block/bio layer.
1088 * @gfp_mask: gfp flags to be used for memory allocation
1090 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1091 * type commands. Where the struct request needs to be farther initialized by
1092 * the caller. It is passed a &struct bio, which describes the memory info of
1095 * The caller of blk_make_request must make sure that bi_io_vec
1096 * are set to describe the memory buffers. That bio_data_dir() will return
1097 * the needed direction of the request. (And all bio's in the passed bio-chain
1098 * are properly set accordingly)
1100 * If called under none-sleepable conditions, mapped bio buffers must not
1101 * need bouncing, by calling the appropriate masked or flagged allocator,
1102 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1105 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1106 * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
1107 * anything but the first bio in the chain. Otherwise you risk waiting for IO
1108 * completion of a bio that hasn't been submitted yet, thus resulting in a
1109 * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
1110 * of bio_alloc(), as that avoids the mempool deadlock.
1111 * If possible a big IO should be split into smaller parts when allocation
1112 * fails. Partial allocation should not be an error, or you risk a live-lock.
1114 struct request
*blk_make_request(struct request_queue
*q
, struct bio
*bio
,
1117 struct request
*rq
= blk_get_request(q
, bio_data_dir(bio
), gfp_mask
);
1120 return ERR_PTR(-ENOMEM
);
1123 struct bio
*bounce_bio
= bio
;
1126 blk_queue_bounce(q
, &bounce_bio
);
1127 ret
= blk_rq_append_bio(q
, rq
, bounce_bio
);
1128 if (unlikely(ret
)) {
1129 blk_put_request(rq
);
1130 return ERR_PTR(ret
);
1136 EXPORT_SYMBOL(blk_make_request
);
1139 * blk_requeue_request - put a request back on queue
1140 * @q: request queue where request should be inserted
1141 * @rq: request to be inserted
1144 * Drivers often keep queueing requests until the hardware cannot accept
1145 * more, when that condition happens we need to put the request back
1146 * on the queue. Must be called with queue lock held.
1148 void blk_requeue_request(struct request_queue
*q
, struct request
*rq
)
1150 blk_delete_timer(rq
);
1151 blk_clear_rq_complete(rq
);
1152 trace_block_rq_requeue(q
, rq
);
1154 if (blk_rq_tagged(rq
))
1155 blk_queue_end_tag(q
, rq
);
1157 BUG_ON(blk_queued_rq(rq
));
1159 elv_requeue_request(q
, rq
);
1161 EXPORT_SYMBOL(blk_requeue_request
);
1163 static void add_acct_request(struct request_queue
*q
, struct request
*rq
,
1166 drive_stat_acct(rq
, 1);
1167 __elv_add_request(q
, rq
, where
);
1170 static void part_round_stats_single(int cpu
, struct hd_struct
*part
,
1173 if (now
== part
->stamp
)
1176 if (part_in_flight(part
)) {
1177 __part_stat_add(cpu
, part
, time_in_queue
,
1178 part_in_flight(part
) * (now
- part
->stamp
));
1179 __part_stat_add(cpu
, part
, io_ticks
, (now
- part
->stamp
));
1185 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1186 * @cpu: cpu number for stats access
1187 * @part: target partition
1189 * The average IO queue length and utilisation statistics are maintained
1190 * by observing the current state of the queue length and the amount of
1191 * time it has been in this state for.
1193 * Normally, that accounting is done on IO completion, but that can result
1194 * in more than a second's worth of IO being accounted for within any one
1195 * second, leading to >100% utilisation. To deal with that, we call this
1196 * function to do a round-off before returning the results when reading
1197 * /proc/diskstats. This accounts immediately for all queue usage up to
1198 * the current jiffies and restarts the counters again.
1200 void part_round_stats(int cpu
, struct hd_struct
*part
)
1202 unsigned long now
= jiffies
;
1205 part_round_stats_single(cpu
, &part_to_disk(part
)->part0
, now
);
1206 part_round_stats_single(cpu
, part
, now
);
1208 EXPORT_SYMBOL_GPL(part_round_stats
);
1211 * queue lock must be held
1213 void __blk_put_request(struct request_queue
*q
, struct request
*req
)
1217 if (unlikely(--req
->ref_count
))
1220 elv_completed_request(q
, req
);
1222 /* this is a bio leak */
1223 WARN_ON(req
->bio
!= NULL
);
1226 * Request may not have originated from ll_rw_blk. if not,
1227 * it didn't come out of our reserved rq pools
1229 if (req
->cmd_flags
& REQ_ALLOCED
) {
1230 unsigned int flags
= req
->cmd_flags
;
1232 BUG_ON(!list_empty(&req
->queuelist
));
1233 BUG_ON(!hlist_unhashed(&req
->hash
));
1235 blk_free_request(q
, req
);
1236 freed_request(q
, flags
);
1239 EXPORT_SYMBOL_GPL(__blk_put_request
);
1241 void blk_put_request(struct request
*req
)
1243 unsigned long flags
;
1244 struct request_queue
*q
= req
->q
;
1246 spin_lock_irqsave(q
->queue_lock
, flags
);
1247 __blk_put_request(q
, req
);
1248 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1250 EXPORT_SYMBOL(blk_put_request
);
1253 * blk_add_request_payload - add a payload to a request
1254 * @rq: request to update
1255 * @page: page backing the payload
1256 * @len: length of the payload.
1258 * This allows to later add a payload to an already submitted request by
1259 * a block driver. The driver needs to take care of freeing the payload
1262 * Note that this is a quite horrible hack and nothing but handling of
1263 * discard requests should ever use it.
1265 void blk_add_request_payload(struct request
*rq
, struct page
*page
,
1268 struct bio
*bio
= rq
->bio
;
1270 bio
->bi_io_vec
->bv_page
= page
;
1271 bio
->bi_io_vec
->bv_offset
= 0;
1272 bio
->bi_io_vec
->bv_len
= len
;
1276 bio
->bi_phys_segments
= 1;
1278 rq
->__data_len
= rq
->resid_len
= len
;
1279 rq
->nr_phys_segments
= 1;
1280 rq
->buffer
= bio_data(bio
);
1282 EXPORT_SYMBOL_GPL(blk_add_request_payload
);
1284 static bool bio_attempt_back_merge(struct request_queue
*q
, struct request
*req
,
1287 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1289 if (!ll_back_merge_fn(q
, req
, bio
))
1292 trace_block_bio_backmerge(q
, bio
);
1294 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1295 blk_rq_set_mixed_merge(req
);
1297 req
->biotail
->bi_next
= bio
;
1299 req
->__data_len
+= bio
->bi_size
;
1300 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1302 drive_stat_acct(req
, 0);
1306 static bool bio_attempt_front_merge(struct request_queue
*q
,
1307 struct request
*req
, struct bio
*bio
)
1309 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1311 if (!ll_front_merge_fn(q
, req
, bio
))
1314 trace_block_bio_frontmerge(q
, bio
);
1316 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1317 blk_rq_set_mixed_merge(req
);
1319 bio
->bi_next
= req
->bio
;
1323 * may not be valid. if the low level driver said
1324 * it didn't need a bounce buffer then it better
1325 * not touch req->buffer either...
1327 req
->buffer
= bio_data(bio
);
1328 req
->__sector
= bio
->bi_sector
;
1329 req
->__data_len
+= bio
->bi_size
;
1330 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1332 drive_stat_acct(req
, 0);
1337 * attempt_plug_merge - try to merge with %current's plugged list
1338 * @q: request_queue new bio is being queued at
1339 * @bio: new bio being queued
1340 * @request_count: out parameter for number of traversed plugged requests
1342 * Determine whether @bio being queued on @q can be merged with a request
1343 * on %current's plugged list. Returns %true if merge was successful,
1346 * Plugging coalesces IOs from the same issuer for the same purpose without
1347 * going through @q->queue_lock. As such it's more of an issuing mechanism
1348 * than scheduling, and the request, while may have elvpriv data, is not
1349 * added on the elevator at this point. In addition, we don't have
1350 * reliable access to the elevator outside queue lock. Only check basic
1351 * merging parameters without querying the elevator.
1353 static bool attempt_plug_merge(struct request_queue
*q
, struct bio
*bio
,
1354 unsigned int *request_count
)
1356 struct blk_plug
*plug
;
1360 plug
= current
->plug
;
1365 list_for_each_entry_reverse(rq
, &plug
->list
, queuelist
) {
1370 if (rq
->q
!= q
|| !blk_rq_merge_ok(rq
, bio
))
1373 el_ret
= blk_try_merge(rq
, bio
);
1374 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1375 ret
= bio_attempt_back_merge(q
, rq
, bio
);
1378 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1379 ret
= bio_attempt_front_merge(q
, rq
, bio
);
1388 void init_request_from_bio(struct request
*req
, struct bio
*bio
)
1390 req
->cmd_type
= REQ_TYPE_FS
;
1392 req
->cmd_flags
|= bio
->bi_rw
& REQ_COMMON_MASK
;
1393 if (bio
->bi_rw
& REQ_RAHEAD
)
1394 req
->cmd_flags
|= REQ_FAILFAST_MASK
;
1397 req
->__sector
= bio
->bi_sector
;
1398 req
->ioprio
= bio_prio(bio
);
1399 blk_rq_bio_prep(req
->q
, req
, bio
);
1402 void blk_queue_bio(struct request_queue
*q
, struct bio
*bio
)
1404 const bool sync
= !!(bio
->bi_rw
& REQ_SYNC
);
1405 struct blk_plug
*plug
;
1406 int el_ret
, rw_flags
, where
= ELEVATOR_INSERT_SORT
;
1407 struct request
*req
;
1408 unsigned int request_count
= 0;
1411 * low level driver can indicate that it wants pages above a
1412 * certain limit bounced to low memory (ie for highmem, or even
1413 * ISA dma in theory)
1415 blk_queue_bounce(q
, &bio
);
1417 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) {
1418 spin_lock_irq(q
->queue_lock
);
1419 where
= ELEVATOR_INSERT_FLUSH
;
1424 * Check if we can merge with the plugged list before grabbing
1427 if (attempt_plug_merge(q
, bio
, &request_count
))
1430 spin_lock_irq(q
->queue_lock
);
1432 el_ret
= elv_merge(q
, &req
, bio
);
1433 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1434 if (bio_attempt_back_merge(q
, req
, bio
)) {
1435 elv_bio_merged(q
, req
, bio
);
1436 if (!attempt_back_merge(q
, req
))
1437 elv_merged_request(q
, req
, el_ret
);
1440 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1441 if (bio_attempt_front_merge(q
, req
, bio
)) {
1442 elv_bio_merged(q
, req
, bio
);
1443 if (!attempt_front_merge(q
, req
))
1444 elv_merged_request(q
, req
, el_ret
);
1451 * This sync check and mask will be re-done in init_request_from_bio(),
1452 * but we need to set it earlier to expose the sync flag to the
1453 * rq allocator and io schedulers.
1455 rw_flags
= bio_data_dir(bio
);
1457 rw_flags
|= REQ_SYNC
;
1460 * Grab a free request. This is might sleep but can not fail.
1461 * Returns with the queue unlocked.
1463 req
= get_request_wait(q
, rw_flags
, bio
);
1464 if (unlikely(!req
)) {
1465 bio_endio(bio
, -ENODEV
); /* @q is dead */
1470 * After dropping the lock and possibly sleeping here, our request
1471 * may now be mergeable after it had proven unmergeable (above).
1472 * We don't worry about that case for efficiency. It won't happen
1473 * often, and the elevators are able to handle it.
1475 init_request_from_bio(req
, bio
);
1477 if (test_bit(QUEUE_FLAG_SAME_COMP
, &q
->queue_flags
))
1478 req
->cpu
= raw_smp_processor_id();
1480 plug
= current
->plug
;
1483 * If this is the first request added after a plug, fire
1484 * of a plug trace. If others have been added before, check
1485 * if we have multiple devices in this plug. If so, make a
1486 * note to sort the list before dispatch.
1488 if (list_empty(&plug
->list
))
1489 trace_block_plug(q
);
1491 if (!plug
->should_sort
) {
1492 struct request
*__rq
;
1494 __rq
= list_entry_rq(plug
->list
.prev
);
1496 plug
->should_sort
= 1;
1498 if (request_count
>= BLK_MAX_REQUEST_COUNT
) {
1499 blk_flush_plug_list(plug
, false);
1500 trace_block_plug(q
);
1503 list_add_tail(&req
->queuelist
, &plug
->list
);
1504 drive_stat_acct(req
, 1);
1506 spin_lock_irq(q
->queue_lock
);
1507 add_acct_request(q
, req
, where
);
1510 spin_unlock_irq(q
->queue_lock
);
1513 EXPORT_SYMBOL_GPL(blk_queue_bio
); /* for device mapper only */
1516 * If bio->bi_dev is a partition, remap the location
1518 static inline void blk_partition_remap(struct bio
*bio
)
1520 struct block_device
*bdev
= bio
->bi_bdev
;
1522 if (bio_sectors(bio
) && bdev
!= bdev
->bd_contains
) {
1523 struct hd_struct
*p
= bdev
->bd_part
;
1525 bio
->bi_sector
+= p
->start_sect
;
1526 bio
->bi_bdev
= bdev
->bd_contains
;
1528 trace_block_bio_remap(bdev_get_queue(bio
->bi_bdev
), bio
,
1530 bio
->bi_sector
- p
->start_sect
);
1534 static void handle_bad_sector(struct bio
*bio
)
1536 char b
[BDEVNAME_SIZE
];
1538 printk(KERN_INFO
"attempt to access beyond end of device\n");
1539 printk(KERN_INFO
"%s: rw=%ld, want=%Lu, limit=%Lu\n",
1540 bdevname(bio
->bi_bdev
, b
),
1542 (unsigned long long)bio
->bi_sector
+ bio_sectors(bio
),
1543 (long long)(i_size_read(bio
->bi_bdev
->bd_inode
) >> 9));
1545 set_bit(BIO_EOF
, &bio
->bi_flags
);
1548 #ifdef CONFIG_FAIL_MAKE_REQUEST
1550 static DECLARE_FAULT_ATTR(fail_make_request
);
1552 static int __init
setup_fail_make_request(char *str
)
1554 return setup_fault_attr(&fail_make_request
, str
);
1556 __setup("fail_make_request=", setup_fail_make_request
);
1558 static bool should_fail_request(struct hd_struct
*part
, unsigned int bytes
)
1560 return part
->make_it_fail
&& should_fail(&fail_make_request
, bytes
);
1563 static int __init
fail_make_request_debugfs(void)
1565 struct dentry
*dir
= fault_create_debugfs_attr("fail_make_request",
1566 NULL
, &fail_make_request
);
1568 return IS_ERR(dir
) ? PTR_ERR(dir
) : 0;
1571 late_initcall(fail_make_request_debugfs
);
1573 #else /* CONFIG_FAIL_MAKE_REQUEST */
1575 static inline bool should_fail_request(struct hd_struct
*part
,
1581 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1584 * Check whether this bio extends beyond the end of the device.
1586 static inline int bio_check_eod(struct bio
*bio
, unsigned int nr_sectors
)
1593 /* Test device or partition size, when known. */
1594 maxsector
= i_size_read(bio
->bi_bdev
->bd_inode
) >> 9;
1596 sector_t sector
= bio
->bi_sector
;
1598 if (maxsector
< nr_sectors
|| maxsector
- nr_sectors
< sector
) {
1600 * This may well happen - the kernel calls bread()
1601 * without checking the size of the device, e.g., when
1602 * mounting a device.
1604 handle_bad_sector(bio
);
1612 static noinline_for_stack
bool
1613 generic_make_request_checks(struct bio
*bio
)
1615 struct request_queue
*q
;
1616 int nr_sectors
= bio_sectors(bio
);
1618 char b
[BDEVNAME_SIZE
];
1619 struct hd_struct
*part
;
1623 if (bio_check_eod(bio
, nr_sectors
))
1626 q
= bdev_get_queue(bio
->bi_bdev
);
1629 "generic_make_request: Trying to access "
1630 "nonexistent block-device %s (%Lu)\n",
1631 bdevname(bio
->bi_bdev
, b
),
1632 (long long) bio
->bi_sector
);
1636 if (unlikely(!(bio
->bi_rw
& REQ_DISCARD
) &&
1637 nr_sectors
> queue_max_hw_sectors(q
))) {
1638 printk(KERN_ERR
"bio too big device %s (%u > %u)\n",
1639 bdevname(bio
->bi_bdev
, b
),
1641 queue_max_hw_sectors(q
));
1645 part
= bio
->bi_bdev
->bd_part
;
1646 if (should_fail_request(part
, bio
->bi_size
) ||
1647 should_fail_request(&part_to_disk(part
)->part0
,
1652 * If this device has partitions, remap block n
1653 * of partition p to block n+start(p) of the disk.
1655 blk_partition_remap(bio
);
1657 if (bio_integrity_enabled(bio
) && bio_integrity_prep(bio
))
1660 if (bio_check_eod(bio
, nr_sectors
))
1664 * Filter flush bio's early so that make_request based
1665 * drivers without flush support don't have to worry
1668 if ((bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) && !q
->flush_flags
) {
1669 bio
->bi_rw
&= ~(REQ_FLUSH
| REQ_FUA
);
1676 if ((bio
->bi_rw
& REQ_DISCARD
) &&
1677 (!blk_queue_discard(q
) ||
1678 ((bio
->bi_rw
& REQ_SECURE
) &&
1679 !blk_queue_secdiscard(q
)))) {
1684 if (blk_throtl_bio(q
, bio
))
1685 return false; /* throttled, will be resubmitted later */
1687 trace_block_bio_queue(q
, bio
);
1691 bio_endio(bio
, err
);
1696 * generic_make_request - hand a buffer to its device driver for I/O
1697 * @bio: The bio describing the location in memory and on the device.
1699 * generic_make_request() is used to make I/O requests of block
1700 * devices. It is passed a &struct bio, which describes the I/O that needs
1703 * generic_make_request() does not return any status. The
1704 * success/failure status of the request, along with notification of
1705 * completion, is delivered asynchronously through the bio->bi_end_io
1706 * function described (one day) else where.
1708 * The caller of generic_make_request must make sure that bi_io_vec
1709 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1710 * set to describe the device address, and the
1711 * bi_end_io and optionally bi_private are set to describe how
1712 * completion notification should be signaled.
1714 * generic_make_request and the drivers it calls may use bi_next if this
1715 * bio happens to be merged with someone else, and may resubmit the bio to
1716 * a lower device by calling into generic_make_request recursively, which
1717 * means the bio should NOT be touched after the call to ->make_request_fn.
1719 void generic_make_request(struct bio
*bio
)
1721 struct bio_list bio_list_on_stack
;
1723 if (!generic_make_request_checks(bio
))
1727 * We only want one ->make_request_fn to be active at a time, else
1728 * stack usage with stacked devices could be a problem. So use
1729 * current->bio_list to keep a list of requests submited by a
1730 * make_request_fn function. current->bio_list is also used as a
1731 * flag to say if generic_make_request is currently active in this
1732 * task or not. If it is NULL, then no make_request is active. If
1733 * it is non-NULL, then a make_request is active, and new requests
1734 * should be added at the tail
1736 if (current
->bio_list
) {
1737 bio_list_add(current
->bio_list
, bio
);
1741 /* following loop may be a bit non-obvious, and so deserves some
1743 * Before entering the loop, bio->bi_next is NULL (as all callers
1744 * ensure that) so we have a list with a single bio.
1745 * We pretend that we have just taken it off a longer list, so
1746 * we assign bio_list to a pointer to the bio_list_on_stack,
1747 * thus initialising the bio_list of new bios to be
1748 * added. ->make_request() may indeed add some more bios
1749 * through a recursive call to generic_make_request. If it
1750 * did, we find a non-NULL value in bio_list and re-enter the loop
1751 * from the top. In this case we really did just take the bio
1752 * of the top of the list (no pretending) and so remove it from
1753 * bio_list, and call into ->make_request() again.
1755 BUG_ON(bio
->bi_next
);
1756 bio_list_init(&bio_list_on_stack
);
1757 current
->bio_list
= &bio_list_on_stack
;
1759 struct request_queue
*q
= bdev_get_queue(bio
->bi_bdev
);
1761 q
->make_request_fn(q
, bio
);
1763 bio
= bio_list_pop(current
->bio_list
);
1765 current
->bio_list
= NULL
; /* deactivate */
1767 EXPORT_SYMBOL(generic_make_request
);
1770 * submit_bio - submit a bio to the block device layer for I/O
1771 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1772 * @bio: The &struct bio which describes the I/O
1774 * submit_bio() is very similar in purpose to generic_make_request(), and
1775 * uses that function to do most of the work. Both are fairly rough
1776 * interfaces; @bio must be presetup and ready for I/O.
1779 void submit_bio(int rw
, struct bio
*bio
)
1781 int count
= bio_sectors(bio
);
1786 * If it's a regular read/write or a barrier with data attached,
1787 * go through the normal accounting stuff before submission.
1789 if (bio_has_data(bio
) && !(rw
& REQ_DISCARD
)) {
1791 count_vm_events(PGPGOUT
, count
);
1793 task_io_account_read(bio
->bi_size
);
1794 count_vm_events(PGPGIN
, count
);
1797 if (unlikely(block_dump
)) {
1798 char b
[BDEVNAME_SIZE
];
1799 printk(KERN_DEBUG
"%s(%d): %s block %Lu on %s (%u sectors)\n",
1800 current
->comm
, task_pid_nr(current
),
1801 (rw
& WRITE
) ? "WRITE" : "READ",
1802 (unsigned long long)bio
->bi_sector
,
1803 bdevname(bio
->bi_bdev
, b
),
1808 generic_make_request(bio
);
1810 EXPORT_SYMBOL(submit_bio
);
1813 * blk_rq_check_limits - Helper function to check a request for the queue limit
1815 * @rq: the request being checked
1818 * @rq may have been made based on weaker limitations of upper-level queues
1819 * in request stacking drivers, and it may violate the limitation of @q.
1820 * Since the block layer and the underlying device driver trust @rq
1821 * after it is inserted to @q, it should be checked against @q before
1822 * the insertion using this generic function.
1824 * This function should also be useful for request stacking drivers
1825 * in some cases below, so export this function.
1826 * Request stacking drivers like request-based dm may change the queue
1827 * limits while requests are in the queue (e.g. dm's table swapping).
1828 * Such request stacking drivers should check those requests agaist
1829 * the new queue limits again when they dispatch those requests,
1830 * although such checkings are also done against the old queue limits
1831 * when submitting requests.
1833 int blk_rq_check_limits(struct request_queue
*q
, struct request
*rq
)
1835 if (rq
->cmd_flags
& REQ_DISCARD
)
1838 if (blk_rq_sectors(rq
) > queue_max_sectors(q
) ||
1839 blk_rq_bytes(rq
) > queue_max_hw_sectors(q
) << 9) {
1840 printk(KERN_ERR
"%s: over max size limit.\n", __func__
);
1845 * queue's settings related to segment counting like q->bounce_pfn
1846 * may differ from that of other stacking queues.
1847 * Recalculate it to check the request correctly on this queue's
1850 blk_recalc_rq_segments(rq
);
1851 if (rq
->nr_phys_segments
> queue_max_segments(q
)) {
1852 printk(KERN_ERR
"%s: over max segments limit.\n", __func__
);
1858 EXPORT_SYMBOL_GPL(blk_rq_check_limits
);
1861 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1862 * @q: the queue to submit the request
1863 * @rq: the request being queued
1865 int blk_insert_cloned_request(struct request_queue
*q
, struct request
*rq
)
1867 unsigned long flags
;
1868 int where
= ELEVATOR_INSERT_BACK
;
1870 if (blk_rq_check_limits(q
, rq
))
1874 should_fail_request(&rq
->rq_disk
->part0
, blk_rq_bytes(rq
)))
1877 spin_lock_irqsave(q
->queue_lock
, flags
);
1878 if (unlikely(blk_queue_dead(q
))) {
1879 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1884 * Submitting request must be dequeued before calling this function
1885 * because it will be linked to another request_queue
1887 BUG_ON(blk_queued_rq(rq
));
1889 if (rq
->cmd_flags
& (REQ_FLUSH
|REQ_FUA
))
1890 where
= ELEVATOR_INSERT_FLUSH
;
1892 add_acct_request(q
, rq
, where
);
1893 if (where
== ELEVATOR_INSERT_FLUSH
)
1895 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1899 EXPORT_SYMBOL_GPL(blk_insert_cloned_request
);
1902 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1903 * @rq: request to examine
1906 * A request could be merge of IOs which require different failure
1907 * handling. This function determines the number of bytes which
1908 * can be failed from the beginning of the request without
1909 * crossing into area which need to be retried further.
1912 * The number of bytes to fail.
1915 * queue_lock must be held.
1917 unsigned int blk_rq_err_bytes(const struct request
*rq
)
1919 unsigned int ff
= rq
->cmd_flags
& REQ_FAILFAST_MASK
;
1920 unsigned int bytes
= 0;
1923 if (!(rq
->cmd_flags
& REQ_MIXED_MERGE
))
1924 return blk_rq_bytes(rq
);
1927 * Currently the only 'mixing' which can happen is between
1928 * different fastfail types. We can safely fail portions
1929 * which have all the failfast bits that the first one has -
1930 * the ones which are at least as eager to fail as the first
1933 for (bio
= rq
->bio
; bio
; bio
= bio
->bi_next
) {
1934 if ((bio
->bi_rw
& ff
) != ff
)
1936 bytes
+= bio
->bi_size
;
1939 /* this could lead to infinite loop */
1940 BUG_ON(blk_rq_bytes(rq
) && !bytes
);
1943 EXPORT_SYMBOL_GPL(blk_rq_err_bytes
);
1945 static void blk_account_io_completion(struct request
*req
, unsigned int bytes
)
1947 if (blk_do_io_stat(req
)) {
1948 const int rw
= rq_data_dir(req
);
1949 struct hd_struct
*part
;
1952 cpu
= part_stat_lock();
1954 part_stat_add(cpu
, part
, sectors
[rw
], bytes
>> 9);
1959 static void blk_account_io_done(struct request
*req
)
1962 * Account IO completion. flush_rq isn't accounted as a
1963 * normal IO on queueing nor completion. Accounting the
1964 * containing request is enough.
1966 if (blk_do_io_stat(req
) && !(req
->cmd_flags
& REQ_FLUSH_SEQ
)) {
1967 unsigned long duration
= jiffies
- req
->start_time
;
1968 const int rw
= rq_data_dir(req
);
1969 struct hd_struct
*part
;
1972 cpu
= part_stat_lock();
1975 part_stat_inc(cpu
, part
, ios
[rw
]);
1976 part_stat_add(cpu
, part
, ticks
[rw
], duration
);
1977 part_round_stats(cpu
, part
);
1978 part_dec_in_flight(part
, rw
);
1980 hd_struct_put(part
);
1986 * blk_peek_request - peek at the top of a request queue
1987 * @q: request queue to peek at
1990 * Return the request at the top of @q. The returned request
1991 * should be started using blk_start_request() before LLD starts
1995 * Pointer to the request at the top of @q if available. Null
1999 * queue_lock must be held.
2001 struct request
*blk_peek_request(struct request_queue
*q
)
2006 while ((rq
= __elv_next_request(q
)) != NULL
) {
2007 if (!(rq
->cmd_flags
& REQ_STARTED
)) {
2009 * This is the first time the device driver
2010 * sees this request (possibly after
2011 * requeueing). Notify IO scheduler.
2013 if (rq
->cmd_flags
& REQ_SORTED
)
2014 elv_activate_rq(q
, rq
);
2017 * just mark as started even if we don't start
2018 * it, a request that has been delayed should
2019 * not be passed by new incoming requests
2021 rq
->cmd_flags
|= REQ_STARTED
;
2022 trace_block_rq_issue(q
, rq
);
2025 if (!q
->boundary_rq
|| q
->boundary_rq
== rq
) {
2026 q
->end_sector
= rq_end_sector(rq
);
2027 q
->boundary_rq
= NULL
;
2030 if (rq
->cmd_flags
& REQ_DONTPREP
)
2033 if (q
->dma_drain_size
&& blk_rq_bytes(rq
)) {
2035 * make sure space for the drain appears we
2036 * know we can do this because max_hw_segments
2037 * has been adjusted to be one fewer than the
2040 rq
->nr_phys_segments
++;
2046 ret
= q
->prep_rq_fn(q
, rq
);
2047 if (ret
== BLKPREP_OK
) {
2049 } else if (ret
== BLKPREP_DEFER
) {
2051 * the request may have been (partially) prepped.
2052 * we need to keep this request in the front to
2053 * avoid resource deadlock. REQ_STARTED will
2054 * prevent other fs requests from passing this one.
2056 if (q
->dma_drain_size
&& blk_rq_bytes(rq
) &&
2057 !(rq
->cmd_flags
& REQ_DONTPREP
)) {
2059 * remove the space for the drain we added
2060 * so that we don't add it again
2062 --rq
->nr_phys_segments
;
2067 } else if (ret
== BLKPREP_KILL
) {
2068 rq
->cmd_flags
|= REQ_QUIET
;
2070 * Mark this request as started so we don't trigger
2071 * any debug logic in the end I/O path.
2073 blk_start_request(rq
);
2074 __blk_end_request_all(rq
, -EIO
);
2076 printk(KERN_ERR
"%s: bad return=%d\n", __func__
, ret
);
2083 EXPORT_SYMBOL(blk_peek_request
);
2085 void blk_dequeue_request(struct request
*rq
)
2087 struct request_queue
*q
= rq
->q
;
2089 BUG_ON(list_empty(&rq
->queuelist
));
2090 BUG_ON(ELV_ON_HASH(rq
));
2092 list_del_init(&rq
->queuelist
);
2095 * the time frame between a request being removed from the lists
2096 * and to it is freed is accounted as io that is in progress at
2099 if (blk_account_rq(rq
)) {
2100 q
->in_flight
[rq_is_sync(rq
)]++;
2101 set_io_start_time_ns(rq
);
2106 * blk_start_request - start request processing on the driver
2107 * @req: request to dequeue
2110 * Dequeue @req and start timeout timer on it. This hands off the
2111 * request to the driver.
2113 * Block internal functions which don't want to start timer should
2114 * call blk_dequeue_request().
2117 * queue_lock must be held.
2119 void blk_start_request(struct request
*req
)
2121 blk_dequeue_request(req
);
2124 * We are now handing the request to the hardware, initialize
2125 * resid_len to full count and add the timeout handler.
2127 req
->resid_len
= blk_rq_bytes(req
);
2128 if (unlikely(blk_bidi_rq(req
)))
2129 req
->next_rq
->resid_len
= blk_rq_bytes(req
->next_rq
);
2133 EXPORT_SYMBOL(blk_start_request
);
2136 * blk_fetch_request - fetch a request from a request queue
2137 * @q: request queue to fetch a request from
2140 * Return the request at the top of @q. The request is started on
2141 * return and LLD can start processing it immediately.
2144 * Pointer to the request at the top of @q if available. Null
2148 * queue_lock must be held.
2150 struct request
*blk_fetch_request(struct request_queue
*q
)
2154 rq
= blk_peek_request(q
);
2156 blk_start_request(rq
);
2159 EXPORT_SYMBOL(blk_fetch_request
);
2162 * blk_update_request - Special helper function for request stacking drivers
2163 * @req: the request being processed
2164 * @error: %0 for success, < %0 for error
2165 * @nr_bytes: number of bytes to complete @req
2168 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2169 * the request structure even if @req doesn't have leftover.
2170 * If @req has leftover, sets it up for the next range of segments.
2172 * This special helper function is only for request stacking drivers
2173 * (e.g. request-based dm) so that they can handle partial completion.
2174 * Actual device drivers should use blk_end_request instead.
2176 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2177 * %false return from this function.
2180 * %false - this request doesn't have any more data
2181 * %true - this request has more data
2183 bool blk_update_request(struct request
*req
, int error
, unsigned int nr_bytes
)
2185 int total_bytes
, bio_nbytes
, next_idx
= 0;
2191 trace_block_rq_complete(req
->q
, req
);
2194 * For fs requests, rq is just carrier of independent bio's
2195 * and each partial completion should be handled separately.
2196 * Reset per-request error on each partial completion.
2198 * TODO: tj: This is too subtle. It would be better to let
2199 * low level drivers do what they see fit.
2201 if (req
->cmd_type
== REQ_TYPE_FS
)
2204 if (error
&& req
->cmd_type
== REQ_TYPE_FS
&&
2205 !(req
->cmd_flags
& REQ_QUIET
)) {
2210 error_type
= "recoverable transport";
2213 error_type
= "critical target";
2216 error_type
= "critical nexus";
2223 printk(KERN_ERR
"end_request: %s error, dev %s, sector %llu\n",
2224 error_type
, req
->rq_disk
? req
->rq_disk
->disk_name
: "?",
2225 (unsigned long long)blk_rq_pos(req
));
2228 blk_account_io_completion(req
, nr_bytes
);
2230 total_bytes
= bio_nbytes
= 0;
2231 while ((bio
= req
->bio
) != NULL
) {
2234 if (nr_bytes
>= bio
->bi_size
) {
2235 req
->bio
= bio
->bi_next
;
2236 nbytes
= bio
->bi_size
;
2237 req_bio_endio(req
, bio
, nbytes
, error
);
2241 int idx
= bio
->bi_idx
+ next_idx
;
2243 if (unlikely(idx
>= bio
->bi_vcnt
)) {
2244 blk_dump_rq_flags(req
, "__end_that");
2245 printk(KERN_ERR
"%s: bio idx %d >= vcnt %d\n",
2246 __func__
, idx
, bio
->bi_vcnt
);
2250 nbytes
= bio_iovec_idx(bio
, idx
)->bv_len
;
2251 BIO_BUG_ON(nbytes
> bio
->bi_size
);
2254 * not a complete bvec done
2256 if (unlikely(nbytes
> nr_bytes
)) {
2257 bio_nbytes
+= nr_bytes
;
2258 total_bytes
+= nr_bytes
;
2263 * advance to the next vector
2266 bio_nbytes
+= nbytes
;
2269 total_bytes
+= nbytes
;
2275 * end more in this run, or just return 'not-done'
2277 if (unlikely(nr_bytes
<= 0))
2287 * Reset counters so that the request stacking driver
2288 * can find how many bytes remain in the request
2291 req
->__data_len
= 0;
2296 * if the request wasn't completed, update state
2299 req_bio_endio(req
, bio
, bio_nbytes
, error
);
2300 bio
->bi_idx
+= next_idx
;
2301 bio_iovec(bio
)->bv_offset
+= nr_bytes
;
2302 bio_iovec(bio
)->bv_len
-= nr_bytes
;
2305 req
->__data_len
-= total_bytes
;
2306 req
->buffer
= bio_data(req
->bio
);
2308 /* update sector only for requests with clear definition of sector */
2309 if (req
->cmd_type
== REQ_TYPE_FS
|| (req
->cmd_flags
& REQ_DISCARD
))
2310 req
->__sector
+= total_bytes
>> 9;
2312 /* mixed attributes always follow the first bio */
2313 if (req
->cmd_flags
& REQ_MIXED_MERGE
) {
2314 req
->cmd_flags
&= ~REQ_FAILFAST_MASK
;
2315 req
->cmd_flags
|= req
->bio
->bi_rw
& REQ_FAILFAST_MASK
;
2319 * If total number of sectors is less than the first segment
2320 * size, something has gone terribly wrong.
2322 if (blk_rq_bytes(req
) < blk_rq_cur_bytes(req
)) {
2323 blk_dump_rq_flags(req
, "request botched");
2324 req
->__data_len
= blk_rq_cur_bytes(req
);
2327 /* recalculate the number of segments */
2328 blk_recalc_rq_segments(req
);
2332 EXPORT_SYMBOL_GPL(blk_update_request
);
2334 static bool blk_update_bidi_request(struct request
*rq
, int error
,
2335 unsigned int nr_bytes
,
2336 unsigned int bidi_bytes
)
2338 if (blk_update_request(rq
, error
, nr_bytes
))
2341 /* Bidi request must be completed as a whole */
2342 if (unlikely(blk_bidi_rq(rq
)) &&
2343 blk_update_request(rq
->next_rq
, error
, bidi_bytes
))
2346 if (blk_queue_add_random(rq
->q
))
2347 add_disk_randomness(rq
->rq_disk
);
2353 * blk_unprep_request - unprepare a request
2356 * This function makes a request ready for complete resubmission (or
2357 * completion). It happens only after all error handling is complete,
2358 * so represents the appropriate moment to deallocate any resources
2359 * that were allocated to the request in the prep_rq_fn. The queue
2360 * lock is held when calling this.
2362 void blk_unprep_request(struct request
*req
)
2364 struct request_queue
*q
= req
->q
;
2366 req
->cmd_flags
&= ~REQ_DONTPREP
;
2367 if (q
->unprep_rq_fn
)
2368 q
->unprep_rq_fn(q
, req
);
2370 EXPORT_SYMBOL_GPL(blk_unprep_request
);
2373 * queue lock must be held
2375 static void blk_finish_request(struct request
*req
, int error
)
2377 if (blk_rq_tagged(req
))
2378 blk_queue_end_tag(req
->q
, req
);
2380 BUG_ON(blk_queued_rq(req
));
2382 if (unlikely(laptop_mode
) && req
->cmd_type
== REQ_TYPE_FS
)
2383 laptop_io_completion(&req
->q
->backing_dev_info
);
2385 blk_delete_timer(req
);
2387 if (req
->cmd_flags
& REQ_DONTPREP
)
2388 blk_unprep_request(req
);
2391 blk_account_io_done(req
);
2394 req
->end_io(req
, error
);
2396 if (blk_bidi_rq(req
))
2397 __blk_put_request(req
->next_rq
->q
, req
->next_rq
);
2399 __blk_put_request(req
->q
, req
);
2404 * blk_end_bidi_request - Complete a bidi request
2405 * @rq: the request to complete
2406 * @error: %0 for success, < %0 for error
2407 * @nr_bytes: number of bytes to complete @rq
2408 * @bidi_bytes: number of bytes to complete @rq->next_rq
2411 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2412 * Drivers that supports bidi can safely call this member for any
2413 * type of request, bidi or uni. In the later case @bidi_bytes is
2417 * %false - we are done with this request
2418 * %true - still buffers pending for this request
2420 static bool blk_end_bidi_request(struct request
*rq
, int error
,
2421 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2423 struct request_queue
*q
= rq
->q
;
2424 unsigned long flags
;
2426 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2429 spin_lock_irqsave(q
->queue_lock
, flags
);
2430 blk_finish_request(rq
, error
);
2431 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2437 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2438 * @rq: the request to complete
2439 * @error: %0 for success, < %0 for error
2440 * @nr_bytes: number of bytes to complete @rq
2441 * @bidi_bytes: number of bytes to complete @rq->next_rq
2444 * Identical to blk_end_bidi_request() except that queue lock is
2445 * assumed to be locked on entry and remains so on return.
2448 * %false - we are done with this request
2449 * %true - still buffers pending for this request
2451 bool __blk_end_bidi_request(struct request
*rq
, int error
,
2452 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2454 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2457 blk_finish_request(rq
, error
);
2463 * blk_end_request - Helper function for drivers to complete the request.
2464 * @rq: the request being processed
2465 * @error: %0 for success, < %0 for error
2466 * @nr_bytes: number of bytes to complete
2469 * Ends I/O on a number of bytes attached to @rq.
2470 * If @rq has leftover, sets it up for the next range of segments.
2473 * %false - we are done with this request
2474 * %true - still buffers pending for this request
2476 bool blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2478 return blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2480 EXPORT_SYMBOL(blk_end_request
);
2483 * blk_end_request_all - Helper function for drives to finish the request.
2484 * @rq: the request to finish
2485 * @error: %0 for success, < %0 for error
2488 * Completely finish @rq.
2490 void blk_end_request_all(struct request
*rq
, int error
)
2493 unsigned int bidi_bytes
= 0;
2495 if (unlikely(blk_bidi_rq(rq
)))
2496 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2498 pending
= blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2501 EXPORT_SYMBOL(blk_end_request_all
);
2504 * blk_end_request_cur - Helper function to finish the current request chunk.
2505 * @rq: the request to finish the current chunk for
2506 * @error: %0 for success, < %0 for error
2509 * Complete the current consecutively mapped chunk from @rq.
2512 * %false - we are done with this request
2513 * %true - still buffers pending for this request
2515 bool blk_end_request_cur(struct request
*rq
, int error
)
2517 return blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2519 EXPORT_SYMBOL(blk_end_request_cur
);
2522 * blk_end_request_err - Finish a request till the next failure boundary.
2523 * @rq: the request to finish till the next failure boundary for
2524 * @error: must be negative errno
2527 * Complete @rq till the next failure boundary.
2530 * %false - we are done with this request
2531 * %true - still buffers pending for this request
2533 bool blk_end_request_err(struct request
*rq
, int error
)
2535 WARN_ON(error
>= 0);
2536 return blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2538 EXPORT_SYMBOL_GPL(blk_end_request_err
);
2541 * __blk_end_request - Helper function for drivers to complete the request.
2542 * @rq: the request being processed
2543 * @error: %0 for success, < %0 for error
2544 * @nr_bytes: number of bytes to complete
2547 * Must be called with queue lock held unlike blk_end_request().
2550 * %false - we are done with this request
2551 * %true - still buffers pending for this request
2553 bool __blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2555 return __blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2557 EXPORT_SYMBOL(__blk_end_request
);
2560 * __blk_end_request_all - Helper function for drives to finish the request.
2561 * @rq: the request to finish
2562 * @error: %0 for success, < %0 for error
2565 * Completely finish @rq. Must be called with queue lock held.
2567 void __blk_end_request_all(struct request
*rq
, int error
)
2570 unsigned int bidi_bytes
= 0;
2572 if (unlikely(blk_bidi_rq(rq
)))
2573 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2575 pending
= __blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2578 EXPORT_SYMBOL(__blk_end_request_all
);
2581 * __blk_end_request_cur - Helper function to finish the current request chunk.
2582 * @rq: the request to finish the current chunk for
2583 * @error: %0 for success, < %0 for error
2586 * Complete the current consecutively mapped chunk from @rq. Must
2587 * be called with queue lock held.
2590 * %false - we are done with this request
2591 * %true - still buffers pending for this request
2593 bool __blk_end_request_cur(struct request
*rq
, int error
)
2595 return __blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2597 EXPORT_SYMBOL(__blk_end_request_cur
);
2600 * __blk_end_request_err - Finish a request till the next failure boundary.
2601 * @rq: the request to finish till the next failure boundary for
2602 * @error: must be negative errno
2605 * Complete @rq till the next failure boundary. Must be called
2606 * with queue lock held.
2609 * %false - we are done with this request
2610 * %true - still buffers pending for this request
2612 bool __blk_end_request_err(struct request
*rq
, int error
)
2614 WARN_ON(error
>= 0);
2615 return __blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2617 EXPORT_SYMBOL_GPL(__blk_end_request_err
);
2619 void blk_rq_bio_prep(struct request_queue
*q
, struct request
*rq
,
2622 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2623 rq
->cmd_flags
|= bio
->bi_rw
& REQ_WRITE
;
2625 if (bio_has_data(bio
)) {
2626 rq
->nr_phys_segments
= bio_phys_segments(q
, bio
);
2627 rq
->buffer
= bio_data(bio
);
2629 rq
->__data_len
= bio
->bi_size
;
2630 rq
->bio
= rq
->biotail
= bio
;
2633 rq
->rq_disk
= bio
->bi_bdev
->bd_disk
;
2636 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2638 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2639 * @rq: the request to be flushed
2642 * Flush all pages in @rq.
2644 void rq_flush_dcache_pages(struct request
*rq
)
2646 struct req_iterator iter
;
2647 struct bio_vec
*bvec
;
2649 rq_for_each_segment(bvec
, rq
, iter
)
2650 flush_dcache_page(bvec
->bv_page
);
2652 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages
);
2656 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2657 * @q : the queue of the device being checked
2660 * Check if underlying low-level drivers of a device are busy.
2661 * If the drivers want to export their busy state, they must set own
2662 * exporting function using blk_queue_lld_busy() first.
2664 * Basically, this function is used only by request stacking drivers
2665 * to stop dispatching requests to underlying devices when underlying
2666 * devices are busy. This behavior helps more I/O merging on the queue
2667 * of the request stacking driver and prevents I/O throughput regression
2668 * on burst I/O load.
2671 * 0 - Not busy (The request stacking driver should dispatch request)
2672 * 1 - Busy (The request stacking driver should stop dispatching request)
2674 int blk_lld_busy(struct request_queue
*q
)
2677 return q
->lld_busy_fn(q
);
2681 EXPORT_SYMBOL_GPL(blk_lld_busy
);
2684 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2685 * @rq: the clone request to be cleaned up
2688 * Free all bios in @rq for a cloned request.
2690 void blk_rq_unprep_clone(struct request
*rq
)
2694 while ((bio
= rq
->bio
) != NULL
) {
2695 rq
->bio
= bio
->bi_next
;
2700 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone
);
2703 * Copy attributes of the original request to the clone request.
2704 * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2706 static void __blk_rq_prep_clone(struct request
*dst
, struct request
*src
)
2708 dst
->cpu
= src
->cpu
;
2709 dst
->cmd_flags
= (src
->cmd_flags
& REQ_CLONE_MASK
) | REQ_NOMERGE
;
2710 dst
->cmd_type
= src
->cmd_type
;
2711 dst
->__sector
= blk_rq_pos(src
);
2712 dst
->__data_len
= blk_rq_bytes(src
);
2713 dst
->nr_phys_segments
= src
->nr_phys_segments
;
2714 dst
->ioprio
= src
->ioprio
;
2715 dst
->extra_len
= src
->extra_len
;
2719 * blk_rq_prep_clone - Helper function to setup clone request
2720 * @rq: the request to be setup
2721 * @rq_src: original request to be cloned
2722 * @bs: bio_set that bios for clone are allocated from
2723 * @gfp_mask: memory allocation mask for bio
2724 * @bio_ctr: setup function to be called for each clone bio.
2725 * Returns %0 for success, non %0 for failure.
2726 * @data: private data to be passed to @bio_ctr
2729 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2730 * The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2731 * are not copied, and copying such parts is the caller's responsibility.
2732 * Also, pages which the original bios are pointing to are not copied
2733 * and the cloned bios just point same pages.
2734 * So cloned bios must be completed before original bios, which means
2735 * the caller must complete @rq before @rq_src.
2737 int blk_rq_prep_clone(struct request
*rq
, struct request
*rq_src
,
2738 struct bio_set
*bs
, gfp_t gfp_mask
,
2739 int (*bio_ctr
)(struct bio
*, struct bio
*, void *),
2742 struct bio
*bio
, *bio_src
;
2747 blk_rq_init(NULL
, rq
);
2749 __rq_for_each_bio(bio_src
, rq_src
) {
2750 bio
= bio_alloc_bioset(gfp_mask
, bio_src
->bi_max_vecs
, bs
);
2754 __bio_clone(bio
, bio_src
);
2756 if (bio_integrity(bio_src
) &&
2757 bio_integrity_clone(bio
, bio_src
, gfp_mask
, bs
))
2760 if (bio_ctr
&& bio_ctr(bio
, bio_src
, data
))
2764 rq
->biotail
->bi_next
= bio
;
2767 rq
->bio
= rq
->biotail
= bio
;
2770 __blk_rq_prep_clone(rq
, rq_src
);
2777 blk_rq_unprep_clone(rq
);
2781 EXPORT_SYMBOL_GPL(blk_rq_prep_clone
);
2783 int kblockd_schedule_work(struct request_queue
*q
, struct work_struct
*work
)
2785 return queue_work(kblockd_workqueue
, work
);
2787 EXPORT_SYMBOL(kblockd_schedule_work
);
2789 int kblockd_schedule_delayed_work(struct request_queue
*q
,
2790 struct delayed_work
*dwork
, unsigned long delay
)
2792 return queue_delayed_work(kblockd_workqueue
, dwork
, delay
);
2794 EXPORT_SYMBOL(kblockd_schedule_delayed_work
);
2796 #define PLUG_MAGIC 0x91827364
2799 * blk_start_plug - initialize blk_plug and track it inside the task_struct
2800 * @plug: The &struct blk_plug that needs to be initialized
2803 * Tracking blk_plug inside the task_struct will help with auto-flushing the
2804 * pending I/O should the task end up blocking between blk_start_plug() and
2805 * blk_finish_plug(). This is important from a performance perspective, but
2806 * also ensures that we don't deadlock. For instance, if the task is blocking
2807 * for a memory allocation, memory reclaim could end up wanting to free a
2808 * page belonging to that request that is currently residing in our private
2809 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
2810 * this kind of deadlock.
2812 void blk_start_plug(struct blk_plug
*plug
)
2814 struct task_struct
*tsk
= current
;
2816 plug
->magic
= PLUG_MAGIC
;
2817 INIT_LIST_HEAD(&plug
->list
);
2818 INIT_LIST_HEAD(&plug
->cb_list
);
2819 plug
->should_sort
= 0;
2822 * If this is a nested plug, don't actually assign it. It will be
2823 * flushed on its own.
2827 * Store ordering should not be needed here, since a potential
2828 * preempt will imply a full memory barrier
2833 EXPORT_SYMBOL(blk_start_plug
);
2835 static int plug_rq_cmp(void *priv
, struct list_head
*a
, struct list_head
*b
)
2837 struct request
*rqa
= container_of(a
, struct request
, queuelist
);
2838 struct request
*rqb
= container_of(b
, struct request
, queuelist
);
2840 return !(rqa
->q
<= rqb
->q
);
2844 * If 'from_schedule' is true, then postpone the dispatch of requests
2845 * until a safe kblockd context. We due this to avoid accidental big
2846 * additional stack usage in driver dispatch, in places where the originally
2847 * plugger did not intend it.
2849 static void queue_unplugged(struct request_queue
*q
, unsigned int depth
,
2851 __releases(q
->queue_lock
)
2853 trace_block_unplug(q
, depth
, !from_schedule
);
2856 * Don't mess with dead queue.
2858 if (unlikely(blk_queue_dead(q
))) {
2859 spin_unlock(q
->queue_lock
);
2864 * If we are punting this to kblockd, then we can safely drop
2865 * the queue_lock before waking kblockd (which needs to take
2868 if (from_schedule
) {
2869 spin_unlock(q
->queue_lock
);
2870 blk_run_queue_async(q
);
2873 spin_unlock(q
->queue_lock
);
2878 static void flush_plug_callbacks(struct blk_plug
*plug
)
2880 LIST_HEAD(callbacks
);
2882 if (list_empty(&plug
->cb_list
))
2885 list_splice_init(&plug
->cb_list
, &callbacks
);
2887 while (!list_empty(&callbacks
)) {
2888 struct blk_plug_cb
*cb
= list_first_entry(&callbacks
,
2891 list_del(&cb
->list
);
2896 void blk_flush_plug_list(struct blk_plug
*plug
, bool from_schedule
)
2898 struct request_queue
*q
;
2899 unsigned long flags
;
2904 BUG_ON(plug
->magic
!= PLUG_MAGIC
);
2906 flush_plug_callbacks(plug
);
2907 if (list_empty(&plug
->list
))
2910 list_splice_init(&plug
->list
, &list
);
2912 if (plug
->should_sort
) {
2913 list_sort(NULL
, &list
, plug_rq_cmp
);
2914 plug
->should_sort
= 0;
2921 * Save and disable interrupts here, to avoid doing it for every
2922 * queue lock we have to take.
2924 local_irq_save(flags
);
2925 while (!list_empty(&list
)) {
2926 rq
= list_entry_rq(list
.next
);
2927 list_del_init(&rq
->queuelist
);
2931 * This drops the queue lock
2934 queue_unplugged(q
, depth
, from_schedule
);
2937 spin_lock(q
->queue_lock
);
2941 * Short-circuit if @q is dead
2943 if (unlikely(blk_queue_dead(q
))) {
2944 __blk_end_request_all(rq
, -ENODEV
);
2949 * rq is already accounted, so use raw insert
2951 if (rq
->cmd_flags
& (REQ_FLUSH
| REQ_FUA
))
2952 __elv_add_request(q
, rq
, ELEVATOR_INSERT_FLUSH
);
2954 __elv_add_request(q
, rq
, ELEVATOR_INSERT_SORT_MERGE
);
2960 * This drops the queue lock
2963 queue_unplugged(q
, depth
, from_schedule
);
2965 local_irq_restore(flags
);
2968 void blk_finish_plug(struct blk_plug
*plug
)
2970 blk_flush_plug_list(plug
, false);
2972 if (plug
== current
->plug
)
2973 current
->plug
= NULL
;
2975 EXPORT_SYMBOL(blk_finish_plug
);
2977 int __init
blk_dev_init(void)
2979 BUILD_BUG_ON(__REQ_NR_BITS
> 8 *
2980 sizeof(((struct request
*)0)->cmd_flags
));
2982 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
2983 kblockd_workqueue
= alloc_workqueue("kblockd",
2984 WQ_MEM_RECLAIM
| WQ_HIGHPRI
, 0);
2985 if (!kblockd_workqueue
)
2986 panic("Failed to create kblockd\n");
2988 request_cachep
= kmem_cache_create("blkdev_requests",
2989 sizeof(struct request
), 0, SLAB_PANIC
, NULL
);
2991 blk_requestq_cachep
= kmem_cache_create("blkdev_queue",
2992 sizeof(struct request_queue
), 0, SLAB_PANIC
, NULL
);