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>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/block.h>
43 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap
);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap
);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete
);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split
);
47 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug
);
49 DEFINE_IDA(blk_queue_ida
);
52 * For the allocated request tables
54 struct kmem_cache
*request_cachep
= NULL
;
57 * For queue allocation
59 struct kmem_cache
*blk_requestq_cachep
;
62 * Controlling structure to kblockd
64 static struct workqueue_struct
*kblockd_workqueue
;
66 static void blk_clear_congested(struct request_list
*rl
, int sync
)
68 #ifdef CONFIG_CGROUP_WRITEBACK
69 clear_wb_congested(rl
->blkg
->wb_congested
, sync
);
72 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
73 * flip its congestion state for events on other blkcgs.
75 if (rl
== &rl
->q
->root_rl
)
76 clear_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
80 static void blk_set_congested(struct request_list
*rl
, int sync
)
82 #ifdef CONFIG_CGROUP_WRITEBACK
83 set_wb_congested(rl
->blkg
->wb_congested
, sync
);
85 /* see blk_clear_congested() */
86 if (rl
== &rl
->q
->root_rl
)
87 set_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
91 void blk_queue_congestion_threshold(struct request_queue
*q
)
95 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) + 1;
96 if (nr
> q
->nr_requests
)
98 q
->nr_congestion_on
= nr
;
100 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) - (q
->nr_requests
/ 16) - 1;
103 q
->nr_congestion_off
= nr
;
106 void blk_rq_init(struct request_queue
*q
, struct request
*rq
)
108 memset(rq
, 0, sizeof(*rq
));
110 INIT_LIST_HEAD(&rq
->queuelist
);
111 INIT_LIST_HEAD(&rq
->timeout_list
);
114 rq
->__sector
= (sector_t
) -1;
115 INIT_HLIST_NODE(&rq
->hash
);
116 RB_CLEAR_NODE(&rq
->rb_node
);
118 rq
->cmd_len
= BLK_MAX_CDB
;
120 rq
->start_time
= jiffies
;
121 set_start_time_ns(rq
);
124 EXPORT_SYMBOL(blk_rq_init
);
126 static void req_bio_endio(struct request
*rq
, struct bio
*bio
,
127 unsigned int nbytes
, int error
)
130 bio
->bi_error
= error
;
132 if (unlikely(rq
->cmd_flags
& REQ_QUIET
))
133 bio_set_flag(bio
, BIO_QUIET
);
135 bio_advance(bio
, nbytes
);
137 /* don't actually finish bio if it's part of flush sequence */
138 if (bio
->bi_iter
.bi_size
== 0 && !(rq
->cmd_flags
& REQ_FLUSH_SEQ
))
142 void blk_dump_rq_flags(struct request
*rq
, char *msg
)
146 printk(KERN_INFO
"%s: dev %s: type=%x, flags=%llx\n", msg
,
147 rq
->rq_disk
? rq
->rq_disk
->disk_name
: "?", rq
->cmd_type
,
148 (unsigned long long) rq
->cmd_flags
);
150 printk(KERN_INFO
" sector %llu, nr/cnr %u/%u\n",
151 (unsigned long long)blk_rq_pos(rq
),
152 blk_rq_sectors(rq
), blk_rq_cur_sectors(rq
));
153 printk(KERN_INFO
" bio %p, biotail %p, len %u\n",
154 rq
->bio
, rq
->biotail
, blk_rq_bytes(rq
));
156 if (rq
->cmd_type
== REQ_TYPE_BLOCK_PC
) {
157 printk(KERN_INFO
" cdb: ");
158 for (bit
= 0; bit
< BLK_MAX_CDB
; bit
++)
159 printk("%02x ", rq
->cmd
[bit
]);
163 EXPORT_SYMBOL(blk_dump_rq_flags
);
165 static void blk_delay_work(struct work_struct
*work
)
167 struct request_queue
*q
;
169 q
= container_of(work
, struct request_queue
, delay_work
.work
);
170 spin_lock_irq(q
->queue_lock
);
172 spin_unlock_irq(q
->queue_lock
);
176 * blk_delay_queue - restart queueing after defined interval
177 * @q: The &struct request_queue in question
178 * @msecs: Delay in msecs
181 * Sometimes queueing needs to be postponed for a little while, to allow
182 * resources to come back. This function will make sure that queueing is
183 * restarted around the specified time. Queue lock must be held.
185 void blk_delay_queue(struct request_queue
*q
, unsigned long msecs
)
187 if (likely(!blk_queue_dead(q
)))
188 queue_delayed_work(kblockd_workqueue
, &q
->delay_work
,
189 msecs_to_jiffies(msecs
));
191 EXPORT_SYMBOL(blk_delay_queue
);
194 * blk_start_queue_async - asynchronously restart a previously stopped queue
195 * @q: The &struct request_queue in question
198 * blk_start_queue_async() will clear the stop flag on the queue, and
199 * ensure that the request_fn for the queue is run from an async
202 void blk_start_queue_async(struct request_queue
*q
)
204 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
205 blk_run_queue_async(q
);
207 EXPORT_SYMBOL(blk_start_queue_async
);
210 * blk_start_queue - restart a previously stopped queue
211 * @q: The &struct request_queue in question
214 * blk_start_queue() will clear the stop flag on the queue, and call
215 * the request_fn for the queue if it was in a stopped state when
216 * entered. Also see blk_stop_queue(). Queue lock must be held.
218 void blk_start_queue(struct request_queue
*q
)
220 WARN_ON(!in_interrupt() && !irqs_disabled());
222 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
225 EXPORT_SYMBOL(blk_start_queue
);
228 * blk_stop_queue - stop a queue
229 * @q: The &struct request_queue in question
232 * The Linux block layer assumes that a block driver will consume all
233 * entries on the request queue when the request_fn strategy is called.
234 * Often this will not happen, because of hardware limitations (queue
235 * depth settings). If a device driver gets a 'queue full' response,
236 * or if it simply chooses not to queue more I/O at one point, it can
237 * call this function to prevent the request_fn from being called until
238 * the driver has signalled it's ready to go again. This happens by calling
239 * blk_start_queue() to restart queue operations. Queue lock must be held.
241 void blk_stop_queue(struct request_queue
*q
)
243 cancel_delayed_work(&q
->delay_work
);
244 queue_flag_set(QUEUE_FLAG_STOPPED
, q
);
246 EXPORT_SYMBOL(blk_stop_queue
);
249 * blk_sync_queue - cancel any pending callbacks on a queue
253 * The block layer may perform asynchronous callback activity
254 * on a queue, such as calling the unplug function after a timeout.
255 * A block device may call blk_sync_queue to ensure that any
256 * such activity is cancelled, thus allowing it to release resources
257 * that the callbacks might use. The caller must already have made sure
258 * that its ->make_request_fn will not re-add plugging prior to calling
261 * This function does not cancel any asynchronous activity arising
262 * out of elevator or throttling code. That would require elevator_exit()
263 * and blkcg_exit_queue() to be called with queue lock initialized.
266 void blk_sync_queue(struct request_queue
*q
)
268 del_timer_sync(&q
->timeout
);
271 struct blk_mq_hw_ctx
*hctx
;
274 queue_for_each_hw_ctx(q
, hctx
, i
) {
275 cancel_delayed_work_sync(&hctx
->run_work
);
276 cancel_delayed_work_sync(&hctx
->delay_work
);
279 cancel_delayed_work_sync(&q
->delay_work
);
282 EXPORT_SYMBOL(blk_sync_queue
);
285 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
286 * @q: The queue to run
289 * Invoke request handling on a queue if there are any pending requests.
290 * May be used to restart request handling after a request has completed.
291 * This variant runs the queue whether or not the queue has been
292 * stopped. Must be called with the queue lock held and interrupts
293 * disabled. See also @blk_run_queue.
295 inline void __blk_run_queue_uncond(struct request_queue
*q
)
297 if (unlikely(blk_queue_dead(q
)))
301 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
302 * the queue lock internally. As a result multiple threads may be
303 * running such a request function concurrently. Keep track of the
304 * number of active request_fn invocations such that blk_drain_queue()
305 * can wait until all these request_fn calls have finished.
307 q
->request_fn_active
++;
309 q
->request_fn_active
--;
311 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond
);
314 * __blk_run_queue - run a single device queue
315 * @q: The queue to run
318 * See @blk_run_queue. This variant must be called with the queue lock
319 * held and interrupts disabled.
321 void __blk_run_queue(struct request_queue
*q
)
323 if (unlikely(blk_queue_stopped(q
)))
326 __blk_run_queue_uncond(q
);
328 EXPORT_SYMBOL(__blk_run_queue
);
331 * blk_run_queue_async - run a single device queue in workqueue context
332 * @q: The queue to run
335 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
336 * of us. The caller must hold the queue lock.
338 void blk_run_queue_async(struct request_queue
*q
)
340 if (likely(!blk_queue_stopped(q
) && !blk_queue_dead(q
)))
341 mod_delayed_work(kblockd_workqueue
, &q
->delay_work
, 0);
343 EXPORT_SYMBOL(blk_run_queue_async
);
346 * blk_run_queue - run a single device queue
347 * @q: The queue to run
350 * Invoke request handling on this queue, if it has pending work to do.
351 * May be used to restart queueing when a request has completed.
353 void blk_run_queue(struct request_queue
*q
)
357 spin_lock_irqsave(q
->queue_lock
, flags
);
359 spin_unlock_irqrestore(q
->queue_lock
, flags
);
361 EXPORT_SYMBOL(blk_run_queue
);
363 void blk_put_queue(struct request_queue
*q
)
365 kobject_put(&q
->kobj
);
367 EXPORT_SYMBOL(blk_put_queue
);
370 * __blk_drain_queue - drain requests from request_queue
372 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
374 * Drain requests from @q. If @drain_all is set, all requests are drained.
375 * If not, only ELVPRIV requests are drained. The caller is responsible
376 * for ensuring that no new requests which need to be drained are queued.
378 static void __blk_drain_queue(struct request_queue
*q
, bool drain_all
)
379 __releases(q
->queue_lock
)
380 __acquires(q
->queue_lock
)
384 lockdep_assert_held(q
->queue_lock
);
390 * The caller might be trying to drain @q before its
391 * elevator is initialized.
394 elv_drain_elevator(q
);
396 blkcg_drain_queue(q
);
399 * This function might be called on a queue which failed
400 * driver init after queue creation or is not yet fully
401 * active yet. Some drivers (e.g. fd and loop) get unhappy
402 * in such cases. Kick queue iff dispatch queue has
403 * something on it and @q has request_fn set.
405 if (!list_empty(&q
->queue_head
) && q
->request_fn
)
408 drain
|= q
->nr_rqs_elvpriv
;
409 drain
|= q
->request_fn_active
;
412 * Unfortunately, requests are queued at and tracked from
413 * multiple places and there's no single counter which can
414 * be drained. Check all the queues and counters.
417 struct blk_flush_queue
*fq
= blk_get_flush_queue(q
, NULL
);
418 drain
|= !list_empty(&q
->queue_head
);
419 for (i
= 0; i
< 2; i
++) {
420 drain
|= q
->nr_rqs
[i
];
421 drain
|= q
->in_flight
[i
];
423 drain
|= !list_empty(&fq
->flush_queue
[i
]);
430 spin_unlock_irq(q
->queue_lock
);
434 spin_lock_irq(q
->queue_lock
);
438 * With queue marked dead, any woken up waiter will fail the
439 * allocation path, so the wakeup chaining is lost and we're
440 * left with hung waiters. We need to wake up those waiters.
443 struct request_list
*rl
;
445 blk_queue_for_each_rl(rl
, q
)
446 for (i
= 0; i
< ARRAY_SIZE(rl
->wait
); i
++)
447 wake_up_all(&rl
->wait
[i
]);
452 * blk_queue_bypass_start - enter queue bypass mode
453 * @q: queue of interest
455 * In bypass mode, only the dispatch FIFO queue of @q is used. This
456 * function makes @q enter bypass mode and drains all requests which were
457 * throttled or issued before. On return, it's guaranteed that no request
458 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
459 * inside queue or RCU read lock.
461 void blk_queue_bypass_start(struct request_queue
*q
)
463 spin_lock_irq(q
->queue_lock
);
465 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
466 spin_unlock_irq(q
->queue_lock
);
469 * Queues start drained. Skip actual draining till init is
470 * complete. This avoids lenghty delays during queue init which
471 * can happen many times during boot.
473 if (blk_queue_init_done(q
)) {
474 spin_lock_irq(q
->queue_lock
);
475 __blk_drain_queue(q
, false);
476 spin_unlock_irq(q
->queue_lock
);
478 /* ensure blk_queue_bypass() is %true inside RCU read lock */
482 EXPORT_SYMBOL_GPL(blk_queue_bypass_start
);
485 * blk_queue_bypass_end - leave queue bypass mode
486 * @q: queue of interest
488 * Leave bypass mode and restore the normal queueing behavior.
490 void blk_queue_bypass_end(struct request_queue
*q
)
492 spin_lock_irq(q
->queue_lock
);
493 if (!--q
->bypass_depth
)
494 queue_flag_clear(QUEUE_FLAG_BYPASS
, q
);
495 WARN_ON_ONCE(q
->bypass_depth
< 0);
496 spin_unlock_irq(q
->queue_lock
);
498 EXPORT_SYMBOL_GPL(blk_queue_bypass_end
);
500 void blk_set_queue_dying(struct request_queue
*q
)
502 spin_lock_irq(q
->queue_lock
);
503 queue_flag_set(QUEUE_FLAG_DYING
, q
);
504 spin_unlock_irq(q
->queue_lock
);
507 blk_mq_wake_waiters(q
);
509 struct request_list
*rl
;
511 blk_queue_for_each_rl(rl
, q
) {
513 wake_up_all(&rl
->wait
[BLK_RW_SYNC
]);
514 wake_up_all(&rl
->wait
[BLK_RW_ASYNC
]);
519 EXPORT_SYMBOL_GPL(blk_set_queue_dying
);
522 * blk_cleanup_queue - shutdown a request queue
523 * @q: request queue to shutdown
525 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
526 * put it. All future requests will be failed immediately with -ENODEV.
528 void blk_cleanup_queue(struct request_queue
*q
)
530 spinlock_t
*lock
= q
->queue_lock
;
532 /* mark @q DYING, no new request or merges will be allowed afterwards */
533 mutex_lock(&q
->sysfs_lock
);
534 blk_set_queue_dying(q
);
538 * A dying queue is permanently in bypass mode till released. Note
539 * that, unlike blk_queue_bypass_start(), we aren't performing
540 * synchronize_rcu() after entering bypass mode to avoid the delay
541 * as some drivers create and destroy a lot of queues while
542 * probing. This is still safe because blk_release_queue() will be
543 * called only after the queue refcnt drops to zero and nothing,
544 * RCU or not, would be traversing the queue by then.
547 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
549 queue_flag_set(QUEUE_FLAG_NOMERGES
, q
);
550 queue_flag_set(QUEUE_FLAG_NOXMERGES
, q
);
551 queue_flag_set(QUEUE_FLAG_DYING
, q
);
552 spin_unlock_irq(lock
);
553 mutex_unlock(&q
->sysfs_lock
);
556 * Drain all requests queued before DYING marking. Set DEAD flag to
557 * prevent that q->request_fn() gets invoked after draining finished.
562 __blk_drain_queue(q
, true);
563 queue_flag_set(QUEUE_FLAG_DEAD
, q
);
564 spin_unlock_irq(lock
);
566 /* for synchronous bio-based driver finish in-flight integrity i/o */
567 blk_flush_integrity();
569 /* @q won't process any more request, flush async actions */
570 del_timer_sync(&q
->backing_dev_info
->laptop_mode_wb_timer
);
574 blk_mq_free_queue(q
);
575 percpu_ref_exit(&q
->q_usage_counter
);
578 if (q
->queue_lock
!= &q
->__queue_lock
)
579 q
->queue_lock
= &q
->__queue_lock
;
580 spin_unlock_irq(lock
);
582 /* @q is and will stay empty, shutdown and put */
585 EXPORT_SYMBOL(blk_cleanup_queue
);
587 /* Allocate memory local to the request queue */
588 static void *alloc_request_struct(gfp_t gfp_mask
, void *data
)
590 int nid
= (int)(long)data
;
591 return kmem_cache_alloc_node(request_cachep
, gfp_mask
, nid
);
594 static void free_request_struct(void *element
, void *unused
)
596 kmem_cache_free(request_cachep
, element
);
599 int blk_init_rl(struct request_list
*rl
, struct request_queue
*q
,
602 if (unlikely(rl
->rq_pool
))
606 rl
->count
[BLK_RW_SYNC
] = rl
->count
[BLK_RW_ASYNC
] = 0;
607 rl
->starved
[BLK_RW_SYNC
] = rl
->starved
[BLK_RW_ASYNC
] = 0;
608 init_waitqueue_head(&rl
->wait
[BLK_RW_SYNC
]);
609 init_waitqueue_head(&rl
->wait
[BLK_RW_ASYNC
]);
611 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
, alloc_request_struct
,
613 (void *)(long)q
->node
, gfp_mask
,
621 void blk_exit_rl(struct request_list
*rl
)
624 mempool_destroy(rl
->rq_pool
);
627 struct request_queue
*blk_alloc_queue(gfp_t gfp_mask
)
629 return blk_alloc_queue_node(gfp_mask
, NUMA_NO_NODE
);
631 EXPORT_SYMBOL(blk_alloc_queue
);
633 int blk_queue_enter(struct request_queue
*q
, bool nowait
)
638 if (percpu_ref_tryget_live(&q
->q_usage_counter
))
644 ret
= wait_event_interruptible(q
->mq_freeze_wq
,
645 !atomic_read(&q
->mq_freeze_depth
) ||
647 if (blk_queue_dying(q
))
654 void blk_queue_exit(struct request_queue
*q
)
656 percpu_ref_put(&q
->q_usage_counter
);
659 static void blk_queue_usage_counter_release(struct percpu_ref
*ref
)
661 struct request_queue
*q
=
662 container_of(ref
, struct request_queue
, q_usage_counter
);
664 wake_up_all(&q
->mq_freeze_wq
);
667 static void blk_rq_timed_out_timer(unsigned long data
)
669 struct request_queue
*q
= (struct request_queue
*)data
;
671 kblockd_schedule_work(&q
->timeout_work
);
674 struct request_queue
*blk_alloc_queue_node(gfp_t gfp_mask
, int node_id
)
676 struct request_queue
*q
;
678 q
= kmem_cache_alloc_node(blk_requestq_cachep
,
679 gfp_mask
| __GFP_ZERO
, node_id
);
683 q
->id
= ida_simple_get(&blk_queue_ida
, 0, 0, gfp_mask
);
687 q
->bio_split
= bioset_create(BIO_POOL_SIZE
, 0);
691 q
->backing_dev_info
= bdi_alloc_node(gfp_mask
, node_id
);
692 if (!q
->backing_dev_info
)
695 q
->backing_dev_info
->ra_pages
=
696 (VM_MAX_READAHEAD
* 1024) / PAGE_CACHE_SIZE
;
697 q
->backing_dev_info
->capabilities
= BDI_CAP_CGROUP_WRITEBACK
;
698 q
->backing_dev_info
->name
= "block";
701 setup_timer(&q
->backing_dev_info
->laptop_mode_wb_timer
,
702 laptop_mode_timer_fn
, (unsigned long) q
);
703 setup_timer(&q
->timeout
, blk_rq_timed_out_timer
, (unsigned long) q
);
704 INIT_LIST_HEAD(&q
->queue_head
);
705 INIT_LIST_HEAD(&q
->timeout_list
);
706 INIT_LIST_HEAD(&q
->icq_list
);
707 #ifdef CONFIG_BLK_CGROUP
708 INIT_LIST_HEAD(&q
->blkg_list
);
710 INIT_DELAYED_WORK(&q
->delay_work
, blk_delay_work
);
712 kobject_init(&q
->kobj
, &blk_queue_ktype
);
714 mutex_init(&q
->sysfs_lock
);
715 spin_lock_init(&q
->__queue_lock
);
718 * By default initialize queue_lock to internal lock and driver can
719 * override it later if need be.
721 q
->queue_lock
= &q
->__queue_lock
;
724 * A queue starts its life with bypass turned on to avoid
725 * unnecessary bypass on/off overhead and nasty surprises during
726 * init. The initial bypass will be finished when the queue is
727 * registered by blk_register_queue().
730 __set_bit(QUEUE_FLAG_BYPASS
, &q
->queue_flags
);
732 init_waitqueue_head(&q
->mq_freeze_wq
);
735 * Init percpu_ref in atomic mode so that it's faster to shutdown.
736 * See blk_register_queue() for details.
738 if (percpu_ref_init(&q
->q_usage_counter
,
739 blk_queue_usage_counter_release
,
740 PERCPU_REF_INIT_ATOMIC
, GFP_KERNEL
))
743 if (blkcg_init_queue(q
))
749 percpu_ref_exit(&q
->q_usage_counter
);
751 bdi_put(q
->backing_dev_info
);
753 bioset_free(q
->bio_split
);
755 ida_simple_remove(&blk_queue_ida
, q
->id
);
757 kmem_cache_free(blk_requestq_cachep
, q
);
760 EXPORT_SYMBOL(blk_alloc_queue_node
);
763 * blk_init_queue - prepare a request queue for use with a block device
764 * @rfn: The function to be called to process requests that have been
765 * placed on the queue.
766 * @lock: Request queue spin lock
769 * If a block device wishes to use the standard request handling procedures,
770 * which sorts requests and coalesces adjacent requests, then it must
771 * call blk_init_queue(). The function @rfn will be called when there
772 * are requests on the queue that need to be processed. If the device
773 * supports plugging, then @rfn may not be called immediately when requests
774 * are available on the queue, but may be called at some time later instead.
775 * Plugged queues are generally unplugged when a buffer belonging to one
776 * of the requests on the queue is needed, or due to memory pressure.
778 * @rfn is not required, or even expected, to remove all requests off the
779 * queue, but only as many as it can handle at a time. If it does leave
780 * requests on the queue, it is responsible for arranging that the requests
781 * get dealt with eventually.
783 * The queue spin lock must be held while manipulating the requests on the
784 * request queue; this lock will be taken also from interrupt context, so irq
785 * disabling is needed for it.
787 * Function returns a pointer to the initialized request queue, or %NULL if
791 * blk_init_queue() must be paired with a blk_cleanup_queue() call
792 * when the block device is deactivated (such as at module unload).
795 struct request_queue
*blk_init_queue(request_fn_proc
*rfn
, spinlock_t
*lock
)
797 return blk_init_queue_node(rfn
, lock
, NUMA_NO_NODE
);
799 EXPORT_SYMBOL(blk_init_queue
);
801 struct request_queue
*
802 blk_init_queue_node(request_fn_proc
*rfn
, spinlock_t
*lock
, int node_id
)
804 struct request_queue
*uninit_q
, *q
;
806 uninit_q
= blk_alloc_queue_node(GFP_KERNEL
, node_id
);
810 q
= blk_init_allocated_queue(uninit_q
, rfn
, lock
);
812 blk_cleanup_queue(uninit_q
);
816 EXPORT_SYMBOL(blk_init_queue_node
);
818 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
);
820 struct request_queue
*
821 blk_init_allocated_queue(struct request_queue
*q
, request_fn_proc
*rfn
,
827 q
->fq
= blk_alloc_flush_queue(q
, NUMA_NO_NODE
, 0);
831 if (blk_init_rl(&q
->root_rl
, q
, GFP_KERNEL
))
834 INIT_WORK(&q
->timeout_work
, blk_timeout_work
);
836 q
->prep_rq_fn
= NULL
;
837 q
->unprep_rq_fn
= NULL
;
838 q
->queue_flags
|= QUEUE_FLAG_DEFAULT
;
840 /* Override internal queue lock with supplied lock pointer */
842 q
->queue_lock
= lock
;
845 * This also sets hw/phys segments, boundary and size
847 blk_queue_make_request(q
, blk_queue_bio
);
849 q
->sg_reserved_size
= INT_MAX
;
851 /* Protect q->elevator from elevator_change */
852 mutex_lock(&q
->sysfs_lock
);
855 if (elevator_init(q
, NULL
)) {
856 mutex_unlock(&q
->sysfs_lock
);
860 mutex_unlock(&q
->sysfs_lock
);
865 blk_free_flush_queue(q
->fq
);
868 EXPORT_SYMBOL(blk_init_allocated_queue
);
870 bool blk_get_queue(struct request_queue
*q
)
872 if (likely(!blk_queue_dying(q
))) {
879 EXPORT_SYMBOL(blk_get_queue
);
881 static inline void blk_free_request(struct request_list
*rl
, struct request
*rq
)
883 if (rq
->cmd_flags
& REQ_ELVPRIV
) {
884 elv_put_request(rl
->q
, rq
);
886 put_io_context(rq
->elv
.icq
->ioc
);
889 mempool_free(rq
, rl
->rq_pool
);
893 * ioc_batching returns true if the ioc is a valid batching request and
894 * should be given priority access to a request.
896 static inline int ioc_batching(struct request_queue
*q
, struct io_context
*ioc
)
902 * Make sure the process is able to allocate at least 1 request
903 * even if the batch times out, otherwise we could theoretically
906 return ioc
->nr_batch_requests
== q
->nr_batching
||
907 (ioc
->nr_batch_requests
> 0
908 && time_before(jiffies
, ioc
->last_waited
+ BLK_BATCH_TIME
));
912 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
913 * will cause the process to be a "batcher" on all queues in the system. This
914 * is the behaviour we want though - once it gets a wakeup it should be given
917 static void ioc_set_batching(struct request_queue
*q
, struct io_context
*ioc
)
919 if (!ioc
|| ioc_batching(q
, ioc
))
922 ioc
->nr_batch_requests
= q
->nr_batching
;
923 ioc
->last_waited
= jiffies
;
926 static void __freed_request(struct request_list
*rl
, int sync
)
928 struct request_queue
*q
= rl
->q
;
930 if (rl
->count
[sync
] < queue_congestion_off_threshold(q
))
931 blk_clear_congested(rl
, sync
);
933 if (rl
->count
[sync
] + 1 <= q
->nr_requests
) {
934 if (waitqueue_active(&rl
->wait
[sync
]))
935 wake_up(&rl
->wait
[sync
]);
937 blk_clear_rl_full(rl
, sync
);
942 * A request has just been released. Account for it, update the full and
943 * congestion status, wake up any waiters. Called under q->queue_lock.
945 static void freed_request(struct request_list
*rl
, unsigned int flags
)
947 struct request_queue
*q
= rl
->q
;
948 int sync
= rw_is_sync(flags
);
952 if (flags
& REQ_ELVPRIV
)
955 __freed_request(rl
, sync
);
957 if (unlikely(rl
->starved
[sync
^ 1]))
958 __freed_request(rl
, sync
^ 1);
961 int blk_update_nr_requests(struct request_queue
*q
, unsigned int nr
)
963 struct request_list
*rl
;
964 int on_thresh
, off_thresh
;
966 spin_lock_irq(q
->queue_lock
);
968 blk_queue_congestion_threshold(q
);
969 on_thresh
= queue_congestion_on_threshold(q
);
970 off_thresh
= queue_congestion_off_threshold(q
);
972 blk_queue_for_each_rl(rl
, q
) {
973 if (rl
->count
[BLK_RW_SYNC
] >= on_thresh
)
974 blk_set_congested(rl
, BLK_RW_SYNC
);
975 else if (rl
->count
[BLK_RW_SYNC
] < off_thresh
)
976 blk_clear_congested(rl
, BLK_RW_SYNC
);
978 if (rl
->count
[BLK_RW_ASYNC
] >= on_thresh
)
979 blk_set_congested(rl
, BLK_RW_ASYNC
);
980 else if (rl
->count
[BLK_RW_ASYNC
] < off_thresh
)
981 blk_clear_congested(rl
, BLK_RW_ASYNC
);
983 if (rl
->count
[BLK_RW_SYNC
] >= q
->nr_requests
) {
984 blk_set_rl_full(rl
, BLK_RW_SYNC
);
986 blk_clear_rl_full(rl
, BLK_RW_SYNC
);
987 wake_up(&rl
->wait
[BLK_RW_SYNC
]);
990 if (rl
->count
[BLK_RW_ASYNC
] >= q
->nr_requests
) {
991 blk_set_rl_full(rl
, BLK_RW_ASYNC
);
993 blk_clear_rl_full(rl
, BLK_RW_ASYNC
);
994 wake_up(&rl
->wait
[BLK_RW_ASYNC
]);
998 spin_unlock_irq(q
->queue_lock
);
1003 * Determine if elevator data should be initialized when allocating the
1004 * request associated with @bio.
1006 static bool blk_rq_should_init_elevator(struct bio
*bio
)
1012 * Flush requests do not use the elevator so skip initialization.
1013 * This allows a request to share the flush and elevator data.
1015 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
))
1022 * rq_ioc - determine io_context for request allocation
1023 * @bio: request being allocated is for this bio (can be %NULL)
1025 * Determine io_context to use for request allocation for @bio. May return
1026 * %NULL if %current->io_context doesn't exist.
1028 static struct io_context
*rq_ioc(struct bio
*bio
)
1030 #ifdef CONFIG_BLK_CGROUP
1031 if (bio
&& bio
->bi_ioc
)
1034 return current
->io_context
;
1038 * __get_request - get a free request
1039 * @rl: request list to allocate from
1040 * @rw_flags: RW and SYNC flags
1041 * @bio: bio to allocate request for (can be %NULL)
1042 * @gfp_mask: allocation mask
1044 * Get a free request from @q. This function may fail under memory
1045 * pressure or if @q is dead.
1047 * Must be called with @q->queue_lock held and,
1048 * Returns ERR_PTR on failure, with @q->queue_lock held.
1049 * Returns request pointer on success, with @q->queue_lock *not held*.
1051 static struct request
*__get_request(struct request_list
*rl
, int rw_flags
,
1052 struct bio
*bio
, gfp_t gfp_mask
)
1054 struct request_queue
*q
= rl
->q
;
1056 struct elevator_type
*et
= q
->elevator
->type
;
1057 struct io_context
*ioc
= rq_ioc(bio
);
1058 struct io_cq
*icq
= NULL
;
1059 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
1062 if (unlikely(blk_queue_dying(q
)))
1063 return ERR_PTR(-ENODEV
);
1065 may_queue
= elv_may_queue(q
, rw_flags
);
1066 if (may_queue
== ELV_MQUEUE_NO
)
1069 if (rl
->count
[is_sync
]+1 >= queue_congestion_on_threshold(q
)) {
1070 if (rl
->count
[is_sync
]+1 >= q
->nr_requests
) {
1072 * The queue will fill after this allocation, so set
1073 * it as full, and mark this process as "batching".
1074 * This process will be allowed to complete a batch of
1075 * requests, others will be blocked.
1077 if (!blk_rl_full(rl
, is_sync
)) {
1078 ioc_set_batching(q
, ioc
);
1079 blk_set_rl_full(rl
, is_sync
);
1081 if (may_queue
!= ELV_MQUEUE_MUST
1082 && !ioc_batching(q
, ioc
)) {
1084 * The queue is full and the allocating
1085 * process is not a "batcher", and not
1086 * exempted by the IO scheduler
1088 return ERR_PTR(-ENOMEM
);
1092 blk_set_congested(rl
, is_sync
);
1096 * Only allow batching queuers to allocate up to 50% over the defined
1097 * limit of requests, otherwise we could have thousands of requests
1098 * allocated with any setting of ->nr_requests
1100 if (rl
->count
[is_sync
] >= (3 * q
->nr_requests
/ 2))
1101 return ERR_PTR(-ENOMEM
);
1103 q
->nr_rqs
[is_sync
]++;
1104 rl
->count
[is_sync
]++;
1105 rl
->starved
[is_sync
] = 0;
1108 * Decide whether the new request will be managed by elevator. If
1109 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
1110 * prevent the current elevator from being destroyed until the new
1111 * request is freed. This guarantees icq's won't be destroyed and
1112 * makes creating new ones safe.
1114 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1115 * it will be created after releasing queue_lock.
1117 if (blk_rq_should_init_elevator(bio
) && !blk_queue_bypass(q
)) {
1118 rw_flags
|= REQ_ELVPRIV
;
1119 q
->nr_rqs_elvpriv
++;
1120 if (et
->icq_cache
&& ioc
)
1121 icq
= ioc_lookup_icq(ioc
, q
);
1124 if (blk_queue_io_stat(q
))
1125 rw_flags
|= REQ_IO_STAT
;
1126 spin_unlock_irq(q
->queue_lock
);
1128 /* allocate and init request */
1129 rq
= mempool_alloc(rl
->rq_pool
, gfp_mask
);
1134 blk_rq_set_rl(rq
, rl
);
1135 rq
->cmd_flags
= rw_flags
| REQ_ALLOCED
;
1138 if (rw_flags
& REQ_ELVPRIV
) {
1139 if (unlikely(et
->icq_cache
&& !icq
)) {
1141 icq
= ioc_create_icq(ioc
, q
, gfp_mask
);
1147 if (unlikely(elv_set_request(q
, rq
, bio
, gfp_mask
)))
1150 /* @rq->elv.icq holds io_context until @rq is freed */
1152 get_io_context(icq
->ioc
);
1156 * ioc may be NULL here, and ioc_batching will be false. That's
1157 * OK, if the queue is under the request limit then requests need
1158 * not count toward the nr_batch_requests limit. There will always
1159 * be some limit enforced by BLK_BATCH_TIME.
1161 if (ioc_batching(q
, ioc
))
1162 ioc
->nr_batch_requests
--;
1164 trace_block_getrq(q
, bio
, rw_flags
& 1);
1169 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1170 * and may fail indefinitely under memory pressure and thus
1171 * shouldn't stall IO. Treat this request as !elvpriv. This will
1172 * disturb iosched and blkcg but weird is bettern than dead.
1174 printk_ratelimited(KERN_WARNING
"%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1175 __func__
, dev_name(q
->backing_dev_info
->dev
));
1177 rq
->cmd_flags
&= ~REQ_ELVPRIV
;
1180 spin_lock_irq(q
->queue_lock
);
1181 q
->nr_rqs_elvpriv
--;
1182 spin_unlock_irq(q
->queue_lock
);
1187 * Allocation failed presumably due to memory. Undo anything we
1188 * might have messed up.
1190 * Allocating task should really be put onto the front of the wait
1191 * queue, but this is pretty rare.
1193 spin_lock_irq(q
->queue_lock
);
1194 freed_request(rl
, rw_flags
);
1197 * in the very unlikely event that allocation failed and no
1198 * requests for this direction was pending, mark us starved so that
1199 * freeing of a request in the other direction will notice
1200 * us. another possible fix would be to split the rq mempool into
1204 if (unlikely(rl
->count
[is_sync
] == 0))
1205 rl
->starved
[is_sync
] = 1;
1206 return ERR_PTR(-ENOMEM
);
1210 * get_request - get a free request
1211 * @q: request_queue to allocate request from
1212 * @rw_flags: RW and SYNC flags
1213 * @bio: bio to allocate request for (can be %NULL)
1214 * @gfp_mask: allocation mask
1216 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1217 * this function keeps retrying under memory pressure and fails iff @q is dead.
1219 * Must be called with @q->queue_lock held and,
1220 * Returns ERR_PTR on failure, with @q->queue_lock held.
1221 * Returns request pointer on success, with @q->queue_lock *not held*.
1223 static struct request
*get_request(struct request_queue
*q
, int rw_flags
,
1224 struct bio
*bio
, gfp_t gfp_mask
)
1226 const bool is_sync
= rw_is_sync(rw_flags
) != 0;
1228 struct request_list
*rl
;
1231 rl
= blk_get_rl(q
, bio
); /* transferred to @rq on success */
1233 rq
= __get_request(rl
, rw_flags
, bio
, gfp_mask
);
1237 if (!gfpflags_allow_blocking(gfp_mask
) || unlikely(blk_queue_dying(q
))) {
1242 /* wait on @rl and retry */
1243 prepare_to_wait_exclusive(&rl
->wait
[is_sync
], &wait
,
1244 TASK_UNINTERRUPTIBLE
);
1246 trace_block_sleeprq(q
, bio
, rw_flags
& 1);
1248 spin_unlock_irq(q
->queue_lock
);
1252 * After sleeping, we become a "batching" process and will be able
1253 * to allocate at least one request, and up to a big batch of them
1254 * for a small period time. See ioc_batching, ioc_set_batching
1256 ioc_set_batching(q
, current
->io_context
);
1258 spin_lock_irq(q
->queue_lock
);
1259 finish_wait(&rl
->wait
[is_sync
], &wait
);
1264 static struct request
*blk_old_get_request(struct request_queue
*q
, int rw
,
1269 BUG_ON(rw
!= READ
&& rw
!= WRITE
);
1271 /* create ioc upfront */
1272 create_io_context(gfp_mask
, q
->node
);
1274 spin_lock_irq(q
->queue_lock
);
1275 rq
= get_request(q
, rw
, NULL
, gfp_mask
);
1277 spin_unlock_irq(q
->queue_lock
);
1278 /* q->queue_lock is unlocked at this point */
1283 struct request
*blk_get_request(struct request_queue
*q
, int rw
, gfp_t gfp_mask
)
1286 return blk_mq_alloc_request(q
, rw
,
1287 (gfp_mask
& __GFP_DIRECT_RECLAIM
) ?
1288 0 : BLK_MQ_REQ_NOWAIT
);
1290 return blk_old_get_request(q
, rw
, gfp_mask
);
1292 EXPORT_SYMBOL(blk_get_request
);
1295 * blk_make_request - given a bio, allocate a corresponding struct request.
1296 * @q: target request queue
1297 * @bio: The bio describing the memory mappings that will be submitted for IO.
1298 * It may be a chained-bio properly constructed by block/bio layer.
1299 * @gfp_mask: gfp flags to be used for memory allocation
1301 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1302 * type commands. Where the struct request needs to be farther initialized by
1303 * the caller. It is passed a &struct bio, which describes the memory info of
1306 * The caller of blk_make_request must make sure that bi_io_vec
1307 * are set to describe the memory buffers. That bio_data_dir() will return
1308 * the needed direction of the request. (And all bio's in the passed bio-chain
1309 * are properly set accordingly)
1311 * If called under none-sleepable conditions, mapped bio buffers must not
1312 * need bouncing, by calling the appropriate masked or flagged allocator,
1313 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1316 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1317 * given to how you allocate bios. In particular, you cannot use
1318 * __GFP_DIRECT_RECLAIM for anything but the first bio in the chain. Otherwise
1319 * you risk waiting for IO completion of a bio that hasn't been submitted yet,
1320 * thus resulting in a deadlock. Alternatively bios should be allocated using
1321 * bio_kmalloc() instead of bio_alloc(), as that avoids the mempool deadlock.
1322 * If possible a big IO should be split into smaller parts when allocation
1323 * fails. Partial allocation should not be an error, or you risk a live-lock.
1325 struct request
*blk_make_request(struct request_queue
*q
, struct bio
*bio
,
1328 struct request
*rq
= blk_get_request(q
, bio_data_dir(bio
), gfp_mask
);
1333 blk_rq_set_block_pc(rq
);
1336 struct bio
*bounce_bio
= bio
;
1339 blk_queue_bounce(q
, &bounce_bio
);
1340 ret
= blk_rq_append_bio(q
, rq
, bounce_bio
);
1341 if (unlikely(ret
)) {
1342 blk_put_request(rq
);
1343 return ERR_PTR(ret
);
1349 EXPORT_SYMBOL(blk_make_request
);
1352 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1353 * @rq: request to be initialized
1356 void blk_rq_set_block_pc(struct request
*rq
)
1358 rq
->cmd_type
= REQ_TYPE_BLOCK_PC
;
1360 rq
->__sector
= (sector_t
) -1;
1361 rq
->bio
= rq
->biotail
= NULL
;
1362 memset(rq
->__cmd
, 0, sizeof(rq
->__cmd
));
1364 EXPORT_SYMBOL(blk_rq_set_block_pc
);
1367 * blk_requeue_request - put a request back on queue
1368 * @q: request queue where request should be inserted
1369 * @rq: request to be inserted
1372 * Drivers often keep queueing requests until the hardware cannot accept
1373 * more, when that condition happens we need to put the request back
1374 * on the queue. Must be called with queue lock held.
1376 void blk_requeue_request(struct request_queue
*q
, struct request
*rq
)
1378 blk_delete_timer(rq
);
1379 blk_clear_rq_complete(rq
);
1380 trace_block_rq_requeue(q
, rq
);
1382 if (rq
->cmd_flags
& REQ_QUEUED
)
1383 blk_queue_end_tag(q
, rq
);
1385 BUG_ON(blk_queued_rq(rq
));
1387 elv_requeue_request(q
, rq
);
1389 EXPORT_SYMBOL(blk_requeue_request
);
1391 static void add_acct_request(struct request_queue
*q
, struct request
*rq
,
1394 blk_account_io_start(rq
, true);
1395 __elv_add_request(q
, rq
, where
);
1398 static void part_round_stats_single(int cpu
, struct hd_struct
*part
,
1403 if (now
== part
->stamp
)
1406 inflight
= part_in_flight(part
);
1408 __part_stat_add(cpu
, part
, time_in_queue
,
1409 inflight
* (now
- part
->stamp
));
1410 __part_stat_add(cpu
, part
, io_ticks
, (now
- part
->stamp
));
1416 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1417 * @cpu: cpu number for stats access
1418 * @part: target partition
1420 * The average IO queue length and utilisation statistics are maintained
1421 * by observing the current state of the queue length and the amount of
1422 * time it has been in this state for.
1424 * Normally, that accounting is done on IO completion, but that can result
1425 * in more than a second's worth of IO being accounted for within any one
1426 * second, leading to >100% utilisation. To deal with that, we call this
1427 * function to do a round-off before returning the results when reading
1428 * /proc/diskstats. This accounts immediately for all queue usage up to
1429 * the current jiffies and restarts the counters again.
1431 void part_round_stats(int cpu
, struct hd_struct
*part
)
1433 unsigned long now
= jiffies
;
1436 part_round_stats_single(cpu
, &part_to_disk(part
)->part0
, now
);
1437 part_round_stats_single(cpu
, part
, now
);
1439 EXPORT_SYMBOL_GPL(part_round_stats
);
1442 static void blk_pm_put_request(struct request
*rq
)
1444 if (rq
->q
->dev
&& !(rq
->cmd_flags
& REQ_PM
) && !--rq
->q
->nr_pending
)
1445 pm_runtime_mark_last_busy(rq
->q
->dev
);
1448 static inline void blk_pm_put_request(struct request
*rq
) {}
1452 * queue lock must be held
1454 void __blk_put_request(struct request_queue
*q
, struct request
*req
)
1460 blk_mq_free_request(req
);
1464 blk_pm_put_request(req
);
1466 elv_completed_request(q
, req
);
1468 /* this is a bio leak */
1469 WARN_ON(req
->bio
!= NULL
);
1472 * Request may not have originated from ll_rw_blk. if not,
1473 * it didn't come out of our reserved rq pools
1475 if (req
->cmd_flags
& REQ_ALLOCED
) {
1476 unsigned int flags
= req
->cmd_flags
;
1477 struct request_list
*rl
= blk_rq_rl(req
);
1479 BUG_ON(!list_empty(&req
->queuelist
));
1480 BUG_ON(ELV_ON_HASH(req
));
1482 blk_free_request(rl
, req
);
1483 freed_request(rl
, flags
);
1487 EXPORT_SYMBOL_GPL(__blk_put_request
);
1489 void blk_put_request(struct request
*req
)
1491 struct request_queue
*q
= req
->q
;
1494 blk_mq_free_request(req
);
1496 unsigned long flags
;
1498 spin_lock_irqsave(q
->queue_lock
, flags
);
1499 __blk_put_request(q
, req
);
1500 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1503 EXPORT_SYMBOL(blk_put_request
);
1506 * blk_add_request_payload - add a payload to a request
1507 * @rq: request to update
1508 * @page: page backing the payload
1509 * @len: length of the payload.
1511 * This allows to later add a payload to an already submitted request by
1512 * a block driver. The driver needs to take care of freeing the payload
1515 * Note that this is a quite horrible hack and nothing but handling of
1516 * discard requests should ever use it.
1518 void blk_add_request_payload(struct request
*rq
, struct page
*page
,
1521 struct bio
*bio
= rq
->bio
;
1523 bio
->bi_io_vec
->bv_page
= page
;
1524 bio
->bi_io_vec
->bv_offset
= 0;
1525 bio
->bi_io_vec
->bv_len
= len
;
1527 bio
->bi_iter
.bi_size
= len
;
1529 bio
->bi_phys_segments
= 1;
1531 rq
->__data_len
= rq
->resid_len
= len
;
1532 rq
->nr_phys_segments
= 1;
1534 EXPORT_SYMBOL_GPL(blk_add_request_payload
);
1536 bool bio_attempt_back_merge(struct request_queue
*q
, struct request
*req
,
1539 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1541 if (!ll_back_merge_fn(q
, req
, bio
))
1544 trace_block_bio_backmerge(q
, req
, bio
);
1546 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1547 blk_rq_set_mixed_merge(req
);
1549 req
->biotail
->bi_next
= bio
;
1551 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1552 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1554 blk_account_io_start(req
, false);
1558 bool bio_attempt_front_merge(struct request_queue
*q
, struct request
*req
,
1561 const int ff
= bio
->bi_rw
& REQ_FAILFAST_MASK
;
1563 if (!ll_front_merge_fn(q
, req
, bio
))
1566 trace_block_bio_frontmerge(q
, req
, bio
);
1568 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1569 blk_rq_set_mixed_merge(req
);
1571 bio
->bi_next
= req
->bio
;
1574 req
->__sector
= bio
->bi_iter
.bi_sector
;
1575 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1576 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1578 blk_account_io_start(req
, false);
1583 * blk_attempt_plug_merge - try to merge with %current's plugged list
1584 * @q: request_queue new bio is being queued at
1585 * @bio: new bio being queued
1586 * @request_count: out parameter for number of traversed plugged requests
1587 * @same_queue_rq: pointer to &struct request that gets filled in when
1588 * another request associated with @q is found on the plug list
1589 * (optional, may be %NULL)
1591 * Determine whether @bio being queued on @q can be merged with a request
1592 * on %current's plugged list. Returns %true if merge was successful,
1595 * Plugging coalesces IOs from the same issuer for the same purpose without
1596 * going through @q->queue_lock. As such it's more of an issuing mechanism
1597 * than scheduling, and the request, while may have elvpriv data, is not
1598 * added on the elevator at this point. In addition, we don't have
1599 * reliable access to the elevator outside queue lock. Only check basic
1600 * merging parameters without querying the elevator.
1602 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1604 bool blk_attempt_plug_merge(struct request_queue
*q
, struct bio
*bio
,
1605 unsigned int *request_count
,
1606 struct request
**same_queue_rq
)
1608 struct blk_plug
*plug
;
1611 struct list_head
*plug_list
;
1613 plug
= current
->plug
;
1619 plug_list
= &plug
->mq_list
;
1621 plug_list
= &plug
->list
;
1623 list_for_each_entry_reverse(rq
, plug_list
, queuelist
) {
1629 * Only blk-mq multiple hardware queues case checks the
1630 * rq in the same queue, there should be only one such
1634 *same_queue_rq
= rq
;
1637 if (rq
->q
!= q
|| !blk_rq_merge_ok(rq
, bio
))
1640 el_ret
= blk_try_merge(rq
, bio
);
1641 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1642 ret
= bio_attempt_back_merge(q
, rq
, bio
);
1645 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1646 ret
= bio_attempt_front_merge(q
, rq
, bio
);
1655 unsigned int blk_plug_queued_count(struct request_queue
*q
)
1657 struct blk_plug
*plug
;
1659 struct list_head
*plug_list
;
1660 unsigned int ret
= 0;
1662 plug
= current
->plug
;
1667 plug_list
= &plug
->mq_list
;
1669 plug_list
= &plug
->list
;
1671 list_for_each_entry(rq
, plug_list
, queuelist
) {
1679 void init_request_from_bio(struct request
*req
, struct bio
*bio
)
1681 req
->cmd_type
= REQ_TYPE_FS
;
1683 req
->cmd_flags
|= bio
->bi_rw
& REQ_COMMON_MASK
;
1684 if (bio
->bi_rw
& REQ_RAHEAD
)
1685 req
->cmd_flags
|= REQ_FAILFAST_MASK
;
1688 req
->__sector
= bio
->bi_iter
.bi_sector
;
1689 req
->ioprio
= bio_prio(bio
);
1690 blk_rq_bio_prep(req
->q
, req
, bio
);
1693 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
)
1695 const bool sync
= !!(bio
->bi_rw
& REQ_SYNC
);
1696 struct blk_plug
*plug
;
1697 int el_ret
, rw_flags
, where
= ELEVATOR_INSERT_SORT
;
1698 struct request
*req
;
1699 unsigned int request_count
= 0;
1702 * low level driver can indicate that it wants pages above a
1703 * certain limit bounced to low memory (ie for highmem, or even
1704 * ISA dma in theory)
1706 blk_queue_bounce(q
, &bio
);
1708 blk_queue_split(q
, &bio
, q
->bio_split
);
1710 if (bio_integrity_enabled(bio
) && bio_integrity_prep(bio
)) {
1711 bio
->bi_error
= -EIO
;
1713 return BLK_QC_T_NONE
;
1716 if (bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) {
1717 spin_lock_irq(q
->queue_lock
);
1718 where
= ELEVATOR_INSERT_FLUSH
;
1723 * Check if we can merge with the plugged list before grabbing
1726 if (!blk_queue_nomerges(q
)) {
1727 if (blk_attempt_plug_merge(q
, bio
, &request_count
, NULL
))
1728 return BLK_QC_T_NONE
;
1730 request_count
= blk_plug_queued_count(q
);
1732 spin_lock_irq(q
->queue_lock
);
1734 el_ret
= elv_merge(q
, &req
, bio
);
1735 if (el_ret
== ELEVATOR_BACK_MERGE
) {
1736 if (bio_attempt_back_merge(q
, req
, bio
)) {
1737 elv_bio_merged(q
, req
, bio
);
1738 if (!attempt_back_merge(q
, req
))
1739 elv_merged_request(q
, req
, el_ret
);
1742 } else if (el_ret
== ELEVATOR_FRONT_MERGE
) {
1743 if (bio_attempt_front_merge(q
, req
, bio
)) {
1744 elv_bio_merged(q
, req
, bio
);
1745 if (!attempt_front_merge(q
, req
))
1746 elv_merged_request(q
, req
, el_ret
);
1753 * This sync check and mask will be re-done in init_request_from_bio(),
1754 * but we need to set it earlier to expose the sync flag to the
1755 * rq allocator and io schedulers.
1757 rw_flags
= bio_data_dir(bio
);
1759 rw_flags
|= REQ_SYNC
;
1762 * Grab a free request. This is might sleep but can not fail.
1763 * Returns with the queue unlocked.
1765 req
= get_request(q
, rw_flags
, bio
, GFP_NOIO
);
1767 bio
->bi_error
= PTR_ERR(req
);
1773 * After dropping the lock and possibly sleeping here, our request
1774 * may now be mergeable after it had proven unmergeable (above).
1775 * We don't worry about that case for efficiency. It won't happen
1776 * often, and the elevators are able to handle it.
1778 init_request_from_bio(req
, bio
);
1780 if (test_bit(QUEUE_FLAG_SAME_COMP
, &q
->queue_flags
))
1781 req
->cpu
= raw_smp_processor_id();
1783 plug
= current
->plug
;
1786 * If this is the first request added after a plug, fire
1790 trace_block_plug(q
);
1792 if (request_count
>= BLK_MAX_REQUEST_COUNT
) {
1793 blk_flush_plug_list(plug
, false);
1794 trace_block_plug(q
);
1797 list_add_tail(&req
->queuelist
, &plug
->list
);
1798 blk_account_io_start(req
, true);
1800 spin_lock_irq(q
->queue_lock
);
1801 add_acct_request(q
, req
, where
);
1804 spin_unlock_irq(q
->queue_lock
);
1807 return BLK_QC_T_NONE
;
1811 * If bio->bi_dev is a partition, remap the location
1813 static inline void blk_partition_remap(struct bio
*bio
)
1815 struct block_device
*bdev
= bio
->bi_bdev
;
1817 if (bio_sectors(bio
) && bdev
!= bdev
->bd_contains
) {
1818 struct hd_struct
*p
= bdev
->bd_part
;
1820 bio
->bi_iter
.bi_sector
+= p
->start_sect
;
1821 bio
->bi_bdev
= bdev
->bd_contains
;
1823 trace_block_bio_remap(bdev_get_queue(bio
->bi_bdev
), bio
,
1825 bio
->bi_iter
.bi_sector
- p
->start_sect
);
1829 static void handle_bad_sector(struct bio
*bio
)
1831 char b
[BDEVNAME_SIZE
];
1833 printk(KERN_INFO
"attempt to access beyond end of device\n");
1834 printk(KERN_INFO
"%s: rw=%ld, want=%Lu, limit=%Lu\n",
1835 bdevname(bio
->bi_bdev
, b
),
1837 (unsigned long long)bio_end_sector(bio
),
1838 (long long)(i_size_read(bio
->bi_bdev
->bd_inode
) >> 9));
1841 #ifdef CONFIG_FAIL_MAKE_REQUEST
1843 static DECLARE_FAULT_ATTR(fail_make_request
);
1845 static int __init
setup_fail_make_request(char *str
)
1847 return setup_fault_attr(&fail_make_request
, str
);
1849 __setup("fail_make_request=", setup_fail_make_request
);
1851 static bool should_fail_request(struct hd_struct
*part
, unsigned int bytes
)
1853 return part
->make_it_fail
&& should_fail(&fail_make_request
, bytes
);
1856 static int __init
fail_make_request_debugfs(void)
1858 struct dentry
*dir
= fault_create_debugfs_attr("fail_make_request",
1859 NULL
, &fail_make_request
);
1861 return PTR_ERR_OR_ZERO(dir
);
1864 late_initcall(fail_make_request_debugfs
);
1866 #else /* CONFIG_FAIL_MAKE_REQUEST */
1868 static inline bool should_fail_request(struct hd_struct
*part
,
1874 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1877 * Check whether this bio extends beyond the end of the device.
1879 static inline int bio_check_eod(struct bio
*bio
, unsigned int nr_sectors
)
1886 /* Test device or partition size, when known. */
1887 maxsector
= i_size_read(bio
->bi_bdev
->bd_inode
) >> 9;
1889 sector_t sector
= bio
->bi_iter
.bi_sector
;
1891 if (maxsector
< nr_sectors
|| maxsector
- nr_sectors
< sector
) {
1893 * This may well happen - the kernel calls bread()
1894 * without checking the size of the device, e.g., when
1895 * mounting a device.
1897 handle_bad_sector(bio
);
1905 static noinline_for_stack
bool
1906 generic_make_request_checks(struct bio
*bio
)
1908 struct request_queue
*q
;
1909 int nr_sectors
= bio_sectors(bio
);
1911 char b
[BDEVNAME_SIZE
];
1912 struct hd_struct
*part
;
1916 if (bio_check_eod(bio
, nr_sectors
))
1919 q
= bdev_get_queue(bio
->bi_bdev
);
1922 "generic_make_request: Trying to access "
1923 "nonexistent block-device %s (%Lu)\n",
1924 bdevname(bio
->bi_bdev
, b
),
1925 (long long) bio
->bi_iter
.bi_sector
);
1929 part
= bio
->bi_bdev
->bd_part
;
1930 if (should_fail_request(part
, bio
->bi_iter
.bi_size
) ||
1931 should_fail_request(&part_to_disk(part
)->part0
,
1932 bio
->bi_iter
.bi_size
))
1936 * If this device has partitions, remap block n
1937 * of partition p to block n+start(p) of the disk.
1939 blk_partition_remap(bio
);
1941 if (bio_check_eod(bio
, nr_sectors
))
1945 * Filter flush bio's early so that make_request based
1946 * drivers without flush support don't have to worry
1949 if ((bio
->bi_rw
& (REQ_FLUSH
| REQ_FUA
)) && !q
->flush_flags
) {
1950 bio
->bi_rw
&= ~(REQ_FLUSH
| REQ_FUA
);
1957 if ((bio
->bi_rw
& REQ_DISCARD
) &&
1958 (!blk_queue_discard(q
) ||
1959 ((bio
->bi_rw
& REQ_SECURE
) && !blk_queue_secdiscard(q
)))) {
1964 if (bio
->bi_rw
& REQ_WRITE_SAME
&& !bdev_write_same(bio
->bi_bdev
)) {
1970 * Various block parts want %current->io_context and lazy ioc
1971 * allocation ends up trading a lot of pain for a small amount of
1972 * memory. Just allocate it upfront. This may fail and block
1973 * layer knows how to live with it.
1975 create_io_context(GFP_ATOMIC
, q
->node
);
1977 if (!blkcg_bio_issue_check(q
, bio
))
1980 trace_block_bio_queue(q
, bio
);
1984 bio
->bi_error
= err
;
1990 * generic_make_request - hand a buffer to its device driver for I/O
1991 * @bio: The bio describing the location in memory and on the device.
1993 * generic_make_request() is used to make I/O requests of block
1994 * devices. It is passed a &struct bio, which describes the I/O that needs
1997 * generic_make_request() does not return any status. The
1998 * success/failure status of the request, along with notification of
1999 * completion, is delivered asynchronously through the bio->bi_end_io
2000 * function described (one day) else where.
2002 * The caller of generic_make_request must make sure that bi_io_vec
2003 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2004 * set to describe the device address, and the
2005 * bi_end_io and optionally bi_private are set to describe how
2006 * completion notification should be signaled.
2008 * generic_make_request and the drivers it calls may use bi_next if this
2009 * bio happens to be merged with someone else, and may resubmit the bio to
2010 * a lower device by calling into generic_make_request recursively, which
2011 * means the bio should NOT be touched after the call to ->make_request_fn.
2013 blk_qc_t
generic_make_request(struct bio
*bio
)
2016 * bio_list_on_stack[0] contains bios submitted by the current
2018 * bio_list_on_stack[1] contains bios that were submitted before
2019 * the current make_request_fn, but that haven't been processed
2022 struct bio_list bio_list_on_stack
[2];
2023 blk_qc_t ret
= BLK_QC_T_NONE
;
2025 if (!generic_make_request_checks(bio
))
2029 * We only want one ->make_request_fn to be active at a time, else
2030 * stack usage with stacked devices could be a problem. So use
2031 * current->bio_list to keep a list of requests submited by a
2032 * make_request_fn function. current->bio_list is also used as a
2033 * flag to say if generic_make_request is currently active in this
2034 * task or not. If it is NULL, then no make_request is active. If
2035 * it is non-NULL, then a make_request is active, and new requests
2036 * should be added at the tail
2038 if (current
->bio_list
) {
2039 bio_list_add(¤t
->bio_list
[0], bio
);
2043 /* following loop may be a bit non-obvious, and so deserves some
2045 * Before entering the loop, bio->bi_next is NULL (as all callers
2046 * ensure that) so we have a list with a single bio.
2047 * We pretend that we have just taken it off a longer list, so
2048 * we assign bio_list to a pointer to the bio_list_on_stack,
2049 * thus initialising the bio_list of new bios to be
2050 * added. ->make_request() may indeed add some more bios
2051 * through a recursive call to generic_make_request. If it
2052 * did, we find a non-NULL value in bio_list and re-enter the loop
2053 * from the top. In this case we really did just take the bio
2054 * of the top of the list (no pretending) and so remove it from
2055 * bio_list, and call into ->make_request() again.
2057 BUG_ON(bio
->bi_next
);
2058 bio_list_init(&bio_list_on_stack
[0]);
2059 current
->bio_list
= bio_list_on_stack
;
2061 struct request_queue
*q
= bdev_get_queue(bio
->bi_bdev
);
2063 if (likely(blk_queue_enter(q
, false) == 0)) {
2064 struct bio_list lower
, same
;
2066 /* Create a fresh bio_list for all subordinate requests */
2067 bio_list_on_stack
[1] = bio_list_on_stack
[0];
2068 bio_list_init(&bio_list_on_stack
[0]);
2070 ret
= q
->make_request_fn(q
, bio
);
2074 /* sort new bios into those for a lower level
2075 * and those for the same level
2077 bio_list_init(&lower
);
2078 bio_list_init(&same
);
2079 while ((bio
= bio_list_pop(&bio_list_on_stack
[0])) != NULL
)
2080 if (q
== bdev_get_queue(bio
->bi_bdev
))
2081 bio_list_add(&same
, bio
);
2083 bio_list_add(&lower
, bio
);
2084 /* now assemble so we handle the lowest level first */
2085 bio_list_merge(&bio_list_on_stack
[0], &lower
);
2086 bio_list_merge(&bio_list_on_stack
[0], &same
);
2087 bio_list_merge(&bio_list_on_stack
[0], &bio_list_on_stack
[1]);
2091 bio
= bio_list_pop(&bio_list_on_stack
[0]);
2093 current
->bio_list
= NULL
; /* deactivate */
2098 EXPORT_SYMBOL(generic_make_request
);
2101 * submit_bio - submit a bio to the block device layer for I/O
2102 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2103 * @bio: The &struct bio which describes the I/O
2105 * submit_bio() is very similar in purpose to generic_make_request(), and
2106 * uses that function to do most of the work. Both are fairly rough
2107 * interfaces; @bio must be presetup and ready for I/O.
2110 blk_qc_t
submit_bio(int rw
, struct bio
*bio
)
2115 * If it's a regular read/write or a barrier with data attached,
2116 * go through the normal accounting stuff before submission.
2118 if (bio_has_data(bio
)) {
2121 if (unlikely(rw
& REQ_WRITE_SAME
))
2122 count
= bdev_logical_block_size(bio
->bi_bdev
) >> 9;
2124 count
= bio_sectors(bio
);
2127 count_vm_events(PGPGOUT
, count
);
2129 task_io_account_read(bio
->bi_iter
.bi_size
);
2130 count_vm_events(PGPGIN
, count
);
2133 if (unlikely(block_dump
)) {
2134 char b
[BDEVNAME_SIZE
];
2135 printk(KERN_DEBUG
"%s(%d): %s block %Lu on %s (%u sectors)\n",
2136 current
->comm
, task_pid_nr(current
),
2137 (rw
& WRITE
) ? "WRITE" : "READ",
2138 (unsigned long long)bio
->bi_iter
.bi_sector
,
2139 bdevname(bio
->bi_bdev
, b
),
2144 return generic_make_request(bio
);
2146 EXPORT_SYMBOL(submit_bio
);
2149 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2150 * for new the queue limits
2152 * @rq: the request being checked
2155 * @rq may have been made based on weaker limitations of upper-level queues
2156 * in request stacking drivers, and it may violate the limitation of @q.
2157 * Since the block layer and the underlying device driver trust @rq
2158 * after it is inserted to @q, it should be checked against @q before
2159 * the insertion using this generic function.
2161 * Request stacking drivers like request-based dm may change the queue
2162 * limits when retrying requests on other queues. Those requests need
2163 * to be checked against the new queue limits again during dispatch.
2165 static int blk_cloned_rq_check_limits(struct request_queue
*q
,
2168 if (blk_rq_sectors(rq
) > blk_queue_get_max_sectors(q
, rq
->cmd_flags
)) {
2169 printk(KERN_ERR
"%s: over max size limit.\n", __func__
);
2174 * queue's settings related to segment counting like q->bounce_pfn
2175 * may differ from that of other stacking queues.
2176 * Recalculate it to check the request correctly on this queue's
2179 blk_recalc_rq_segments(rq
);
2180 if (rq
->nr_phys_segments
> queue_max_segments(q
)) {
2181 printk(KERN_ERR
"%s: over max segments limit.\n", __func__
);
2189 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2190 * @q: the queue to submit the request
2191 * @rq: the request being queued
2193 int blk_insert_cloned_request(struct request_queue
*q
, struct request
*rq
)
2195 unsigned long flags
;
2196 int where
= ELEVATOR_INSERT_BACK
;
2198 if (blk_cloned_rq_check_limits(q
, rq
))
2202 should_fail_request(&rq
->rq_disk
->part0
, blk_rq_bytes(rq
)))
2206 if (blk_queue_io_stat(q
))
2207 blk_account_io_start(rq
, true);
2208 blk_mq_insert_request(rq
, false, true, false);
2212 spin_lock_irqsave(q
->queue_lock
, flags
);
2213 if (unlikely(blk_queue_dying(q
))) {
2214 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2219 * Submitting request must be dequeued before calling this function
2220 * because it will be linked to another request_queue
2222 BUG_ON(blk_queued_rq(rq
));
2224 if (rq
->cmd_flags
& (REQ_FLUSH
|REQ_FUA
))
2225 where
= ELEVATOR_INSERT_FLUSH
;
2227 add_acct_request(q
, rq
, where
);
2228 if (where
== ELEVATOR_INSERT_FLUSH
)
2230 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2234 EXPORT_SYMBOL_GPL(blk_insert_cloned_request
);
2237 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2238 * @rq: request to examine
2241 * A request could be merge of IOs which require different failure
2242 * handling. This function determines the number of bytes which
2243 * can be failed from the beginning of the request without
2244 * crossing into area which need to be retried further.
2247 * The number of bytes to fail.
2250 * queue_lock must be held.
2252 unsigned int blk_rq_err_bytes(const struct request
*rq
)
2254 unsigned int ff
= rq
->cmd_flags
& REQ_FAILFAST_MASK
;
2255 unsigned int bytes
= 0;
2258 if (!(rq
->cmd_flags
& REQ_MIXED_MERGE
))
2259 return blk_rq_bytes(rq
);
2262 * Currently the only 'mixing' which can happen is between
2263 * different fastfail types. We can safely fail portions
2264 * which have all the failfast bits that the first one has -
2265 * the ones which are at least as eager to fail as the first
2268 for (bio
= rq
->bio
; bio
; bio
= bio
->bi_next
) {
2269 if ((bio
->bi_rw
& ff
) != ff
)
2271 bytes
+= bio
->bi_iter
.bi_size
;
2274 /* this could lead to infinite loop */
2275 BUG_ON(blk_rq_bytes(rq
) && !bytes
);
2278 EXPORT_SYMBOL_GPL(blk_rq_err_bytes
);
2280 void blk_account_io_completion(struct request
*req
, unsigned int bytes
)
2282 if (blk_do_io_stat(req
)) {
2283 const int rw
= rq_data_dir(req
);
2284 struct hd_struct
*part
;
2287 cpu
= part_stat_lock();
2289 part_stat_add(cpu
, part
, sectors
[rw
], bytes
>> 9);
2294 void blk_account_io_done(struct request
*req
)
2297 * Account IO completion. flush_rq isn't accounted as a
2298 * normal IO on queueing nor completion. Accounting the
2299 * containing request is enough.
2301 if (blk_do_io_stat(req
) && !(req
->cmd_flags
& REQ_FLUSH_SEQ
)) {
2302 unsigned long duration
= jiffies
- req
->start_time
;
2303 const int rw
= rq_data_dir(req
);
2304 struct hd_struct
*part
;
2307 cpu
= part_stat_lock();
2310 part_stat_inc(cpu
, part
, ios
[rw
]);
2311 part_stat_add(cpu
, part
, ticks
[rw
], duration
);
2312 part_round_stats(cpu
, part
);
2313 part_dec_in_flight(part
, rw
);
2315 hd_struct_put(part
);
2322 * Don't process normal requests when queue is suspended
2323 * or in the process of suspending/resuming
2325 static struct request
*blk_pm_peek_request(struct request_queue
*q
,
2328 if (q
->dev
&& (q
->rpm_status
== RPM_SUSPENDED
||
2329 (q
->rpm_status
!= RPM_ACTIVE
&& !(rq
->cmd_flags
& REQ_PM
))))
2335 static inline struct request
*blk_pm_peek_request(struct request_queue
*q
,
2342 void blk_account_io_start(struct request
*rq
, bool new_io
)
2344 struct hd_struct
*part
;
2345 int rw
= rq_data_dir(rq
);
2348 if (!blk_do_io_stat(rq
))
2351 cpu
= part_stat_lock();
2355 part_stat_inc(cpu
, part
, merges
[rw
]);
2357 part
= disk_map_sector_rcu(rq
->rq_disk
, blk_rq_pos(rq
));
2358 if (!hd_struct_try_get(part
)) {
2360 * The partition is already being removed,
2361 * the request will be accounted on the disk only
2363 * We take a reference on disk->part0 although that
2364 * partition will never be deleted, so we can treat
2365 * it as any other partition.
2367 part
= &rq
->rq_disk
->part0
;
2368 hd_struct_get(part
);
2370 part_round_stats(cpu
, part
);
2371 part_inc_in_flight(part
, rw
);
2379 * blk_peek_request - peek at the top of a request queue
2380 * @q: request queue to peek at
2383 * Return the request at the top of @q. The returned request
2384 * should be started using blk_start_request() before LLD starts
2388 * Pointer to the request at the top of @q if available. Null
2392 * queue_lock must be held.
2394 struct request
*blk_peek_request(struct request_queue
*q
)
2399 while ((rq
= __elv_next_request(q
)) != NULL
) {
2401 rq
= blk_pm_peek_request(q
, rq
);
2405 if (!(rq
->cmd_flags
& REQ_STARTED
)) {
2407 * This is the first time the device driver
2408 * sees this request (possibly after
2409 * requeueing). Notify IO scheduler.
2411 if (rq
->cmd_flags
& REQ_SORTED
)
2412 elv_activate_rq(q
, rq
);
2415 * just mark as started even if we don't start
2416 * it, a request that has been delayed should
2417 * not be passed by new incoming requests
2419 rq
->cmd_flags
|= REQ_STARTED
;
2420 trace_block_rq_issue(q
, rq
);
2423 if (!q
->boundary_rq
|| q
->boundary_rq
== rq
) {
2424 q
->end_sector
= rq_end_sector(rq
);
2425 q
->boundary_rq
= NULL
;
2428 if (rq
->cmd_flags
& REQ_DONTPREP
)
2431 if (q
->dma_drain_size
&& blk_rq_bytes(rq
)) {
2433 * make sure space for the drain appears we
2434 * know we can do this because max_hw_segments
2435 * has been adjusted to be one fewer than the
2438 rq
->nr_phys_segments
++;
2444 ret
= q
->prep_rq_fn(q
, rq
);
2445 if (ret
== BLKPREP_OK
) {
2447 } else if (ret
== BLKPREP_DEFER
) {
2449 * the request may have been (partially) prepped.
2450 * we need to keep this request in the front to
2451 * avoid resource deadlock. REQ_STARTED will
2452 * prevent other fs requests from passing this one.
2454 if (q
->dma_drain_size
&& blk_rq_bytes(rq
) &&
2455 !(rq
->cmd_flags
& REQ_DONTPREP
)) {
2457 * remove the space for the drain we added
2458 * so that we don't add it again
2460 --rq
->nr_phys_segments
;
2465 } else if (ret
== BLKPREP_KILL
) {
2466 rq
->cmd_flags
|= REQ_QUIET
;
2468 * Mark this request as started so we don't trigger
2469 * any debug logic in the end I/O path.
2471 blk_start_request(rq
);
2472 __blk_end_request_all(rq
, -EIO
);
2474 printk(KERN_ERR
"%s: bad return=%d\n", __func__
, ret
);
2481 EXPORT_SYMBOL(blk_peek_request
);
2483 void blk_dequeue_request(struct request
*rq
)
2485 struct request_queue
*q
= rq
->q
;
2487 BUG_ON(list_empty(&rq
->queuelist
));
2488 BUG_ON(ELV_ON_HASH(rq
));
2490 list_del_init(&rq
->queuelist
);
2493 * the time frame between a request being removed from the lists
2494 * and to it is freed is accounted as io that is in progress at
2497 if (blk_account_rq(rq
)) {
2498 q
->in_flight
[rq_is_sync(rq
)]++;
2499 set_io_start_time_ns(rq
);
2504 * blk_start_request - start request processing on the driver
2505 * @req: request to dequeue
2508 * Dequeue @req and start timeout timer on it. This hands off the
2509 * request to the driver.
2511 * Block internal functions which don't want to start timer should
2512 * call blk_dequeue_request().
2515 * queue_lock must be held.
2517 void blk_start_request(struct request
*req
)
2519 blk_dequeue_request(req
);
2522 * We are now handing the request to the hardware, initialize
2523 * resid_len to full count and add the timeout handler.
2525 req
->resid_len
= blk_rq_bytes(req
);
2526 if (unlikely(blk_bidi_rq(req
)))
2527 req
->next_rq
->resid_len
= blk_rq_bytes(req
->next_rq
);
2529 BUG_ON(test_bit(REQ_ATOM_COMPLETE
, &req
->atomic_flags
));
2532 EXPORT_SYMBOL(blk_start_request
);
2535 * blk_fetch_request - fetch a request from a request queue
2536 * @q: request queue to fetch a request from
2539 * Return the request at the top of @q. The request is started on
2540 * return and LLD can start processing it immediately.
2543 * Pointer to the request at the top of @q if available. Null
2547 * queue_lock must be held.
2549 struct request
*blk_fetch_request(struct request_queue
*q
)
2553 rq
= blk_peek_request(q
);
2555 blk_start_request(rq
);
2558 EXPORT_SYMBOL(blk_fetch_request
);
2561 * blk_update_request - Special helper function for request stacking drivers
2562 * @req: the request being processed
2563 * @error: %0 for success, < %0 for error
2564 * @nr_bytes: number of bytes to complete @req
2567 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2568 * the request structure even if @req doesn't have leftover.
2569 * If @req has leftover, sets it up for the next range of segments.
2571 * This special helper function is only for request stacking drivers
2572 * (e.g. request-based dm) so that they can handle partial completion.
2573 * Actual device drivers should use blk_end_request instead.
2575 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2576 * %false return from this function.
2579 * %false - this request doesn't have any more data
2580 * %true - this request has more data
2582 bool blk_update_request(struct request
*req
, int error
, unsigned int nr_bytes
)
2586 trace_block_rq_complete(req
->q
, req
, nr_bytes
);
2592 * For fs requests, rq is just carrier of independent bio's
2593 * and each partial completion should be handled separately.
2594 * Reset per-request error on each partial completion.
2596 * TODO: tj: This is too subtle. It would be better to let
2597 * low level drivers do what they see fit.
2599 if (req
->cmd_type
== REQ_TYPE_FS
)
2602 if (error
&& req
->cmd_type
== REQ_TYPE_FS
&&
2603 !(req
->cmd_flags
& REQ_QUIET
)) {
2608 error_type
= "recoverable transport";
2611 error_type
= "critical target";
2614 error_type
= "critical nexus";
2617 error_type
= "timeout";
2620 error_type
= "critical space allocation";
2623 error_type
= "critical medium";
2630 printk_ratelimited(KERN_ERR
"%s: %s error, dev %s, sector %llu\n",
2631 __func__
, error_type
, req
->rq_disk
?
2632 req
->rq_disk
->disk_name
: "?",
2633 (unsigned long long)blk_rq_pos(req
));
2637 blk_account_io_completion(req
, nr_bytes
);
2641 struct bio
*bio
= req
->bio
;
2642 unsigned bio_bytes
= min(bio
->bi_iter
.bi_size
, nr_bytes
);
2644 if (bio_bytes
== bio
->bi_iter
.bi_size
)
2645 req
->bio
= bio
->bi_next
;
2647 req_bio_endio(req
, bio
, bio_bytes
, error
);
2649 total_bytes
+= bio_bytes
;
2650 nr_bytes
-= bio_bytes
;
2661 * Reset counters so that the request stacking driver
2662 * can find how many bytes remain in the request
2665 req
->__data_len
= 0;
2669 req
->__data_len
-= total_bytes
;
2671 /* update sector only for requests with clear definition of sector */
2672 if (req
->cmd_type
== REQ_TYPE_FS
)
2673 req
->__sector
+= total_bytes
>> 9;
2675 /* mixed attributes always follow the first bio */
2676 if (req
->cmd_flags
& REQ_MIXED_MERGE
) {
2677 req
->cmd_flags
&= ~REQ_FAILFAST_MASK
;
2678 req
->cmd_flags
|= req
->bio
->bi_rw
& REQ_FAILFAST_MASK
;
2682 * If total number of sectors is less than the first segment
2683 * size, something has gone terribly wrong.
2685 if (blk_rq_bytes(req
) < blk_rq_cur_bytes(req
)) {
2686 blk_dump_rq_flags(req
, "request botched");
2687 req
->__data_len
= blk_rq_cur_bytes(req
);
2690 /* recalculate the number of segments */
2691 blk_recalc_rq_segments(req
);
2695 EXPORT_SYMBOL_GPL(blk_update_request
);
2697 static bool blk_update_bidi_request(struct request
*rq
, int error
,
2698 unsigned int nr_bytes
,
2699 unsigned int bidi_bytes
)
2701 if (blk_update_request(rq
, error
, nr_bytes
))
2704 /* Bidi request must be completed as a whole */
2705 if (unlikely(blk_bidi_rq(rq
)) &&
2706 blk_update_request(rq
->next_rq
, error
, bidi_bytes
))
2709 if (blk_queue_add_random(rq
->q
))
2710 add_disk_randomness(rq
->rq_disk
);
2716 * blk_unprep_request - unprepare a request
2719 * This function makes a request ready for complete resubmission (or
2720 * completion). It happens only after all error handling is complete,
2721 * so represents the appropriate moment to deallocate any resources
2722 * that were allocated to the request in the prep_rq_fn. The queue
2723 * lock is held when calling this.
2725 void blk_unprep_request(struct request
*req
)
2727 struct request_queue
*q
= req
->q
;
2729 req
->cmd_flags
&= ~REQ_DONTPREP
;
2730 if (q
->unprep_rq_fn
)
2731 q
->unprep_rq_fn(q
, req
);
2733 EXPORT_SYMBOL_GPL(blk_unprep_request
);
2736 * queue lock must be held
2738 void blk_finish_request(struct request
*req
, int error
)
2740 if (req
->cmd_flags
& REQ_QUEUED
)
2741 blk_queue_end_tag(req
->q
, req
);
2743 BUG_ON(blk_queued_rq(req
));
2745 if (unlikely(laptop_mode
) && req
->cmd_type
== REQ_TYPE_FS
)
2746 laptop_io_completion(req
->q
->backing_dev_info
);
2748 blk_delete_timer(req
);
2750 if (req
->cmd_flags
& REQ_DONTPREP
)
2751 blk_unprep_request(req
);
2753 blk_account_io_done(req
);
2756 req
->end_io(req
, error
);
2758 if (blk_bidi_rq(req
))
2759 __blk_put_request(req
->next_rq
->q
, req
->next_rq
);
2761 __blk_put_request(req
->q
, req
);
2764 EXPORT_SYMBOL(blk_finish_request
);
2767 * blk_end_bidi_request - Complete a bidi request
2768 * @rq: the request to complete
2769 * @error: %0 for success, < %0 for error
2770 * @nr_bytes: number of bytes to complete @rq
2771 * @bidi_bytes: number of bytes to complete @rq->next_rq
2774 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2775 * Drivers that supports bidi can safely call this member for any
2776 * type of request, bidi or uni. In the later case @bidi_bytes is
2780 * %false - we are done with this request
2781 * %true - still buffers pending for this request
2783 static bool blk_end_bidi_request(struct request
*rq
, int error
,
2784 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2786 struct request_queue
*q
= rq
->q
;
2787 unsigned long flags
;
2789 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2792 spin_lock_irqsave(q
->queue_lock
, flags
);
2793 blk_finish_request(rq
, error
);
2794 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2800 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2801 * @rq: the request to complete
2802 * @error: %0 for success, < %0 for error
2803 * @nr_bytes: number of bytes to complete @rq
2804 * @bidi_bytes: number of bytes to complete @rq->next_rq
2807 * Identical to blk_end_bidi_request() except that queue lock is
2808 * assumed to be locked on entry and remains so on return.
2811 * %false - we are done with this request
2812 * %true - still buffers pending for this request
2814 bool __blk_end_bidi_request(struct request
*rq
, int error
,
2815 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2817 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2820 blk_finish_request(rq
, error
);
2826 * blk_end_request - Helper function for drivers to complete the request.
2827 * @rq: the request being processed
2828 * @error: %0 for success, < %0 for error
2829 * @nr_bytes: number of bytes to complete
2832 * Ends I/O on a number of bytes attached to @rq.
2833 * If @rq has leftover, sets it up for the next range of segments.
2836 * %false - we are done with this request
2837 * %true - still buffers pending for this request
2839 bool blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2841 return blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2843 EXPORT_SYMBOL(blk_end_request
);
2846 * blk_end_request_all - Helper function for drives to finish the request.
2847 * @rq: the request to finish
2848 * @error: %0 for success, < %0 for error
2851 * Completely finish @rq.
2853 void blk_end_request_all(struct request
*rq
, int error
)
2856 unsigned int bidi_bytes
= 0;
2858 if (unlikely(blk_bidi_rq(rq
)))
2859 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2861 pending
= blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2864 EXPORT_SYMBOL(blk_end_request_all
);
2867 * blk_end_request_cur - Helper function to finish the current request chunk.
2868 * @rq: the request to finish the current chunk for
2869 * @error: %0 for success, < %0 for error
2872 * Complete the current consecutively mapped chunk from @rq.
2875 * %false - we are done with this request
2876 * %true - still buffers pending for this request
2878 bool blk_end_request_cur(struct request
*rq
, int error
)
2880 return blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2882 EXPORT_SYMBOL(blk_end_request_cur
);
2885 * blk_end_request_err - Finish a request till the next failure boundary.
2886 * @rq: the request to finish till the next failure boundary for
2887 * @error: must be negative errno
2890 * Complete @rq till the next failure boundary.
2893 * %false - we are done with this request
2894 * %true - still buffers pending for this request
2896 bool blk_end_request_err(struct request
*rq
, int error
)
2898 WARN_ON(error
>= 0);
2899 return blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2901 EXPORT_SYMBOL_GPL(blk_end_request_err
);
2904 * __blk_end_request - Helper function for drivers to complete the request.
2905 * @rq: the request being processed
2906 * @error: %0 for success, < %0 for error
2907 * @nr_bytes: number of bytes to complete
2910 * Must be called with queue lock held unlike blk_end_request().
2913 * %false - we are done with this request
2914 * %true - still buffers pending for this request
2916 bool __blk_end_request(struct request
*rq
, int error
, unsigned int nr_bytes
)
2918 return __blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2920 EXPORT_SYMBOL(__blk_end_request
);
2923 * __blk_end_request_all - Helper function for drives to finish the request.
2924 * @rq: the request to finish
2925 * @error: %0 for success, < %0 for error
2928 * Completely finish @rq. Must be called with queue lock held.
2930 void __blk_end_request_all(struct request
*rq
, int error
)
2933 unsigned int bidi_bytes
= 0;
2935 if (unlikely(blk_bidi_rq(rq
)))
2936 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2938 pending
= __blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2941 EXPORT_SYMBOL(__blk_end_request_all
);
2944 * __blk_end_request_cur - Helper function to finish the current request chunk.
2945 * @rq: the request to finish the current chunk for
2946 * @error: %0 for success, < %0 for error
2949 * Complete the current consecutively mapped chunk from @rq. Must
2950 * be called with queue lock held.
2953 * %false - we are done with this request
2954 * %true - still buffers pending for this request
2956 bool __blk_end_request_cur(struct request
*rq
, int error
)
2958 return __blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2960 EXPORT_SYMBOL(__blk_end_request_cur
);
2963 * __blk_end_request_err - Finish a request till the next failure boundary.
2964 * @rq: the request to finish till the next failure boundary for
2965 * @error: must be negative errno
2968 * Complete @rq till the next failure boundary. Must be called
2969 * with queue lock held.
2972 * %false - we are done with this request
2973 * %true - still buffers pending for this request
2975 bool __blk_end_request_err(struct request
*rq
, int error
)
2977 WARN_ON(error
>= 0);
2978 return __blk_end_request(rq
, error
, blk_rq_err_bytes(rq
));
2980 EXPORT_SYMBOL_GPL(__blk_end_request_err
);
2982 void blk_rq_bio_prep(struct request_queue
*q
, struct request
*rq
,
2985 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2986 rq
->cmd_flags
|= bio
->bi_rw
& REQ_WRITE
;
2988 if (bio_has_data(bio
))
2989 rq
->nr_phys_segments
= bio_phys_segments(q
, bio
);
2991 rq
->__data_len
= bio
->bi_iter
.bi_size
;
2992 rq
->bio
= rq
->biotail
= bio
;
2995 rq
->rq_disk
= bio
->bi_bdev
->bd_disk
;
2998 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
3000 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3001 * @rq: the request to be flushed
3004 * Flush all pages in @rq.
3006 void rq_flush_dcache_pages(struct request
*rq
)
3008 struct req_iterator iter
;
3009 struct bio_vec bvec
;
3011 rq_for_each_segment(bvec
, rq
, iter
)
3012 flush_dcache_page(bvec
.bv_page
);
3014 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages
);
3018 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3019 * @q : the queue of the device being checked
3022 * Check if underlying low-level drivers of a device are busy.
3023 * If the drivers want to export their busy state, they must set own
3024 * exporting function using blk_queue_lld_busy() first.
3026 * Basically, this function is used only by request stacking drivers
3027 * to stop dispatching requests to underlying devices when underlying
3028 * devices are busy. This behavior helps more I/O merging on the queue
3029 * of the request stacking driver and prevents I/O throughput regression
3030 * on burst I/O load.
3033 * 0 - Not busy (The request stacking driver should dispatch request)
3034 * 1 - Busy (The request stacking driver should stop dispatching request)
3036 int blk_lld_busy(struct request_queue
*q
)
3039 return q
->lld_busy_fn(q
);
3043 EXPORT_SYMBOL_GPL(blk_lld_busy
);
3046 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3047 * @rq: the clone request to be cleaned up
3050 * Free all bios in @rq for a cloned request.
3052 void blk_rq_unprep_clone(struct request
*rq
)
3056 while ((bio
= rq
->bio
) != NULL
) {
3057 rq
->bio
= bio
->bi_next
;
3062 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone
);
3065 * Copy attributes of the original request to the clone request.
3066 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3068 static void __blk_rq_prep_clone(struct request
*dst
, struct request
*src
)
3070 dst
->cpu
= src
->cpu
;
3071 dst
->cmd_flags
|= (src
->cmd_flags
& REQ_CLONE_MASK
) | REQ_NOMERGE
;
3072 dst
->cmd_type
= src
->cmd_type
;
3073 dst
->__sector
= blk_rq_pos(src
);
3074 dst
->__data_len
= blk_rq_bytes(src
);
3075 dst
->nr_phys_segments
= src
->nr_phys_segments
;
3076 dst
->ioprio
= src
->ioprio
;
3077 dst
->extra_len
= src
->extra_len
;
3081 * blk_rq_prep_clone - Helper function to setup clone request
3082 * @rq: the request to be setup
3083 * @rq_src: original request to be cloned
3084 * @bs: bio_set that bios for clone are allocated from
3085 * @gfp_mask: memory allocation mask for bio
3086 * @bio_ctr: setup function to be called for each clone bio.
3087 * Returns %0 for success, non %0 for failure.
3088 * @data: private data to be passed to @bio_ctr
3091 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3092 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3093 * are not copied, and copying such parts is the caller's responsibility.
3094 * Also, pages which the original bios are pointing to are not copied
3095 * and the cloned bios just point same pages.
3096 * So cloned bios must be completed before original bios, which means
3097 * the caller must complete @rq before @rq_src.
3099 int blk_rq_prep_clone(struct request
*rq
, struct request
*rq_src
,
3100 struct bio_set
*bs
, gfp_t gfp_mask
,
3101 int (*bio_ctr
)(struct bio
*, struct bio
*, void *),
3104 struct bio
*bio
, *bio_src
;
3109 __rq_for_each_bio(bio_src
, rq_src
) {
3110 bio
= bio_clone_fast(bio_src
, gfp_mask
, bs
);
3114 if (bio_ctr
&& bio_ctr(bio
, bio_src
, data
))
3118 rq
->biotail
->bi_next
= bio
;
3121 rq
->bio
= rq
->biotail
= bio
;
3124 __blk_rq_prep_clone(rq
, rq_src
);
3131 blk_rq_unprep_clone(rq
);
3135 EXPORT_SYMBOL_GPL(blk_rq_prep_clone
);
3137 int kblockd_schedule_work(struct work_struct
*work
)
3139 return queue_work(kblockd_workqueue
, work
);
3141 EXPORT_SYMBOL(kblockd_schedule_work
);
3143 int kblockd_schedule_delayed_work(struct delayed_work
*dwork
,
3144 unsigned long delay
)
3146 return queue_delayed_work(kblockd_workqueue
, dwork
, delay
);
3148 EXPORT_SYMBOL(kblockd_schedule_delayed_work
);
3150 int kblockd_schedule_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
3151 unsigned long delay
)
3153 return queue_delayed_work_on(cpu
, kblockd_workqueue
, dwork
, delay
);
3155 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on
);
3158 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3159 * @plug: The &struct blk_plug that needs to be initialized
3162 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3163 * pending I/O should the task end up blocking between blk_start_plug() and
3164 * blk_finish_plug(). This is important from a performance perspective, but
3165 * also ensures that we don't deadlock. For instance, if the task is blocking
3166 * for a memory allocation, memory reclaim could end up wanting to free a
3167 * page belonging to that request that is currently residing in our private
3168 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3169 * this kind of deadlock.
3171 void blk_start_plug(struct blk_plug
*plug
)
3173 struct task_struct
*tsk
= current
;
3176 * If this is a nested plug, don't actually assign it.
3181 INIT_LIST_HEAD(&plug
->list
);
3182 INIT_LIST_HEAD(&plug
->mq_list
);
3183 INIT_LIST_HEAD(&plug
->cb_list
);
3185 * Store ordering should not be needed here, since a potential
3186 * preempt will imply a full memory barrier
3190 EXPORT_SYMBOL(blk_start_plug
);
3192 static int plug_rq_cmp(void *priv
, struct list_head
*a
, struct list_head
*b
)
3194 struct request
*rqa
= container_of(a
, struct request
, queuelist
);
3195 struct request
*rqb
= container_of(b
, struct request
, queuelist
);
3197 return !(rqa
->q
< rqb
->q
||
3198 (rqa
->q
== rqb
->q
&& blk_rq_pos(rqa
) < blk_rq_pos(rqb
)));
3202 * If 'from_schedule' is true, then postpone the dispatch of requests
3203 * until a safe kblockd context. We due this to avoid accidental big
3204 * additional stack usage in driver dispatch, in places where the originally
3205 * plugger did not intend it.
3207 static void queue_unplugged(struct request_queue
*q
, unsigned int depth
,
3209 __releases(q
->queue_lock
)
3211 trace_block_unplug(q
, depth
, !from_schedule
);
3214 blk_run_queue_async(q
);
3217 spin_unlock(q
->queue_lock
);
3220 static void flush_plug_callbacks(struct blk_plug
*plug
, bool from_schedule
)
3222 LIST_HEAD(callbacks
);
3224 while (!list_empty(&plug
->cb_list
)) {
3225 list_splice_init(&plug
->cb_list
, &callbacks
);
3227 while (!list_empty(&callbacks
)) {
3228 struct blk_plug_cb
*cb
= list_first_entry(&callbacks
,
3231 list_del(&cb
->list
);
3232 cb
->callback(cb
, from_schedule
);
3237 struct blk_plug_cb
*blk_check_plugged(blk_plug_cb_fn unplug
, void *data
,
3240 struct blk_plug
*plug
= current
->plug
;
3241 struct blk_plug_cb
*cb
;
3246 list_for_each_entry(cb
, &plug
->cb_list
, list
)
3247 if (cb
->callback
== unplug
&& cb
->data
== data
)
3250 /* Not currently on the callback list */
3251 BUG_ON(size
< sizeof(*cb
));
3252 cb
= kzalloc(size
, GFP_ATOMIC
);
3255 cb
->callback
= unplug
;
3256 list_add(&cb
->list
, &plug
->cb_list
);
3260 EXPORT_SYMBOL(blk_check_plugged
);
3262 void blk_flush_plug_list(struct blk_plug
*plug
, bool from_schedule
)
3264 struct request_queue
*q
;
3265 unsigned long flags
;
3270 flush_plug_callbacks(plug
, from_schedule
);
3272 if (!list_empty(&plug
->mq_list
))
3273 blk_mq_flush_plug_list(plug
, from_schedule
);
3275 if (list_empty(&plug
->list
))
3278 list_splice_init(&plug
->list
, &list
);
3280 list_sort(NULL
, &list
, plug_rq_cmp
);
3286 * Save and disable interrupts here, to avoid doing it for every
3287 * queue lock we have to take.
3289 local_irq_save(flags
);
3290 while (!list_empty(&list
)) {
3291 rq
= list_entry_rq(list
.next
);
3292 list_del_init(&rq
->queuelist
);
3296 * This drops the queue lock
3299 queue_unplugged(q
, depth
, from_schedule
);
3302 spin_lock(q
->queue_lock
);
3306 * Short-circuit if @q is dead
3308 if (unlikely(blk_queue_dying(q
))) {
3309 __blk_end_request_all(rq
, -ENODEV
);
3314 * rq is already accounted, so use raw insert
3316 if (rq
->cmd_flags
& (REQ_FLUSH
| REQ_FUA
))
3317 __elv_add_request(q
, rq
, ELEVATOR_INSERT_FLUSH
);
3319 __elv_add_request(q
, rq
, ELEVATOR_INSERT_SORT_MERGE
);
3325 * This drops the queue lock
3328 queue_unplugged(q
, depth
, from_schedule
);
3330 local_irq_restore(flags
);
3333 void blk_finish_plug(struct blk_plug
*plug
)
3335 if (plug
!= current
->plug
)
3337 blk_flush_plug_list(plug
, false);
3339 current
->plug
= NULL
;
3341 EXPORT_SYMBOL(blk_finish_plug
);
3343 bool blk_poll(struct request_queue
*q
, blk_qc_t cookie
)
3345 struct blk_plug
*plug
;
3348 if (!q
->mq_ops
|| !q
->mq_ops
->poll
|| !blk_qc_t_valid(cookie
) ||
3349 !test_bit(QUEUE_FLAG_POLL
, &q
->queue_flags
))
3352 plug
= current
->plug
;
3354 blk_flush_plug_list(plug
, false);
3356 state
= current
->state
;
3357 while (!need_resched()) {
3358 unsigned int queue_num
= blk_qc_t_to_queue_num(cookie
);
3359 struct blk_mq_hw_ctx
*hctx
= q
->queue_hw_ctx
[queue_num
];
3362 hctx
->poll_invoked
++;
3364 ret
= q
->mq_ops
->poll(hctx
, blk_qc_t_to_tag(cookie
));
3366 hctx
->poll_success
++;
3367 set_current_state(TASK_RUNNING
);
3371 if (signal_pending_state(state
, current
))
3372 set_current_state(TASK_RUNNING
);
3374 if (current
->state
== TASK_RUNNING
)
3386 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3387 * @q: the queue of the device
3388 * @dev: the device the queue belongs to
3391 * Initialize runtime-PM-related fields for @q and start auto suspend for
3392 * @dev. Drivers that want to take advantage of request-based runtime PM
3393 * should call this function after @dev has been initialized, and its
3394 * request queue @q has been allocated, and runtime PM for it can not happen
3395 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3396 * cases, driver should call this function before any I/O has taken place.
3398 * This function takes care of setting up using auto suspend for the device,
3399 * the autosuspend delay is set to -1 to make runtime suspend impossible
3400 * until an updated value is either set by user or by driver. Drivers do
3401 * not need to touch other autosuspend settings.
3403 * The block layer runtime PM is request based, so only works for drivers
3404 * that use request as their IO unit instead of those directly use bio's.
3406 void blk_pm_runtime_init(struct request_queue
*q
, struct device
*dev
)
3409 q
->rpm_status
= RPM_ACTIVE
;
3410 pm_runtime_set_autosuspend_delay(q
->dev
, -1);
3411 pm_runtime_use_autosuspend(q
->dev
);
3413 EXPORT_SYMBOL(blk_pm_runtime_init
);
3416 * blk_pre_runtime_suspend - Pre runtime suspend check
3417 * @q: the queue of the device
3420 * This function will check if runtime suspend is allowed for the device
3421 * by examining if there are any requests pending in the queue. If there
3422 * are requests pending, the device can not be runtime suspended; otherwise,
3423 * the queue's status will be updated to SUSPENDING and the driver can
3424 * proceed to suspend the device.
3426 * For the not allowed case, we mark last busy for the device so that
3427 * runtime PM core will try to autosuspend it some time later.
3429 * This function should be called near the start of the device's
3430 * runtime_suspend callback.
3433 * 0 - OK to runtime suspend the device
3434 * -EBUSY - Device should not be runtime suspended
3436 int blk_pre_runtime_suspend(struct request_queue
*q
)
3443 spin_lock_irq(q
->queue_lock
);
3444 if (q
->nr_pending
) {
3446 pm_runtime_mark_last_busy(q
->dev
);
3448 q
->rpm_status
= RPM_SUSPENDING
;
3450 spin_unlock_irq(q
->queue_lock
);
3453 EXPORT_SYMBOL(blk_pre_runtime_suspend
);
3456 * blk_post_runtime_suspend - Post runtime suspend processing
3457 * @q: the queue of the device
3458 * @err: return value of the device's runtime_suspend function
3461 * Update the queue's runtime status according to the return value of the
3462 * device's runtime suspend function and mark last busy for the device so
3463 * that PM core will try to auto suspend the device at a later time.
3465 * This function should be called near the end of the device's
3466 * runtime_suspend callback.
3468 void blk_post_runtime_suspend(struct request_queue
*q
, int err
)
3473 spin_lock_irq(q
->queue_lock
);
3475 q
->rpm_status
= RPM_SUSPENDED
;
3477 q
->rpm_status
= RPM_ACTIVE
;
3478 pm_runtime_mark_last_busy(q
->dev
);
3480 spin_unlock_irq(q
->queue_lock
);
3482 EXPORT_SYMBOL(blk_post_runtime_suspend
);
3485 * blk_pre_runtime_resume - Pre runtime resume processing
3486 * @q: the queue of the device
3489 * Update the queue's runtime status to RESUMING in preparation for the
3490 * runtime resume of the device.
3492 * This function should be called near the start of the device's
3493 * runtime_resume callback.
3495 void blk_pre_runtime_resume(struct request_queue
*q
)
3500 spin_lock_irq(q
->queue_lock
);
3501 q
->rpm_status
= RPM_RESUMING
;
3502 spin_unlock_irq(q
->queue_lock
);
3504 EXPORT_SYMBOL(blk_pre_runtime_resume
);
3507 * blk_post_runtime_resume - Post runtime resume processing
3508 * @q: the queue of the device
3509 * @err: return value of the device's runtime_resume function
3512 * Update the queue's runtime status according to the return value of the
3513 * device's runtime_resume function. If it is successfully resumed, process
3514 * the requests that are queued into the device's queue when it is resuming
3515 * and then mark last busy and initiate autosuspend for it.
3517 * This function should be called near the end of the device's
3518 * runtime_resume callback.
3520 void blk_post_runtime_resume(struct request_queue
*q
, int err
)
3525 spin_lock_irq(q
->queue_lock
);
3527 q
->rpm_status
= RPM_ACTIVE
;
3529 pm_runtime_mark_last_busy(q
->dev
);
3530 pm_request_autosuspend(q
->dev
);
3532 q
->rpm_status
= RPM_SUSPENDED
;
3534 spin_unlock_irq(q
->queue_lock
);
3536 EXPORT_SYMBOL(blk_post_runtime_resume
);
3539 int __init
blk_dev_init(void)
3541 BUILD_BUG_ON(__REQ_NR_BITS
> 8 *
3542 FIELD_SIZEOF(struct request
, cmd_flags
));
3544 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3545 kblockd_workqueue
= alloc_workqueue("kblockd",
3546 WQ_MEM_RECLAIM
| WQ_HIGHPRI
, 0);
3547 if (!kblockd_workqueue
)
3548 panic("Failed to create kblockd\n");
3550 request_cachep
= kmem_cache_create("blkdev_requests",
3551 sizeof(struct request
), 0, SLAB_PANIC
, NULL
);
3553 blk_requestq_cachep
= kmem_cache_create("blkdev_queue",
3554 sizeof(struct request_queue
), 0, SLAB_PANIC
, NULL
);