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/blk-mq.h>
20 #include <linux/highmem.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/blk-cgroup.h>
36 #include <linux/debugfs.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/block.h>
43 #include "blk-mq-debugfs.h"
44 #include "blk-mq-sched.h"
47 #ifdef CONFIG_DEBUG_FS
48 struct dentry
*blk_debugfs_root
;
51 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap
);
52 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap
);
53 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete
);
54 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split
);
55 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug
);
57 DEFINE_IDA(blk_queue_ida
);
60 * For the allocated request tables
62 struct kmem_cache
*request_cachep
;
65 * For queue allocation
67 struct kmem_cache
*blk_requestq_cachep
;
70 * Controlling structure to kblockd
72 static struct workqueue_struct
*kblockd_workqueue
;
74 static void blk_clear_congested(struct request_list
*rl
, int sync
)
76 #ifdef CONFIG_CGROUP_WRITEBACK
77 clear_wb_congested(rl
->blkg
->wb_congested
, sync
);
80 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
81 * flip its congestion state for events on other blkcgs.
83 if (rl
== &rl
->q
->root_rl
)
84 clear_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
88 static void blk_set_congested(struct request_list
*rl
, int sync
)
90 #ifdef CONFIG_CGROUP_WRITEBACK
91 set_wb_congested(rl
->blkg
->wb_congested
, sync
);
93 /* see blk_clear_congested() */
94 if (rl
== &rl
->q
->root_rl
)
95 set_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
99 void blk_queue_congestion_threshold(struct request_queue
*q
)
103 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) + 1;
104 if (nr
> q
->nr_requests
)
106 q
->nr_congestion_on
= nr
;
108 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) - (q
->nr_requests
/ 16) - 1;
111 q
->nr_congestion_off
= nr
;
114 void blk_rq_init(struct request_queue
*q
, struct request
*rq
)
116 memset(rq
, 0, sizeof(*rq
));
118 INIT_LIST_HEAD(&rq
->queuelist
);
119 INIT_LIST_HEAD(&rq
->timeout_list
);
122 rq
->__sector
= (sector_t
) -1;
123 INIT_HLIST_NODE(&rq
->hash
);
124 RB_CLEAR_NODE(&rq
->rb_node
);
126 rq
->internal_tag
= -1;
127 rq
->start_time
= jiffies
;
128 set_start_time_ns(rq
);
131 EXPORT_SYMBOL(blk_rq_init
);
133 static void req_bio_endio(struct request
*rq
, struct bio
*bio
,
134 unsigned int nbytes
, int error
)
137 bio
->bi_error
= error
;
139 if (unlikely(rq
->rq_flags
& RQF_QUIET
))
140 bio_set_flag(bio
, BIO_QUIET
);
142 bio_advance(bio
, nbytes
);
144 /* don't actually finish bio if it's part of flush sequence */
145 if (bio
->bi_iter
.bi_size
== 0 && !(rq
->rq_flags
& RQF_FLUSH_SEQ
))
149 void blk_dump_rq_flags(struct request
*rq
, char *msg
)
151 printk(KERN_INFO
"%s: dev %s: flags=%llx\n", msg
,
152 rq
->rq_disk
? rq
->rq_disk
->disk_name
: "?",
153 (unsigned long long) rq
->cmd_flags
);
155 printk(KERN_INFO
" sector %llu, nr/cnr %u/%u\n",
156 (unsigned long long)blk_rq_pos(rq
),
157 blk_rq_sectors(rq
), blk_rq_cur_sectors(rq
));
158 printk(KERN_INFO
" bio %p, biotail %p, len %u\n",
159 rq
->bio
, rq
->biotail
, blk_rq_bytes(rq
));
161 EXPORT_SYMBOL(blk_dump_rq_flags
);
163 static void blk_delay_work(struct work_struct
*work
)
165 struct request_queue
*q
;
167 q
= container_of(work
, struct request_queue
, delay_work
.work
);
168 spin_lock_irq(q
->queue_lock
);
170 spin_unlock_irq(q
->queue_lock
);
174 * blk_delay_queue - restart queueing after defined interval
175 * @q: The &struct request_queue in question
176 * @msecs: Delay in msecs
179 * Sometimes queueing needs to be postponed for a little while, to allow
180 * resources to come back. This function will make sure that queueing is
181 * restarted around the specified time. Queue lock must be held.
183 void blk_delay_queue(struct request_queue
*q
, unsigned long msecs
)
185 if (likely(!blk_queue_dead(q
)))
186 queue_delayed_work(kblockd_workqueue
, &q
->delay_work
,
187 msecs_to_jiffies(msecs
));
189 EXPORT_SYMBOL(blk_delay_queue
);
192 * blk_start_queue_async - asynchronously restart a previously stopped queue
193 * @q: The &struct request_queue in question
196 * blk_start_queue_async() will clear the stop flag on the queue, and
197 * ensure that the request_fn for the queue is run from an async
200 void blk_start_queue_async(struct request_queue
*q
)
202 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
203 blk_run_queue_async(q
);
205 EXPORT_SYMBOL(blk_start_queue_async
);
208 * blk_start_queue - restart a previously stopped queue
209 * @q: The &struct request_queue in question
212 * blk_start_queue() will clear the stop flag on the queue, and call
213 * the request_fn for the queue if it was in a stopped state when
214 * entered. Also see blk_stop_queue(). Queue lock must be held.
216 void blk_start_queue(struct request_queue
*q
)
218 WARN_ON(!irqs_disabled());
220 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
223 EXPORT_SYMBOL(blk_start_queue
);
226 * blk_stop_queue - stop a queue
227 * @q: The &struct request_queue in question
230 * The Linux block layer assumes that a block driver will consume all
231 * entries on the request queue when the request_fn strategy is called.
232 * Often this will not happen, because of hardware limitations (queue
233 * depth settings). If a device driver gets a 'queue full' response,
234 * or if it simply chooses not to queue more I/O at one point, it can
235 * call this function to prevent the request_fn from being called until
236 * the driver has signalled it's ready to go again. This happens by calling
237 * blk_start_queue() to restart queue operations. Queue lock must be held.
239 void blk_stop_queue(struct request_queue
*q
)
241 cancel_delayed_work(&q
->delay_work
);
242 queue_flag_set(QUEUE_FLAG_STOPPED
, q
);
244 EXPORT_SYMBOL(blk_stop_queue
);
247 * blk_sync_queue - cancel any pending callbacks on a queue
251 * The block layer may perform asynchronous callback activity
252 * on a queue, such as calling the unplug function after a timeout.
253 * A block device may call blk_sync_queue to ensure that any
254 * such activity is cancelled, thus allowing it to release resources
255 * that the callbacks might use. The caller must already have made sure
256 * that its ->make_request_fn will not re-add plugging prior to calling
259 * This function does not cancel any asynchronous activity arising
260 * out of elevator or throttling code. That would require elevator_exit()
261 * and blkcg_exit_queue() to be called with queue lock initialized.
264 void blk_sync_queue(struct request_queue
*q
)
266 del_timer_sync(&q
->timeout
);
269 struct blk_mq_hw_ctx
*hctx
;
272 queue_for_each_hw_ctx(q
, hctx
, i
)
273 cancel_delayed_work_sync(&hctx
->run_work
);
275 cancel_delayed_work_sync(&q
->delay_work
);
278 EXPORT_SYMBOL(blk_sync_queue
);
281 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
282 * @q: The queue to run
285 * Invoke request handling on a queue if there are any pending requests.
286 * May be used to restart request handling after a request has completed.
287 * This variant runs the queue whether or not the queue has been
288 * stopped. Must be called with the queue lock held and interrupts
289 * disabled. See also @blk_run_queue.
291 inline void __blk_run_queue_uncond(struct request_queue
*q
)
293 if (unlikely(blk_queue_dead(q
)))
297 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
298 * the queue lock internally. As a result multiple threads may be
299 * running such a request function concurrently. Keep track of the
300 * number of active request_fn invocations such that blk_drain_queue()
301 * can wait until all these request_fn calls have finished.
303 q
->request_fn_active
++;
305 q
->request_fn_active
--;
307 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond
);
310 * __blk_run_queue - run a single device queue
311 * @q: The queue to run
314 * See @blk_run_queue. This variant must be called with the queue lock
315 * held and interrupts disabled.
317 void __blk_run_queue(struct request_queue
*q
)
319 if (unlikely(blk_queue_stopped(q
)))
322 __blk_run_queue_uncond(q
);
324 EXPORT_SYMBOL(__blk_run_queue
);
327 * blk_run_queue_async - run a single device queue in workqueue context
328 * @q: The queue to run
331 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
332 * of us. The caller must hold the queue lock.
334 void blk_run_queue_async(struct request_queue
*q
)
336 if (likely(!blk_queue_stopped(q
) && !blk_queue_dead(q
)))
337 mod_delayed_work(kblockd_workqueue
, &q
->delay_work
, 0);
339 EXPORT_SYMBOL(blk_run_queue_async
);
342 * blk_run_queue - run a single device queue
343 * @q: The queue to run
346 * Invoke request handling on this queue, if it has pending work to do.
347 * May be used to restart queueing when a request has completed.
349 void blk_run_queue(struct request_queue
*q
)
353 spin_lock_irqsave(q
->queue_lock
, flags
);
355 spin_unlock_irqrestore(q
->queue_lock
, flags
);
357 EXPORT_SYMBOL(blk_run_queue
);
359 void blk_put_queue(struct request_queue
*q
)
361 kobject_put(&q
->kobj
);
363 EXPORT_SYMBOL(blk_put_queue
);
366 * __blk_drain_queue - drain requests from request_queue
368 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
370 * Drain requests from @q. If @drain_all is set, all requests are drained.
371 * If not, only ELVPRIV requests are drained. The caller is responsible
372 * for ensuring that no new requests which need to be drained are queued.
374 static void __blk_drain_queue(struct request_queue
*q
, bool drain_all
)
375 __releases(q
->queue_lock
)
376 __acquires(q
->queue_lock
)
380 lockdep_assert_held(q
->queue_lock
);
386 * The caller might be trying to drain @q before its
387 * elevator is initialized.
390 elv_drain_elevator(q
);
392 blkcg_drain_queue(q
);
395 * This function might be called on a queue which failed
396 * driver init after queue creation or is not yet fully
397 * active yet. Some drivers (e.g. fd and loop) get unhappy
398 * in such cases. Kick queue iff dispatch queue has
399 * something on it and @q has request_fn set.
401 if (!list_empty(&q
->queue_head
) && q
->request_fn
)
404 drain
|= q
->nr_rqs_elvpriv
;
405 drain
|= q
->request_fn_active
;
408 * Unfortunately, requests are queued at and tracked from
409 * multiple places and there's no single counter which can
410 * be drained. Check all the queues and counters.
413 struct blk_flush_queue
*fq
= blk_get_flush_queue(q
, NULL
);
414 drain
|= !list_empty(&q
->queue_head
);
415 for (i
= 0; i
< 2; i
++) {
416 drain
|= q
->nr_rqs
[i
];
417 drain
|= q
->in_flight
[i
];
419 drain
|= !list_empty(&fq
->flush_queue
[i
]);
426 spin_unlock_irq(q
->queue_lock
);
430 spin_lock_irq(q
->queue_lock
);
434 * With queue marked dead, any woken up waiter will fail the
435 * allocation path, so the wakeup chaining is lost and we're
436 * left with hung waiters. We need to wake up those waiters.
439 struct request_list
*rl
;
441 blk_queue_for_each_rl(rl
, q
)
442 for (i
= 0; i
< ARRAY_SIZE(rl
->wait
); i
++)
443 wake_up_all(&rl
->wait
[i
]);
448 * blk_queue_bypass_start - enter queue bypass mode
449 * @q: queue of interest
451 * In bypass mode, only the dispatch FIFO queue of @q is used. This
452 * function makes @q enter bypass mode and drains all requests which were
453 * throttled or issued before. On return, it's guaranteed that no request
454 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
455 * inside queue or RCU read lock.
457 void blk_queue_bypass_start(struct request_queue
*q
)
459 spin_lock_irq(q
->queue_lock
);
461 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
462 spin_unlock_irq(q
->queue_lock
);
465 * Queues start drained. Skip actual draining till init is
466 * complete. This avoids lenghty delays during queue init which
467 * can happen many times during boot.
469 if (blk_queue_init_done(q
)) {
470 spin_lock_irq(q
->queue_lock
);
471 __blk_drain_queue(q
, false);
472 spin_unlock_irq(q
->queue_lock
);
474 /* ensure blk_queue_bypass() is %true inside RCU read lock */
478 EXPORT_SYMBOL_GPL(blk_queue_bypass_start
);
481 * blk_queue_bypass_end - leave queue bypass mode
482 * @q: queue of interest
484 * Leave bypass mode and restore the normal queueing behavior.
486 void blk_queue_bypass_end(struct request_queue
*q
)
488 spin_lock_irq(q
->queue_lock
);
489 if (!--q
->bypass_depth
)
490 queue_flag_clear(QUEUE_FLAG_BYPASS
, q
);
491 WARN_ON_ONCE(q
->bypass_depth
< 0);
492 spin_unlock_irq(q
->queue_lock
);
494 EXPORT_SYMBOL_GPL(blk_queue_bypass_end
);
496 void blk_set_queue_dying(struct request_queue
*q
)
498 spin_lock_irq(q
->queue_lock
);
499 queue_flag_set(QUEUE_FLAG_DYING
, q
);
500 spin_unlock_irq(q
->queue_lock
);
503 * When queue DYING flag is set, we need to block new req
504 * entering queue, so we call blk_freeze_queue_start() to
505 * prevent I/O from crossing blk_queue_enter().
507 blk_freeze_queue_start(q
);
510 blk_mq_wake_waiters(q
);
512 struct request_list
*rl
;
514 spin_lock_irq(q
->queue_lock
);
515 blk_queue_for_each_rl(rl
, q
) {
517 wake_up(&rl
->wait
[BLK_RW_SYNC
]);
518 wake_up(&rl
->wait
[BLK_RW_ASYNC
]);
521 spin_unlock_irq(q
->queue_lock
);
524 EXPORT_SYMBOL_GPL(blk_set_queue_dying
);
527 * blk_cleanup_queue - shutdown a request queue
528 * @q: request queue to shutdown
530 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
531 * put it. All future requests will be failed immediately with -ENODEV.
533 void blk_cleanup_queue(struct request_queue
*q
)
535 spinlock_t
*lock
= q
->queue_lock
;
537 /* mark @q DYING, no new request or merges will be allowed afterwards */
538 mutex_lock(&q
->sysfs_lock
);
539 blk_set_queue_dying(q
);
543 * A dying queue is permanently in bypass mode till released. Note
544 * that, unlike blk_queue_bypass_start(), we aren't performing
545 * synchronize_rcu() after entering bypass mode to avoid the delay
546 * as some drivers create and destroy a lot of queues while
547 * probing. This is still safe because blk_release_queue() will be
548 * called only after the queue refcnt drops to zero and nothing,
549 * RCU or not, would be traversing the queue by then.
552 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
554 queue_flag_set(QUEUE_FLAG_NOMERGES
, q
);
555 queue_flag_set(QUEUE_FLAG_NOXMERGES
, q
);
556 queue_flag_set(QUEUE_FLAG_DYING
, q
);
557 spin_unlock_irq(lock
);
558 mutex_unlock(&q
->sysfs_lock
);
561 * Drain all requests queued before DYING marking. Set DEAD flag to
562 * prevent that q->request_fn() gets invoked after draining finished.
567 __blk_drain_queue(q
, true);
569 blk_mq_debugfs_unregister_mq(q
);
572 queue_flag_set(QUEUE_FLAG_DEAD
, q
);
573 spin_unlock_irq(lock
);
575 /* for synchronous bio-based driver finish in-flight integrity i/o */
576 blk_flush_integrity();
578 /* @q won't process any more request, flush async actions */
579 del_timer_sync(&q
->backing_dev_info
->laptop_mode_wb_timer
);
583 blk_mq_free_queue(q
);
584 percpu_ref_exit(&q
->q_usage_counter
);
587 if (q
->queue_lock
!= &q
->__queue_lock
)
588 q
->queue_lock
= &q
->__queue_lock
;
589 spin_unlock_irq(lock
);
591 /* @q is and will stay empty, shutdown and put */
594 EXPORT_SYMBOL(blk_cleanup_queue
);
596 /* Allocate memory local to the request queue */
597 static void *alloc_request_simple(gfp_t gfp_mask
, void *data
)
599 struct request_queue
*q
= data
;
601 return kmem_cache_alloc_node(request_cachep
, gfp_mask
, q
->node
);
604 static void free_request_simple(void *element
, void *data
)
606 kmem_cache_free(request_cachep
, element
);
609 static void *alloc_request_size(gfp_t gfp_mask
, void *data
)
611 struct request_queue
*q
= data
;
614 rq
= kmalloc_node(sizeof(struct request
) + q
->cmd_size
, gfp_mask
,
616 if (rq
&& q
->init_rq_fn
&& q
->init_rq_fn(q
, rq
, gfp_mask
) < 0) {
623 static void free_request_size(void *element
, void *data
)
625 struct request_queue
*q
= data
;
628 q
->exit_rq_fn(q
, element
);
632 int blk_init_rl(struct request_list
*rl
, struct request_queue
*q
,
635 if (unlikely(rl
->rq_pool
))
639 rl
->count
[BLK_RW_SYNC
] = rl
->count
[BLK_RW_ASYNC
] = 0;
640 rl
->starved
[BLK_RW_SYNC
] = rl
->starved
[BLK_RW_ASYNC
] = 0;
641 init_waitqueue_head(&rl
->wait
[BLK_RW_SYNC
]);
642 init_waitqueue_head(&rl
->wait
[BLK_RW_ASYNC
]);
645 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
,
646 alloc_request_size
, free_request_size
,
647 q
, gfp_mask
, q
->node
);
649 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
,
650 alloc_request_simple
, free_request_simple
,
651 q
, gfp_mask
, q
->node
);
659 void blk_exit_rl(struct request_list
*rl
)
662 mempool_destroy(rl
->rq_pool
);
665 struct request_queue
*blk_alloc_queue(gfp_t gfp_mask
)
667 return blk_alloc_queue_node(gfp_mask
, NUMA_NO_NODE
);
669 EXPORT_SYMBOL(blk_alloc_queue
);
671 int blk_queue_enter(struct request_queue
*q
, bool nowait
)
676 if (percpu_ref_tryget_live(&q
->q_usage_counter
))
683 * read pair of barrier in blk_freeze_queue_start(),
684 * we need to order reading __PERCPU_REF_DEAD flag of
685 * .q_usage_counter and reading .mq_freeze_depth or
686 * queue dying flag, otherwise the following wait may
687 * never return if the two reads are reordered.
691 ret
= wait_event_interruptible(q
->mq_freeze_wq
,
692 !atomic_read(&q
->mq_freeze_depth
) ||
694 if (blk_queue_dying(q
))
701 void blk_queue_exit(struct request_queue
*q
)
703 percpu_ref_put(&q
->q_usage_counter
);
706 static void blk_queue_usage_counter_release(struct percpu_ref
*ref
)
708 struct request_queue
*q
=
709 container_of(ref
, struct request_queue
, q_usage_counter
);
711 wake_up_all(&q
->mq_freeze_wq
);
714 static void blk_rq_timed_out_timer(unsigned long data
)
716 struct request_queue
*q
= (struct request_queue
*)data
;
718 kblockd_schedule_work(&q
->timeout_work
);
721 struct request_queue
*blk_alloc_queue_node(gfp_t gfp_mask
, int node_id
)
723 struct request_queue
*q
;
725 q
= kmem_cache_alloc_node(blk_requestq_cachep
,
726 gfp_mask
| __GFP_ZERO
, node_id
);
730 q
->id
= ida_simple_get(&blk_queue_ida
, 0, 0, gfp_mask
);
734 q
->bio_split
= bioset_create(BIO_POOL_SIZE
, 0);
738 q
->backing_dev_info
= bdi_alloc_node(gfp_mask
, node_id
);
739 if (!q
->backing_dev_info
)
742 q
->stats
= blk_alloc_queue_stats();
746 q
->backing_dev_info
->ra_pages
=
747 (VM_MAX_READAHEAD
* 1024) / PAGE_SIZE
;
748 q
->backing_dev_info
->capabilities
= BDI_CAP_CGROUP_WRITEBACK
;
749 q
->backing_dev_info
->name
= "block";
752 setup_timer(&q
->backing_dev_info
->laptop_mode_wb_timer
,
753 laptop_mode_timer_fn
, (unsigned long) q
);
754 setup_timer(&q
->timeout
, blk_rq_timed_out_timer
, (unsigned long) q
);
755 INIT_LIST_HEAD(&q
->queue_head
);
756 INIT_LIST_HEAD(&q
->timeout_list
);
757 INIT_LIST_HEAD(&q
->icq_list
);
758 #ifdef CONFIG_BLK_CGROUP
759 INIT_LIST_HEAD(&q
->blkg_list
);
761 INIT_DELAYED_WORK(&q
->delay_work
, blk_delay_work
);
763 kobject_init(&q
->kobj
, &blk_queue_ktype
);
765 mutex_init(&q
->sysfs_lock
);
766 spin_lock_init(&q
->__queue_lock
);
769 * By default initialize queue_lock to internal lock and driver can
770 * override it later if need be.
772 q
->queue_lock
= &q
->__queue_lock
;
775 * A queue starts its life with bypass turned on to avoid
776 * unnecessary bypass on/off overhead and nasty surprises during
777 * init. The initial bypass will be finished when the queue is
778 * registered by blk_register_queue().
781 __set_bit(QUEUE_FLAG_BYPASS
, &q
->queue_flags
);
783 init_waitqueue_head(&q
->mq_freeze_wq
);
786 * Init percpu_ref in atomic mode so that it's faster to shutdown.
787 * See blk_register_queue() for details.
789 if (percpu_ref_init(&q
->q_usage_counter
,
790 blk_queue_usage_counter_release
,
791 PERCPU_REF_INIT_ATOMIC
, GFP_KERNEL
))
794 if (blkcg_init_queue(q
))
800 percpu_ref_exit(&q
->q_usage_counter
);
802 blk_free_queue_stats(q
->stats
);
804 bdi_put(q
->backing_dev_info
);
806 bioset_free(q
->bio_split
);
808 ida_simple_remove(&blk_queue_ida
, q
->id
);
810 kmem_cache_free(blk_requestq_cachep
, q
);
813 EXPORT_SYMBOL(blk_alloc_queue_node
);
816 * blk_init_queue - prepare a request queue for use with a block device
817 * @rfn: The function to be called to process requests that have been
818 * placed on the queue.
819 * @lock: Request queue spin lock
822 * If a block device wishes to use the standard request handling procedures,
823 * which sorts requests and coalesces adjacent requests, then it must
824 * call blk_init_queue(). The function @rfn will be called when there
825 * are requests on the queue that need to be processed. If the device
826 * supports plugging, then @rfn may not be called immediately when requests
827 * are available on the queue, but may be called at some time later instead.
828 * Plugged queues are generally unplugged when a buffer belonging to one
829 * of the requests on the queue is needed, or due to memory pressure.
831 * @rfn is not required, or even expected, to remove all requests off the
832 * queue, but only as many as it can handle at a time. If it does leave
833 * requests on the queue, it is responsible for arranging that the requests
834 * get dealt with eventually.
836 * The queue spin lock must be held while manipulating the requests on the
837 * request queue; this lock will be taken also from interrupt context, so irq
838 * disabling is needed for it.
840 * Function returns a pointer to the initialized request queue, or %NULL if
844 * blk_init_queue() must be paired with a blk_cleanup_queue() call
845 * when the block device is deactivated (such as at module unload).
848 struct request_queue
*blk_init_queue(request_fn_proc
*rfn
, spinlock_t
*lock
)
850 return blk_init_queue_node(rfn
, lock
, NUMA_NO_NODE
);
852 EXPORT_SYMBOL(blk_init_queue
);
854 struct request_queue
*
855 blk_init_queue_node(request_fn_proc
*rfn
, spinlock_t
*lock
, int node_id
)
857 struct request_queue
*q
;
859 q
= blk_alloc_queue_node(GFP_KERNEL
, node_id
);
865 q
->queue_lock
= lock
;
866 if (blk_init_allocated_queue(q
) < 0) {
867 blk_cleanup_queue(q
);
873 EXPORT_SYMBOL(blk_init_queue_node
);
875 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
);
878 int blk_init_allocated_queue(struct request_queue
*q
)
880 q
->fq
= blk_alloc_flush_queue(q
, NUMA_NO_NODE
, q
->cmd_size
);
884 if (q
->init_rq_fn
&& q
->init_rq_fn(q
, q
->fq
->flush_rq
, GFP_KERNEL
))
885 goto out_free_flush_queue
;
887 if (blk_init_rl(&q
->root_rl
, q
, GFP_KERNEL
))
888 goto out_exit_flush_rq
;
890 INIT_WORK(&q
->timeout_work
, blk_timeout_work
);
891 q
->queue_flags
|= QUEUE_FLAG_DEFAULT
;
894 * This also sets hw/phys segments, boundary and size
896 blk_queue_make_request(q
, blk_queue_bio
);
898 q
->sg_reserved_size
= INT_MAX
;
900 /* Protect q->elevator from elevator_change */
901 mutex_lock(&q
->sysfs_lock
);
904 if (elevator_init(q
, NULL
)) {
905 mutex_unlock(&q
->sysfs_lock
);
906 goto out_exit_flush_rq
;
909 mutex_unlock(&q
->sysfs_lock
);
914 q
->exit_rq_fn(q
, q
->fq
->flush_rq
);
915 out_free_flush_queue
:
916 blk_free_flush_queue(q
->fq
);
919 EXPORT_SYMBOL(blk_init_allocated_queue
);
921 bool blk_get_queue(struct request_queue
*q
)
923 if (likely(!blk_queue_dying(q
))) {
930 EXPORT_SYMBOL(blk_get_queue
);
932 static inline void blk_free_request(struct request_list
*rl
, struct request
*rq
)
934 if (rq
->rq_flags
& RQF_ELVPRIV
) {
935 elv_put_request(rl
->q
, rq
);
937 put_io_context(rq
->elv
.icq
->ioc
);
940 mempool_free(rq
, rl
->rq_pool
);
944 * ioc_batching returns true if the ioc is a valid batching request and
945 * should be given priority access to a request.
947 static inline int ioc_batching(struct request_queue
*q
, struct io_context
*ioc
)
953 * Make sure the process is able to allocate at least 1 request
954 * even if the batch times out, otherwise we could theoretically
957 return ioc
->nr_batch_requests
== q
->nr_batching
||
958 (ioc
->nr_batch_requests
> 0
959 && time_before(jiffies
, ioc
->last_waited
+ BLK_BATCH_TIME
));
963 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
964 * will cause the process to be a "batcher" on all queues in the system. This
965 * is the behaviour we want though - once it gets a wakeup it should be given
968 static void ioc_set_batching(struct request_queue
*q
, struct io_context
*ioc
)
970 if (!ioc
|| ioc_batching(q
, ioc
))
973 ioc
->nr_batch_requests
= q
->nr_batching
;
974 ioc
->last_waited
= jiffies
;
977 static void __freed_request(struct request_list
*rl
, int sync
)
979 struct request_queue
*q
= rl
->q
;
981 if (rl
->count
[sync
] < queue_congestion_off_threshold(q
))
982 blk_clear_congested(rl
, sync
);
984 if (rl
->count
[sync
] + 1 <= q
->nr_requests
) {
985 if (waitqueue_active(&rl
->wait
[sync
]))
986 wake_up(&rl
->wait
[sync
]);
988 blk_clear_rl_full(rl
, sync
);
993 * A request has just been released. Account for it, update the full and
994 * congestion status, wake up any waiters. Called under q->queue_lock.
996 static void freed_request(struct request_list
*rl
, bool sync
,
997 req_flags_t rq_flags
)
999 struct request_queue
*q
= rl
->q
;
1003 if (rq_flags
& RQF_ELVPRIV
)
1004 q
->nr_rqs_elvpriv
--;
1006 __freed_request(rl
, sync
);
1008 if (unlikely(rl
->starved
[sync
^ 1]))
1009 __freed_request(rl
, sync
^ 1);
1012 int blk_update_nr_requests(struct request_queue
*q
, unsigned int nr
)
1014 struct request_list
*rl
;
1015 int on_thresh
, off_thresh
;
1017 spin_lock_irq(q
->queue_lock
);
1018 q
->nr_requests
= nr
;
1019 blk_queue_congestion_threshold(q
);
1020 on_thresh
= queue_congestion_on_threshold(q
);
1021 off_thresh
= queue_congestion_off_threshold(q
);
1023 blk_queue_for_each_rl(rl
, q
) {
1024 if (rl
->count
[BLK_RW_SYNC
] >= on_thresh
)
1025 blk_set_congested(rl
, BLK_RW_SYNC
);
1026 else if (rl
->count
[BLK_RW_SYNC
] < off_thresh
)
1027 blk_clear_congested(rl
, BLK_RW_SYNC
);
1029 if (rl
->count
[BLK_RW_ASYNC
] >= on_thresh
)
1030 blk_set_congested(rl
, BLK_RW_ASYNC
);
1031 else if (rl
->count
[BLK_RW_ASYNC
] < off_thresh
)
1032 blk_clear_congested(rl
, BLK_RW_ASYNC
);
1034 if (rl
->count
[BLK_RW_SYNC
] >= q
->nr_requests
) {
1035 blk_set_rl_full(rl
, BLK_RW_SYNC
);
1037 blk_clear_rl_full(rl
, BLK_RW_SYNC
);
1038 wake_up(&rl
->wait
[BLK_RW_SYNC
]);
1041 if (rl
->count
[BLK_RW_ASYNC
] >= q
->nr_requests
) {
1042 blk_set_rl_full(rl
, BLK_RW_ASYNC
);
1044 blk_clear_rl_full(rl
, BLK_RW_ASYNC
);
1045 wake_up(&rl
->wait
[BLK_RW_ASYNC
]);
1049 spin_unlock_irq(q
->queue_lock
);
1054 * __get_request - get a free request
1055 * @rl: request list to allocate from
1056 * @op: operation and flags
1057 * @bio: bio to allocate request for (can be %NULL)
1058 * @gfp_mask: allocation mask
1060 * Get a free request from @q. This function may fail under memory
1061 * pressure or if @q is dead.
1063 * Must be called with @q->queue_lock held and,
1064 * Returns ERR_PTR on failure, with @q->queue_lock held.
1065 * Returns request pointer on success, with @q->queue_lock *not held*.
1067 static struct request
*__get_request(struct request_list
*rl
, unsigned int op
,
1068 struct bio
*bio
, gfp_t gfp_mask
)
1070 struct request_queue
*q
= rl
->q
;
1072 struct elevator_type
*et
= q
->elevator
->type
;
1073 struct io_context
*ioc
= rq_ioc(bio
);
1074 struct io_cq
*icq
= NULL
;
1075 const bool is_sync
= op_is_sync(op
);
1077 req_flags_t rq_flags
= RQF_ALLOCED
;
1079 if (unlikely(blk_queue_dying(q
)))
1080 return ERR_PTR(-ENODEV
);
1082 may_queue
= elv_may_queue(q
, op
);
1083 if (may_queue
== ELV_MQUEUE_NO
)
1086 if (rl
->count
[is_sync
]+1 >= queue_congestion_on_threshold(q
)) {
1087 if (rl
->count
[is_sync
]+1 >= q
->nr_requests
) {
1089 * The queue will fill after this allocation, so set
1090 * it as full, and mark this process as "batching".
1091 * This process will be allowed to complete a batch of
1092 * requests, others will be blocked.
1094 if (!blk_rl_full(rl
, is_sync
)) {
1095 ioc_set_batching(q
, ioc
);
1096 blk_set_rl_full(rl
, is_sync
);
1098 if (may_queue
!= ELV_MQUEUE_MUST
1099 && !ioc_batching(q
, ioc
)) {
1101 * The queue is full and the allocating
1102 * process is not a "batcher", and not
1103 * exempted by the IO scheduler
1105 return ERR_PTR(-ENOMEM
);
1109 blk_set_congested(rl
, is_sync
);
1113 * Only allow batching queuers to allocate up to 50% over the defined
1114 * limit of requests, otherwise we could have thousands of requests
1115 * allocated with any setting of ->nr_requests
1117 if (rl
->count
[is_sync
] >= (3 * q
->nr_requests
/ 2))
1118 return ERR_PTR(-ENOMEM
);
1120 q
->nr_rqs
[is_sync
]++;
1121 rl
->count
[is_sync
]++;
1122 rl
->starved
[is_sync
] = 0;
1125 * Decide whether the new request will be managed by elevator. If
1126 * so, mark @rq_flags and increment elvpriv. Non-zero elvpriv will
1127 * prevent the current elevator from being destroyed until the new
1128 * request is freed. This guarantees icq's won't be destroyed and
1129 * makes creating new ones safe.
1131 * Flush requests do not use the elevator so skip initialization.
1132 * This allows a request to share the flush and elevator data.
1134 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1135 * it will be created after releasing queue_lock.
1137 if (!op_is_flush(op
) && !blk_queue_bypass(q
)) {
1138 rq_flags
|= RQF_ELVPRIV
;
1139 q
->nr_rqs_elvpriv
++;
1140 if (et
->icq_cache
&& ioc
)
1141 icq
= ioc_lookup_icq(ioc
, q
);
1144 if (blk_queue_io_stat(q
))
1145 rq_flags
|= RQF_IO_STAT
;
1146 spin_unlock_irq(q
->queue_lock
);
1148 /* allocate and init request */
1149 rq
= mempool_alloc(rl
->rq_pool
, gfp_mask
);
1154 blk_rq_set_rl(rq
, rl
);
1156 rq
->rq_flags
= rq_flags
;
1159 if (rq_flags
& RQF_ELVPRIV
) {
1160 if (unlikely(et
->icq_cache
&& !icq
)) {
1162 icq
= ioc_create_icq(ioc
, q
, gfp_mask
);
1168 if (unlikely(elv_set_request(q
, rq
, bio
, gfp_mask
)))
1171 /* @rq->elv.icq holds io_context until @rq is freed */
1173 get_io_context(icq
->ioc
);
1177 * ioc may be NULL here, and ioc_batching will be false. That's
1178 * OK, if the queue is under the request limit then requests need
1179 * not count toward the nr_batch_requests limit. There will always
1180 * be some limit enforced by BLK_BATCH_TIME.
1182 if (ioc_batching(q
, ioc
))
1183 ioc
->nr_batch_requests
--;
1185 trace_block_getrq(q
, bio
, op
);
1190 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1191 * and may fail indefinitely under memory pressure and thus
1192 * shouldn't stall IO. Treat this request as !elvpriv. This will
1193 * disturb iosched and blkcg but weird is bettern than dead.
1195 printk_ratelimited(KERN_WARNING
"%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1196 __func__
, dev_name(q
->backing_dev_info
->dev
));
1198 rq
->rq_flags
&= ~RQF_ELVPRIV
;
1201 spin_lock_irq(q
->queue_lock
);
1202 q
->nr_rqs_elvpriv
--;
1203 spin_unlock_irq(q
->queue_lock
);
1208 * Allocation failed presumably due to memory. Undo anything we
1209 * might have messed up.
1211 * Allocating task should really be put onto the front of the wait
1212 * queue, but this is pretty rare.
1214 spin_lock_irq(q
->queue_lock
);
1215 freed_request(rl
, is_sync
, rq_flags
);
1218 * in the very unlikely event that allocation failed and no
1219 * requests for this direction was pending, mark us starved so that
1220 * freeing of a request in the other direction will notice
1221 * us. another possible fix would be to split the rq mempool into
1225 if (unlikely(rl
->count
[is_sync
] == 0))
1226 rl
->starved
[is_sync
] = 1;
1227 return ERR_PTR(-ENOMEM
);
1231 * get_request - get a free request
1232 * @q: request_queue to allocate request from
1233 * @op: operation and flags
1234 * @bio: bio to allocate request for (can be %NULL)
1235 * @gfp_mask: allocation mask
1237 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1238 * this function keeps retrying under memory pressure and fails iff @q is dead.
1240 * Must be called with @q->queue_lock held and,
1241 * Returns ERR_PTR on failure, with @q->queue_lock held.
1242 * Returns request pointer on success, with @q->queue_lock *not held*.
1244 static struct request
*get_request(struct request_queue
*q
, unsigned int op
,
1245 struct bio
*bio
, gfp_t gfp_mask
)
1247 const bool is_sync
= op_is_sync(op
);
1249 struct request_list
*rl
;
1252 rl
= blk_get_rl(q
, bio
); /* transferred to @rq on success */
1254 rq
= __get_request(rl
, op
, bio
, gfp_mask
);
1258 if (!gfpflags_allow_blocking(gfp_mask
) || unlikely(blk_queue_dying(q
))) {
1263 /* wait on @rl and retry */
1264 prepare_to_wait_exclusive(&rl
->wait
[is_sync
], &wait
,
1265 TASK_UNINTERRUPTIBLE
);
1267 trace_block_sleeprq(q
, bio
, op
);
1269 spin_unlock_irq(q
->queue_lock
);
1273 * After sleeping, we become a "batching" process and will be able
1274 * to allocate at least one request, and up to a big batch of them
1275 * for a small period time. See ioc_batching, ioc_set_batching
1277 ioc_set_batching(q
, current
->io_context
);
1279 spin_lock_irq(q
->queue_lock
);
1280 finish_wait(&rl
->wait
[is_sync
], &wait
);
1285 static struct request
*blk_old_get_request(struct request_queue
*q
, int rw
,
1290 /* create ioc upfront */
1291 create_io_context(gfp_mask
, q
->node
);
1293 spin_lock_irq(q
->queue_lock
);
1294 rq
= get_request(q
, rw
, NULL
, gfp_mask
);
1296 spin_unlock_irq(q
->queue_lock
);
1300 /* q->queue_lock is unlocked at this point */
1302 rq
->__sector
= (sector_t
) -1;
1303 rq
->bio
= rq
->biotail
= NULL
;
1307 struct request
*blk_get_request(struct request_queue
*q
, int rw
, gfp_t gfp_mask
)
1310 return blk_mq_alloc_request(q
, rw
,
1311 (gfp_mask
& __GFP_DIRECT_RECLAIM
) ?
1312 0 : BLK_MQ_REQ_NOWAIT
);
1314 return blk_old_get_request(q
, rw
, gfp_mask
);
1316 EXPORT_SYMBOL(blk_get_request
);
1319 * blk_requeue_request - put a request back on queue
1320 * @q: request queue where request should be inserted
1321 * @rq: request to be inserted
1324 * Drivers often keep queueing requests until the hardware cannot accept
1325 * more, when that condition happens we need to put the request back
1326 * on the queue. Must be called with queue lock held.
1328 void blk_requeue_request(struct request_queue
*q
, struct request
*rq
)
1330 blk_delete_timer(rq
);
1331 blk_clear_rq_complete(rq
);
1332 trace_block_rq_requeue(q
, rq
);
1333 wbt_requeue(q
->rq_wb
, &rq
->issue_stat
);
1335 if (rq
->rq_flags
& RQF_QUEUED
)
1336 blk_queue_end_tag(q
, rq
);
1338 BUG_ON(blk_queued_rq(rq
));
1340 elv_requeue_request(q
, rq
);
1342 EXPORT_SYMBOL(blk_requeue_request
);
1344 static void add_acct_request(struct request_queue
*q
, struct request
*rq
,
1347 blk_account_io_start(rq
, true);
1348 __elv_add_request(q
, rq
, where
);
1351 static void part_round_stats_single(int cpu
, struct hd_struct
*part
,
1356 if (now
== part
->stamp
)
1359 inflight
= part_in_flight(part
);
1361 __part_stat_add(cpu
, part
, time_in_queue
,
1362 inflight
* (now
- part
->stamp
));
1363 __part_stat_add(cpu
, part
, io_ticks
, (now
- part
->stamp
));
1369 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1370 * @cpu: cpu number for stats access
1371 * @part: target partition
1373 * The average IO queue length and utilisation statistics are maintained
1374 * by observing the current state of the queue length and the amount of
1375 * time it has been in this state for.
1377 * Normally, that accounting is done on IO completion, but that can result
1378 * in more than a second's worth of IO being accounted for within any one
1379 * second, leading to >100% utilisation. To deal with that, we call this
1380 * function to do a round-off before returning the results when reading
1381 * /proc/diskstats. This accounts immediately for all queue usage up to
1382 * the current jiffies and restarts the counters again.
1384 void part_round_stats(int cpu
, struct hd_struct
*part
)
1386 unsigned long now
= jiffies
;
1389 part_round_stats_single(cpu
, &part_to_disk(part
)->part0
, now
);
1390 part_round_stats_single(cpu
, part
, now
);
1392 EXPORT_SYMBOL_GPL(part_round_stats
);
1395 static void blk_pm_put_request(struct request
*rq
)
1397 if (rq
->q
->dev
&& !(rq
->rq_flags
& RQF_PM
) && !--rq
->q
->nr_pending
)
1398 pm_runtime_mark_last_busy(rq
->q
->dev
);
1401 static inline void blk_pm_put_request(struct request
*rq
) {}
1405 * queue lock must be held
1407 void __blk_put_request(struct request_queue
*q
, struct request
*req
)
1409 req_flags_t rq_flags
= req
->rq_flags
;
1415 blk_mq_free_request(req
);
1419 blk_pm_put_request(req
);
1421 elv_completed_request(q
, req
);
1423 /* this is a bio leak */
1424 WARN_ON(req
->bio
!= NULL
);
1426 wbt_done(q
->rq_wb
, &req
->issue_stat
);
1429 * Request may not have originated from ll_rw_blk. if not,
1430 * it didn't come out of our reserved rq pools
1432 if (rq_flags
& RQF_ALLOCED
) {
1433 struct request_list
*rl
= blk_rq_rl(req
);
1434 bool sync
= op_is_sync(req
->cmd_flags
);
1436 BUG_ON(!list_empty(&req
->queuelist
));
1437 BUG_ON(ELV_ON_HASH(req
));
1439 blk_free_request(rl
, req
);
1440 freed_request(rl
, sync
, rq_flags
);
1444 EXPORT_SYMBOL_GPL(__blk_put_request
);
1446 void blk_put_request(struct request
*req
)
1448 struct request_queue
*q
= req
->q
;
1451 blk_mq_free_request(req
);
1453 unsigned long flags
;
1455 spin_lock_irqsave(q
->queue_lock
, flags
);
1456 __blk_put_request(q
, req
);
1457 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1460 EXPORT_SYMBOL(blk_put_request
);
1462 bool bio_attempt_back_merge(struct request_queue
*q
, struct request
*req
,
1465 const int ff
= bio
->bi_opf
& REQ_FAILFAST_MASK
;
1467 if (!ll_back_merge_fn(q
, req
, bio
))
1470 trace_block_bio_backmerge(q
, req
, bio
);
1472 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1473 blk_rq_set_mixed_merge(req
);
1475 req
->biotail
->bi_next
= bio
;
1477 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1478 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1480 blk_account_io_start(req
, false);
1484 bool bio_attempt_front_merge(struct request_queue
*q
, struct request
*req
,
1487 const int ff
= bio
->bi_opf
& REQ_FAILFAST_MASK
;
1489 if (!ll_front_merge_fn(q
, req
, bio
))
1492 trace_block_bio_frontmerge(q
, req
, bio
);
1494 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1495 blk_rq_set_mixed_merge(req
);
1497 bio
->bi_next
= req
->bio
;
1500 req
->__sector
= bio
->bi_iter
.bi_sector
;
1501 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1502 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1504 blk_account_io_start(req
, false);
1508 bool bio_attempt_discard_merge(struct request_queue
*q
, struct request
*req
,
1511 unsigned short segments
= blk_rq_nr_discard_segments(req
);
1513 if (segments
>= queue_max_discard_segments(q
))
1515 if (blk_rq_sectors(req
) + bio_sectors(bio
) >
1516 blk_rq_get_max_sectors(req
, blk_rq_pos(req
)))
1519 req
->biotail
->bi_next
= bio
;
1521 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1522 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1523 req
->nr_phys_segments
= segments
+ 1;
1525 blk_account_io_start(req
, false);
1528 req_set_nomerge(q
, req
);
1533 * blk_attempt_plug_merge - try to merge with %current's plugged list
1534 * @q: request_queue new bio is being queued at
1535 * @bio: new bio being queued
1536 * @request_count: out parameter for number of traversed plugged requests
1537 * @same_queue_rq: pointer to &struct request that gets filled in when
1538 * another request associated with @q is found on the plug list
1539 * (optional, may be %NULL)
1541 * Determine whether @bio being queued on @q can be merged with a request
1542 * on %current's plugged list. Returns %true if merge was successful,
1545 * Plugging coalesces IOs from the same issuer for the same purpose without
1546 * going through @q->queue_lock. As such it's more of an issuing mechanism
1547 * than scheduling, and the request, while may have elvpriv data, is not
1548 * added on the elevator at this point. In addition, we don't have
1549 * reliable access to the elevator outside queue lock. Only check basic
1550 * merging parameters without querying the elevator.
1552 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1554 bool blk_attempt_plug_merge(struct request_queue
*q
, struct bio
*bio
,
1555 unsigned int *request_count
,
1556 struct request
**same_queue_rq
)
1558 struct blk_plug
*plug
;
1560 struct list_head
*plug_list
;
1562 plug
= current
->plug
;
1568 plug_list
= &plug
->mq_list
;
1570 plug_list
= &plug
->list
;
1572 list_for_each_entry_reverse(rq
, plug_list
, queuelist
) {
1573 bool merged
= false;
1578 * Only blk-mq multiple hardware queues case checks the
1579 * rq in the same queue, there should be only one such
1583 *same_queue_rq
= rq
;
1586 if (rq
->q
!= q
|| !blk_rq_merge_ok(rq
, bio
))
1589 switch (blk_try_merge(rq
, bio
)) {
1590 case ELEVATOR_BACK_MERGE
:
1591 merged
= bio_attempt_back_merge(q
, rq
, bio
);
1593 case ELEVATOR_FRONT_MERGE
:
1594 merged
= bio_attempt_front_merge(q
, rq
, bio
);
1596 case ELEVATOR_DISCARD_MERGE
:
1597 merged
= bio_attempt_discard_merge(q
, rq
, bio
);
1610 unsigned int blk_plug_queued_count(struct request_queue
*q
)
1612 struct blk_plug
*plug
;
1614 struct list_head
*plug_list
;
1615 unsigned int ret
= 0;
1617 plug
= current
->plug
;
1622 plug_list
= &plug
->mq_list
;
1624 plug_list
= &plug
->list
;
1626 list_for_each_entry(rq
, plug_list
, queuelist
) {
1634 void blk_init_request_from_bio(struct request
*req
, struct bio
*bio
)
1636 struct io_context
*ioc
= rq_ioc(bio
);
1638 if (bio
->bi_opf
& REQ_RAHEAD
)
1639 req
->cmd_flags
|= REQ_FAILFAST_MASK
;
1641 req
->__sector
= bio
->bi_iter
.bi_sector
;
1642 if (ioprio_valid(bio_prio(bio
)))
1643 req
->ioprio
= bio_prio(bio
);
1645 req
->ioprio
= ioc
->ioprio
;
1647 req
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE
, 0);
1648 blk_rq_bio_prep(req
->q
, req
, bio
);
1650 EXPORT_SYMBOL_GPL(blk_init_request_from_bio
);
1652 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
)
1654 struct blk_plug
*plug
;
1655 int where
= ELEVATOR_INSERT_SORT
;
1656 struct request
*req
, *free
;
1657 unsigned int request_count
= 0;
1658 unsigned int wb_acct
;
1661 * low level driver can indicate that it wants pages above a
1662 * certain limit bounced to low memory (ie for highmem, or even
1663 * ISA dma in theory)
1665 blk_queue_bounce(q
, &bio
);
1667 blk_queue_split(q
, &bio
, q
->bio_split
);
1669 if (bio_integrity_enabled(bio
) && bio_integrity_prep(bio
)) {
1670 bio
->bi_error
= -EIO
;
1672 return BLK_QC_T_NONE
;
1675 if (op_is_flush(bio
->bi_opf
)) {
1676 spin_lock_irq(q
->queue_lock
);
1677 where
= ELEVATOR_INSERT_FLUSH
;
1682 * Check if we can merge with the plugged list before grabbing
1685 if (!blk_queue_nomerges(q
)) {
1686 if (blk_attempt_plug_merge(q
, bio
, &request_count
, NULL
))
1687 return BLK_QC_T_NONE
;
1689 request_count
= blk_plug_queued_count(q
);
1691 spin_lock_irq(q
->queue_lock
);
1693 switch (elv_merge(q
, &req
, bio
)) {
1694 case ELEVATOR_BACK_MERGE
:
1695 if (!bio_attempt_back_merge(q
, req
, bio
))
1697 elv_bio_merged(q
, req
, bio
);
1698 free
= attempt_back_merge(q
, req
);
1700 __blk_put_request(q
, free
);
1702 elv_merged_request(q
, req
, ELEVATOR_BACK_MERGE
);
1704 case ELEVATOR_FRONT_MERGE
:
1705 if (!bio_attempt_front_merge(q
, req
, bio
))
1707 elv_bio_merged(q
, req
, bio
);
1708 free
= attempt_front_merge(q
, req
);
1710 __blk_put_request(q
, free
);
1712 elv_merged_request(q
, req
, ELEVATOR_FRONT_MERGE
);
1719 wb_acct
= wbt_wait(q
->rq_wb
, bio
, q
->queue_lock
);
1722 * Grab a free request. This is might sleep but can not fail.
1723 * Returns with the queue unlocked.
1725 req
= get_request(q
, bio
->bi_opf
, bio
, GFP_NOIO
);
1727 __wbt_done(q
->rq_wb
, wb_acct
);
1728 bio
->bi_error
= PTR_ERR(req
);
1733 wbt_track(&req
->issue_stat
, wb_acct
);
1736 * After dropping the lock and possibly sleeping here, our request
1737 * may now be mergeable after it had proven unmergeable (above).
1738 * We don't worry about that case for efficiency. It won't happen
1739 * often, and the elevators are able to handle it.
1741 blk_init_request_from_bio(req
, bio
);
1743 if (test_bit(QUEUE_FLAG_SAME_COMP
, &q
->queue_flags
))
1744 req
->cpu
= raw_smp_processor_id();
1746 plug
= current
->plug
;
1749 * If this is the first request added after a plug, fire
1752 * @request_count may become stale because of schedule
1753 * out, so check plug list again.
1755 if (!request_count
|| list_empty(&plug
->list
))
1756 trace_block_plug(q
);
1758 struct request
*last
= list_entry_rq(plug
->list
.prev
);
1759 if (request_count
>= BLK_MAX_REQUEST_COUNT
||
1760 blk_rq_bytes(last
) >= BLK_PLUG_FLUSH_SIZE
) {
1761 blk_flush_plug_list(plug
, false);
1762 trace_block_plug(q
);
1765 list_add_tail(&req
->queuelist
, &plug
->list
);
1766 blk_account_io_start(req
, true);
1768 spin_lock_irq(q
->queue_lock
);
1769 add_acct_request(q
, req
, where
);
1772 spin_unlock_irq(q
->queue_lock
);
1775 return BLK_QC_T_NONE
;
1779 * If bio->bi_dev is a partition, remap the location
1781 static inline void blk_partition_remap(struct bio
*bio
)
1783 struct block_device
*bdev
= bio
->bi_bdev
;
1786 * Zone reset does not include bi_size so bio_sectors() is always 0.
1787 * Include a test for the reset op code and perform the remap if needed.
1789 if (bdev
!= bdev
->bd_contains
&&
1790 (bio_sectors(bio
) || bio_op(bio
) == REQ_OP_ZONE_RESET
)) {
1791 struct hd_struct
*p
= bdev
->bd_part
;
1793 bio
->bi_iter
.bi_sector
+= p
->start_sect
;
1794 bio
->bi_bdev
= bdev
->bd_contains
;
1796 trace_block_bio_remap(bdev_get_queue(bio
->bi_bdev
), bio
,
1798 bio
->bi_iter
.bi_sector
- p
->start_sect
);
1802 static void handle_bad_sector(struct bio
*bio
)
1804 char b
[BDEVNAME_SIZE
];
1806 printk(KERN_INFO
"attempt to access beyond end of device\n");
1807 printk(KERN_INFO
"%s: rw=%d, want=%Lu, limit=%Lu\n",
1808 bdevname(bio
->bi_bdev
, b
),
1810 (unsigned long long)bio_end_sector(bio
),
1811 (long long)(i_size_read(bio
->bi_bdev
->bd_inode
) >> 9));
1814 #ifdef CONFIG_FAIL_MAKE_REQUEST
1816 static DECLARE_FAULT_ATTR(fail_make_request
);
1818 static int __init
setup_fail_make_request(char *str
)
1820 return setup_fault_attr(&fail_make_request
, str
);
1822 __setup("fail_make_request=", setup_fail_make_request
);
1824 static bool should_fail_request(struct hd_struct
*part
, unsigned int bytes
)
1826 return part
->make_it_fail
&& should_fail(&fail_make_request
, bytes
);
1829 static int __init
fail_make_request_debugfs(void)
1831 struct dentry
*dir
= fault_create_debugfs_attr("fail_make_request",
1832 NULL
, &fail_make_request
);
1834 return PTR_ERR_OR_ZERO(dir
);
1837 late_initcall(fail_make_request_debugfs
);
1839 #else /* CONFIG_FAIL_MAKE_REQUEST */
1841 static inline bool should_fail_request(struct hd_struct
*part
,
1847 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1850 * Check whether this bio extends beyond the end of the device.
1852 static inline int bio_check_eod(struct bio
*bio
, unsigned int nr_sectors
)
1859 /* Test device or partition size, when known. */
1860 maxsector
= i_size_read(bio
->bi_bdev
->bd_inode
) >> 9;
1862 sector_t sector
= bio
->bi_iter
.bi_sector
;
1864 if (maxsector
< nr_sectors
|| maxsector
- nr_sectors
< sector
) {
1866 * This may well happen - the kernel calls bread()
1867 * without checking the size of the device, e.g., when
1868 * mounting a device.
1870 handle_bad_sector(bio
);
1878 static noinline_for_stack
bool
1879 generic_make_request_checks(struct bio
*bio
)
1881 struct request_queue
*q
;
1882 int nr_sectors
= bio_sectors(bio
);
1884 char b
[BDEVNAME_SIZE
];
1885 struct hd_struct
*part
;
1889 if (bio_check_eod(bio
, nr_sectors
))
1892 q
= bdev_get_queue(bio
->bi_bdev
);
1895 "generic_make_request: Trying to access "
1896 "nonexistent block-device %s (%Lu)\n",
1897 bdevname(bio
->bi_bdev
, b
),
1898 (long long) bio
->bi_iter
.bi_sector
);
1902 part
= bio
->bi_bdev
->bd_part
;
1903 if (should_fail_request(part
, bio
->bi_iter
.bi_size
) ||
1904 should_fail_request(&part_to_disk(part
)->part0
,
1905 bio
->bi_iter
.bi_size
))
1909 * If this device has partitions, remap block n
1910 * of partition p to block n+start(p) of the disk.
1912 blk_partition_remap(bio
);
1914 if (bio_check_eod(bio
, nr_sectors
))
1918 * Filter flush bio's early so that make_request based
1919 * drivers without flush support don't have to worry
1922 if (op_is_flush(bio
->bi_opf
) &&
1923 !test_bit(QUEUE_FLAG_WC
, &q
->queue_flags
)) {
1924 bio
->bi_opf
&= ~(REQ_PREFLUSH
| REQ_FUA
);
1931 switch (bio_op(bio
)) {
1932 case REQ_OP_DISCARD
:
1933 if (!blk_queue_discard(q
))
1936 case REQ_OP_SECURE_ERASE
:
1937 if (!blk_queue_secure_erase(q
))
1940 case REQ_OP_WRITE_SAME
:
1941 if (!bdev_write_same(bio
->bi_bdev
))
1944 case REQ_OP_ZONE_REPORT
:
1945 case REQ_OP_ZONE_RESET
:
1946 if (!bdev_is_zoned(bio
->bi_bdev
))
1949 case REQ_OP_WRITE_ZEROES
:
1950 if (!bdev_write_zeroes_sectors(bio
->bi_bdev
))
1958 * Various block parts want %current->io_context and lazy ioc
1959 * allocation ends up trading a lot of pain for a small amount of
1960 * memory. Just allocate it upfront. This may fail and block
1961 * layer knows how to live with it.
1963 create_io_context(GFP_ATOMIC
, q
->node
);
1965 if (!blkcg_bio_issue_check(q
, bio
))
1968 if (!bio_flagged(bio
, BIO_TRACE_COMPLETION
)) {
1969 trace_block_bio_queue(q
, bio
);
1970 /* Now that enqueuing has been traced, we need to trace
1971 * completion as well.
1973 bio_set_flag(bio
, BIO_TRACE_COMPLETION
);
1980 bio
->bi_error
= err
;
1986 * generic_make_request - hand a buffer to its device driver for I/O
1987 * @bio: The bio describing the location in memory and on the device.
1989 * generic_make_request() is used to make I/O requests of block
1990 * devices. It is passed a &struct bio, which describes the I/O that needs
1993 * generic_make_request() does not return any status. The
1994 * success/failure status of the request, along with notification of
1995 * completion, is delivered asynchronously through the bio->bi_end_io
1996 * function described (one day) else where.
1998 * The caller of generic_make_request must make sure that bi_io_vec
1999 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2000 * set to describe the device address, and the
2001 * bi_end_io and optionally bi_private are set to describe how
2002 * completion notification should be signaled.
2004 * generic_make_request and the drivers it calls may use bi_next if this
2005 * bio happens to be merged with someone else, and may resubmit the bio to
2006 * a lower device by calling into generic_make_request recursively, which
2007 * means the bio should NOT be touched after the call to ->make_request_fn.
2009 blk_qc_t
generic_make_request(struct bio
*bio
)
2012 * bio_list_on_stack[0] contains bios submitted by the current
2014 * bio_list_on_stack[1] contains bios that were submitted before
2015 * the current make_request_fn, but that haven't been processed
2018 struct bio_list bio_list_on_stack
[2];
2019 blk_qc_t ret
= BLK_QC_T_NONE
;
2021 if (!generic_make_request_checks(bio
))
2025 * We only want one ->make_request_fn to be active at a time, else
2026 * stack usage with stacked devices could be a problem. So use
2027 * current->bio_list to keep a list of requests submited by a
2028 * make_request_fn function. current->bio_list is also used as a
2029 * flag to say if generic_make_request is currently active in this
2030 * task or not. If it is NULL, then no make_request is active. If
2031 * it is non-NULL, then a make_request is active, and new requests
2032 * should be added at the tail
2034 if (current
->bio_list
) {
2035 bio_list_add(¤t
->bio_list
[0], bio
);
2039 /* following loop may be a bit non-obvious, and so deserves some
2041 * Before entering the loop, bio->bi_next is NULL (as all callers
2042 * ensure that) so we have a list with a single bio.
2043 * We pretend that we have just taken it off a longer list, so
2044 * we assign bio_list to a pointer to the bio_list_on_stack,
2045 * thus initialising the bio_list of new bios to be
2046 * added. ->make_request() may indeed add some more bios
2047 * through a recursive call to generic_make_request. If it
2048 * did, we find a non-NULL value in bio_list and re-enter the loop
2049 * from the top. In this case we really did just take the bio
2050 * of the top of the list (no pretending) and so remove it from
2051 * bio_list, and call into ->make_request() again.
2053 BUG_ON(bio
->bi_next
);
2054 bio_list_init(&bio_list_on_stack
[0]);
2055 current
->bio_list
= bio_list_on_stack
;
2057 struct request_queue
*q
= bdev_get_queue(bio
->bi_bdev
);
2059 if (likely(blk_queue_enter(q
, false) == 0)) {
2060 struct bio_list lower
, same
;
2062 /* Create a fresh bio_list for all subordinate requests */
2063 bio_list_on_stack
[1] = bio_list_on_stack
[0];
2064 bio_list_init(&bio_list_on_stack
[0]);
2065 ret
= q
->make_request_fn(q
, bio
);
2069 /* sort new bios into those for a lower level
2070 * and those for the same level
2072 bio_list_init(&lower
);
2073 bio_list_init(&same
);
2074 while ((bio
= bio_list_pop(&bio_list_on_stack
[0])) != NULL
)
2075 if (q
== bdev_get_queue(bio
->bi_bdev
))
2076 bio_list_add(&same
, bio
);
2078 bio_list_add(&lower
, bio
);
2079 /* now assemble so we handle the lowest level first */
2080 bio_list_merge(&bio_list_on_stack
[0], &lower
);
2081 bio_list_merge(&bio_list_on_stack
[0], &same
);
2082 bio_list_merge(&bio_list_on_stack
[0], &bio_list_on_stack
[1]);
2086 bio
= bio_list_pop(&bio_list_on_stack
[0]);
2088 current
->bio_list
= NULL
; /* deactivate */
2093 EXPORT_SYMBOL(generic_make_request
);
2096 * submit_bio - submit a bio to the block device layer for I/O
2097 * @bio: The &struct bio which describes the I/O
2099 * submit_bio() is very similar in purpose to generic_make_request(), and
2100 * uses that function to do most of the work. Both are fairly rough
2101 * interfaces; @bio must be presetup and ready for I/O.
2104 blk_qc_t
submit_bio(struct bio
*bio
)
2107 * If it's a regular read/write or a barrier with data attached,
2108 * go through the normal accounting stuff before submission.
2110 if (bio_has_data(bio
)) {
2113 if (unlikely(bio_op(bio
) == REQ_OP_WRITE_SAME
))
2114 count
= bdev_logical_block_size(bio
->bi_bdev
) >> 9;
2116 count
= bio_sectors(bio
);
2118 if (op_is_write(bio_op(bio
))) {
2119 count_vm_events(PGPGOUT
, count
);
2121 task_io_account_read(bio
->bi_iter
.bi_size
);
2122 count_vm_events(PGPGIN
, count
);
2125 if (unlikely(block_dump
)) {
2126 char b
[BDEVNAME_SIZE
];
2127 printk(KERN_DEBUG
"%s(%d): %s block %Lu on %s (%u sectors)\n",
2128 current
->comm
, task_pid_nr(current
),
2129 op_is_write(bio_op(bio
)) ? "WRITE" : "READ",
2130 (unsigned long long)bio
->bi_iter
.bi_sector
,
2131 bdevname(bio
->bi_bdev
, b
),
2136 return generic_make_request(bio
);
2138 EXPORT_SYMBOL(submit_bio
);
2141 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2142 * for new the queue limits
2144 * @rq: the request being checked
2147 * @rq may have been made based on weaker limitations of upper-level queues
2148 * in request stacking drivers, and it may violate the limitation of @q.
2149 * Since the block layer and the underlying device driver trust @rq
2150 * after it is inserted to @q, it should be checked against @q before
2151 * the insertion using this generic function.
2153 * Request stacking drivers like request-based dm may change the queue
2154 * limits when retrying requests on other queues. Those requests need
2155 * to be checked against the new queue limits again during dispatch.
2157 static int blk_cloned_rq_check_limits(struct request_queue
*q
,
2160 if (blk_rq_sectors(rq
) > blk_queue_get_max_sectors(q
, req_op(rq
))) {
2161 printk(KERN_ERR
"%s: over max size limit.\n", __func__
);
2166 * queue's settings related to segment counting like q->bounce_pfn
2167 * may differ from that of other stacking queues.
2168 * Recalculate it to check the request correctly on this queue's
2171 blk_recalc_rq_segments(rq
);
2172 if (rq
->nr_phys_segments
> queue_max_segments(q
)) {
2173 printk(KERN_ERR
"%s: over max segments limit.\n", __func__
);
2181 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2182 * @q: the queue to submit the request
2183 * @rq: the request being queued
2185 int blk_insert_cloned_request(struct request_queue
*q
, struct request
*rq
)
2187 unsigned long flags
;
2188 int where
= ELEVATOR_INSERT_BACK
;
2190 if (blk_cloned_rq_check_limits(q
, rq
))
2194 should_fail_request(&rq
->rq_disk
->part0
, blk_rq_bytes(rq
)))
2198 if (blk_queue_io_stat(q
))
2199 blk_account_io_start(rq
, true);
2200 blk_mq_sched_insert_request(rq
, false, true, false, false);
2204 spin_lock_irqsave(q
->queue_lock
, flags
);
2205 if (unlikely(blk_queue_dying(q
))) {
2206 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2211 * Submitting request must be dequeued before calling this function
2212 * because it will be linked to another request_queue
2214 BUG_ON(blk_queued_rq(rq
));
2216 if (op_is_flush(rq
->cmd_flags
))
2217 where
= ELEVATOR_INSERT_FLUSH
;
2219 add_acct_request(q
, rq
, where
);
2220 if (where
== ELEVATOR_INSERT_FLUSH
)
2222 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2226 EXPORT_SYMBOL_GPL(blk_insert_cloned_request
);
2229 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2230 * @rq: request to examine
2233 * A request could be merge of IOs which require different failure
2234 * handling. This function determines the number of bytes which
2235 * can be failed from the beginning of the request without
2236 * crossing into area which need to be retried further.
2239 * The number of bytes to fail.
2242 * queue_lock must be held.
2244 unsigned int blk_rq_err_bytes(const struct request
*rq
)
2246 unsigned int ff
= rq
->cmd_flags
& REQ_FAILFAST_MASK
;
2247 unsigned int bytes
= 0;
2250 if (!(rq
->rq_flags
& RQF_MIXED_MERGE
))
2251 return blk_rq_bytes(rq
);
2254 * Currently the only 'mixing' which can happen is between
2255 * different fastfail types. We can safely fail portions
2256 * which have all the failfast bits that the first one has -
2257 * the ones which are at least as eager to fail as the first
2260 for (bio
= rq
->bio
; bio
; bio
= bio
->bi_next
) {
2261 if ((bio
->bi_opf
& ff
) != ff
)
2263 bytes
+= bio
->bi_iter
.bi_size
;
2266 /* this could lead to infinite loop */
2267 BUG_ON(blk_rq_bytes(rq
) && !bytes
);
2270 EXPORT_SYMBOL_GPL(blk_rq_err_bytes
);
2272 void blk_account_io_completion(struct request
*req
, unsigned int bytes
)
2274 if (blk_do_io_stat(req
)) {
2275 const int rw
= rq_data_dir(req
);
2276 struct hd_struct
*part
;
2279 cpu
= part_stat_lock();
2281 part_stat_add(cpu
, part
, sectors
[rw
], bytes
>> 9);
2286 void blk_account_io_done(struct request
*req
)
2289 * Account IO completion. flush_rq isn't accounted as a
2290 * normal IO on queueing nor completion. Accounting the
2291 * containing request is enough.
2293 if (blk_do_io_stat(req
) && !(req
->rq_flags
& RQF_FLUSH_SEQ
)) {
2294 unsigned long duration
= jiffies
- req
->start_time
;
2295 const int rw
= rq_data_dir(req
);
2296 struct hd_struct
*part
;
2299 cpu
= part_stat_lock();
2302 part_stat_inc(cpu
, part
, ios
[rw
]);
2303 part_stat_add(cpu
, part
, ticks
[rw
], duration
);
2304 part_round_stats(cpu
, part
);
2305 part_dec_in_flight(part
, rw
);
2307 hd_struct_put(part
);
2314 * Don't process normal requests when queue is suspended
2315 * or in the process of suspending/resuming
2317 static struct request
*blk_pm_peek_request(struct request_queue
*q
,
2320 if (q
->dev
&& (q
->rpm_status
== RPM_SUSPENDED
||
2321 (q
->rpm_status
!= RPM_ACTIVE
&& !(rq
->rq_flags
& RQF_PM
))))
2327 static inline struct request
*blk_pm_peek_request(struct request_queue
*q
,
2334 void blk_account_io_start(struct request
*rq
, bool new_io
)
2336 struct hd_struct
*part
;
2337 int rw
= rq_data_dir(rq
);
2340 if (!blk_do_io_stat(rq
))
2343 cpu
= part_stat_lock();
2347 part_stat_inc(cpu
, part
, merges
[rw
]);
2349 part
= disk_map_sector_rcu(rq
->rq_disk
, blk_rq_pos(rq
));
2350 if (!hd_struct_try_get(part
)) {
2352 * The partition is already being removed,
2353 * the request will be accounted on the disk only
2355 * We take a reference on disk->part0 although that
2356 * partition will never be deleted, so we can treat
2357 * it as any other partition.
2359 part
= &rq
->rq_disk
->part0
;
2360 hd_struct_get(part
);
2362 part_round_stats(cpu
, part
);
2363 part_inc_in_flight(part
, rw
);
2371 * blk_peek_request - peek at the top of a request queue
2372 * @q: request queue to peek at
2375 * Return the request at the top of @q. The returned request
2376 * should be started using blk_start_request() before LLD starts
2380 * Pointer to the request at the top of @q if available. Null
2384 * queue_lock must be held.
2386 struct request
*blk_peek_request(struct request_queue
*q
)
2391 while ((rq
= __elv_next_request(q
)) != NULL
) {
2393 rq
= blk_pm_peek_request(q
, rq
);
2397 if (!(rq
->rq_flags
& RQF_STARTED
)) {
2399 * This is the first time the device driver
2400 * sees this request (possibly after
2401 * requeueing). Notify IO scheduler.
2403 if (rq
->rq_flags
& RQF_SORTED
)
2404 elv_activate_rq(q
, rq
);
2407 * just mark as started even if we don't start
2408 * it, a request that has been delayed should
2409 * not be passed by new incoming requests
2411 rq
->rq_flags
|= RQF_STARTED
;
2412 trace_block_rq_issue(q
, rq
);
2415 if (!q
->boundary_rq
|| q
->boundary_rq
== rq
) {
2416 q
->end_sector
= rq_end_sector(rq
);
2417 q
->boundary_rq
= NULL
;
2420 if (rq
->rq_flags
& RQF_DONTPREP
)
2423 if (q
->dma_drain_size
&& blk_rq_bytes(rq
)) {
2425 * make sure space for the drain appears we
2426 * know we can do this because max_hw_segments
2427 * has been adjusted to be one fewer than the
2430 rq
->nr_phys_segments
++;
2436 ret
= q
->prep_rq_fn(q
, rq
);
2437 if (ret
== BLKPREP_OK
) {
2439 } else if (ret
== BLKPREP_DEFER
) {
2441 * the request may have been (partially) prepped.
2442 * we need to keep this request in the front to
2443 * avoid resource deadlock. RQF_STARTED will
2444 * prevent other fs requests from passing this one.
2446 if (q
->dma_drain_size
&& blk_rq_bytes(rq
) &&
2447 !(rq
->rq_flags
& RQF_DONTPREP
)) {
2449 * remove the space for the drain we added
2450 * so that we don't add it again
2452 --rq
->nr_phys_segments
;
2457 } else if (ret
== BLKPREP_KILL
|| ret
== BLKPREP_INVALID
) {
2458 int err
= (ret
== BLKPREP_INVALID
) ? -EREMOTEIO
: -EIO
;
2460 rq
->rq_flags
|= RQF_QUIET
;
2462 * Mark this request as started so we don't trigger
2463 * any debug logic in the end I/O path.
2465 blk_start_request(rq
);
2466 __blk_end_request_all(rq
, err
);
2468 printk(KERN_ERR
"%s: bad return=%d\n", __func__
, ret
);
2475 EXPORT_SYMBOL(blk_peek_request
);
2477 void blk_dequeue_request(struct request
*rq
)
2479 struct request_queue
*q
= rq
->q
;
2481 BUG_ON(list_empty(&rq
->queuelist
));
2482 BUG_ON(ELV_ON_HASH(rq
));
2484 list_del_init(&rq
->queuelist
);
2487 * the time frame between a request being removed from the lists
2488 * and to it is freed is accounted as io that is in progress at
2491 if (blk_account_rq(rq
)) {
2492 q
->in_flight
[rq_is_sync(rq
)]++;
2493 set_io_start_time_ns(rq
);
2498 * blk_start_request - start request processing on the driver
2499 * @req: request to dequeue
2502 * Dequeue @req and start timeout timer on it. This hands off the
2503 * request to the driver.
2505 * Block internal functions which don't want to start timer should
2506 * call blk_dequeue_request().
2509 * queue_lock must be held.
2511 void blk_start_request(struct request
*req
)
2513 blk_dequeue_request(req
);
2515 if (test_bit(QUEUE_FLAG_STATS
, &req
->q
->queue_flags
)) {
2516 blk_stat_set_issue(&req
->issue_stat
, blk_rq_sectors(req
));
2517 req
->rq_flags
|= RQF_STATS
;
2518 wbt_issue(req
->q
->rq_wb
, &req
->issue_stat
);
2521 BUG_ON(test_bit(REQ_ATOM_COMPLETE
, &req
->atomic_flags
));
2524 EXPORT_SYMBOL(blk_start_request
);
2527 * blk_fetch_request - fetch a request from a request queue
2528 * @q: request queue to fetch a request from
2531 * Return the request at the top of @q. The request is started on
2532 * return and LLD can start processing it immediately.
2535 * Pointer to the request at the top of @q if available. Null
2539 * queue_lock must be held.
2541 struct request
*blk_fetch_request(struct request_queue
*q
)
2545 rq
= blk_peek_request(q
);
2547 blk_start_request(rq
);
2550 EXPORT_SYMBOL(blk_fetch_request
);
2553 * blk_update_request - Special helper function for request stacking drivers
2554 * @req: the request being processed
2555 * @error: %0 for success, < %0 for error
2556 * @nr_bytes: number of bytes to complete @req
2559 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2560 * the request structure even if @req doesn't have leftover.
2561 * If @req has leftover, sets it up for the next range of segments.
2563 * This special helper function is only for request stacking drivers
2564 * (e.g. request-based dm) so that they can handle partial completion.
2565 * Actual device drivers should use blk_end_request instead.
2567 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2568 * %false return from this function.
2571 * %false - this request doesn't have any more data
2572 * %true - this request has more data
2574 bool blk_update_request(struct request
*req
, int error
, unsigned int nr_bytes
)
2578 trace_block_rq_complete(req
, error
, nr_bytes
);
2583 if (error
&& !blk_rq_is_passthrough(req
) &&
2584 !(req
->rq_flags
& RQF_QUIET
)) {
2589 error_type
= "recoverable transport";
2592 error_type
= "critical target";
2595 error_type
= "critical nexus";
2598 error_type
= "timeout";
2601 error_type
= "critical space allocation";
2604 error_type
= "critical medium";
2611 printk_ratelimited(KERN_ERR
"%s: %s error, dev %s, sector %llu\n",
2612 __func__
, error_type
, req
->rq_disk
?
2613 req
->rq_disk
->disk_name
: "?",
2614 (unsigned long long)blk_rq_pos(req
));
2618 blk_account_io_completion(req
, nr_bytes
);
2622 struct bio
*bio
= req
->bio
;
2623 unsigned bio_bytes
= min(bio
->bi_iter
.bi_size
, nr_bytes
);
2625 if (bio_bytes
== bio
->bi_iter
.bi_size
)
2626 req
->bio
= bio
->bi_next
;
2628 /* Completion has already been traced */
2629 bio_clear_flag(bio
, BIO_TRACE_COMPLETION
);
2630 req_bio_endio(req
, bio
, bio_bytes
, error
);
2632 total_bytes
+= bio_bytes
;
2633 nr_bytes
-= bio_bytes
;
2644 * Reset counters so that the request stacking driver
2645 * can find how many bytes remain in the request
2648 req
->__data_len
= 0;
2652 WARN_ON_ONCE(req
->rq_flags
& RQF_SPECIAL_PAYLOAD
);
2654 req
->__data_len
-= total_bytes
;
2656 /* update sector only for requests with clear definition of sector */
2657 if (!blk_rq_is_passthrough(req
))
2658 req
->__sector
+= total_bytes
>> 9;
2660 /* mixed attributes always follow the first bio */
2661 if (req
->rq_flags
& RQF_MIXED_MERGE
) {
2662 req
->cmd_flags
&= ~REQ_FAILFAST_MASK
;
2663 req
->cmd_flags
|= req
->bio
->bi_opf
& REQ_FAILFAST_MASK
;
2667 * If total number of sectors is less than the first segment
2668 * size, something has gone terribly wrong.
2670 if (blk_rq_bytes(req
) < blk_rq_cur_bytes(req
)) {
2671 blk_dump_rq_flags(req
, "request botched");
2672 req
->__data_len
= blk_rq_cur_bytes(req
);
2675 /* recalculate the number of segments */
2676 blk_recalc_rq_segments(req
);
2680 EXPORT_SYMBOL_GPL(blk_update_request
);
2682 static bool blk_update_bidi_request(struct request
*rq
, int error
,
2683 unsigned int nr_bytes
,
2684 unsigned int bidi_bytes
)
2686 if (blk_update_request(rq
, error
, nr_bytes
))
2689 /* Bidi request must be completed as a whole */
2690 if (unlikely(blk_bidi_rq(rq
)) &&
2691 blk_update_request(rq
->next_rq
, error
, bidi_bytes
))
2694 if (blk_queue_add_random(rq
->q
))
2695 add_disk_randomness(rq
->rq_disk
);
2701 * blk_unprep_request - unprepare a request
2704 * This function makes a request ready for complete resubmission (or
2705 * completion). It happens only after all error handling is complete,
2706 * so represents the appropriate moment to deallocate any resources
2707 * that were allocated to the request in the prep_rq_fn. The queue
2708 * lock is held when calling this.
2710 void blk_unprep_request(struct request
*req
)
2712 struct request_queue
*q
= req
->q
;
2714 req
->rq_flags
&= ~RQF_DONTPREP
;
2715 if (q
->unprep_rq_fn
)
2716 q
->unprep_rq_fn(q
, req
);
2718 EXPORT_SYMBOL_GPL(blk_unprep_request
);
2721 * queue lock must be held
2723 void blk_finish_request(struct request
*req
, int error
)
2725 struct request_queue
*q
= req
->q
;
2727 if (req
->rq_flags
& RQF_STATS
)
2730 if (req
->rq_flags
& RQF_QUEUED
)
2731 blk_queue_end_tag(q
, req
);
2733 BUG_ON(blk_queued_rq(req
));
2735 if (unlikely(laptop_mode
) && !blk_rq_is_passthrough(req
))
2736 laptop_io_completion(req
->q
->backing_dev_info
);
2738 blk_delete_timer(req
);
2740 if (req
->rq_flags
& RQF_DONTPREP
)
2741 blk_unprep_request(req
);
2743 blk_account_io_done(req
);
2746 wbt_done(req
->q
->rq_wb
, &req
->issue_stat
);
2747 req
->end_io(req
, error
);
2749 if (blk_bidi_rq(req
))
2750 __blk_put_request(req
->next_rq
->q
, req
->next_rq
);
2752 __blk_put_request(q
, req
);
2755 EXPORT_SYMBOL(blk_finish_request
);
2758 * blk_end_bidi_request - Complete a bidi request
2759 * @rq: the request to complete
2760 * @error: %0 for success, < %0 for error
2761 * @nr_bytes: number of bytes to complete @rq
2762 * @bidi_bytes: number of bytes to complete @rq->next_rq
2765 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2766 * Drivers that supports bidi can safely call this member for any
2767 * type of request, bidi or uni. In the later case @bidi_bytes is
2771 * %false - we are done with this request
2772 * %true - still buffers pending for this request
2774 static bool blk_end_bidi_request(struct request
*rq
, int error
,
2775 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2777 struct request_queue
*q
= rq
->q
;
2778 unsigned long flags
;
2780 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2783 spin_lock_irqsave(q
->queue_lock
, flags
);
2784 blk_finish_request(rq
, error
);
2785 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2791 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2792 * @rq: the request to complete
2793 * @error: %0 for success, < %0 for error
2794 * @nr_bytes: number of bytes to complete @rq
2795 * @bidi_bytes: number of bytes to complete @rq->next_rq
2798 * Identical to blk_end_bidi_request() except that queue lock is
2799 * assumed to be locked on entry and remains so on return.
2802 * %false - we are done with this request
2803 * %true - still buffers pending for this request
2805 static bool __blk_end_bidi_request(struct request
*rq
, int error
,
2806 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2808 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2811 blk_finish_request(rq
, error
);
2817 * blk_end_request - Helper function for drivers to complete the request.
2818 * @rq: the request being processed
2819 * @error: %0 for success, < %0 for error
2820 * @nr_bytes: number of bytes to complete
2823 * Ends I/O on a number of bytes attached to @rq.
2824 * If @rq has leftover, sets it up for the next range of segments.
2827 * %false - we are done with this request
2828 * %true - still buffers pending for this request
2830 bool blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2832 return blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2834 EXPORT_SYMBOL(blk_end_request
);
2837 * blk_end_request_all - Helper function for drives to finish the request.
2838 * @rq: the request to finish
2839 * @error: %0 for success, < %0 for error
2842 * Completely finish @rq.
2844 void blk_end_request_all(struct request
*rq
, int error
)
2847 unsigned int bidi_bytes
= 0;
2849 if (unlikely(blk_bidi_rq(rq
)))
2850 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2852 pending
= blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2855 EXPORT_SYMBOL(blk_end_request_all
);
2858 * __blk_end_request - Helper function for drivers to complete the request.
2859 * @rq: the request being processed
2860 * @error: %0 for success, < %0 for error
2861 * @nr_bytes: number of bytes to complete
2864 * Must be called with queue lock held unlike blk_end_request().
2867 * %false - we are done with this request
2868 * %true - still buffers pending for this request
2870 bool __blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2872 return __blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2874 EXPORT_SYMBOL(__blk_end_request
);
2877 * __blk_end_request_all - Helper function for drives to finish the request.
2878 * @rq: the request to finish
2879 * @error: %0 for success, < %0 for error
2882 * Completely finish @rq. Must be called with queue lock held.
2884 void __blk_end_request_all(struct request
*rq
, int error
)
2887 unsigned int bidi_bytes
= 0;
2889 if (unlikely(blk_bidi_rq(rq
)))
2890 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2892 pending
= __blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2895 EXPORT_SYMBOL(__blk_end_request_all
);
2898 * __blk_end_request_cur - Helper function to finish the current request chunk.
2899 * @rq: the request to finish the current chunk for
2900 * @error: %0 for success, < %0 for error
2903 * Complete the current consecutively mapped chunk from @rq. Must
2904 * be called with queue lock held.
2907 * %false - we are done with this request
2908 * %true - still buffers pending for this request
2910 bool __blk_end_request_cur(struct request
*rq
, int error
)
2912 return __blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2914 EXPORT_SYMBOL(__blk_end_request_cur
);
2916 void blk_rq_bio_prep(struct request_queue
*q
, struct request
*rq
,
2919 if (bio_has_data(bio
))
2920 rq
->nr_phys_segments
= bio_phys_segments(q
, bio
);
2922 rq
->__data_len
= bio
->bi_iter
.bi_size
;
2923 rq
->bio
= rq
->biotail
= bio
;
2926 rq
->rq_disk
= bio
->bi_bdev
->bd_disk
;
2929 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2931 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2932 * @rq: the request to be flushed
2935 * Flush all pages in @rq.
2937 void rq_flush_dcache_pages(struct request
*rq
)
2939 struct req_iterator iter
;
2940 struct bio_vec bvec
;
2942 rq_for_each_segment(bvec
, rq
, iter
)
2943 flush_dcache_page(bvec
.bv_page
);
2945 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages
);
2949 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2950 * @q : the queue of the device being checked
2953 * Check if underlying low-level drivers of a device are busy.
2954 * If the drivers want to export their busy state, they must set own
2955 * exporting function using blk_queue_lld_busy() first.
2957 * Basically, this function is used only by request stacking drivers
2958 * to stop dispatching requests to underlying devices when underlying
2959 * devices are busy. This behavior helps more I/O merging on the queue
2960 * of the request stacking driver and prevents I/O throughput regression
2961 * on burst I/O load.
2964 * 0 - Not busy (The request stacking driver should dispatch request)
2965 * 1 - Busy (The request stacking driver should stop dispatching request)
2967 int blk_lld_busy(struct request_queue
*q
)
2970 return q
->lld_busy_fn(q
);
2974 EXPORT_SYMBOL_GPL(blk_lld_busy
);
2977 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2978 * @rq: the clone request to be cleaned up
2981 * Free all bios in @rq for a cloned request.
2983 void blk_rq_unprep_clone(struct request
*rq
)
2987 while ((bio
= rq
->bio
) != NULL
) {
2988 rq
->bio
= bio
->bi_next
;
2993 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone
);
2996 * Copy attributes of the original request to the clone request.
2997 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
2999 static void __blk_rq_prep_clone(struct request
*dst
, struct request
*src
)
3001 dst
->cpu
= src
->cpu
;
3002 dst
->__sector
= blk_rq_pos(src
);
3003 dst
->__data_len
= blk_rq_bytes(src
);
3004 dst
->nr_phys_segments
= src
->nr_phys_segments
;
3005 dst
->ioprio
= src
->ioprio
;
3006 dst
->extra_len
= src
->extra_len
;
3010 * blk_rq_prep_clone - Helper function to setup clone request
3011 * @rq: the request to be setup
3012 * @rq_src: original request to be cloned
3013 * @bs: bio_set that bios for clone are allocated from
3014 * @gfp_mask: memory allocation mask for bio
3015 * @bio_ctr: setup function to be called for each clone bio.
3016 * Returns %0 for success, non %0 for failure.
3017 * @data: private data to be passed to @bio_ctr
3020 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3021 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3022 * are not copied, and copying such parts is the caller's responsibility.
3023 * Also, pages which the original bios are pointing to are not copied
3024 * and the cloned bios just point same pages.
3025 * So cloned bios must be completed before original bios, which means
3026 * the caller must complete @rq before @rq_src.
3028 int blk_rq_prep_clone(struct request
*rq
, struct request
*rq_src
,
3029 struct bio_set
*bs
, gfp_t gfp_mask
,
3030 int (*bio_ctr
)(struct bio
*, struct bio
*, void *),
3033 struct bio
*bio
, *bio_src
;
3038 __rq_for_each_bio(bio_src
, rq_src
) {
3039 bio
= bio_clone_fast(bio_src
, gfp_mask
, bs
);
3043 if (bio_ctr
&& bio_ctr(bio
, bio_src
, data
))
3047 rq
->biotail
->bi_next
= bio
;
3050 rq
->bio
= rq
->biotail
= bio
;
3053 __blk_rq_prep_clone(rq
, rq_src
);
3060 blk_rq_unprep_clone(rq
);
3064 EXPORT_SYMBOL_GPL(blk_rq_prep_clone
);
3066 int kblockd_schedule_work(struct work_struct
*work
)
3068 return queue_work(kblockd_workqueue
, work
);
3070 EXPORT_SYMBOL(kblockd_schedule_work
);
3072 int kblockd_schedule_work_on(int cpu
, struct work_struct
*work
)
3074 return queue_work_on(cpu
, kblockd_workqueue
, work
);
3076 EXPORT_SYMBOL(kblockd_schedule_work_on
);
3078 int kblockd_mod_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
3079 unsigned long delay
)
3081 return mod_delayed_work_on(cpu
, kblockd_workqueue
, dwork
, delay
);
3083 EXPORT_SYMBOL(kblockd_mod_delayed_work_on
);
3085 int kblockd_schedule_delayed_work(struct delayed_work
*dwork
,
3086 unsigned long delay
)
3088 return queue_delayed_work(kblockd_workqueue
, dwork
, delay
);
3090 EXPORT_SYMBOL(kblockd_schedule_delayed_work
);
3092 int kblockd_schedule_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
3093 unsigned long delay
)
3095 return queue_delayed_work_on(cpu
, kblockd_workqueue
, dwork
, delay
);
3097 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on
);
3100 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3101 * @plug: The &struct blk_plug that needs to be initialized
3104 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3105 * pending I/O should the task end up blocking between blk_start_plug() and
3106 * blk_finish_plug(). This is important from a performance perspective, but
3107 * also ensures that we don't deadlock. For instance, if the task is blocking
3108 * for a memory allocation, memory reclaim could end up wanting to free a
3109 * page belonging to that request that is currently residing in our private
3110 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3111 * this kind of deadlock.
3113 void blk_start_plug(struct blk_plug
*plug
)
3115 struct task_struct
*tsk
= current
;
3118 * If this is a nested plug, don't actually assign it.
3123 INIT_LIST_HEAD(&plug
->list
);
3124 INIT_LIST_HEAD(&plug
->mq_list
);
3125 INIT_LIST_HEAD(&plug
->cb_list
);
3127 * Store ordering should not be needed here, since a potential
3128 * preempt will imply a full memory barrier
3132 EXPORT_SYMBOL(blk_start_plug
);
3134 static int plug_rq_cmp(void *priv
, struct list_head
*a
, struct list_head
*b
)
3136 struct request
*rqa
= container_of(a
, struct request
, queuelist
);
3137 struct request
*rqb
= container_of(b
, struct request
, queuelist
);
3139 return !(rqa
->q
< rqb
->q
||
3140 (rqa
->q
== rqb
->q
&& blk_rq_pos(rqa
) < blk_rq_pos(rqb
)));
3144 * If 'from_schedule' is true, then postpone the dispatch of requests
3145 * until a safe kblockd context. We due this to avoid accidental big
3146 * additional stack usage in driver dispatch, in places where the originally
3147 * plugger did not intend it.
3149 static void queue_unplugged(struct request_queue
*q
, unsigned int depth
,
3151 __releases(q
->queue_lock
)
3153 trace_block_unplug(q
, depth
, !from_schedule
);
3156 blk_run_queue_async(q
);
3159 spin_unlock(q
->queue_lock
);
3162 static void flush_plug_callbacks(struct blk_plug
*plug
, bool from_schedule
)
3164 LIST_HEAD(callbacks
);
3166 while (!list_empty(&plug
->cb_list
)) {
3167 list_splice_init(&plug
->cb_list
, &callbacks
);
3169 while (!list_empty(&callbacks
)) {
3170 struct blk_plug_cb
*cb
= list_first_entry(&callbacks
,
3173 list_del(&cb
->list
);
3174 cb
->callback(cb
, from_schedule
);
3179 struct blk_plug_cb
*blk_check_plugged(blk_plug_cb_fn unplug
, void *data
,
3182 struct blk_plug
*plug
= current
->plug
;
3183 struct blk_plug_cb
*cb
;
3188 list_for_each_entry(cb
, &plug
->cb_list
, list
)
3189 if (cb
->callback
== unplug
&& cb
->data
== data
)
3192 /* Not currently on the callback list */
3193 BUG_ON(size
< sizeof(*cb
));
3194 cb
= kzalloc(size
, GFP_ATOMIC
);
3197 cb
->callback
= unplug
;
3198 list_add(&cb
->list
, &plug
->cb_list
);
3202 EXPORT_SYMBOL(blk_check_plugged
);
3204 void blk_flush_plug_list(struct blk_plug
*plug
, bool from_schedule
)
3206 struct request_queue
*q
;
3207 unsigned long flags
;
3212 flush_plug_callbacks(plug
, from_schedule
);
3214 if (!list_empty(&plug
->mq_list
))
3215 blk_mq_flush_plug_list(plug
, from_schedule
);
3217 if (list_empty(&plug
->list
))
3220 list_splice_init(&plug
->list
, &list
);
3222 list_sort(NULL
, &list
, plug_rq_cmp
);
3228 * Save and disable interrupts here, to avoid doing it for every
3229 * queue lock we have to take.
3231 local_irq_save(flags
);
3232 while (!list_empty(&list
)) {
3233 rq
= list_entry_rq(list
.next
);
3234 list_del_init(&rq
->queuelist
);
3238 * This drops the queue lock
3241 queue_unplugged(q
, depth
, from_schedule
);
3244 spin_lock(q
->queue_lock
);
3248 * Short-circuit if @q is dead
3250 if (unlikely(blk_queue_dying(q
))) {
3251 __blk_end_request_all(rq
, -ENODEV
);
3256 * rq is already accounted, so use raw insert
3258 if (op_is_flush(rq
->cmd_flags
))
3259 __elv_add_request(q
, rq
, ELEVATOR_INSERT_FLUSH
);
3261 __elv_add_request(q
, rq
, ELEVATOR_INSERT_SORT_MERGE
);
3267 * This drops the queue lock
3270 queue_unplugged(q
, depth
, from_schedule
);
3272 local_irq_restore(flags
);
3275 void blk_finish_plug(struct blk_plug
*plug
)
3277 if (plug
!= current
->plug
)
3279 blk_flush_plug_list(plug
, false);
3281 current
->plug
= NULL
;
3283 EXPORT_SYMBOL(blk_finish_plug
);
3287 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3288 * @q: the queue of the device
3289 * @dev: the device the queue belongs to
3292 * Initialize runtime-PM-related fields for @q and start auto suspend for
3293 * @dev. Drivers that want to take advantage of request-based runtime PM
3294 * should call this function after @dev has been initialized, and its
3295 * request queue @q has been allocated, and runtime PM for it can not happen
3296 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3297 * cases, driver should call this function before any I/O has taken place.
3299 * This function takes care of setting up using auto suspend for the device,
3300 * the autosuspend delay is set to -1 to make runtime suspend impossible
3301 * until an updated value is either set by user or by driver. Drivers do
3302 * not need to touch other autosuspend settings.
3304 * The block layer runtime PM is request based, so only works for drivers
3305 * that use request as their IO unit instead of those directly use bio's.
3307 void blk_pm_runtime_init(struct request_queue
*q
, struct device
*dev
)
3310 q
->rpm_status
= RPM_ACTIVE
;
3311 pm_runtime_set_autosuspend_delay(q
->dev
, -1);
3312 pm_runtime_use_autosuspend(q
->dev
);
3314 EXPORT_SYMBOL(blk_pm_runtime_init
);
3317 * blk_pre_runtime_suspend - Pre runtime suspend check
3318 * @q: the queue of the device
3321 * This function will check if runtime suspend is allowed for the device
3322 * by examining if there are any requests pending in the queue. If there
3323 * are requests pending, the device can not be runtime suspended; otherwise,
3324 * the queue's status will be updated to SUSPENDING and the driver can
3325 * proceed to suspend the device.
3327 * For the not allowed case, we mark last busy for the device so that
3328 * runtime PM core will try to autosuspend it some time later.
3330 * This function should be called near the start of the device's
3331 * runtime_suspend callback.
3334 * 0 - OK to runtime suspend the device
3335 * -EBUSY - Device should not be runtime suspended
3337 int blk_pre_runtime_suspend(struct request_queue
*q
)
3344 spin_lock_irq(q
->queue_lock
);
3345 if (q
->nr_pending
) {
3347 pm_runtime_mark_last_busy(q
->dev
);
3349 q
->rpm_status
= RPM_SUSPENDING
;
3351 spin_unlock_irq(q
->queue_lock
);
3354 EXPORT_SYMBOL(blk_pre_runtime_suspend
);
3357 * blk_post_runtime_suspend - Post runtime suspend processing
3358 * @q: the queue of the device
3359 * @err: return value of the device's runtime_suspend function
3362 * Update the queue's runtime status according to the return value of the
3363 * device's runtime suspend function and mark last busy for the device so
3364 * that PM core will try to auto suspend the device at a later time.
3366 * This function should be called near the end of the device's
3367 * runtime_suspend callback.
3369 void blk_post_runtime_suspend(struct request_queue
*q
, int err
)
3374 spin_lock_irq(q
->queue_lock
);
3376 q
->rpm_status
= RPM_SUSPENDED
;
3378 q
->rpm_status
= RPM_ACTIVE
;
3379 pm_runtime_mark_last_busy(q
->dev
);
3381 spin_unlock_irq(q
->queue_lock
);
3383 EXPORT_SYMBOL(blk_post_runtime_suspend
);
3386 * blk_pre_runtime_resume - Pre runtime resume processing
3387 * @q: the queue of the device
3390 * Update the queue's runtime status to RESUMING in preparation for the
3391 * runtime resume of the device.
3393 * This function should be called near the start of the device's
3394 * runtime_resume callback.
3396 void blk_pre_runtime_resume(struct request_queue
*q
)
3401 spin_lock_irq(q
->queue_lock
);
3402 q
->rpm_status
= RPM_RESUMING
;
3403 spin_unlock_irq(q
->queue_lock
);
3405 EXPORT_SYMBOL(blk_pre_runtime_resume
);
3408 * blk_post_runtime_resume - Post runtime resume processing
3409 * @q: the queue of the device
3410 * @err: return value of the device's runtime_resume function
3413 * Update the queue's runtime status according to the return value of the
3414 * device's runtime_resume function. If it is successfully resumed, process
3415 * the requests that are queued into the device's queue when it is resuming
3416 * and then mark last busy and initiate autosuspend for it.
3418 * This function should be called near the end of the device's
3419 * runtime_resume callback.
3421 void blk_post_runtime_resume(struct request_queue
*q
, int err
)
3426 spin_lock_irq(q
->queue_lock
);
3428 q
->rpm_status
= RPM_ACTIVE
;
3430 pm_runtime_mark_last_busy(q
->dev
);
3431 pm_request_autosuspend(q
->dev
);
3433 q
->rpm_status
= RPM_SUSPENDED
;
3435 spin_unlock_irq(q
->queue_lock
);
3437 EXPORT_SYMBOL(blk_post_runtime_resume
);
3440 * blk_set_runtime_active - Force runtime status of the queue to be active
3441 * @q: the queue of the device
3443 * If the device is left runtime suspended during system suspend the resume
3444 * hook typically resumes the device and corrects runtime status
3445 * accordingly. However, that does not affect the queue runtime PM status
3446 * which is still "suspended". This prevents processing requests from the
3449 * This function can be used in driver's resume hook to correct queue
3450 * runtime PM status and re-enable peeking requests from the queue. It
3451 * should be called before first request is added to the queue.
3453 void blk_set_runtime_active(struct request_queue
*q
)
3455 spin_lock_irq(q
->queue_lock
);
3456 q
->rpm_status
= RPM_ACTIVE
;
3457 pm_runtime_mark_last_busy(q
->dev
);
3458 pm_request_autosuspend(q
->dev
);
3459 spin_unlock_irq(q
->queue_lock
);
3461 EXPORT_SYMBOL(blk_set_runtime_active
);
3464 int __init
blk_dev_init(void)
3466 BUILD_BUG_ON(REQ_OP_LAST
>= (1 << REQ_OP_BITS
));
3467 BUILD_BUG_ON(REQ_OP_BITS
+ REQ_FLAG_BITS
> 8 *
3468 FIELD_SIZEOF(struct request
, cmd_flags
));
3469 BUILD_BUG_ON(REQ_OP_BITS
+ REQ_FLAG_BITS
> 8 *
3470 FIELD_SIZEOF(struct bio
, bi_opf
));
3472 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3473 kblockd_workqueue
= alloc_workqueue("kblockd",
3474 WQ_MEM_RECLAIM
| WQ_HIGHPRI
, 0);
3475 if (!kblockd_workqueue
)
3476 panic("Failed to create kblockd\n");
3478 request_cachep
= kmem_cache_create("blkdev_requests",
3479 sizeof(struct request
), 0, SLAB_PANIC
, NULL
);
3481 blk_requestq_cachep
= kmem_cache_create("request_queue",
3482 sizeof(struct request_queue
), 0, SLAB_PANIC
, NULL
);
3484 #ifdef CONFIG_DEBUG_FS
3485 blk_debugfs_root
= debugfs_create_dir("block", NULL
);