2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
12 * This handles all read/write requests to block devices
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-mq.h>
20 #include <linux/highmem.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/blk-cgroup.h>
36 #include <linux/debugfs.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/block.h>
43 #include "blk-mq-sched.h"
46 #ifdef CONFIG_DEBUG_FS
47 struct dentry
*blk_debugfs_root
;
50 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap
);
51 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap
);
52 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete
);
53 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split
);
54 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug
);
56 DEFINE_IDA(blk_queue_ida
);
59 * For the allocated request tables
61 struct kmem_cache
*request_cachep
;
64 * For queue allocation
66 struct kmem_cache
*blk_requestq_cachep
;
69 * Controlling structure to kblockd
71 static struct workqueue_struct
*kblockd_workqueue
;
73 static void blk_clear_congested(struct request_list
*rl
, int sync
)
75 #ifdef CONFIG_CGROUP_WRITEBACK
76 clear_wb_congested(rl
->blkg
->wb_congested
, sync
);
79 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
80 * flip its congestion state for events on other blkcgs.
82 if (rl
== &rl
->q
->root_rl
)
83 clear_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
87 static void blk_set_congested(struct request_list
*rl
, int sync
)
89 #ifdef CONFIG_CGROUP_WRITEBACK
90 set_wb_congested(rl
->blkg
->wb_congested
, sync
);
92 /* see blk_clear_congested() */
93 if (rl
== &rl
->q
->root_rl
)
94 set_wb_congested(rl
->q
->backing_dev_info
->wb
.congested
, sync
);
98 void blk_queue_congestion_threshold(struct request_queue
*q
)
102 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) + 1;
103 if (nr
> q
->nr_requests
)
105 q
->nr_congestion_on
= nr
;
107 nr
= q
->nr_requests
- (q
->nr_requests
/ 8) - (q
->nr_requests
/ 16) - 1;
110 q
->nr_congestion_off
= nr
;
113 void blk_rq_init(struct request_queue
*q
, struct request
*rq
)
115 memset(rq
, 0, sizeof(*rq
));
117 INIT_LIST_HEAD(&rq
->queuelist
);
118 INIT_LIST_HEAD(&rq
->timeout_list
);
121 rq
->__sector
= (sector_t
) -1;
122 INIT_HLIST_NODE(&rq
->hash
);
123 RB_CLEAR_NODE(&rq
->rb_node
);
125 rq
->internal_tag
= -1;
126 rq
->start_time
= jiffies
;
127 set_start_time_ns(rq
);
130 EXPORT_SYMBOL(blk_rq_init
);
132 static const struct {
136 [BLK_STS_OK
] = { 0, "" },
137 [BLK_STS_NOTSUPP
] = { -EOPNOTSUPP
, "operation not supported" },
138 [BLK_STS_TIMEOUT
] = { -ETIMEDOUT
, "timeout" },
139 [BLK_STS_NOSPC
] = { -ENOSPC
, "critical space allocation" },
140 [BLK_STS_TRANSPORT
] = { -ENOLINK
, "recoverable transport" },
141 [BLK_STS_TARGET
] = { -EREMOTEIO
, "critical target" },
142 [BLK_STS_NEXUS
] = { -EBADE
, "critical nexus" },
143 [BLK_STS_MEDIUM
] = { -ENODATA
, "critical medium" },
144 [BLK_STS_PROTECTION
] = { -EILSEQ
, "protection" },
145 [BLK_STS_RESOURCE
] = { -ENOMEM
, "kernel resource" },
147 /* everything else not covered above: */
148 [BLK_STS_IOERR
] = { -EIO
, "I/O" },
151 blk_status_t
errno_to_blk_status(int errno
)
155 for (i
= 0; i
< ARRAY_SIZE(blk_errors
); i
++) {
156 if (blk_errors
[i
].errno
== errno
)
157 return (__force blk_status_t
)i
;
160 return BLK_STS_IOERR
;
162 EXPORT_SYMBOL_GPL(errno_to_blk_status
);
164 int blk_status_to_errno(blk_status_t status
)
166 int idx
= (__force
int)status
;
168 if (WARN_ON_ONCE(idx
> ARRAY_SIZE(blk_errors
)))
170 return blk_errors
[idx
].errno
;
172 EXPORT_SYMBOL_GPL(blk_status_to_errno
);
174 static void print_req_error(struct request
*req
, blk_status_t status
)
176 int idx
= (__force
int)status
;
178 if (WARN_ON_ONCE(idx
> ARRAY_SIZE(blk_errors
)))
181 printk_ratelimited(KERN_ERR
"%s: %s error, dev %s, sector %llu\n",
182 __func__
, blk_errors
[idx
].name
, req
->rq_disk
?
183 req
->rq_disk
->disk_name
: "?",
184 (unsigned long long)blk_rq_pos(req
));
187 static void req_bio_endio(struct request
*rq
, struct bio
*bio
,
188 unsigned int nbytes
, blk_status_t error
)
191 bio
->bi_error
= blk_status_to_errno(error
);
193 if (unlikely(rq
->rq_flags
& RQF_QUIET
))
194 bio_set_flag(bio
, BIO_QUIET
);
196 bio_advance(bio
, nbytes
);
198 /* don't actually finish bio if it's part of flush sequence */
199 if (bio
->bi_iter
.bi_size
== 0 && !(rq
->rq_flags
& RQF_FLUSH_SEQ
))
203 void blk_dump_rq_flags(struct request
*rq
, char *msg
)
205 printk(KERN_INFO
"%s: dev %s: flags=%llx\n", msg
,
206 rq
->rq_disk
? rq
->rq_disk
->disk_name
: "?",
207 (unsigned long long) rq
->cmd_flags
);
209 printk(KERN_INFO
" sector %llu, nr/cnr %u/%u\n",
210 (unsigned long long)blk_rq_pos(rq
),
211 blk_rq_sectors(rq
), blk_rq_cur_sectors(rq
));
212 printk(KERN_INFO
" bio %p, biotail %p, len %u\n",
213 rq
->bio
, rq
->biotail
, blk_rq_bytes(rq
));
215 EXPORT_SYMBOL(blk_dump_rq_flags
);
217 static void blk_delay_work(struct work_struct
*work
)
219 struct request_queue
*q
;
221 q
= container_of(work
, struct request_queue
, delay_work
.work
);
222 spin_lock_irq(q
->queue_lock
);
224 spin_unlock_irq(q
->queue_lock
);
228 * blk_delay_queue - restart queueing after defined interval
229 * @q: The &struct request_queue in question
230 * @msecs: Delay in msecs
233 * Sometimes queueing needs to be postponed for a little while, to allow
234 * resources to come back. This function will make sure that queueing is
235 * restarted around the specified time. Queue lock must be held.
237 void blk_delay_queue(struct request_queue
*q
, unsigned long msecs
)
239 if (likely(!blk_queue_dead(q
)))
240 queue_delayed_work(kblockd_workqueue
, &q
->delay_work
,
241 msecs_to_jiffies(msecs
));
243 EXPORT_SYMBOL(blk_delay_queue
);
246 * blk_start_queue_async - asynchronously restart a previously stopped queue
247 * @q: The &struct request_queue in question
250 * blk_start_queue_async() will clear the stop flag on the queue, and
251 * ensure that the request_fn for the queue is run from an async
254 void blk_start_queue_async(struct request_queue
*q
)
256 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
257 blk_run_queue_async(q
);
259 EXPORT_SYMBOL(blk_start_queue_async
);
262 * blk_start_queue - restart a previously stopped queue
263 * @q: The &struct request_queue in question
266 * blk_start_queue() will clear the stop flag on the queue, and call
267 * the request_fn for the queue if it was in a stopped state when
268 * entered. Also see blk_stop_queue(). Queue lock must be held.
270 void blk_start_queue(struct request_queue
*q
)
272 WARN_ON(!irqs_disabled());
274 queue_flag_clear(QUEUE_FLAG_STOPPED
, q
);
277 EXPORT_SYMBOL(blk_start_queue
);
280 * blk_stop_queue - stop a queue
281 * @q: The &struct request_queue in question
284 * The Linux block layer assumes that a block driver will consume all
285 * entries on the request queue when the request_fn strategy is called.
286 * Often this will not happen, because of hardware limitations (queue
287 * depth settings). If a device driver gets a 'queue full' response,
288 * or if it simply chooses not to queue more I/O at one point, it can
289 * call this function to prevent the request_fn from being called until
290 * the driver has signalled it's ready to go again. This happens by calling
291 * blk_start_queue() to restart queue operations. Queue lock must be held.
293 void blk_stop_queue(struct request_queue
*q
)
295 cancel_delayed_work(&q
->delay_work
);
296 queue_flag_set(QUEUE_FLAG_STOPPED
, q
);
298 EXPORT_SYMBOL(blk_stop_queue
);
301 * blk_sync_queue - cancel any pending callbacks on a queue
305 * The block layer may perform asynchronous callback activity
306 * on a queue, such as calling the unplug function after a timeout.
307 * A block device may call blk_sync_queue to ensure that any
308 * such activity is cancelled, thus allowing it to release resources
309 * that the callbacks might use. The caller must already have made sure
310 * that its ->make_request_fn will not re-add plugging prior to calling
313 * This function does not cancel any asynchronous activity arising
314 * out of elevator or throttling code. That would require elevator_exit()
315 * and blkcg_exit_queue() to be called with queue lock initialized.
318 void blk_sync_queue(struct request_queue
*q
)
320 del_timer_sync(&q
->timeout
);
323 struct blk_mq_hw_ctx
*hctx
;
326 queue_for_each_hw_ctx(q
, hctx
, i
)
327 cancel_delayed_work_sync(&hctx
->run_work
);
329 cancel_delayed_work_sync(&q
->delay_work
);
332 EXPORT_SYMBOL(blk_sync_queue
);
335 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
336 * @q: The queue to run
339 * Invoke request handling on a queue if there are any pending requests.
340 * May be used to restart request handling after a request has completed.
341 * This variant runs the queue whether or not the queue has been
342 * stopped. Must be called with the queue lock held and interrupts
343 * disabled. See also @blk_run_queue.
345 inline void __blk_run_queue_uncond(struct request_queue
*q
)
347 if (unlikely(blk_queue_dead(q
)))
351 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
352 * the queue lock internally. As a result multiple threads may be
353 * running such a request function concurrently. Keep track of the
354 * number of active request_fn invocations such that blk_drain_queue()
355 * can wait until all these request_fn calls have finished.
357 q
->request_fn_active
++;
359 q
->request_fn_active
--;
361 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond
);
364 * __blk_run_queue - run a single device queue
365 * @q: The queue to run
368 * See @blk_run_queue. This variant must be called with the queue lock
369 * held and interrupts disabled.
371 void __blk_run_queue(struct request_queue
*q
)
373 if (unlikely(blk_queue_stopped(q
)))
376 __blk_run_queue_uncond(q
);
378 EXPORT_SYMBOL(__blk_run_queue
);
381 * blk_run_queue_async - run a single device queue in workqueue context
382 * @q: The queue to run
385 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
386 * of us. The caller must hold the queue lock.
388 void blk_run_queue_async(struct request_queue
*q
)
390 if (likely(!blk_queue_stopped(q
) && !blk_queue_dead(q
)))
391 mod_delayed_work(kblockd_workqueue
, &q
->delay_work
, 0);
393 EXPORT_SYMBOL(blk_run_queue_async
);
396 * blk_run_queue - run a single device queue
397 * @q: The queue to run
400 * Invoke request handling on this queue, if it has pending work to do.
401 * May be used to restart queueing when a request has completed.
403 void blk_run_queue(struct request_queue
*q
)
407 spin_lock_irqsave(q
->queue_lock
, flags
);
409 spin_unlock_irqrestore(q
->queue_lock
, flags
);
411 EXPORT_SYMBOL(blk_run_queue
);
413 void blk_put_queue(struct request_queue
*q
)
415 kobject_put(&q
->kobj
);
417 EXPORT_SYMBOL(blk_put_queue
);
420 * __blk_drain_queue - drain requests from request_queue
422 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
424 * Drain requests from @q. If @drain_all is set, all requests are drained.
425 * If not, only ELVPRIV requests are drained. The caller is responsible
426 * for ensuring that no new requests which need to be drained are queued.
428 static void __blk_drain_queue(struct request_queue
*q
, bool drain_all
)
429 __releases(q
->queue_lock
)
430 __acquires(q
->queue_lock
)
434 lockdep_assert_held(q
->queue_lock
);
440 * The caller might be trying to drain @q before its
441 * elevator is initialized.
444 elv_drain_elevator(q
);
446 blkcg_drain_queue(q
);
449 * This function might be called on a queue which failed
450 * driver init after queue creation or is not yet fully
451 * active yet. Some drivers (e.g. fd and loop) get unhappy
452 * in such cases. Kick queue iff dispatch queue has
453 * something on it and @q has request_fn set.
455 if (!list_empty(&q
->queue_head
) && q
->request_fn
)
458 drain
|= q
->nr_rqs_elvpriv
;
459 drain
|= q
->request_fn_active
;
462 * Unfortunately, requests are queued at and tracked from
463 * multiple places and there's no single counter which can
464 * be drained. Check all the queues and counters.
467 struct blk_flush_queue
*fq
= blk_get_flush_queue(q
, NULL
);
468 drain
|= !list_empty(&q
->queue_head
);
469 for (i
= 0; i
< 2; i
++) {
470 drain
|= q
->nr_rqs
[i
];
471 drain
|= q
->in_flight
[i
];
473 drain
|= !list_empty(&fq
->flush_queue
[i
]);
480 spin_unlock_irq(q
->queue_lock
);
484 spin_lock_irq(q
->queue_lock
);
488 * With queue marked dead, any woken up waiter will fail the
489 * allocation path, so the wakeup chaining is lost and we're
490 * left with hung waiters. We need to wake up those waiters.
493 struct request_list
*rl
;
495 blk_queue_for_each_rl(rl
, q
)
496 for (i
= 0; i
< ARRAY_SIZE(rl
->wait
); i
++)
497 wake_up_all(&rl
->wait
[i
]);
502 * blk_queue_bypass_start - enter queue bypass mode
503 * @q: queue of interest
505 * In bypass mode, only the dispatch FIFO queue of @q is used. This
506 * function makes @q enter bypass mode and drains all requests which were
507 * throttled or issued before. On return, it's guaranteed that no request
508 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
509 * inside queue or RCU read lock.
511 void blk_queue_bypass_start(struct request_queue
*q
)
513 spin_lock_irq(q
->queue_lock
);
515 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
516 spin_unlock_irq(q
->queue_lock
);
519 * Queues start drained. Skip actual draining till init is
520 * complete. This avoids lenghty delays during queue init which
521 * can happen many times during boot.
523 if (blk_queue_init_done(q
)) {
524 spin_lock_irq(q
->queue_lock
);
525 __blk_drain_queue(q
, false);
526 spin_unlock_irq(q
->queue_lock
);
528 /* ensure blk_queue_bypass() is %true inside RCU read lock */
532 EXPORT_SYMBOL_GPL(blk_queue_bypass_start
);
535 * blk_queue_bypass_end - leave queue bypass mode
536 * @q: queue of interest
538 * Leave bypass mode and restore the normal queueing behavior.
540 void blk_queue_bypass_end(struct request_queue
*q
)
542 spin_lock_irq(q
->queue_lock
);
543 if (!--q
->bypass_depth
)
544 queue_flag_clear(QUEUE_FLAG_BYPASS
, q
);
545 WARN_ON_ONCE(q
->bypass_depth
< 0);
546 spin_unlock_irq(q
->queue_lock
);
548 EXPORT_SYMBOL_GPL(blk_queue_bypass_end
);
550 void blk_set_queue_dying(struct request_queue
*q
)
552 spin_lock_irq(q
->queue_lock
);
553 queue_flag_set(QUEUE_FLAG_DYING
, q
);
554 spin_unlock_irq(q
->queue_lock
);
557 * When queue DYING flag is set, we need to block new req
558 * entering queue, so we call blk_freeze_queue_start() to
559 * prevent I/O from crossing blk_queue_enter().
561 blk_freeze_queue_start(q
);
564 blk_mq_wake_waiters(q
);
566 struct request_list
*rl
;
568 spin_lock_irq(q
->queue_lock
);
569 blk_queue_for_each_rl(rl
, q
) {
571 wake_up(&rl
->wait
[BLK_RW_SYNC
]);
572 wake_up(&rl
->wait
[BLK_RW_ASYNC
]);
575 spin_unlock_irq(q
->queue_lock
);
578 EXPORT_SYMBOL_GPL(blk_set_queue_dying
);
581 * blk_cleanup_queue - shutdown a request queue
582 * @q: request queue to shutdown
584 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
585 * put it. All future requests will be failed immediately with -ENODEV.
587 void blk_cleanup_queue(struct request_queue
*q
)
589 spinlock_t
*lock
= q
->queue_lock
;
591 /* mark @q DYING, no new request or merges will be allowed afterwards */
592 mutex_lock(&q
->sysfs_lock
);
593 blk_set_queue_dying(q
);
597 * A dying queue is permanently in bypass mode till released. Note
598 * that, unlike blk_queue_bypass_start(), we aren't performing
599 * synchronize_rcu() after entering bypass mode to avoid the delay
600 * as some drivers create and destroy a lot of queues while
601 * probing. This is still safe because blk_release_queue() will be
602 * called only after the queue refcnt drops to zero and nothing,
603 * RCU or not, would be traversing the queue by then.
606 queue_flag_set(QUEUE_FLAG_BYPASS
, q
);
608 queue_flag_set(QUEUE_FLAG_NOMERGES
, q
);
609 queue_flag_set(QUEUE_FLAG_NOXMERGES
, q
);
610 queue_flag_set(QUEUE_FLAG_DYING
, q
);
611 spin_unlock_irq(lock
);
612 mutex_unlock(&q
->sysfs_lock
);
615 * Drain all requests queued before DYING marking. Set DEAD flag to
616 * prevent that q->request_fn() gets invoked after draining finished.
621 __blk_drain_queue(q
, true);
622 queue_flag_set(QUEUE_FLAG_DEAD
, q
);
623 spin_unlock_irq(lock
);
625 /* for synchronous bio-based driver finish in-flight integrity i/o */
626 blk_flush_integrity();
628 /* @q won't process any more request, flush async actions */
629 del_timer_sync(&q
->backing_dev_info
->laptop_mode_wb_timer
);
633 blk_mq_free_queue(q
);
634 percpu_ref_exit(&q
->q_usage_counter
);
637 if (q
->queue_lock
!= &q
->__queue_lock
)
638 q
->queue_lock
= &q
->__queue_lock
;
639 spin_unlock_irq(lock
);
641 /* @q is and will stay empty, shutdown and put */
644 EXPORT_SYMBOL(blk_cleanup_queue
);
646 /* Allocate memory local to the request queue */
647 static void *alloc_request_simple(gfp_t gfp_mask
, void *data
)
649 struct request_queue
*q
= data
;
651 return kmem_cache_alloc_node(request_cachep
, gfp_mask
, q
->node
);
654 static void free_request_simple(void *element
, void *data
)
656 kmem_cache_free(request_cachep
, element
);
659 static void *alloc_request_size(gfp_t gfp_mask
, void *data
)
661 struct request_queue
*q
= data
;
664 rq
= kmalloc_node(sizeof(struct request
) + q
->cmd_size
, gfp_mask
,
666 if (rq
&& q
->init_rq_fn
&& q
->init_rq_fn(q
, rq
, gfp_mask
) < 0) {
673 static void free_request_size(void *element
, void *data
)
675 struct request_queue
*q
= data
;
678 q
->exit_rq_fn(q
, element
);
682 int blk_init_rl(struct request_list
*rl
, struct request_queue
*q
,
685 if (unlikely(rl
->rq_pool
))
689 rl
->count
[BLK_RW_SYNC
] = rl
->count
[BLK_RW_ASYNC
] = 0;
690 rl
->starved
[BLK_RW_SYNC
] = rl
->starved
[BLK_RW_ASYNC
] = 0;
691 init_waitqueue_head(&rl
->wait
[BLK_RW_SYNC
]);
692 init_waitqueue_head(&rl
->wait
[BLK_RW_ASYNC
]);
695 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
,
696 alloc_request_size
, free_request_size
,
697 q
, gfp_mask
, q
->node
);
699 rl
->rq_pool
= mempool_create_node(BLKDEV_MIN_RQ
,
700 alloc_request_simple
, free_request_simple
,
701 q
, gfp_mask
, q
->node
);
709 void blk_exit_rl(struct request_list
*rl
)
712 mempool_destroy(rl
->rq_pool
);
715 struct request_queue
*blk_alloc_queue(gfp_t gfp_mask
)
717 return blk_alloc_queue_node(gfp_mask
, NUMA_NO_NODE
);
719 EXPORT_SYMBOL(blk_alloc_queue
);
721 int blk_queue_enter(struct request_queue
*q
, bool nowait
)
726 if (percpu_ref_tryget_live(&q
->q_usage_counter
))
733 * read pair of barrier in blk_freeze_queue_start(),
734 * we need to order reading __PERCPU_REF_DEAD flag of
735 * .q_usage_counter and reading .mq_freeze_depth or
736 * queue dying flag, otherwise the following wait may
737 * never return if the two reads are reordered.
741 ret
= wait_event_interruptible(q
->mq_freeze_wq
,
742 !atomic_read(&q
->mq_freeze_depth
) ||
744 if (blk_queue_dying(q
))
751 void blk_queue_exit(struct request_queue
*q
)
753 percpu_ref_put(&q
->q_usage_counter
);
756 static void blk_queue_usage_counter_release(struct percpu_ref
*ref
)
758 struct request_queue
*q
=
759 container_of(ref
, struct request_queue
, q_usage_counter
);
761 wake_up_all(&q
->mq_freeze_wq
);
764 static void blk_rq_timed_out_timer(unsigned long data
)
766 struct request_queue
*q
= (struct request_queue
*)data
;
768 kblockd_schedule_work(&q
->timeout_work
);
771 struct request_queue
*blk_alloc_queue_node(gfp_t gfp_mask
, int node_id
)
773 struct request_queue
*q
;
775 q
= kmem_cache_alloc_node(blk_requestq_cachep
,
776 gfp_mask
| __GFP_ZERO
, node_id
);
780 q
->id
= ida_simple_get(&blk_queue_ida
, 0, 0, gfp_mask
);
784 q
->bio_split
= bioset_create(BIO_POOL_SIZE
, 0);
788 q
->backing_dev_info
= bdi_alloc_node(gfp_mask
, node_id
);
789 if (!q
->backing_dev_info
)
792 q
->stats
= blk_alloc_queue_stats();
796 q
->backing_dev_info
->ra_pages
=
797 (VM_MAX_READAHEAD
* 1024) / PAGE_SIZE
;
798 q
->backing_dev_info
->capabilities
= BDI_CAP_CGROUP_WRITEBACK
;
799 q
->backing_dev_info
->name
= "block";
802 setup_timer(&q
->backing_dev_info
->laptop_mode_wb_timer
,
803 laptop_mode_timer_fn
, (unsigned long) q
);
804 setup_timer(&q
->timeout
, blk_rq_timed_out_timer
, (unsigned long) q
);
805 INIT_LIST_HEAD(&q
->queue_head
);
806 INIT_LIST_HEAD(&q
->timeout_list
);
807 INIT_LIST_HEAD(&q
->icq_list
);
808 #ifdef CONFIG_BLK_CGROUP
809 INIT_LIST_HEAD(&q
->blkg_list
);
811 INIT_DELAYED_WORK(&q
->delay_work
, blk_delay_work
);
813 kobject_init(&q
->kobj
, &blk_queue_ktype
);
815 mutex_init(&q
->sysfs_lock
);
816 spin_lock_init(&q
->__queue_lock
);
819 * By default initialize queue_lock to internal lock and driver can
820 * override it later if need be.
822 q
->queue_lock
= &q
->__queue_lock
;
825 * A queue starts its life with bypass turned on to avoid
826 * unnecessary bypass on/off overhead and nasty surprises during
827 * init. The initial bypass will be finished when the queue is
828 * registered by blk_register_queue().
831 __set_bit(QUEUE_FLAG_BYPASS
, &q
->queue_flags
);
833 init_waitqueue_head(&q
->mq_freeze_wq
);
836 * Init percpu_ref in atomic mode so that it's faster to shutdown.
837 * See blk_register_queue() for details.
839 if (percpu_ref_init(&q
->q_usage_counter
,
840 blk_queue_usage_counter_release
,
841 PERCPU_REF_INIT_ATOMIC
, GFP_KERNEL
))
844 if (blkcg_init_queue(q
))
850 percpu_ref_exit(&q
->q_usage_counter
);
852 blk_free_queue_stats(q
->stats
);
854 bdi_put(q
->backing_dev_info
);
856 bioset_free(q
->bio_split
);
858 ida_simple_remove(&blk_queue_ida
, q
->id
);
860 kmem_cache_free(blk_requestq_cachep
, q
);
863 EXPORT_SYMBOL(blk_alloc_queue_node
);
866 * blk_init_queue - prepare a request queue for use with a block device
867 * @rfn: The function to be called to process requests that have been
868 * placed on the queue.
869 * @lock: Request queue spin lock
872 * If a block device wishes to use the standard request handling procedures,
873 * which sorts requests and coalesces adjacent requests, then it must
874 * call blk_init_queue(). The function @rfn will be called when there
875 * are requests on the queue that need to be processed. If the device
876 * supports plugging, then @rfn may not be called immediately when requests
877 * are available on the queue, but may be called at some time later instead.
878 * Plugged queues are generally unplugged when a buffer belonging to one
879 * of the requests on the queue is needed, or due to memory pressure.
881 * @rfn is not required, or even expected, to remove all requests off the
882 * queue, but only as many as it can handle at a time. If it does leave
883 * requests on the queue, it is responsible for arranging that the requests
884 * get dealt with eventually.
886 * The queue spin lock must be held while manipulating the requests on the
887 * request queue; this lock will be taken also from interrupt context, so irq
888 * disabling is needed for it.
890 * Function returns a pointer to the initialized request queue, or %NULL if
894 * blk_init_queue() must be paired with a blk_cleanup_queue() call
895 * when the block device is deactivated (such as at module unload).
898 struct request_queue
*blk_init_queue(request_fn_proc
*rfn
, spinlock_t
*lock
)
900 return blk_init_queue_node(rfn
, lock
, NUMA_NO_NODE
);
902 EXPORT_SYMBOL(blk_init_queue
);
904 struct request_queue
*
905 blk_init_queue_node(request_fn_proc
*rfn
, spinlock_t
*lock
, int node_id
)
907 struct request_queue
*q
;
909 q
= blk_alloc_queue_node(GFP_KERNEL
, node_id
);
915 q
->queue_lock
= lock
;
916 if (blk_init_allocated_queue(q
) < 0) {
917 blk_cleanup_queue(q
);
923 EXPORT_SYMBOL(blk_init_queue_node
);
925 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
);
928 int blk_init_allocated_queue(struct request_queue
*q
)
930 q
->fq
= blk_alloc_flush_queue(q
, NUMA_NO_NODE
, q
->cmd_size
);
934 if (q
->init_rq_fn
&& q
->init_rq_fn(q
, q
->fq
->flush_rq
, GFP_KERNEL
))
935 goto out_free_flush_queue
;
937 if (blk_init_rl(&q
->root_rl
, q
, GFP_KERNEL
))
938 goto out_exit_flush_rq
;
940 INIT_WORK(&q
->timeout_work
, blk_timeout_work
);
941 q
->queue_flags
|= QUEUE_FLAG_DEFAULT
;
944 * This also sets hw/phys segments, boundary and size
946 blk_queue_make_request(q
, blk_queue_bio
);
948 q
->sg_reserved_size
= INT_MAX
;
950 /* Protect q->elevator from elevator_change */
951 mutex_lock(&q
->sysfs_lock
);
954 if (elevator_init(q
, NULL
)) {
955 mutex_unlock(&q
->sysfs_lock
);
956 goto out_exit_flush_rq
;
959 mutex_unlock(&q
->sysfs_lock
);
964 q
->exit_rq_fn(q
, q
->fq
->flush_rq
);
965 out_free_flush_queue
:
966 blk_free_flush_queue(q
->fq
);
969 EXPORT_SYMBOL(blk_init_allocated_queue
);
971 bool blk_get_queue(struct request_queue
*q
)
973 if (likely(!blk_queue_dying(q
))) {
980 EXPORT_SYMBOL(blk_get_queue
);
982 static inline void blk_free_request(struct request_list
*rl
, struct request
*rq
)
984 if (rq
->rq_flags
& RQF_ELVPRIV
) {
985 elv_put_request(rl
->q
, rq
);
987 put_io_context(rq
->elv
.icq
->ioc
);
990 mempool_free(rq
, rl
->rq_pool
);
994 * ioc_batching returns true if the ioc is a valid batching request and
995 * should be given priority access to a request.
997 static inline int ioc_batching(struct request_queue
*q
, struct io_context
*ioc
)
1003 * Make sure the process is able to allocate at least 1 request
1004 * even if the batch times out, otherwise we could theoretically
1007 return ioc
->nr_batch_requests
== q
->nr_batching
||
1008 (ioc
->nr_batch_requests
> 0
1009 && time_before(jiffies
, ioc
->last_waited
+ BLK_BATCH_TIME
));
1013 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1014 * will cause the process to be a "batcher" on all queues in the system. This
1015 * is the behaviour we want though - once it gets a wakeup it should be given
1018 static void ioc_set_batching(struct request_queue
*q
, struct io_context
*ioc
)
1020 if (!ioc
|| ioc_batching(q
, ioc
))
1023 ioc
->nr_batch_requests
= q
->nr_batching
;
1024 ioc
->last_waited
= jiffies
;
1027 static void __freed_request(struct request_list
*rl
, int sync
)
1029 struct request_queue
*q
= rl
->q
;
1031 if (rl
->count
[sync
] < queue_congestion_off_threshold(q
))
1032 blk_clear_congested(rl
, sync
);
1034 if (rl
->count
[sync
] + 1 <= q
->nr_requests
) {
1035 if (waitqueue_active(&rl
->wait
[sync
]))
1036 wake_up(&rl
->wait
[sync
]);
1038 blk_clear_rl_full(rl
, sync
);
1043 * A request has just been released. Account for it, update the full and
1044 * congestion status, wake up any waiters. Called under q->queue_lock.
1046 static void freed_request(struct request_list
*rl
, bool sync
,
1047 req_flags_t rq_flags
)
1049 struct request_queue
*q
= rl
->q
;
1053 if (rq_flags
& RQF_ELVPRIV
)
1054 q
->nr_rqs_elvpriv
--;
1056 __freed_request(rl
, sync
);
1058 if (unlikely(rl
->starved
[sync
^ 1]))
1059 __freed_request(rl
, sync
^ 1);
1062 int blk_update_nr_requests(struct request_queue
*q
, unsigned int nr
)
1064 struct request_list
*rl
;
1065 int on_thresh
, off_thresh
;
1067 spin_lock_irq(q
->queue_lock
);
1068 q
->nr_requests
= nr
;
1069 blk_queue_congestion_threshold(q
);
1070 on_thresh
= queue_congestion_on_threshold(q
);
1071 off_thresh
= queue_congestion_off_threshold(q
);
1073 blk_queue_for_each_rl(rl
, q
) {
1074 if (rl
->count
[BLK_RW_SYNC
] >= on_thresh
)
1075 blk_set_congested(rl
, BLK_RW_SYNC
);
1076 else if (rl
->count
[BLK_RW_SYNC
] < off_thresh
)
1077 blk_clear_congested(rl
, BLK_RW_SYNC
);
1079 if (rl
->count
[BLK_RW_ASYNC
] >= on_thresh
)
1080 blk_set_congested(rl
, BLK_RW_ASYNC
);
1081 else if (rl
->count
[BLK_RW_ASYNC
] < off_thresh
)
1082 blk_clear_congested(rl
, BLK_RW_ASYNC
);
1084 if (rl
->count
[BLK_RW_SYNC
] >= q
->nr_requests
) {
1085 blk_set_rl_full(rl
, BLK_RW_SYNC
);
1087 blk_clear_rl_full(rl
, BLK_RW_SYNC
);
1088 wake_up(&rl
->wait
[BLK_RW_SYNC
]);
1091 if (rl
->count
[BLK_RW_ASYNC
] >= q
->nr_requests
) {
1092 blk_set_rl_full(rl
, BLK_RW_ASYNC
);
1094 blk_clear_rl_full(rl
, BLK_RW_ASYNC
);
1095 wake_up(&rl
->wait
[BLK_RW_ASYNC
]);
1099 spin_unlock_irq(q
->queue_lock
);
1104 * __get_request - get a free request
1105 * @rl: request list to allocate from
1106 * @op: operation and flags
1107 * @bio: bio to allocate request for (can be %NULL)
1108 * @gfp_mask: allocation mask
1110 * Get a free request from @q. This function may fail under memory
1111 * pressure or if @q is dead.
1113 * Must be called with @q->queue_lock held and,
1114 * Returns ERR_PTR on failure, with @q->queue_lock held.
1115 * Returns request pointer on success, with @q->queue_lock *not held*.
1117 static struct request
*__get_request(struct request_list
*rl
, unsigned int op
,
1118 struct bio
*bio
, gfp_t gfp_mask
)
1120 struct request_queue
*q
= rl
->q
;
1122 struct elevator_type
*et
= q
->elevator
->type
;
1123 struct io_context
*ioc
= rq_ioc(bio
);
1124 struct io_cq
*icq
= NULL
;
1125 const bool is_sync
= op_is_sync(op
);
1127 req_flags_t rq_flags
= RQF_ALLOCED
;
1129 if (unlikely(blk_queue_dying(q
)))
1130 return ERR_PTR(-ENODEV
);
1132 may_queue
= elv_may_queue(q
, op
);
1133 if (may_queue
== ELV_MQUEUE_NO
)
1136 if (rl
->count
[is_sync
]+1 >= queue_congestion_on_threshold(q
)) {
1137 if (rl
->count
[is_sync
]+1 >= q
->nr_requests
) {
1139 * The queue will fill after this allocation, so set
1140 * it as full, and mark this process as "batching".
1141 * This process will be allowed to complete a batch of
1142 * requests, others will be blocked.
1144 if (!blk_rl_full(rl
, is_sync
)) {
1145 ioc_set_batching(q
, ioc
);
1146 blk_set_rl_full(rl
, is_sync
);
1148 if (may_queue
!= ELV_MQUEUE_MUST
1149 && !ioc_batching(q
, ioc
)) {
1151 * The queue is full and the allocating
1152 * process is not a "batcher", and not
1153 * exempted by the IO scheduler
1155 return ERR_PTR(-ENOMEM
);
1159 blk_set_congested(rl
, is_sync
);
1163 * Only allow batching queuers to allocate up to 50% over the defined
1164 * limit of requests, otherwise we could have thousands of requests
1165 * allocated with any setting of ->nr_requests
1167 if (rl
->count
[is_sync
] >= (3 * q
->nr_requests
/ 2))
1168 return ERR_PTR(-ENOMEM
);
1170 q
->nr_rqs
[is_sync
]++;
1171 rl
->count
[is_sync
]++;
1172 rl
->starved
[is_sync
] = 0;
1175 * Decide whether the new request will be managed by elevator. If
1176 * so, mark @rq_flags and increment elvpriv. Non-zero elvpriv will
1177 * prevent the current elevator from being destroyed until the new
1178 * request is freed. This guarantees icq's won't be destroyed and
1179 * makes creating new ones safe.
1181 * Flush requests do not use the elevator so skip initialization.
1182 * This allows a request to share the flush and elevator data.
1184 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1185 * it will be created after releasing queue_lock.
1187 if (!op_is_flush(op
) && !blk_queue_bypass(q
)) {
1188 rq_flags
|= RQF_ELVPRIV
;
1189 q
->nr_rqs_elvpriv
++;
1190 if (et
->icq_cache
&& ioc
)
1191 icq
= ioc_lookup_icq(ioc
, q
);
1194 if (blk_queue_io_stat(q
))
1195 rq_flags
|= RQF_IO_STAT
;
1196 spin_unlock_irq(q
->queue_lock
);
1198 /* allocate and init request */
1199 rq
= mempool_alloc(rl
->rq_pool
, gfp_mask
);
1204 blk_rq_set_rl(rq
, rl
);
1206 rq
->rq_flags
= rq_flags
;
1209 if (rq_flags
& RQF_ELVPRIV
) {
1210 if (unlikely(et
->icq_cache
&& !icq
)) {
1212 icq
= ioc_create_icq(ioc
, q
, gfp_mask
);
1218 if (unlikely(elv_set_request(q
, rq
, bio
, gfp_mask
)))
1221 /* @rq->elv.icq holds io_context until @rq is freed */
1223 get_io_context(icq
->ioc
);
1227 * ioc may be NULL here, and ioc_batching will be false. That's
1228 * OK, if the queue is under the request limit then requests need
1229 * not count toward the nr_batch_requests limit. There will always
1230 * be some limit enforced by BLK_BATCH_TIME.
1232 if (ioc_batching(q
, ioc
))
1233 ioc
->nr_batch_requests
--;
1235 trace_block_getrq(q
, bio
, op
);
1240 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1241 * and may fail indefinitely under memory pressure and thus
1242 * shouldn't stall IO. Treat this request as !elvpriv. This will
1243 * disturb iosched and blkcg but weird is bettern than dead.
1245 printk_ratelimited(KERN_WARNING
"%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1246 __func__
, dev_name(q
->backing_dev_info
->dev
));
1248 rq
->rq_flags
&= ~RQF_ELVPRIV
;
1251 spin_lock_irq(q
->queue_lock
);
1252 q
->nr_rqs_elvpriv
--;
1253 spin_unlock_irq(q
->queue_lock
);
1258 * Allocation failed presumably due to memory. Undo anything we
1259 * might have messed up.
1261 * Allocating task should really be put onto the front of the wait
1262 * queue, but this is pretty rare.
1264 spin_lock_irq(q
->queue_lock
);
1265 freed_request(rl
, is_sync
, rq_flags
);
1268 * in the very unlikely event that allocation failed and no
1269 * requests for this direction was pending, mark us starved so that
1270 * freeing of a request in the other direction will notice
1271 * us. another possible fix would be to split the rq mempool into
1275 if (unlikely(rl
->count
[is_sync
] == 0))
1276 rl
->starved
[is_sync
] = 1;
1277 return ERR_PTR(-ENOMEM
);
1281 * get_request - get a free request
1282 * @q: request_queue to allocate request from
1283 * @op: operation and flags
1284 * @bio: bio to allocate request for (can be %NULL)
1285 * @gfp_mask: allocation mask
1287 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1288 * this function keeps retrying under memory pressure and fails iff @q is dead.
1290 * Must be called with @q->queue_lock held and,
1291 * Returns ERR_PTR on failure, with @q->queue_lock held.
1292 * Returns request pointer on success, with @q->queue_lock *not held*.
1294 static struct request
*get_request(struct request_queue
*q
, unsigned int op
,
1295 struct bio
*bio
, gfp_t gfp_mask
)
1297 const bool is_sync
= op_is_sync(op
);
1299 struct request_list
*rl
;
1302 rl
= blk_get_rl(q
, bio
); /* transferred to @rq on success */
1304 rq
= __get_request(rl
, op
, bio
, gfp_mask
);
1308 if (!gfpflags_allow_blocking(gfp_mask
) || unlikely(blk_queue_dying(q
))) {
1313 /* wait on @rl and retry */
1314 prepare_to_wait_exclusive(&rl
->wait
[is_sync
], &wait
,
1315 TASK_UNINTERRUPTIBLE
);
1317 trace_block_sleeprq(q
, bio
, op
);
1319 spin_unlock_irq(q
->queue_lock
);
1323 * After sleeping, we become a "batching" process and will be able
1324 * to allocate at least one request, and up to a big batch of them
1325 * for a small period time. See ioc_batching, ioc_set_batching
1327 ioc_set_batching(q
, current
->io_context
);
1329 spin_lock_irq(q
->queue_lock
);
1330 finish_wait(&rl
->wait
[is_sync
], &wait
);
1335 static struct request
*blk_old_get_request(struct request_queue
*q
, int rw
,
1340 /* create ioc upfront */
1341 create_io_context(gfp_mask
, q
->node
);
1343 spin_lock_irq(q
->queue_lock
);
1344 rq
= get_request(q
, rw
, NULL
, gfp_mask
);
1346 spin_unlock_irq(q
->queue_lock
);
1350 /* q->queue_lock is unlocked at this point */
1352 rq
->__sector
= (sector_t
) -1;
1353 rq
->bio
= rq
->biotail
= NULL
;
1357 struct request
*blk_get_request(struct request_queue
*q
, int rw
, gfp_t gfp_mask
)
1360 return blk_mq_alloc_request(q
, rw
,
1361 (gfp_mask
& __GFP_DIRECT_RECLAIM
) ?
1362 0 : BLK_MQ_REQ_NOWAIT
);
1364 return blk_old_get_request(q
, rw
, gfp_mask
);
1366 EXPORT_SYMBOL(blk_get_request
);
1369 * blk_requeue_request - put a request back on queue
1370 * @q: request queue where request should be inserted
1371 * @rq: request to be inserted
1374 * Drivers often keep queueing requests until the hardware cannot accept
1375 * more, when that condition happens we need to put the request back
1376 * on the queue. Must be called with queue lock held.
1378 void blk_requeue_request(struct request_queue
*q
, struct request
*rq
)
1380 blk_delete_timer(rq
);
1381 blk_clear_rq_complete(rq
);
1382 trace_block_rq_requeue(q
, rq
);
1383 wbt_requeue(q
->rq_wb
, &rq
->issue_stat
);
1385 if (rq
->rq_flags
& RQF_QUEUED
)
1386 blk_queue_end_tag(q
, rq
);
1388 BUG_ON(blk_queued_rq(rq
));
1390 elv_requeue_request(q
, rq
);
1392 EXPORT_SYMBOL(blk_requeue_request
);
1394 static void add_acct_request(struct request_queue
*q
, struct request
*rq
,
1397 blk_account_io_start(rq
, true);
1398 __elv_add_request(q
, rq
, where
);
1401 static void part_round_stats_single(int cpu
, struct hd_struct
*part
,
1406 if (now
== part
->stamp
)
1409 inflight
= part_in_flight(part
);
1411 __part_stat_add(cpu
, part
, time_in_queue
,
1412 inflight
* (now
- part
->stamp
));
1413 __part_stat_add(cpu
, part
, io_ticks
, (now
- part
->stamp
));
1419 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1420 * @cpu: cpu number for stats access
1421 * @part: target partition
1423 * The average IO queue length and utilisation statistics are maintained
1424 * by observing the current state of the queue length and the amount of
1425 * time it has been in this state for.
1427 * Normally, that accounting is done on IO completion, but that can result
1428 * in more than a second's worth of IO being accounted for within any one
1429 * second, leading to >100% utilisation. To deal with that, we call this
1430 * function to do a round-off before returning the results when reading
1431 * /proc/diskstats. This accounts immediately for all queue usage up to
1432 * the current jiffies and restarts the counters again.
1434 void part_round_stats(int cpu
, struct hd_struct
*part
)
1436 unsigned long now
= jiffies
;
1439 part_round_stats_single(cpu
, &part_to_disk(part
)->part0
, now
);
1440 part_round_stats_single(cpu
, part
, now
);
1442 EXPORT_SYMBOL_GPL(part_round_stats
);
1445 static void blk_pm_put_request(struct request
*rq
)
1447 if (rq
->q
->dev
&& !(rq
->rq_flags
& RQF_PM
) && !--rq
->q
->nr_pending
)
1448 pm_runtime_mark_last_busy(rq
->q
->dev
);
1451 static inline void blk_pm_put_request(struct request
*rq
) {}
1455 * queue lock must be held
1457 void __blk_put_request(struct request_queue
*q
, struct request
*req
)
1459 req_flags_t rq_flags
= req
->rq_flags
;
1465 blk_mq_free_request(req
);
1469 blk_pm_put_request(req
);
1471 elv_completed_request(q
, req
);
1473 /* this is a bio leak */
1474 WARN_ON(req
->bio
!= NULL
);
1476 wbt_done(q
->rq_wb
, &req
->issue_stat
);
1479 * Request may not have originated from ll_rw_blk. if not,
1480 * it didn't come out of our reserved rq pools
1482 if (rq_flags
& RQF_ALLOCED
) {
1483 struct request_list
*rl
= blk_rq_rl(req
);
1484 bool sync
= op_is_sync(req
->cmd_flags
);
1486 BUG_ON(!list_empty(&req
->queuelist
));
1487 BUG_ON(ELV_ON_HASH(req
));
1489 blk_free_request(rl
, req
);
1490 freed_request(rl
, sync
, rq_flags
);
1494 EXPORT_SYMBOL_GPL(__blk_put_request
);
1496 void blk_put_request(struct request
*req
)
1498 struct request_queue
*q
= req
->q
;
1501 blk_mq_free_request(req
);
1503 unsigned long flags
;
1505 spin_lock_irqsave(q
->queue_lock
, flags
);
1506 __blk_put_request(q
, req
);
1507 spin_unlock_irqrestore(q
->queue_lock
, flags
);
1510 EXPORT_SYMBOL(blk_put_request
);
1512 bool bio_attempt_back_merge(struct request_queue
*q
, struct request
*req
,
1515 const int ff
= bio
->bi_opf
& REQ_FAILFAST_MASK
;
1517 if (!ll_back_merge_fn(q
, req
, bio
))
1520 trace_block_bio_backmerge(q
, req
, bio
);
1522 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1523 blk_rq_set_mixed_merge(req
);
1525 req
->biotail
->bi_next
= bio
;
1527 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1528 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1530 blk_account_io_start(req
, false);
1534 bool bio_attempt_front_merge(struct request_queue
*q
, struct request
*req
,
1537 const int ff
= bio
->bi_opf
& REQ_FAILFAST_MASK
;
1539 if (!ll_front_merge_fn(q
, req
, bio
))
1542 trace_block_bio_frontmerge(q
, req
, bio
);
1544 if ((req
->cmd_flags
& REQ_FAILFAST_MASK
) != ff
)
1545 blk_rq_set_mixed_merge(req
);
1547 bio
->bi_next
= req
->bio
;
1550 req
->__sector
= bio
->bi_iter
.bi_sector
;
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_discard_merge(struct request_queue
*q
, struct request
*req
,
1561 unsigned short segments
= blk_rq_nr_discard_segments(req
);
1563 if (segments
>= queue_max_discard_segments(q
))
1565 if (blk_rq_sectors(req
) + bio_sectors(bio
) >
1566 blk_rq_get_max_sectors(req
, blk_rq_pos(req
)))
1569 req
->biotail
->bi_next
= bio
;
1571 req
->__data_len
+= bio
->bi_iter
.bi_size
;
1572 req
->ioprio
= ioprio_best(req
->ioprio
, bio_prio(bio
));
1573 req
->nr_phys_segments
= segments
+ 1;
1575 blk_account_io_start(req
, false);
1578 req_set_nomerge(q
, req
);
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
;
1610 struct list_head
*plug_list
;
1612 plug
= current
->plug
;
1618 plug_list
= &plug
->mq_list
;
1620 plug_list
= &plug
->list
;
1622 list_for_each_entry_reverse(rq
, plug_list
, queuelist
) {
1623 bool merged
= false;
1628 * Only blk-mq multiple hardware queues case checks the
1629 * rq in the same queue, there should be only one such
1633 *same_queue_rq
= rq
;
1636 if (rq
->q
!= q
|| !blk_rq_merge_ok(rq
, bio
))
1639 switch (blk_try_merge(rq
, bio
)) {
1640 case ELEVATOR_BACK_MERGE
:
1641 merged
= bio_attempt_back_merge(q
, rq
, bio
);
1643 case ELEVATOR_FRONT_MERGE
:
1644 merged
= bio_attempt_front_merge(q
, rq
, bio
);
1646 case ELEVATOR_DISCARD_MERGE
:
1647 merged
= bio_attempt_discard_merge(q
, rq
, bio
);
1660 unsigned int blk_plug_queued_count(struct request_queue
*q
)
1662 struct blk_plug
*plug
;
1664 struct list_head
*plug_list
;
1665 unsigned int ret
= 0;
1667 plug
= current
->plug
;
1672 plug_list
= &plug
->mq_list
;
1674 plug_list
= &plug
->list
;
1676 list_for_each_entry(rq
, plug_list
, queuelist
) {
1684 void blk_init_request_from_bio(struct request
*req
, struct bio
*bio
)
1686 struct io_context
*ioc
= rq_ioc(bio
);
1688 if (bio
->bi_opf
& REQ_RAHEAD
)
1689 req
->cmd_flags
|= REQ_FAILFAST_MASK
;
1691 req
->__sector
= bio
->bi_iter
.bi_sector
;
1692 if (ioprio_valid(bio_prio(bio
)))
1693 req
->ioprio
= bio_prio(bio
);
1695 req
->ioprio
= ioc
->ioprio
;
1697 req
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE
, 0);
1698 blk_rq_bio_prep(req
->q
, req
, bio
);
1700 EXPORT_SYMBOL_GPL(blk_init_request_from_bio
);
1702 static blk_qc_t
blk_queue_bio(struct request_queue
*q
, struct bio
*bio
)
1704 struct blk_plug
*plug
;
1705 int where
= ELEVATOR_INSERT_SORT
;
1706 struct request
*req
, *free
;
1707 unsigned int request_count
= 0;
1708 unsigned int wb_acct
;
1711 * low level driver can indicate that it wants pages above a
1712 * certain limit bounced to low memory (ie for highmem, or even
1713 * ISA dma in theory)
1715 blk_queue_bounce(q
, &bio
);
1717 blk_queue_split(q
, &bio
, q
->bio_split
);
1719 if (bio_integrity_enabled(bio
) && bio_integrity_prep(bio
)) {
1720 bio
->bi_error
= -EIO
;
1722 return BLK_QC_T_NONE
;
1725 if (op_is_flush(bio
->bi_opf
)) {
1726 spin_lock_irq(q
->queue_lock
);
1727 where
= ELEVATOR_INSERT_FLUSH
;
1732 * Check if we can merge with the plugged list before grabbing
1735 if (!blk_queue_nomerges(q
)) {
1736 if (blk_attempt_plug_merge(q
, bio
, &request_count
, NULL
))
1737 return BLK_QC_T_NONE
;
1739 request_count
= blk_plug_queued_count(q
);
1741 spin_lock_irq(q
->queue_lock
);
1743 switch (elv_merge(q
, &req
, bio
)) {
1744 case ELEVATOR_BACK_MERGE
:
1745 if (!bio_attempt_back_merge(q
, req
, bio
))
1747 elv_bio_merged(q
, req
, bio
);
1748 free
= attempt_back_merge(q
, req
);
1750 __blk_put_request(q
, free
);
1752 elv_merged_request(q
, req
, ELEVATOR_BACK_MERGE
);
1754 case ELEVATOR_FRONT_MERGE
:
1755 if (!bio_attempt_front_merge(q
, req
, bio
))
1757 elv_bio_merged(q
, req
, bio
);
1758 free
= attempt_front_merge(q
, req
);
1760 __blk_put_request(q
, free
);
1762 elv_merged_request(q
, req
, ELEVATOR_FRONT_MERGE
);
1769 wb_acct
= wbt_wait(q
->rq_wb
, bio
, q
->queue_lock
);
1772 * Grab a free request. This is might sleep but can not fail.
1773 * Returns with the queue unlocked.
1775 req
= get_request(q
, bio
->bi_opf
, bio
, GFP_NOIO
);
1777 __wbt_done(q
->rq_wb
, wb_acct
);
1778 bio
->bi_error
= PTR_ERR(req
);
1783 wbt_track(&req
->issue_stat
, wb_acct
);
1786 * After dropping the lock and possibly sleeping here, our request
1787 * may now be mergeable after it had proven unmergeable (above).
1788 * We don't worry about that case for efficiency. It won't happen
1789 * often, and the elevators are able to handle it.
1791 blk_init_request_from_bio(req
, bio
);
1793 if (test_bit(QUEUE_FLAG_SAME_COMP
, &q
->queue_flags
))
1794 req
->cpu
= raw_smp_processor_id();
1796 plug
= current
->plug
;
1799 * If this is the first request added after a plug, fire
1802 * @request_count may become stale because of schedule
1803 * out, so check plug list again.
1805 if (!request_count
|| list_empty(&plug
->list
))
1806 trace_block_plug(q
);
1808 struct request
*last
= list_entry_rq(plug
->list
.prev
);
1809 if (request_count
>= BLK_MAX_REQUEST_COUNT
||
1810 blk_rq_bytes(last
) >= BLK_PLUG_FLUSH_SIZE
) {
1811 blk_flush_plug_list(plug
, false);
1812 trace_block_plug(q
);
1815 list_add_tail(&req
->queuelist
, &plug
->list
);
1816 blk_account_io_start(req
, true);
1818 spin_lock_irq(q
->queue_lock
);
1819 add_acct_request(q
, req
, where
);
1822 spin_unlock_irq(q
->queue_lock
);
1825 return BLK_QC_T_NONE
;
1829 * If bio->bi_dev is a partition, remap the location
1831 static inline void blk_partition_remap(struct bio
*bio
)
1833 struct block_device
*bdev
= bio
->bi_bdev
;
1836 * Zone reset does not include bi_size so bio_sectors() is always 0.
1837 * Include a test for the reset op code and perform the remap if needed.
1839 if (bdev
!= bdev
->bd_contains
&&
1840 (bio_sectors(bio
) || bio_op(bio
) == REQ_OP_ZONE_RESET
)) {
1841 struct hd_struct
*p
= bdev
->bd_part
;
1843 bio
->bi_iter
.bi_sector
+= p
->start_sect
;
1844 bio
->bi_bdev
= bdev
->bd_contains
;
1846 trace_block_bio_remap(bdev_get_queue(bio
->bi_bdev
), bio
,
1848 bio
->bi_iter
.bi_sector
- p
->start_sect
);
1852 static void handle_bad_sector(struct bio
*bio
)
1854 char b
[BDEVNAME_SIZE
];
1856 printk(KERN_INFO
"attempt to access beyond end of device\n");
1857 printk(KERN_INFO
"%s: rw=%d, want=%Lu, limit=%Lu\n",
1858 bdevname(bio
->bi_bdev
, b
),
1860 (unsigned long long)bio_end_sector(bio
),
1861 (long long)(i_size_read(bio
->bi_bdev
->bd_inode
) >> 9));
1864 #ifdef CONFIG_FAIL_MAKE_REQUEST
1866 static DECLARE_FAULT_ATTR(fail_make_request
);
1868 static int __init
setup_fail_make_request(char *str
)
1870 return setup_fault_attr(&fail_make_request
, str
);
1872 __setup("fail_make_request=", setup_fail_make_request
);
1874 static bool should_fail_request(struct hd_struct
*part
, unsigned int bytes
)
1876 return part
->make_it_fail
&& should_fail(&fail_make_request
, bytes
);
1879 static int __init
fail_make_request_debugfs(void)
1881 struct dentry
*dir
= fault_create_debugfs_attr("fail_make_request",
1882 NULL
, &fail_make_request
);
1884 return PTR_ERR_OR_ZERO(dir
);
1887 late_initcall(fail_make_request_debugfs
);
1889 #else /* CONFIG_FAIL_MAKE_REQUEST */
1891 static inline bool should_fail_request(struct hd_struct
*part
,
1897 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1900 * Check whether this bio extends beyond the end of the device.
1902 static inline int bio_check_eod(struct bio
*bio
, unsigned int nr_sectors
)
1909 /* Test device or partition size, when known. */
1910 maxsector
= i_size_read(bio
->bi_bdev
->bd_inode
) >> 9;
1912 sector_t sector
= bio
->bi_iter
.bi_sector
;
1914 if (maxsector
< nr_sectors
|| maxsector
- nr_sectors
< sector
) {
1916 * This may well happen - the kernel calls bread()
1917 * without checking the size of the device, e.g., when
1918 * mounting a device.
1920 handle_bad_sector(bio
);
1928 static noinline_for_stack
bool
1929 generic_make_request_checks(struct bio
*bio
)
1931 struct request_queue
*q
;
1932 int nr_sectors
= bio_sectors(bio
);
1934 char b
[BDEVNAME_SIZE
];
1935 struct hd_struct
*part
;
1939 if (bio_check_eod(bio
, nr_sectors
))
1942 q
= bdev_get_queue(bio
->bi_bdev
);
1945 "generic_make_request: Trying to access "
1946 "nonexistent block-device %s (%Lu)\n",
1947 bdevname(bio
->bi_bdev
, b
),
1948 (long long) bio
->bi_iter
.bi_sector
);
1952 part
= bio
->bi_bdev
->bd_part
;
1953 if (should_fail_request(part
, bio
->bi_iter
.bi_size
) ||
1954 should_fail_request(&part_to_disk(part
)->part0
,
1955 bio
->bi_iter
.bi_size
))
1959 * If this device has partitions, remap block n
1960 * of partition p to block n+start(p) of the disk.
1962 blk_partition_remap(bio
);
1964 if (bio_check_eod(bio
, nr_sectors
))
1968 * Filter flush bio's early so that make_request based
1969 * drivers without flush support don't have to worry
1972 if (op_is_flush(bio
->bi_opf
) &&
1973 !test_bit(QUEUE_FLAG_WC
, &q
->queue_flags
)) {
1974 bio
->bi_opf
&= ~(REQ_PREFLUSH
| REQ_FUA
);
1981 switch (bio_op(bio
)) {
1982 case REQ_OP_DISCARD
:
1983 if (!blk_queue_discard(q
))
1986 case REQ_OP_SECURE_ERASE
:
1987 if (!blk_queue_secure_erase(q
))
1990 case REQ_OP_WRITE_SAME
:
1991 if (!bdev_write_same(bio
->bi_bdev
))
1994 case REQ_OP_ZONE_REPORT
:
1995 case REQ_OP_ZONE_RESET
:
1996 if (!bdev_is_zoned(bio
->bi_bdev
))
1999 case REQ_OP_WRITE_ZEROES
:
2000 if (!bdev_write_zeroes_sectors(bio
->bi_bdev
))
2008 * Various block parts want %current->io_context and lazy ioc
2009 * allocation ends up trading a lot of pain for a small amount of
2010 * memory. Just allocate it upfront. This may fail and block
2011 * layer knows how to live with it.
2013 create_io_context(GFP_ATOMIC
, q
->node
);
2015 if (!blkcg_bio_issue_check(q
, bio
))
2018 if (!bio_flagged(bio
, BIO_TRACE_COMPLETION
)) {
2019 trace_block_bio_queue(q
, bio
);
2020 /* Now that enqueuing has been traced, we need to trace
2021 * completion as well.
2023 bio_set_flag(bio
, BIO_TRACE_COMPLETION
);
2030 bio
->bi_error
= err
;
2036 * generic_make_request - hand a buffer to its device driver for I/O
2037 * @bio: The bio describing the location in memory and on the device.
2039 * generic_make_request() is used to make I/O requests of block
2040 * devices. It is passed a &struct bio, which describes the I/O that needs
2043 * generic_make_request() does not return any status. The
2044 * success/failure status of the request, along with notification of
2045 * completion, is delivered asynchronously through the bio->bi_end_io
2046 * function described (one day) else where.
2048 * The caller of generic_make_request must make sure that bi_io_vec
2049 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2050 * set to describe the device address, and the
2051 * bi_end_io and optionally bi_private are set to describe how
2052 * completion notification should be signaled.
2054 * generic_make_request and the drivers it calls may use bi_next if this
2055 * bio happens to be merged with someone else, and may resubmit the bio to
2056 * a lower device by calling into generic_make_request recursively, which
2057 * means the bio should NOT be touched after the call to ->make_request_fn.
2059 blk_qc_t
generic_make_request(struct bio
*bio
)
2062 * bio_list_on_stack[0] contains bios submitted by the current
2064 * bio_list_on_stack[1] contains bios that were submitted before
2065 * the current make_request_fn, but that haven't been processed
2068 struct bio_list bio_list_on_stack
[2];
2069 blk_qc_t ret
= BLK_QC_T_NONE
;
2071 if (!generic_make_request_checks(bio
))
2075 * We only want one ->make_request_fn to be active at a time, else
2076 * stack usage with stacked devices could be a problem. So use
2077 * current->bio_list to keep a list of requests submited by a
2078 * make_request_fn function. current->bio_list is also used as a
2079 * flag to say if generic_make_request is currently active in this
2080 * task or not. If it is NULL, then no make_request is active. If
2081 * it is non-NULL, then a make_request is active, and new requests
2082 * should be added at the tail
2084 if (current
->bio_list
) {
2085 bio_list_add(¤t
->bio_list
[0], bio
);
2089 /* following loop may be a bit non-obvious, and so deserves some
2091 * Before entering the loop, bio->bi_next is NULL (as all callers
2092 * ensure that) so we have a list with a single bio.
2093 * We pretend that we have just taken it off a longer list, so
2094 * we assign bio_list to a pointer to the bio_list_on_stack,
2095 * thus initialising the bio_list of new bios to be
2096 * added. ->make_request() may indeed add some more bios
2097 * through a recursive call to generic_make_request. If it
2098 * did, we find a non-NULL value in bio_list and re-enter the loop
2099 * from the top. In this case we really did just take the bio
2100 * of the top of the list (no pretending) and so remove it from
2101 * bio_list, and call into ->make_request() again.
2103 BUG_ON(bio
->bi_next
);
2104 bio_list_init(&bio_list_on_stack
[0]);
2105 current
->bio_list
= bio_list_on_stack
;
2107 struct request_queue
*q
= bdev_get_queue(bio
->bi_bdev
);
2109 if (likely(blk_queue_enter(q
, false) == 0)) {
2110 struct bio_list lower
, same
;
2112 /* Create a fresh bio_list for all subordinate requests */
2113 bio_list_on_stack
[1] = bio_list_on_stack
[0];
2114 bio_list_init(&bio_list_on_stack
[0]);
2115 ret
= q
->make_request_fn(q
, bio
);
2119 /* sort new bios into those for a lower level
2120 * and those for the same level
2122 bio_list_init(&lower
);
2123 bio_list_init(&same
);
2124 while ((bio
= bio_list_pop(&bio_list_on_stack
[0])) != NULL
)
2125 if (q
== bdev_get_queue(bio
->bi_bdev
))
2126 bio_list_add(&same
, bio
);
2128 bio_list_add(&lower
, bio
);
2129 /* now assemble so we handle the lowest level first */
2130 bio_list_merge(&bio_list_on_stack
[0], &lower
);
2131 bio_list_merge(&bio_list_on_stack
[0], &same
);
2132 bio_list_merge(&bio_list_on_stack
[0], &bio_list_on_stack
[1]);
2136 bio
= bio_list_pop(&bio_list_on_stack
[0]);
2138 current
->bio_list
= NULL
; /* deactivate */
2143 EXPORT_SYMBOL(generic_make_request
);
2146 * submit_bio - submit a bio to the block device layer for I/O
2147 * @bio: The &struct bio which describes the I/O
2149 * submit_bio() is very similar in purpose to generic_make_request(), and
2150 * uses that function to do most of the work. Both are fairly rough
2151 * interfaces; @bio must be presetup and ready for I/O.
2154 blk_qc_t
submit_bio(struct bio
*bio
)
2157 * If it's a regular read/write or a barrier with data attached,
2158 * go through the normal accounting stuff before submission.
2160 if (bio_has_data(bio
)) {
2163 if (unlikely(bio_op(bio
) == REQ_OP_WRITE_SAME
))
2164 count
= bdev_logical_block_size(bio
->bi_bdev
) >> 9;
2166 count
= bio_sectors(bio
);
2168 if (op_is_write(bio_op(bio
))) {
2169 count_vm_events(PGPGOUT
, count
);
2171 task_io_account_read(bio
->bi_iter
.bi_size
);
2172 count_vm_events(PGPGIN
, count
);
2175 if (unlikely(block_dump
)) {
2176 char b
[BDEVNAME_SIZE
];
2177 printk(KERN_DEBUG
"%s(%d): %s block %Lu on %s (%u sectors)\n",
2178 current
->comm
, task_pid_nr(current
),
2179 op_is_write(bio_op(bio
)) ? "WRITE" : "READ",
2180 (unsigned long long)bio
->bi_iter
.bi_sector
,
2181 bdevname(bio
->bi_bdev
, b
),
2186 return generic_make_request(bio
);
2188 EXPORT_SYMBOL(submit_bio
);
2191 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2192 * for new the queue limits
2194 * @rq: the request being checked
2197 * @rq may have been made based on weaker limitations of upper-level queues
2198 * in request stacking drivers, and it may violate the limitation of @q.
2199 * Since the block layer and the underlying device driver trust @rq
2200 * after it is inserted to @q, it should be checked against @q before
2201 * the insertion using this generic function.
2203 * Request stacking drivers like request-based dm may change the queue
2204 * limits when retrying requests on other queues. Those requests need
2205 * to be checked against the new queue limits again during dispatch.
2207 static int blk_cloned_rq_check_limits(struct request_queue
*q
,
2210 if (blk_rq_sectors(rq
) > blk_queue_get_max_sectors(q
, req_op(rq
))) {
2211 printk(KERN_ERR
"%s: over max size limit.\n", __func__
);
2216 * queue's settings related to segment counting like q->bounce_pfn
2217 * may differ from that of other stacking queues.
2218 * Recalculate it to check the request correctly on this queue's
2221 blk_recalc_rq_segments(rq
);
2222 if (rq
->nr_phys_segments
> queue_max_segments(q
)) {
2223 printk(KERN_ERR
"%s: over max segments limit.\n", __func__
);
2231 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2232 * @q: the queue to submit the request
2233 * @rq: the request being queued
2235 blk_status_t
blk_insert_cloned_request(struct request_queue
*q
, struct request
*rq
)
2237 unsigned long flags
;
2238 int where
= ELEVATOR_INSERT_BACK
;
2240 if (blk_cloned_rq_check_limits(q
, rq
))
2241 return BLK_STS_IOERR
;
2244 should_fail_request(&rq
->rq_disk
->part0
, blk_rq_bytes(rq
)))
2245 return BLK_STS_IOERR
;
2248 if (blk_queue_io_stat(q
))
2249 blk_account_io_start(rq
, true);
2250 blk_mq_sched_insert_request(rq
, false, true, false, false);
2254 spin_lock_irqsave(q
->queue_lock
, flags
);
2255 if (unlikely(blk_queue_dying(q
))) {
2256 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2257 return BLK_STS_IOERR
;
2261 * Submitting request must be dequeued before calling this function
2262 * because it will be linked to another request_queue
2264 BUG_ON(blk_queued_rq(rq
));
2266 if (op_is_flush(rq
->cmd_flags
))
2267 where
= ELEVATOR_INSERT_FLUSH
;
2269 add_acct_request(q
, rq
, where
);
2270 if (where
== ELEVATOR_INSERT_FLUSH
)
2272 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2276 EXPORT_SYMBOL_GPL(blk_insert_cloned_request
);
2279 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2280 * @rq: request to examine
2283 * A request could be merge of IOs which require different failure
2284 * handling. This function determines the number of bytes which
2285 * can be failed from the beginning of the request without
2286 * crossing into area which need to be retried further.
2289 * The number of bytes to fail.
2292 * queue_lock must be held.
2294 unsigned int blk_rq_err_bytes(const struct request
*rq
)
2296 unsigned int ff
= rq
->cmd_flags
& REQ_FAILFAST_MASK
;
2297 unsigned int bytes
= 0;
2300 if (!(rq
->rq_flags
& RQF_MIXED_MERGE
))
2301 return blk_rq_bytes(rq
);
2304 * Currently the only 'mixing' which can happen is between
2305 * different fastfail types. We can safely fail portions
2306 * which have all the failfast bits that the first one has -
2307 * the ones which are at least as eager to fail as the first
2310 for (bio
= rq
->bio
; bio
; bio
= bio
->bi_next
) {
2311 if ((bio
->bi_opf
& ff
) != ff
)
2313 bytes
+= bio
->bi_iter
.bi_size
;
2316 /* this could lead to infinite loop */
2317 BUG_ON(blk_rq_bytes(rq
) && !bytes
);
2320 EXPORT_SYMBOL_GPL(blk_rq_err_bytes
);
2322 void blk_account_io_completion(struct request
*req
, unsigned int bytes
)
2324 if (blk_do_io_stat(req
)) {
2325 const int rw
= rq_data_dir(req
);
2326 struct hd_struct
*part
;
2329 cpu
= part_stat_lock();
2331 part_stat_add(cpu
, part
, sectors
[rw
], bytes
>> 9);
2336 void blk_account_io_done(struct request
*req
)
2339 * Account IO completion. flush_rq isn't accounted as a
2340 * normal IO on queueing nor completion. Accounting the
2341 * containing request is enough.
2343 if (blk_do_io_stat(req
) && !(req
->rq_flags
& RQF_FLUSH_SEQ
)) {
2344 unsigned long duration
= jiffies
- req
->start_time
;
2345 const int rw
= rq_data_dir(req
);
2346 struct hd_struct
*part
;
2349 cpu
= part_stat_lock();
2352 part_stat_inc(cpu
, part
, ios
[rw
]);
2353 part_stat_add(cpu
, part
, ticks
[rw
], duration
);
2354 part_round_stats(cpu
, part
);
2355 part_dec_in_flight(part
, rw
);
2357 hd_struct_put(part
);
2364 * Don't process normal requests when queue is suspended
2365 * or in the process of suspending/resuming
2367 static struct request
*blk_pm_peek_request(struct request_queue
*q
,
2370 if (q
->dev
&& (q
->rpm_status
== RPM_SUSPENDED
||
2371 (q
->rpm_status
!= RPM_ACTIVE
&& !(rq
->rq_flags
& RQF_PM
))))
2377 static inline struct request
*blk_pm_peek_request(struct request_queue
*q
,
2384 void blk_account_io_start(struct request
*rq
, bool new_io
)
2386 struct hd_struct
*part
;
2387 int rw
= rq_data_dir(rq
);
2390 if (!blk_do_io_stat(rq
))
2393 cpu
= part_stat_lock();
2397 part_stat_inc(cpu
, part
, merges
[rw
]);
2399 part
= disk_map_sector_rcu(rq
->rq_disk
, blk_rq_pos(rq
));
2400 if (!hd_struct_try_get(part
)) {
2402 * The partition is already being removed,
2403 * the request will be accounted on the disk only
2405 * We take a reference on disk->part0 although that
2406 * partition will never be deleted, so we can treat
2407 * it as any other partition.
2409 part
= &rq
->rq_disk
->part0
;
2410 hd_struct_get(part
);
2412 part_round_stats(cpu
, part
);
2413 part_inc_in_flight(part
, rw
);
2421 * blk_peek_request - peek at the top of a request queue
2422 * @q: request queue to peek at
2425 * Return the request at the top of @q. The returned request
2426 * should be started using blk_start_request() before LLD starts
2430 * Pointer to the request at the top of @q if available. Null
2434 * queue_lock must be held.
2436 struct request
*blk_peek_request(struct request_queue
*q
)
2441 while ((rq
= __elv_next_request(q
)) != NULL
) {
2443 rq
= blk_pm_peek_request(q
, rq
);
2447 if (!(rq
->rq_flags
& RQF_STARTED
)) {
2449 * This is the first time the device driver
2450 * sees this request (possibly after
2451 * requeueing). Notify IO scheduler.
2453 if (rq
->rq_flags
& RQF_SORTED
)
2454 elv_activate_rq(q
, rq
);
2457 * just mark as started even if we don't start
2458 * it, a request that has been delayed should
2459 * not be passed by new incoming requests
2461 rq
->rq_flags
|= RQF_STARTED
;
2462 trace_block_rq_issue(q
, rq
);
2465 if (!q
->boundary_rq
|| q
->boundary_rq
== rq
) {
2466 q
->end_sector
= rq_end_sector(rq
);
2467 q
->boundary_rq
= NULL
;
2470 if (rq
->rq_flags
& RQF_DONTPREP
)
2473 if (q
->dma_drain_size
&& blk_rq_bytes(rq
)) {
2475 * make sure space for the drain appears we
2476 * know we can do this because max_hw_segments
2477 * has been adjusted to be one fewer than the
2480 rq
->nr_phys_segments
++;
2486 ret
= q
->prep_rq_fn(q
, rq
);
2487 if (ret
== BLKPREP_OK
) {
2489 } else if (ret
== BLKPREP_DEFER
) {
2491 * the request may have been (partially) prepped.
2492 * we need to keep this request in the front to
2493 * avoid resource deadlock. RQF_STARTED will
2494 * prevent other fs requests from passing this one.
2496 if (q
->dma_drain_size
&& blk_rq_bytes(rq
) &&
2497 !(rq
->rq_flags
& RQF_DONTPREP
)) {
2499 * remove the space for the drain we added
2500 * so that we don't add it again
2502 --rq
->nr_phys_segments
;
2507 } else if (ret
== BLKPREP_KILL
|| ret
== BLKPREP_INVALID
) {
2508 rq
->rq_flags
|= RQF_QUIET
;
2510 * Mark this request as started so we don't trigger
2511 * any debug logic in the end I/O path.
2513 blk_start_request(rq
);
2514 __blk_end_request_all(rq
, ret
== BLKPREP_INVALID
?
2515 BLK_STS_TARGET
: BLK_STS_IOERR
);
2517 printk(KERN_ERR
"%s: bad return=%d\n", __func__
, ret
);
2524 EXPORT_SYMBOL(blk_peek_request
);
2526 void blk_dequeue_request(struct request
*rq
)
2528 struct request_queue
*q
= rq
->q
;
2530 BUG_ON(list_empty(&rq
->queuelist
));
2531 BUG_ON(ELV_ON_HASH(rq
));
2533 list_del_init(&rq
->queuelist
);
2536 * the time frame between a request being removed from the lists
2537 * and to it is freed is accounted as io that is in progress at
2540 if (blk_account_rq(rq
)) {
2541 q
->in_flight
[rq_is_sync(rq
)]++;
2542 set_io_start_time_ns(rq
);
2547 * blk_start_request - start request processing on the driver
2548 * @req: request to dequeue
2551 * Dequeue @req and start timeout timer on it. This hands off the
2552 * request to the driver.
2554 * Block internal functions which don't want to start timer should
2555 * call blk_dequeue_request().
2558 * queue_lock must be held.
2560 void blk_start_request(struct request
*req
)
2562 blk_dequeue_request(req
);
2564 if (test_bit(QUEUE_FLAG_STATS
, &req
->q
->queue_flags
)) {
2565 blk_stat_set_issue(&req
->issue_stat
, blk_rq_sectors(req
));
2566 req
->rq_flags
|= RQF_STATS
;
2567 wbt_issue(req
->q
->rq_wb
, &req
->issue_stat
);
2570 BUG_ON(test_bit(REQ_ATOM_COMPLETE
, &req
->atomic_flags
));
2573 EXPORT_SYMBOL(blk_start_request
);
2576 * blk_fetch_request - fetch a request from a request queue
2577 * @q: request queue to fetch a request from
2580 * Return the request at the top of @q. The request is started on
2581 * return and LLD can start processing it immediately.
2584 * Pointer to the request at the top of @q if available. Null
2588 * queue_lock must be held.
2590 struct request
*blk_fetch_request(struct request_queue
*q
)
2594 rq
= blk_peek_request(q
);
2596 blk_start_request(rq
);
2599 EXPORT_SYMBOL(blk_fetch_request
);
2602 * blk_update_request - Special helper function for request stacking drivers
2603 * @req: the request being processed
2604 * @error: block status code
2605 * @nr_bytes: number of bytes to complete @req
2608 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2609 * the request structure even if @req doesn't have leftover.
2610 * If @req has leftover, sets it up for the next range of segments.
2612 * This special helper function is only for request stacking drivers
2613 * (e.g. request-based dm) so that they can handle partial completion.
2614 * Actual device drivers should use blk_end_request instead.
2616 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2617 * %false return from this function.
2620 * %false - this request doesn't have any more data
2621 * %true - this request has more data
2623 bool blk_update_request(struct request
*req
, blk_status_t error
,
2624 unsigned int nr_bytes
)
2628 trace_block_rq_complete(req
, blk_status_to_errno(error
), nr_bytes
);
2633 if (unlikely(error
&& !blk_rq_is_passthrough(req
) &&
2634 !(req
->rq_flags
& RQF_QUIET
)))
2635 print_req_error(req
, error
);
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 /* Completion has already been traced */
2648 bio_clear_flag(bio
, BIO_TRACE_COMPLETION
);
2649 req_bio_endio(req
, bio
, bio_bytes
, error
);
2651 total_bytes
+= bio_bytes
;
2652 nr_bytes
-= bio_bytes
;
2663 * Reset counters so that the request stacking driver
2664 * can find how many bytes remain in the request
2667 req
->__data_len
= 0;
2671 req
->__data_len
-= total_bytes
;
2673 /* update sector only for requests with clear definition of sector */
2674 if (!blk_rq_is_passthrough(req
))
2675 req
->__sector
+= total_bytes
>> 9;
2677 /* mixed attributes always follow the first bio */
2678 if (req
->rq_flags
& RQF_MIXED_MERGE
) {
2679 req
->cmd_flags
&= ~REQ_FAILFAST_MASK
;
2680 req
->cmd_flags
|= req
->bio
->bi_opf
& REQ_FAILFAST_MASK
;
2683 if (!(req
->rq_flags
& RQF_SPECIAL_PAYLOAD
)) {
2685 * If total number of sectors is less than the first segment
2686 * size, something has gone terribly wrong.
2688 if (blk_rq_bytes(req
) < blk_rq_cur_bytes(req
)) {
2689 blk_dump_rq_flags(req
, "request botched");
2690 req
->__data_len
= blk_rq_cur_bytes(req
);
2693 /* recalculate the number of segments */
2694 blk_recalc_rq_segments(req
);
2699 EXPORT_SYMBOL_GPL(blk_update_request
);
2701 static bool blk_update_bidi_request(struct request
*rq
, blk_status_t error
,
2702 unsigned int nr_bytes
,
2703 unsigned int bidi_bytes
)
2705 if (blk_update_request(rq
, error
, nr_bytes
))
2708 /* Bidi request must be completed as a whole */
2709 if (unlikely(blk_bidi_rq(rq
)) &&
2710 blk_update_request(rq
->next_rq
, error
, bidi_bytes
))
2713 if (blk_queue_add_random(rq
->q
))
2714 add_disk_randomness(rq
->rq_disk
);
2720 * blk_unprep_request - unprepare a request
2723 * This function makes a request ready for complete resubmission (or
2724 * completion). It happens only after all error handling is complete,
2725 * so represents the appropriate moment to deallocate any resources
2726 * that were allocated to the request in the prep_rq_fn. The queue
2727 * lock is held when calling this.
2729 void blk_unprep_request(struct request
*req
)
2731 struct request_queue
*q
= req
->q
;
2733 req
->rq_flags
&= ~RQF_DONTPREP
;
2734 if (q
->unprep_rq_fn
)
2735 q
->unprep_rq_fn(q
, req
);
2737 EXPORT_SYMBOL_GPL(blk_unprep_request
);
2740 * queue lock must be held
2742 void blk_finish_request(struct request
*req
, blk_status_t error
)
2744 struct request_queue
*q
= req
->q
;
2746 if (req
->rq_flags
& RQF_STATS
)
2749 if (req
->rq_flags
& RQF_QUEUED
)
2750 blk_queue_end_tag(q
, req
);
2752 BUG_ON(blk_queued_rq(req
));
2754 if (unlikely(laptop_mode
) && !blk_rq_is_passthrough(req
))
2755 laptop_io_completion(req
->q
->backing_dev_info
);
2757 blk_delete_timer(req
);
2759 if (req
->rq_flags
& RQF_DONTPREP
)
2760 blk_unprep_request(req
);
2762 blk_account_io_done(req
);
2765 wbt_done(req
->q
->rq_wb
, &req
->issue_stat
);
2766 req
->end_io(req
, error
);
2768 if (blk_bidi_rq(req
))
2769 __blk_put_request(req
->next_rq
->q
, req
->next_rq
);
2771 __blk_put_request(q
, req
);
2774 EXPORT_SYMBOL(blk_finish_request
);
2777 * blk_end_bidi_request - Complete a bidi request
2778 * @rq: the request to complete
2779 * @error: block status code
2780 * @nr_bytes: number of bytes to complete @rq
2781 * @bidi_bytes: number of bytes to complete @rq->next_rq
2784 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2785 * Drivers that supports bidi can safely call this member for any
2786 * type of request, bidi or uni. In the later case @bidi_bytes is
2790 * %false - we are done with this request
2791 * %true - still buffers pending for this request
2793 static bool blk_end_bidi_request(struct request
*rq
, blk_status_t error
,
2794 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2796 struct request_queue
*q
= rq
->q
;
2797 unsigned long flags
;
2799 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2802 spin_lock_irqsave(q
->queue_lock
, flags
);
2803 blk_finish_request(rq
, error
);
2804 spin_unlock_irqrestore(q
->queue_lock
, flags
);
2810 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2811 * @rq: the request to complete
2812 * @error: block status code
2813 * @nr_bytes: number of bytes to complete @rq
2814 * @bidi_bytes: number of bytes to complete @rq->next_rq
2817 * Identical to blk_end_bidi_request() except that queue lock is
2818 * assumed to be locked on entry and remains so on return.
2821 * %false - we are done with this request
2822 * %true - still buffers pending for this request
2824 static bool __blk_end_bidi_request(struct request
*rq
, blk_status_t error
,
2825 unsigned int nr_bytes
, unsigned int bidi_bytes
)
2827 if (blk_update_bidi_request(rq
, error
, nr_bytes
, bidi_bytes
))
2830 blk_finish_request(rq
, error
);
2836 * blk_end_request - Helper function for drivers to complete the request.
2837 * @rq: the request being processed
2838 * @error: block status code
2839 * @nr_bytes: number of bytes to complete
2842 * Ends I/O on a number of bytes attached to @rq.
2843 * If @rq has leftover, sets it up for the next range of segments.
2846 * %false - we are done with this request
2847 * %true - still buffers pending for this request
2849 bool blk_end_request(struct request
*rq
, blk_status_t error
,
2850 unsigned int nr_bytes
)
2852 return blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2854 EXPORT_SYMBOL(blk_end_request
);
2857 * blk_end_request_all - Helper function for drives to finish the request.
2858 * @rq: the request to finish
2859 * @error: block status code
2862 * Completely finish @rq.
2864 void blk_end_request_all(struct request
*rq
, blk_status_t error
)
2867 unsigned int bidi_bytes
= 0;
2869 if (unlikely(blk_bidi_rq(rq
)))
2870 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2872 pending
= blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2875 EXPORT_SYMBOL(blk_end_request_all
);
2878 * __blk_end_request - Helper function for drivers to complete the request.
2879 * @rq: the request being processed
2880 * @error: block status code
2881 * @nr_bytes: number of bytes to complete
2884 * Must be called with queue lock held unlike blk_end_request().
2887 * %false - we are done with this request
2888 * %true - still buffers pending for this request
2890 bool __blk_end_request(struct request
*rq
, blk_status_t error
,
2891 unsigned int nr_bytes
)
2893 return __blk_end_bidi_request(rq
, error
, nr_bytes
, 0);
2895 EXPORT_SYMBOL(__blk_end_request
);
2898 * __blk_end_request_all - Helper function for drives to finish the request.
2899 * @rq: the request to finish
2900 * @error: block status code
2903 * Completely finish @rq. Must be called with queue lock held.
2905 void __blk_end_request_all(struct request
*rq
, blk_status_t error
)
2908 unsigned int bidi_bytes
= 0;
2910 if (unlikely(blk_bidi_rq(rq
)))
2911 bidi_bytes
= blk_rq_bytes(rq
->next_rq
);
2913 pending
= __blk_end_bidi_request(rq
, error
, blk_rq_bytes(rq
), bidi_bytes
);
2916 EXPORT_SYMBOL(__blk_end_request_all
);
2919 * __blk_end_request_cur - Helper function to finish the current request chunk.
2920 * @rq: the request to finish the current chunk for
2921 * @error: block status code
2924 * Complete the current consecutively mapped chunk from @rq. Must
2925 * be called with queue lock held.
2928 * %false - we are done with this request
2929 * %true - still buffers pending for this request
2931 bool __blk_end_request_cur(struct request
*rq
, blk_status_t error
)
2933 return __blk_end_request(rq
, error
, blk_rq_cur_bytes(rq
));
2935 EXPORT_SYMBOL(__blk_end_request_cur
);
2937 void blk_rq_bio_prep(struct request_queue
*q
, struct request
*rq
,
2940 if (bio_has_data(bio
))
2941 rq
->nr_phys_segments
= bio_phys_segments(q
, bio
);
2943 rq
->__data_len
= bio
->bi_iter
.bi_size
;
2944 rq
->bio
= rq
->biotail
= bio
;
2947 rq
->rq_disk
= bio
->bi_bdev
->bd_disk
;
2950 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2952 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2953 * @rq: the request to be flushed
2956 * Flush all pages in @rq.
2958 void rq_flush_dcache_pages(struct request
*rq
)
2960 struct req_iterator iter
;
2961 struct bio_vec bvec
;
2963 rq_for_each_segment(bvec
, rq
, iter
)
2964 flush_dcache_page(bvec
.bv_page
);
2966 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages
);
2970 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2971 * @q : the queue of the device being checked
2974 * Check if underlying low-level drivers of a device are busy.
2975 * If the drivers want to export their busy state, they must set own
2976 * exporting function using blk_queue_lld_busy() first.
2978 * Basically, this function is used only by request stacking drivers
2979 * to stop dispatching requests to underlying devices when underlying
2980 * devices are busy. This behavior helps more I/O merging on the queue
2981 * of the request stacking driver and prevents I/O throughput regression
2982 * on burst I/O load.
2985 * 0 - Not busy (The request stacking driver should dispatch request)
2986 * 1 - Busy (The request stacking driver should stop dispatching request)
2988 int blk_lld_busy(struct request_queue
*q
)
2991 return q
->lld_busy_fn(q
);
2995 EXPORT_SYMBOL_GPL(blk_lld_busy
);
2998 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2999 * @rq: the clone request to be cleaned up
3002 * Free all bios in @rq for a cloned request.
3004 void blk_rq_unprep_clone(struct request
*rq
)
3008 while ((bio
= rq
->bio
) != NULL
) {
3009 rq
->bio
= bio
->bi_next
;
3014 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone
);
3017 * Copy attributes of the original request to the clone request.
3018 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3020 static void __blk_rq_prep_clone(struct request
*dst
, struct request
*src
)
3022 dst
->cpu
= src
->cpu
;
3023 dst
->__sector
= blk_rq_pos(src
);
3024 dst
->__data_len
= blk_rq_bytes(src
);
3025 dst
->nr_phys_segments
= src
->nr_phys_segments
;
3026 dst
->ioprio
= src
->ioprio
;
3027 dst
->extra_len
= src
->extra_len
;
3031 * blk_rq_prep_clone - Helper function to setup clone request
3032 * @rq: the request to be setup
3033 * @rq_src: original request to be cloned
3034 * @bs: bio_set that bios for clone are allocated from
3035 * @gfp_mask: memory allocation mask for bio
3036 * @bio_ctr: setup function to be called for each clone bio.
3037 * Returns %0 for success, non %0 for failure.
3038 * @data: private data to be passed to @bio_ctr
3041 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3042 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3043 * are not copied, and copying such parts is the caller's responsibility.
3044 * Also, pages which the original bios are pointing to are not copied
3045 * and the cloned bios just point same pages.
3046 * So cloned bios must be completed before original bios, which means
3047 * the caller must complete @rq before @rq_src.
3049 int blk_rq_prep_clone(struct request
*rq
, struct request
*rq_src
,
3050 struct bio_set
*bs
, gfp_t gfp_mask
,
3051 int (*bio_ctr
)(struct bio
*, struct bio
*, void *),
3054 struct bio
*bio
, *bio_src
;
3059 __rq_for_each_bio(bio_src
, rq_src
) {
3060 bio
= bio_clone_fast(bio_src
, gfp_mask
, bs
);
3064 if (bio_ctr
&& bio_ctr(bio
, bio_src
, data
))
3068 rq
->biotail
->bi_next
= bio
;
3071 rq
->bio
= rq
->biotail
= bio
;
3074 __blk_rq_prep_clone(rq
, rq_src
);
3081 blk_rq_unprep_clone(rq
);
3085 EXPORT_SYMBOL_GPL(blk_rq_prep_clone
);
3087 int kblockd_schedule_work(struct work_struct
*work
)
3089 return queue_work(kblockd_workqueue
, work
);
3091 EXPORT_SYMBOL(kblockd_schedule_work
);
3093 int kblockd_schedule_work_on(int cpu
, struct work_struct
*work
)
3095 return queue_work_on(cpu
, kblockd_workqueue
, work
);
3097 EXPORT_SYMBOL(kblockd_schedule_work_on
);
3099 int kblockd_mod_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
3100 unsigned long delay
)
3102 return mod_delayed_work_on(cpu
, kblockd_workqueue
, dwork
, delay
);
3104 EXPORT_SYMBOL(kblockd_mod_delayed_work_on
);
3106 int kblockd_schedule_delayed_work(struct delayed_work
*dwork
,
3107 unsigned long delay
)
3109 return queue_delayed_work(kblockd_workqueue
, dwork
, delay
);
3111 EXPORT_SYMBOL(kblockd_schedule_delayed_work
);
3113 int kblockd_schedule_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
3114 unsigned long delay
)
3116 return queue_delayed_work_on(cpu
, kblockd_workqueue
, dwork
, delay
);
3118 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on
);
3121 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3122 * @plug: The &struct blk_plug that needs to be initialized
3125 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3126 * pending I/O should the task end up blocking between blk_start_plug() and
3127 * blk_finish_plug(). This is important from a performance perspective, but
3128 * also ensures that we don't deadlock. For instance, if the task is blocking
3129 * for a memory allocation, memory reclaim could end up wanting to free a
3130 * page belonging to that request that is currently residing in our private
3131 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3132 * this kind of deadlock.
3134 void blk_start_plug(struct blk_plug
*plug
)
3136 struct task_struct
*tsk
= current
;
3139 * If this is a nested plug, don't actually assign it.
3144 INIT_LIST_HEAD(&plug
->list
);
3145 INIT_LIST_HEAD(&plug
->mq_list
);
3146 INIT_LIST_HEAD(&plug
->cb_list
);
3148 * Store ordering should not be needed here, since a potential
3149 * preempt will imply a full memory barrier
3153 EXPORT_SYMBOL(blk_start_plug
);
3155 static int plug_rq_cmp(void *priv
, struct list_head
*a
, struct list_head
*b
)
3157 struct request
*rqa
= container_of(a
, struct request
, queuelist
);
3158 struct request
*rqb
= container_of(b
, struct request
, queuelist
);
3160 return !(rqa
->q
< rqb
->q
||
3161 (rqa
->q
== rqb
->q
&& blk_rq_pos(rqa
) < blk_rq_pos(rqb
)));
3165 * If 'from_schedule' is true, then postpone the dispatch of requests
3166 * until a safe kblockd context. We due this to avoid accidental big
3167 * additional stack usage in driver dispatch, in places where the originally
3168 * plugger did not intend it.
3170 static void queue_unplugged(struct request_queue
*q
, unsigned int depth
,
3172 __releases(q
->queue_lock
)
3174 trace_block_unplug(q
, depth
, !from_schedule
);
3177 blk_run_queue_async(q
);
3180 spin_unlock(q
->queue_lock
);
3183 static void flush_plug_callbacks(struct blk_plug
*plug
, bool from_schedule
)
3185 LIST_HEAD(callbacks
);
3187 while (!list_empty(&plug
->cb_list
)) {
3188 list_splice_init(&plug
->cb_list
, &callbacks
);
3190 while (!list_empty(&callbacks
)) {
3191 struct blk_plug_cb
*cb
= list_first_entry(&callbacks
,
3194 list_del(&cb
->list
);
3195 cb
->callback(cb
, from_schedule
);
3200 struct blk_plug_cb
*blk_check_plugged(blk_plug_cb_fn unplug
, void *data
,
3203 struct blk_plug
*plug
= current
->plug
;
3204 struct blk_plug_cb
*cb
;
3209 list_for_each_entry(cb
, &plug
->cb_list
, list
)
3210 if (cb
->callback
== unplug
&& cb
->data
== data
)
3213 /* Not currently on the callback list */
3214 BUG_ON(size
< sizeof(*cb
));
3215 cb
= kzalloc(size
, GFP_ATOMIC
);
3218 cb
->callback
= unplug
;
3219 list_add(&cb
->list
, &plug
->cb_list
);
3223 EXPORT_SYMBOL(blk_check_plugged
);
3225 void blk_flush_plug_list(struct blk_plug
*plug
, bool from_schedule
)
3227 struct request_queue
*q
;
3228 unsigned long flags
;
3233 flush_plug_callbacks(plug
, from_schedule
);
3235 if (!list_empty(&plug
->mq_list
))
3236 blk_mq_flush_plug_list(plug
, from_schedule
);
3238 if (list_empty(&plug
->list
))
3241 list_splice_init(&plug
->list
, &list
);
3243 list_sort(NULL
, &list
, plug_rq_cmp
);
3249 * Save and disable interrupts here, to avoid doing it for every
3250 * queue lock we have to take.
3252 local_irq_save(flags
);
3253 while (!list_empty(&list
)) {
3254 rq
= list_entry_rq(list
.next
);
3255 list_del_init(&rq
->queuelist
);
3259 * This drops the queue lock
3262 queue_unplugged(q
, depth
, from_schedule
);
3265 spin_lock(q
->queue_lock
);
3269 * Short-circuit if @q is dead
3271 if (unlikely(blk_queue_dying(q
))) {
3272 __blk_end_request_all(rq
, BLK_STS_IOERR
);
3277 * rq is already accounted, so use raw insert
3279 if (op_is_flush(rq
->cmd_flags
))
3280 __elv_add_request(q
, rq
, ELEVATOR_INSERT_FLUSH
);
3282 __elv_add_request(q
, rq
, ELEVATOR_INSERT_SORT_MERGE
);
3288 * This drops the queue lock
3291 queue_unplugged(q
, depth
, from_schedule
);
3293 local_irq_restore(flags
);
3296 void blk_finish_plug(struct blk_plug
*plug
)
3298 if (plug
!= current
->plug
)
3300 blk_flush_plug_list(plug
, false);
3302 current
->plug
= NULL
;
3304 EXPORT_SYMBOL(blk_finish_plug
);
3308 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3309 * @q: the queue of the device
3310 * @dev: the device the queue belongs to
3313 * Initialize runtime-PM-related fields for @q and start auto suspend for
3314 * @dev. Drivers that want to take advantage of request-based runtime PM
3315 * should call this function after @dev has been initialized, and its
3316 * request queue @q has been allocated, and runtime PM for it can not happen
3317 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3318 * cases, driver should call this function before any I/O has taken place.
3320 * This function takes care of setting up using auto suspend for the device,
3321 * the autosuspend delay is set to -1 to make runtime suspend impossible
3322 * until an updated value is either set by user or by driver. Drivers do
3323 * not need to touch other autosuspend settings.
3325 * The block layer runtime PM is request based, so only works for drivers
3326 * that use request as their IO unit instead of those directly use bio's.
3328 void blk_pm_runtime_init(struct request_queue
*q
, struct device
*dev
)
3331 q
->rpm_status
= RPM_ACTIVE
;
3332 pm_runtime_set_autosuspend_delay(q
->dev
, -1);
3333 pm_runtime_use_autosuspend(q
->dev
);
3335 EXPORT_SYMBOL(blk_pm_runtime_init
);
3338 * blk_pre_runtime_suspend - Pre runtime suspend check
3339 * @q: the queue of the device
3342 * This function will check if runtime suspend is allowed for the device
3343 * by examining if there are any requests pending in the queue. If there
3344 * are requests pending, the device can not be runtime suspended; otherwise,
3345 * the queue's status will be updated to SUSPENDING and the driver can
3346 * proceed to suspend the device.
3348 * For the not allowed case, we mark last busy for the device so that
3349 * runtime PM core will try to autosuspend it some time later.
3351 * This function should be called near the start of the device's
3352 * runtime_suspend callback.
3355 * 0 - OK to runtime suspend the device
3356 * -EBUSY - Device should not be runtime suspended
3358 int blk_pre_runtime_suspend(struct request_queue
*q
)
3365 spin_lock_irq(q
->queue_lock
);
3366 if (q
->nr_pending
) {
3368 pm_runtime_mark_last_busy(q
->dev
);
3370 q
->rpm_status
= RPM_SUSPENDING
;
3372 spin_unlock_irq(q
->queue_lock
);
3375 EXPORT_SYMBOL(blk_pre_runtime_suspend
);
3378 * blk_post_runtime_suspend - Post runtime suspend processing
3379 * @q: the queue of the device
3380 * @err: return value of the device's runtime_suspend function
3383 * Update the queue's runtime status according to the return value of the
3384 * device's runtime suspend function and mark last busy for the device so
3385 * that PM core will try to auto suspend the device at a later time.
3387 * This function should be called near the end of the device's
3388 * runtime_suspend callback.
3390 void blk_post_runtime_suspend(struct request_queue
*q
, int err
)
3395 spin_lock_irq(q
->queue_lock
);
3397 q
->rpm_status
= RPM_SUSPENDED
;
3399 q
->rpm_status
= RPM_ACTIVE
;
3400 pm_runtime_mark_last_busy(q
->dev
);
3402 spin_unlock_irq(q
->queue_lock
);
3404 EXPORT_SYMBOL(blk_post_runtime_suspend
);
3407 * blk_pre_runtime_resume - Pre runtime resume processing
3408 * @q: the queue of the device
3411 * Update the queue's runtime status to RESUMING in preparation for the
3412 * runtime resume of the device.
3414 * This function should be called near the start of the device's
3415 * runtime_resume callback.
3417 void blk_pre_runtime_resume(struct request_queue
*q
)
3422 spin_lock_irq(q
->queue_lock
);
3423 q
->rpm_status
= RPM_RESUMING
;
3424 spin_unlock_irq(q
->queue_lock
);
3426 EXPORT_SYMBOL(blk_pre_runtime_resume
);
3429 * blk_post_runtime_resume - Post runtime resume processing
3430 * @q: the queue of the device
3431 * @err: return value of the device's runtime_resume function
3434 * Update the queue's runtime status according to the return value of the
3435 * device's runtime_resume function. If it is successfully resumed, process
3436 * the requests that are queued into the device's queue when it is resuming
3437 * and then mark last busy and initiate autosuspend for it.
3439 * This function should be called near the end of the device's
3440 * runtime_resume callback.
3442 void blk_post_runtime_resume(struct request_queue
*q
, int err
)
3447 spin_lock_irq(q
->queue_lock
);
3449 q
->rpm_status
= RPM_ACTIVE
;
3451 pm_runtime_mark_last_busy(q
->dev
);
3452 pm_request_autosuspend(q
->dev
);
3454 q
->rpm_status
= RPM_SUSPENDED
;
3456 spin_unlock_irq(q
->queue_lock
);
3458 EXPORT_SYMBOL(blk_post_runtime_resume
);
3461 * blk_set_runtime_active - Force runtime status of the queue to be active
3462 * @q: the queue of the device
3464 * If the device is left runtime suspended during system suspend the resume
3465 * hook typically resumes the device and corrects runtime status
3466 * accordingly. However, that does not affect the queue runtime PM status
3467 * which is still "suspended". This prevents processing requests from the
3470 * This function can be used in driver's resume hook to correct queue
3471 * runtime PM status and re-enable peeking requests from the queue. It
3472 * should be called before first request is added to the queue.
3474 void blk_set_runtime_active(struct request_queue
*q
)
3476 spin_lock_irq(q
->queue_lock
);
3477 q
->rpm_status
= RPM_ACTIVE
;
3478 pm_runtime_mark_last_busy(q
->dev
);
3479 pm_request_autosuspend(q
->dev
);
3480 spin_unlock_irq(q
->queue_lock
);
3482 EXPORT_SYMBOL(blk_set_runtime_active
);
3485 int __init
blk_dev_init(void)
3487 BUILD_BUG_ON(REQ_OP_LAST
>= (1 << REQ_OP_BITS
));
3488 BUILD_BUG_ON(REQ_OP_BITS
+ REQ_FLAG_BITS
> 8 *
3489 FIELD_SIZEOF(struct request
, cmd_flags
));
3490 BUILD_BUG_ON(REQ_OP_BITS
+ REQ_FLAG_BITS
> 8 *
3491 FIELD_SIZEOF(struct bio
, bi_opf
));
3493 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3494 kblockd_workqueue
= alloc_workqueue("kblockd",
3495 WQ_MEM_RECLAIM
| WQ_HIGHPRI
, 0);
3496 if (!kblockd_workqueue
)
3497 panic("Failed to create kblockd\n");
3499 request_cachep
= kmem_cache_create("blkdev_requests",
3500 sizeof(struct request
), 0, SLAB_PANIC
, NULL
);
3502 blk_requestq_cachep
= kmem_cache_create("request_queue",
3503 sizeof(struct request_queue
), 0, SLAB_PANIC
, NULL
);
3505 #ifdef CONFIG_DEBUG_FS
3506 blk_debugfs_root
= debugfs_create_dir("block", NULL
);