]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - block/blk-core.c
UBUNTU: Ubuntu-snapdragon-4.4.0-1044.48
[mirror_ubuntu-artful-kernel.git] / block / blk-core.c
CommitLineData
1da177e4 1/*
1da177e4
LT
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>
6728cb0e
JA
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7 * - July2000
1da177e4
LT
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9 */
10
11/*
12 * This handles all read/write requests to block devices
13 */
1da177e4
LT
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>
320ae51f 19#include <linux/blk-mq.h>
1da177e4
LT
20#include <linux/highmem.h>
21#include <linux/mm.h>
22#include <linux/kernel_stat.h>
23#include <linux/string.h>
24#include <linux/init.h>
1da177e4
LT
25#include <linux/completion.h>
26#include <linux/slab.h>
27#include <linux/swap.h>
28#include <linux/writeback.h>
faccbd4b 29#include <linux/task_io_accounting_ops.h>
c17bb495 30#include <linux/fault-inject.h>
73c10101 31#include <linux/list_sort.h>
e3c78ca5 32#include <linux/delay.h>
aaf7c680 33#include <linux/ratelimit.h>
6c954667 34#include <linux/pm_runtime.h>
eea8f41c 35#include <linux/blk-cgroup.h>
55782138
LZ
36
37#define CREATE_TRACE_POINTS
38#include <trace/events/block.h>
1da177e4 39
8324aa91 40#include "blk.h"
43a5e4e2 41#include "blk-mq.h"
8324aa91 42
d07335e5 43EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
b0da3f0d 44EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
0a82a8d1 45EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
3291fa57 46EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
cbae8d45 47EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
0bfc2455 48
a73f730d
TH
49DEFINE_IDA(blk_queue_ida);
50
1da177e4
LT
51/*
52 * For the allocated request tables
53 */
320ae51f 54struct kmem_cache *request_cachep = NULL;
1da177e4
LT
55
56/*
57 * For queue allocation
58 */
6728cb0e 59struct kmem_cache *blk_requestq_cachep;
1da177e4 60
1da177e4
LT
61/*
62 * Controlling structure to kblockd
63 */
ff856bad 64static struct workqueue_struct *kblockd_workqueue;
1da177e4 65
d40f75a0
TH
66static void blk_clear_congested(struct request_list *rl, int sync)
67{
d40f75a0
TH
68#ifdef CONFIG_CGROUP_WRITEBACK
69 clear_wb_congested(rl->blkg->wb_congested, sync);
70#else
482cf79c
TH
71 /*
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.
74 */
75 if (rl == &rl->q->root_rl)
f53624d5 76 clear_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
d40f75a0
TH
77#endif
78}
79
80static void blk_set_congested(struct request_list *rl, int sync)
81{
d40f75a0
TH
82#ifdef CONFIG_CGROUP_WRITEBACK
83 set_wb_congested(rl->blkg->wb_congested, sync);
84#else
482cf79c
TH
85 /* see blk_clear_congested() */
86 if (rl == &rl->q->root_rl)
f53624d5 87 set_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
d40f75a0
TH
88#endif
89}
90
8324aa91 91void blk_queue_congestion_threshold(struct request_queue *q)
1da177e4
LT
92{
93 int nr;
94
95 nr = q->nr_requests - (q->nr_requests / 8) + 1;
96 if (nr > q->nr_requests)
97 nr = q->nr_requests;
98 q->nr_congestion_on = nr;
99
100 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
101 if (nr < 1)
102 nr = 1;
103 q->nr_congestion_off = nr;
104}
105
2a4aa30c 106void blk_rq_init(struct request_queue *q, struct request *rq)
1da177e4 107{
1afb20f3
FT
108 memset(rq, 0, sizeof(*rq));
109
1da177e4 110 INIT_LIST_HEAD(&rq->queuelist);
242f9dcb 111 INIT_LIST_HEAD(&rq->timeout_list);
c7c22e4d 112 rq->cpu = -1;
63a71386 113 rq->q = q;
a2dec7b3 114 rq->__sector = (sector_t) -1;
2e662b65
JA
115 INIT_HLIST_NODE(&rq->hash);
116 RB_CLEAR_NODE(&rq->rb_node);
d7e3c324 117 rq->cmd = rq->__cmd;
e2494e1b 118 rq->cmd_len = BLK_MAX_CDB;
63a71386 119 rq->tag = -1;
b243ddcb 120 rq->start_time = jiffies;
9195291e 121 set_start_time_ns(rq);
09e099d4 122 rq->part = NULL;
1da177e4 123}
2a4aa30c 124EXPORT_SYMBOL(blk_rq_init);
1da177e4 125
5bb23a68
N
126static void req_bio_endio(struct request *rq, struct bio *bio,
127 unsigned int nbytes, int error)
1da177e4 128{
78d8e58a 129 if (error)
4246a0b6 130 bio->bi_error = error;
797e7dbb 131
143a87f4 132 if (unlikely(rq->cmd_flags & REQ_QUIET))
b7c44ed9 133 bio_set_flag(bio, BIO_QUIET);
08bafc03 134
f79ea416 135 bio_advance(bio, nbytes);
7ba1ba12 136
143a87f4 137 /* don't actually finish bio if it's part of flush sequence */
78d8e58a 138 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
4246a0b6 139 bio_endio(bio);
1da177e4 140}
1da177e4 141
1da177e4
LT
142void blk_dump_rq_flags(struct request *rq, char *msg)
143{
144 int bit;
145
5953316d 146 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
4aff5e23 147 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
5953316d 148 (unsigned long long) rq->cmd_flags);
1da177e4 149
83096ebf
TH
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));
b4f42e28
JA
153 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
154 rq->bio, rq->biotail, blk_rq_bytes(rq));
1da177e4 155
33659ebb 156 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
6728cb0e 157 printk(KERN_INFO " cdb: ");
d34c87e4 158 for (bit = 0; bit < BLK_MAX_CDB; bit++)
1da177e4
LT
159 printk("%02x ", rq->cmd[bit]);
160 printk("\n");
161 }
162}
1da177e4
LT
163EXPORT_SYMBOL(blk_dump_rq_flags);
164
3cca6dc1 165static void blk_delay_work(struct work_struct *work)
1da177e4 166{
3cca6dc1 167 struct request_queue *q;
1da177e4 168
3cca6dc1
JA
169 q = container_of(work, struct request_queue, delay_work.work);
170 spin_lock_irq(q->queue_lock);
24ecfbe2 171 __blk_run_queue(q);
3cca6dc1 172 spin_unlock_irq(q->queue_lock);
1da177e4 173}
1da177e4
LT
174
175/**
3cca6dc1
JA
176 * blk_delay_queue - restart queueing after defined interval
177 * @q: The &struct request_queue in question
178 * @msecs: Delay in msecs
1da177e4
LT
179 *
180 * Description:
3cca6dc1
JA
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
70460571 183 * restarted around the specified time. Queue lock must be held.
3cca6dc1
JA
184 */
185void blk_delay_queue(struct request_queue *q, unsigned long msecs)
2ad8b1ef 186{
70460571
BVA
187 if (likely(!blk_queue_dead(q)))
188 queue_delayed_work(kblockd_workqueue, &q->delay_work,
189 msecs_to_jiffies(msecs));
2ad8b1ef 190}
3cca6dc1 191EXPORT_SYMBOL(blk_delay_queue);
2ad8b1ef 192
21491412
JA
193/**
194 * blk_start_queue_async - asynchronously restart a previously stopped queue
195 * @q: The &struct request_queue in question
196 *
197 * Description:
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
200 * context.
201 **/
202void blk_start_queue_async(struct request_queue *q)
203{
204 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
205 blk_run_queue_async(q);
206}
207EXPORT_SYMBOL(blk_start_queue_async);
208
1da177e4
LT
209/**
210 * blk_start_queue - restart a previously stopped queue
165125e1 211 * @q: The &struct request_queue in question
1da177e4
LT
212 *
213 * Description:
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.
217 **/
165125e1 218void blk_start_queue(struct request_queue *q)
1da177e4 219{
e493d6b5 220 WARN_ON(!in_interrupt() && !irqs_disabled());
a038e253 221
75ad23bc 222 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
24ecfbe2 223 __blk_run_queue(q);
1da177e4 224}
1da177e4
LT
225EXPORT_SYMBOL(blk_start_queue);
226
227/**
228 * blk_stop_queue - stop a queue
165125e1 229 * @q: The &struct request_queue in question
1da177e4
LT
230 *
231 * Description:
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.
240 **/
165125e1 241void blk_stop_queue(struct request_queue *q)
1da177e4 242{
136b5721 243 cancel_delayed_work(&q->delay_work);
75ad23bc 244 queue_flag_set(QUEUE_FLAG_STOPPED, q);
1da177e4
LT
245}
246EXPORT_SYMBOL(blk_stop_queue);
247
248/**
249 * blk_sync_queue - cancel any pending callbacks on a queue
250 * @q: the queue
251 *
252 * Description:
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
59c51591 257 * that the callbacks might use. The caller must already have made sure
1da177e4
LT
258 * that its ->make_request_fn will not re-add plugging prior to calling
259 * this function.
260 *
da527770 261 * This function does not cancel any asynchronous activity arising
da3dae54 262 * out of elevator or throttling code. That would require elevator_exit()
5efd6113 263 * and blkcg_exit_queue() to be called with queue lock initialized.
da527770 264 *
1da177e4
LT
265 */
266void blk_sync_queue(struct request_queue *q)
267{
70ed28b9 268 del_timer_sync(&q->timeout);
f04c1fe7
ML
269
270 if (q->mq_ops) {
271 struct blk_mq_hw_ctx *hctx;
272 int i;
273
70f4db63
CH
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);
277 }
f04c1fe7
ML
278 } else {
279 cancel_delayed_work_sync(&q->delay_work);
280 }
1da177e4
LT
281}
282EXPORT_SYMBOL(blk_sync_queue);
283
c246e80d
BVA
284/**
285 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
286 * @q: The queue to run
287 *
288 * Description:
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.
294 */
295inline void __blk_run_queue_uncond(struct request_queue *q)
296{
297 if (unlikely(blk_queue_dead(q)))
298 return;
299
24faf6f6
BVA
300 /*
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.
306 */
307 q->request_fn_active++;
c246e80d 308 q->request_fn(q);
24faf6f6 309 q->request_fn_active--;
c246e80d 310}
a7928c15 311EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
c246e80d 312
1da177e4 313/**
80a4b58e 314 * __blk_run_queue - run a single device queue
1da177e4 315 * @q: The queue to run
80a4b58e
JA
316 *
317 * Description:
318 * See @blk_run_queue. This variant must be called with the queue lock
24ecfbe2 319 * held and interrupts disabled.
1da177e4 320 */
24ecfbe2 321void __blk_run_queue(struct request_queue *q)
1da177e4 322{
a538cd03
TH
323 if (unlikely(blk_queue_stopped(q)))
324 return;
325
c246e80d 326 __blk_run_queue_uncond(q);
75ad23bc
NP
327}
328EXPORT_SYMBOL(__blk_run_queue);
dac07ec1 329
24ecfbe2
CH
330/**
331 * blk_run_queue_async - run a single device queue in workqueue context
332 * @q: The queue to run
333 *
334 * Description:
335 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
70460571 336 * of us. The caller must hold the queue lock.
24ecfbe2
CH
337 */
338void blk_run_queue_async(struct request_queue *q)
339{
70460571 340 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
e7c2f967 341 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
24ecfbe2 342}
c21e6beb 343EXPORT_SYMBOL(blk_run_queue_async);
24ecfbe2 344
75ad23bc
NP
345/**
346 * blk_run_queue - run a single device queue
347 * @q: The queue to run
80a4b58e
JA
348 *
349 * Description:
350 * Invoke request handling on this queue, if it has pending work to do.
a7f55792 351 * May be used to restart queueing when a request has completed.
75ad23bc
NP
352 */
353void blk_run_queue(struct request_queue *q)
354{
355 unsigned long flags;
356
357 spin_lock_irqsave(q->queue_lock, flags);
24ecfbe2 358 __blk_run_queue(q);
1da177e4
LT
359 spin_unlock_irqrestore(q->queue_lock, flags);
360}
361EXPORT_SYMBOL(blk_run_queue);
362
165125e1 363void blk_put_queue(struct request_queue *q)
483f4afc
AV
364{
365 kobject_put(&q->kobj);
366}
d86e0e83 367EXPORT_SYMBOL(blk_put_queue);
483f4afc 368
e3c78ca5 369/**
807592a4 370 * __blk_drain_queue - drain requests from request_queue
e3c78ca5 371 * @q: queue to drain
c9a929dd 372 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
e3c78ca5 373 *
c9a929dd
TH
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.
e3c78ca5 377 */
807592a4
BVA
378static void __blk_drain_queue(struct request_queue *q, bool drain_all)
379 __releases(q->queue_lock)
380 __acquires(q->queue_lock)
e3c78ca5 381{
458f27a9
AH
382 int i;
383
807592a4
BVA
384 lockdep_assert_held(q->queue_lock);
385
e3c78ca5 386 while (true) {
481a7d64 387 bool drain = false;
e3c78ca5 388
b855b04a
TH
389 /*
390 * The caller might be trying to drain @q before its
391 * elevator is initialized.
392 */
393 if (q->elevator)
394 elv_drain_elevator(q);
395
5efd6113 396 blkcg_drain_queue(q);
e3c78ca5 397
4eabc941
TH
398 /*
399 * This function might be called on a queue which failed
b855b04a
TH
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.
4eabc941 404 */
b855b04a 405 if (!list_empty(&q->queue_head) && q->request_fn)
4eabc941 406 __blk_run_queue(q);
c9a929dd 407
8a5ecdd4 408 drain |= q->nr_rqs_elvpriv;
24faf6f6 409 drain |= q->request_fn_active;
481a7d64
TH
410
411 /*
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.
415 */
416 if (drain_all) {
e97c293c 417 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
481a7d64
TH
418 drain |= !list_empty(&q->queue_head);
419 for (i = 0; i < 2; i++) {
8a5ecdd4 420 drain |= q->nr_rqs[i];
481a7d64 421 drain |= q->in_flight[i];
7c94e1c1
ML
422 if (fq)
423 drain |= !list_empty(&fq->flush_queue[i]);
481a7d64
TH
424 }
425 }
e3c78ca5 426
481a7d64 427 if (!drain)
e3c78ca5 428 break;
807592a4
BVA
429
430 spin_unlock_irq(q->queue_lock);
431
e3c78ca5 432 msleep(10);
807592a4
BVA
433
434 spin_lock_irq(q->queue_lock);
e3c78ca5 435 }
458f27a9
AH
436
437 /*
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.
441 */
442 if (q->request_fn) {
a051661c
TH
443 struct request_list *rl;
444
a051661c
TH
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]);
458f27a9 448 }
e3c78ca5
TH
449}
450
d732580b
TH
451/**
452 * blk_queue_bypass_start - enter queue bypass mode
453 * @q: queue of interest
454 *
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
6ecf23af 457 * throttled or issued before. On return, it's guaranteed that no request
80fd9979
TH
458 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
459 * inside queue or RCU read lock.
d732580b
TH
460 */
461void blk_queue_bypass_start(struct request_queue *q)
462{
463 spin_lock_irq(q->queue_lock);
776687bc 464 q->bypass_depth++;
d732580b
TH
465 queue_flag_set(QUEUE_FLAG_BYPASS, q);
466 spin_unlock_irq(q->queue_lock);
467
776687bc
TH
468 /*
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.
472 */
473 if (blk_queue_init_done(q)) {
807592a4
BVA
474 spin_lock_irq(q->queue_lock);
475 __blk_drain_queue(q, false);
476 spin_unlock_irq(q->queue_lock);
477
b82d4b19
TH
478 /* ensure blk_queue_bypass() is %true inside RCU read lock */
479 synchronize_rcu();
480 }
d732580b
TH
481}
482EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
483
484/**
485 * blk_queue_bypass_end - leave queue bypass mode
486 * @q: queue of interest
487 *
488 * Leave bypass mode and restore the normal queueing behavior.
489 */
490void blk_queue_bypass_end(struct request_queue *q)
491{
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);
497}
498EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
499
aed3ea94
JA
500void blk_set_queue_dying(struct request_queue *q)
501{
2b23f3ed
BVA
502 spin_lock_irq(q->queue_lock);
503 queue_flag_set(QUEUE_FLAG_DYING, q);
504 spin_unlock_irq(q->queue_lock);
aed3ea94
JA
505
506 if (q->mq_ops)
507 blk_mq_wake_waiters(q);
508 else {
509 struct request_list *rl;
510
511 blk_queue_for_each_rl(rl, q) {
512 if (rl->rq_pool) {
906691fc
ML
513 wake_up_all(&rl->wait[BLK_RW_SYNC]);
514 wake_up_all(&rl->wait[BLK_RW_ASYNC]);
aed3ea94
JA
515 }
516 }
517 }
518}
519EXPORT_SYMBOL_GPL(blk_set_queue_dying);
520
c9a929dd
TH
521/**
522 * blk_cleanup_queue - shutdown a request queue
523 * @q: request queue to shutdown
524 *
c246e80d
BVA
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.
c94a96ac 527 */
6728cb0e 528void blk_cleanup_queue(struct request_queue *q)
483f4afc 529{
c9a929dd 530 spinlock_t *lock = q->queue_lock;
e3335de9 531
3f3299d5 532 /* mark @q DYING, no new request or merges will be allowed afterwards */
483f4afc 533 mutex_lock(&q->sysfs_lock);
aed3ea94 534 blk_set_queue_dying(q);
c9a929dd 535 spin_lock_irq(lock);
6ecf23af 536
80fd9979 537 /*
3f3299d5 538 * A dying queue is permanently in bypass mode till released. Note
80fd9979
TH
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.
545 */
6ecf23af
TH
546 q->bypass_depth++;
547 queue_flag_set(QUEUE_FLAG_BYPASS, q);
548
c9a929dd
TH
549 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
550 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
3f3299d5 551 queue_flag_set(QUEUE_FLAG_DYING, q);
c9a929dd
TH
552 spin_unlock_irq(lock);
553 mutex_unlock(&q->sysfs_lock);
554
c246e80d
BVA
555 /*
556 * Drain all requests queued before DYING marking. Set DEAD flag to
557 * prevent that q->request_fn() gets invoked after draining finished.
558 */
3ef28e83
DW
559 blk_freeze_queue(q);
560 spin_lock_irq(lock);
561 if (!q->mq_ops)
43a5e4e2 562 __blk_drain_queue(q, true);
c246e80d 563 queue_flag_set(QUEUE_FLAG_DEAD, q);
807592a4 564 spin_unlock_irq(lock);
c9a929dd 565
5a48fc14
DW
566 /* for synchronous bio-based driver finish in-flight integrity i/o */
567 blk_flush_integrity();
568
c9a929dd 569 /* @q won't process any more request, flush async actions */
f53624d5 570 del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
c9a929dd
TH
571 blk_sync_queue(q);
572
45a9c9d9
BVA
573 if (q->mq_ops)
574 blk_mq_free_queue(q);
3ef28e83 575 percpu_ref_exit(&q->q_usage_counter);
45a9c9d9 576
5e5cfac0
AH
577 spin_lock_irq(lock);
578 if (q->queue_lock != &q->__queue_lock)
579 q->queue_lock = &q->__queue_lock;
580 spin_unlock_irq(lock);
581
c9a929dd 582 /* @q is and will stay empty, shutdown and put */
483f4afc
AV
583 blk_put_queue(q);
584}
1da177e4
LT
585EXPORT_SYMBOL(blk_cleanup_queue);
586
271508db
DR
587/* Allocate memory local to the request queue */
588static void *alloc_request_struct(gfp_t gfp_mask, void *data)
589{
590 int nid = (int)(long)data;
591 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
592}
593
594static void free_request_struct(void *element, void *unused)
595{
596 kmem_cache_free(request_cachep, element);
597}
598
5b788ce3
TH
599int blk_init_rl(struct request_list *rl, struct request_queue *q,
600 gfp_t gfp_mask)
1da177e4 601{
1abec4fd
MS
602 if (unlikely(rl->rq_pool))
603 return 0;
604
5b788ce3 605 rl->q = q;
1faa16d2
JA
606 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
607 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
1faa16d2
JA
608 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
609 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
1da177e4 610
271508db
DR
611 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
612 free_request_struct,
613 (void *)(long)q->node, gfp_mask,
614 q->node);
1da177e4
LT
615 if (!rl->rq_pool)
616 return -ENOMEM;
617
618 return 0;
619}
620
5b788ce3
TH
621void blk_exit_rl(struct request_list *rl)
622{
623 if (rl->rq_pool)
624 mempool_destroy(rl->rq_pool);
625}
626
165125e1 627struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
1da177e4 628{
c304a51b 629 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
1946089a
CL
630}
631EXPORT_SYMBOL(blk_alloc_queue);
1da177e4 632
3c92db6a 633int blk_queue_enter(struct request_queue *q, bool nowait)
3ef28e83
DW
634{
635 while (true) {
636 int ret;
637
638 if (percpu_ref_tryget_live(&q->q_usage_counter))
639 return 0;
640
3c92db6a 641 if (nowait)
3ef28e83
DW
642 return -EBUSY;
643
644 ret = wait_event_interruptible(q->mq_freeze_wq,
645 !atomic_read(&q->mq_freeze_depth) ||
646 blk_queue_dying(q));
647 if (blk_queue_dying(q))
648 return -ENODEV;
649 if (ret)
650 return ret;
651 }
652}
653
654void blk_queue_exit(struct request_queue *q)
655{
656 percpu_ref_put(&q->q_usage_counter);
657}
658
659static void blk_queue_usage_counter_release(struct percpu_ref *ref)
660{
661 struct request_queue *q =
662 container_of(ref, struct request_queue, q_usage_counter);
663
664 wake_up_all(&q->mq_freeze_wq);
665}
666
fc3bda55
CH
667static void blk_rq_timed_out_timer(unsigned long data)
668{
669 struct request_queue *q = (struct request_queue *)data;
670
671 kblockd_schedule_work(&q->timeout_work);
672}
673
165125e1 674struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1946089a 675{
165125e1 676 struct request_queue *q;
1946089a 677
8324aa91 678 q = kmem_cache_alloc_node(blk_requestq_cachep,
94f6030c 679 gfp_mask | __GFP_ZERO, node_id);
1da177e4
LT
680 if (!q)
681 return NULL;
682
00380a40 683 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
a73f730d 684 if (q->id < 0)
3d2936f4 685 goto fail_q;
a73f730d 686
54efd50b
KO
687 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
688 if (!q->bio_split)
689 goto fail_id;
690
1a1eab55
JK
691 q->backing_dev_info = bdi_alloc_node(gfp_mask, node_id);
692 if (!q->backing_dev_info)
693 goto fail_split;
694
f53624d5 695 q->backing_dev_info->ra_pages =
0989a025 696 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
f53624d5
JK
697 q->backing_dev_info->capabilities = BDI_CAP_CGROUP_WRITEBACK;
698 q->backing_dev_info->name = "block";
5151412d 699 q->node = node_id;
0989a025 700
f53624d5 701 setup_timer(&q->backing_dev_info->laptop_mode_wb_timer,
31373d09 702 laptop_mode_timer_fn, (unsigned long) q);
242f9dcb 703 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
b855b04a 704 INIT_LIST_HEAD(&q->queue_head);
242f9dcb 705 INIT_LIST_HEAD(&q->timeout_list);
a612fddf 706 INIT_LIST_HEAD(&q->icq_list);
4eef3049 707#ifdef CONFIG_BLK_CGROUP
e8989fae 708 INIT_LIST_HEAD(&q->blkg_list);
4eef3049 709#endif
3cca6dc1 710 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
483f4afc 711
8324aa91 712 kobject_init(&q->kobj, &blk_queue_ktype);
1da177e4 713
483f4afc 714 mutex_init(&q->sysfs_lock);
e7e72bf6 715 spin_lock_init(&q->__queue_lock);
483f4afc 716
c94a96ac
VG
717 /*
718 * By default initialize queue_lock to internal lock and driver can
719 * override it later if need be.
720 */
721 q->queue_lock = &q->__queue_lock;
722
b82d4b19
TH
723 /*
724 * A queue starts its life with bypass turned on to avoid
725 * unnecessary bypass on/off overhead and nasty surprises during
749fefe6
TH
726 * init. The initial bypass will be finished when the queue is
727 * registered by blk_register_queue().
b82d4b19
TH
728 */
729 q->bypass_depth = 1;
730 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
731
320ae51f
JA
732 init_waitqueue_head(&q->mq_freeze_wq);
733
3ef28e83
DW
734 /*
735 * Init percpu_ref in atomic mode so that it's faster to shutdown.
736 * See blk_register_queue() for details.
737 */
738 if (percpu_ref_init(&q->q_usage_counter,
739 blk_queue_usage_counter_release,
740 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
fff4996b 741 goto fail_bdi;
f51b802c 742
3ef28e83
DW
743 if (blkcg_init_queue(q))
744 goto fail_ref;
745
1da177e4 746 return q;
a73f730d 747
3ef28e83
DW
748fail_ref:
749 percpu_ref_exit(&q->q_usage_counter);
fff4996b 750fail_bdi:
1a1eab55 751 bdi_put(q->backing_dev_info);
54efd50b
KO
752fail_split:
753 bioset_free(q->bio_split);
a73f730d
TH
754fail_id:
755 ida_simple_remove(&blk_queue_ida, q->id);
756fail_q:
757 kmem_cache_free(blk_requestq_cachep, q);
758 return NULL;
1da177e4 759}
1946089a 760EXPORT_SYMBOL(blk_alloc_queue_node);
1da177e4
LT
761
762/**
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
767 *
768 * Description:
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.
777 *
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.
782 *
783 * The queue spin lock must be held while manipulating the requests on the
a038e253
PBG
784 * request queue; this lock will be taken also from interrupt context, so irq
785 * disabling is needed for it.
1da177e4 786 *
710027a4 787 * Function returns a pointer to the initialized request queue, or %NULL if
1da177e4
LT
788 * it didn't succeed.
789 *
790 * Note:
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).
793 **/
1946089a 794
165125e1 795struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1da177e4 796{
c304a51b 797 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
1946089a
CL
798}
799EXPORT_SYMBOL(blk_init_queue);
800
165125e1 801struct request_queue *
1946089a
CL
802blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
803{
c86d1b8a 804 struct request_queue *uninit_q, *q;
1da177e4 805
c86d1b8a
MS
806 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
807 if (!uninit_q)
808 return NULL;
809
5151412d 810 q = blk_init_allocated_queue(uninit_q, rfn, lock);
c86d1b8a 811 if (!q)
7982e90c 812 blk_cleanup_queue(uninit_q);
18741986 813
7982e90c 814 return q;
01effb0d
MS
815}
816EXPORT_SYMBOL(blk_init_queue_node);
817
dece1635 818static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
336b7e1f 819
01effb0d
MS
820struct request_queue *
821blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
822 spinlock_t *lock)
01effb0d 823{
1da177e4
LT
824 if (!q)
825 return NULL;
826
f70ced09 827 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
ba483388 828 if (!q->fq)
7982e90c
MS
829 return NULL;
830
a051661c 831 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
708f04d2 832 goto fail;
1da177e4 833
fc3bda55 834 INIT_WORK(&q->timeout_work, blk_timeout_work);
1da177e4 835 q->request_fn = rfn;
1da177e4 836 q->prep_rq_fn = NULL;
28018c24 837 q->unprep_rq_fn = NULL;
60ea8226 838 q->queue_flags |= QUEUE_FLAG_DEFAULT;
c94a96ac
VG
839
840 /* Override internal queue lock with supplied lock pointer */
841 if (lock)
842 q->queue_lock = lock;
1da177e4 843
f3b144aa
JA
844 /*
845 * This also sets hw/phys segments, boundary and size
846 */
c20e8de2 847 blk_queue_make_request(q, blk_queue_bio);
1da177e4 848
44ec9542
AS
849 q->sg_reserved_size = INT_MAX;
850
eb1c160b
TS
851 /* Protect q->elevator from elevator_change */
852 mutex_lock(&q->sysfs_lock);
853
b82d4b19 854 /* init elevator */
eb1c160b
TS
855 if (elevator_init(q, NULL)) {
856 mutex_unlock(&q->sysfs_lock);
708f04d2 857 goto fail;
eb1c160b
TS
858 }
859
860 mutex_unlock(&q->sysfs_lock);
861
b82d4b19 862 return q;
708f04d2
DJ
863
864fail:
ba483388 865 blk_free_flush_queue(q->fq);
708f04d2 866 return NULL;
1da177e4 867}
5151412d 868EXPORT_SYMBOL(blk_init_allocated_queue);
1da177e4 869
09ac46c4 870bool blk_get_queue(struct request_queue *q)
1da177e4 871{
3f3299d5 872 if (likely(!blk_queue_dying(q))) {
09ac46c4
TH
873 __blk_get_queue(q);
874 return true;
1da177e4
LT
875 }
876
09ac46c4 877 return false;
1da177e4 878}
d86e0e83 879EXPORT_SYMBOL(blk_get_queue);
1da177e4 880
5b788ce3 881static inline void blk_free_request(struct request_list *rl, struct request *rq)
1da177e4 882{
f1f8cc94 883 if (rq->cmd_flags & REQ_ELVPRIV) {
5b788ce3 884 elv_put_request(rl->q, rq);
f1f8cc94 885 if (rq->elv.icq)
11a3122f 886 put_io_context(rq->elv.icq->ioc);
f1f8cc94
TH
887 }
888
5b788ce3 889 mempool_free(rq, rl->rq_pool);
1da177e4
LT
890}
891
1da177e4
LT
892/*
893 * ioc_batching returns true if the ioc is a valid batching request and
894 * should be given priority access to a request.
895 */
165125e1 896static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
897{
898 if (!ioc)
899 return 0;
900
901 /*
902 * Make sure the process is able to allocate at least 1 request
903 * even if the batch times out, otherwise we could theoretically
904 * lose wakeups.
905 */
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));
909}
910
911/*
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
915 * a nice run.
916 */
165125e1 917static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
918{
919 if (!ioc || ioc_batching(q, ioc))
920 return;
921
922 ioc->nr_batch_requests = q->nr_batching;
923 ioc->last_waited = jiffies;
924}
925
5b788ce3 926static void __freed_request(struct request_list *rl, int sync)
1da177e4 927{
5b788ce3 928 struct request_queue *q = rl->q;
1da177e4 929
d40f75a0
TH
930 if (rl->count[sync] < queue_congestion_off_threshold(q))
931 blk_clear_congested(rl, sync);
1da177e4 932
1faa16d2
JA
933 if (rl->count[sync] + 1 <= q->nr_requests) {
934 if (waitqueue_active(&rl->wait[sync]))
935 wake_up(&rl->wait[sync]);
1da177e4 936
5b788ce3 937 blk_clear_rl_full(rl, sync);
1da177e4
LT
938 }
939}
940
941/*
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.
944 */
5b788ce3 945static void freed_request(struct request_list *rl, unsigned int flags)
1da177e4 946{
5b788ce3 947 struct request_queue *q = rl->q;
75eb6c37 948 int sync = rw_is_sync(flags);
1da177e4 949
8a5ecdd4 950 q->nr_rqs[sync]--;
1faa16d2 951 rl->count[sync]--;
75eb6c37 952 if (flags & REQ_ELVPRIV)
8a5ecdd4 953 q->nr_rqs_elvpriv--;
1da177e4 954
5b788ce3 955 __freed_request(rl, sync);
1da177e4 956
1faa16d2 957 if (unlikely(rl->starved[sync ^ 1]))
5b788ce3 958 __freed_request(rl, sync ^ 1);
1da177e4
LT
959}
960
e3a2b3f9
JA
961int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
962{
963 struct request_list *rl;
d40f75a0 964 int on_thresh, off_thresh;
e3a2b3f9
JA
965
966 spin_lock_irq(q->queue_lock);
967 q->nr_requests = nr;
968 blk_queue_congestion_threshold(q);
d40f75a0
TH
969 on_thresh = queue_congestion_on_threshold(q);
970 off_thresh = queue_congestion_off_threshold(q);
e3a2b3f9 971
d40f75a0
TH
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);
e3a2b3f9 977
d40f75a0
TH
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);
e3a2b3f9 982
e3a2b3f9
JA
983 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
984 blk_set_rl_full(rl, BLK_RW_SYNC);
985 } else {
986 blk_clear_rl_full(rl, BLK_RW_SYNC);
987 wake_up(&rl->wait[BLK_RW_SYNC]);
988 }
989
990 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
991 blk_set_rl_full(rl, BLK_RW_ASYNC);
992 } else {
993 blk_clear_rl_full(rl, BLK_RW_ASYNC);
994 wake_up(&rl->wait[BLK_RW_ASYNC]);
995 }
996 }
997
998 spin_unlock_irq(q->queue_lock);
999 return 0;
1000}
1001
9d5a4e94
MS
1002/*
1003 * Determine if elevator data should be initialized when allocating the
1004 * request associated with @bio.
1005 */
1006static bool blk_rq_should_init_elevator(struct bio *bio)
1007{
1008 if (!bio)
1009 return true;
1010
1011 /*
1012 * Flush requests do not use the elevator so skip initialization.
1013 * This allows a request to share the flush and elevator data.
1014 */
1015 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
1016 return false;
1017
1018 return true;
1019}
1020
852c788f
TH
1021/**
1022 * rq_ioc - determine io_context for request allocation
1023 * @bio: request being allocated is for this bio (can be %NULL)
1024 *
1025 * Determine io_context to use for request allocation for @bio. May return
1026 * %NULL if %current->io_context doesn't exist.
1027 */
1028static struct io_context *rq_ioc(struct bio *bio)
1029{
1030#ifdef CONFIG_BLK_CGROUP
1031 if (bio && bio->bi_ioc)
1032 return bio->bi_ioc;
1033#endif
1034 return current->io_context;
1035}
1036
da8303c6 1037/**
a06e05e6 1038 * __get_request - get a free request
5b788ce3 1039 * @rl: request list to allocate from
da8303c6
TH
1040 * @rw_flags: RW and SYNC flags
1041 * @bio: bio to allocate request for (can be %NULL)
1042 * @gfp_mask: allocation mask
1043 *
1044 * Get a free request from @q. This function may fail under memory
1045 * pressure or if @q is dead.
1046 *
da3dae54 1047 * Must be called with @q->queue_lock held and,
a492f075
JL
1048 * Returns ERR_PTR on failure, with @q->queue_lock held.
1049 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1050 */
5b788ce3 1051static struct request *__get_request(struct request_list *rl, int rw_flags,
a06e05e6 1052 struct bio *bio, gfp_t gfp_mask)
1da177e4 1053{
5b788ce3 1054 struct request_queue *q = rl->q;
b679281a 1055 struct request *rq;
7f4b35d1
TH
1056 struct elevator_type *et = q->elevator->type;
1057 struct io_context *ioc = rq_ioc(bio);
f1f8cc94 1058 struct io_cq *icq = NULL;
1faa16d2 1059 const bool is_sync = rw_is_sync(rw_flags) != 0;
75eb6c37 1060 int may_queue;
88ee5ef1 1061
3f3299d5 1062 if (unlikely(blk_queue_dying(q)))
a492f075 1063 return ERR_PTR(-ENODEV);
da8303c6 1064
7749a8d4 1065 may_queue = elv_may_queue(q, rw_flags);
88ee5ef1
JA
1066 if (may_queue == ELV_MQUEUE_NO)
1067 goto rq_starved;
1068
1faa16d2
JA
1069 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1070 if (rl->count[is_sync]+1 >= q->nr_requests) {
88ee5ef1
JA
1071 /*
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.
1076 */
5b788ce3 1077 if (!blk_rl_full(rl, is_sync)) {
88ee5ef1 1078 ioc_set_batching(q, ioc);
5b788ce3 1079 blk_set_rl_full(rl, is_sync);
88ee5ef1
JA
1080 } else {
1081 if (may_queue != ELV_MQUEUE_MUST
1082 && !ioc_batching(q, ioc)) {
1083 /*
1084 * The queue is full and the allocating
1085 * process is not a "batcher", and not
1086 * exempted by the IO scheduler
1087 */
a492f075 1088 return ERR_PTR(-ENOMEM);
88ee5ef1
JA
1089 }
1090 }
1da177e4 1091 }
d40f75a0 1092 blk_set_congested(rl, is_sync);
1da177e4
LT
1093 }
1094
082cf69e
JA
1095 /*
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
1099 */
1faa16d2 1100 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
a492f075 1101 return ERR_PTR(-ENOMEM);
fd782a4a 1102
8a5ecdd4 1103 q->nr_rqs[is_sync]++;
1faa16d2
JA
1104 rl->count[is_sync]++;
1105 rl->starved[is_sync] = 0;
cb98fc8b 1106
f1f8cc94
TH
1107 /*
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.
1113 *
1114 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1115 * it will be created after releasing queue_lock.
1116 */
d732580b 1117 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
75eb6c37 1118 rw_flags |= REQ_ELVPRIV;
8a5ecdd4 1119 q->nr_rqs_elvpriv++;
f1f8cc94
TH
1120 if (et->icq_cache && ioc)
1121 icq = ioc_lookup_icq(ioc, q);
9d5a4e94 1122 }
cb98fc8b 1123
f253b86b
JA
1124 if (blk_queue_io_stat(q))
1125 rw_flags |= REQ_IO_STAT;
1da177e4
LT
1126 spin_unlock_irq(q->queue_lock);
1127
29e2b09a 1128 /* allocate and init request */
5b788ce3 1129 rq = mempool_alloc(rl->rq_pool, gfp_mask);
29e2b09a 1130 if (!rq)
b679281a 1131 goto fail_alloc;
1da177e4 1132
29e2b09a 1133 blk_rq_init(q, rq);
a051661c 1134 blk_rq_set_rl(rq, rl);
29e2b09a
TH
1135 rq->cmd_flags = rw_flags | REQ_ALLOCED;
1136
aaf7c680 1137 /* init elvpriv */
29e2b09a 1138 if (rw_flags & REQ_ELVPRIV) {
aaf7c680 1139 if (unlikely(et->icq_cache && !icq)) {
7f4b35d1
TH
1140 if (ioc)
1141 icq = ioc_create_icq(ioc, q, gfp_mask);
aaf7c680
TH
1142 if (!icq)
1143 goto fail_elvpriv;
29e2b09a 1144 }
aaf7c680
TH
1145
1146 rq->elv.icq = icq;
1147 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1148 goto fail_elvpriv;
1149
1150 /* @rq->elv.icq holds io_context until @rq is freed */
29e2b09a
TH
1151 if (icq)
1152 get_io_context(icq->ioc);
1153 }
aaf7c680 1154out:
88ee5ef1
JA
1155 /*
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.
1160 */
1da177e4
LT
1161 if (ioc_batching(q, ioc))
1162 ioc->nr_batch_requests--;
6728cb0e 1163
1faa16d2 1164 trace_block_getrq(q, bio, rw_flags & 1);
1da177e4 1165 return rq;
b679281a 1166
aaf7c680
TH
1167fail_elvpriv:
1168 /*
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.
1173 */
7b2b10e0 1174 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
f53624d5 1175 __func__, dev_name(q->backing_dev_info->dev));
aaf7c680
TH
1176
1177 rq->cmd_flags &= ~REQ_ELVPRIV;
1178 rq->elv.icq = NULL;
1179
1180 spin_lock_irq(q->queue_lock);
8a5ecdd4 1181 q->nr_rqs_elvpriv--;
aaf7c680
TH
1182 spin_unlock_irq(q->queue_lock);
1183 goto out;
1184
b679281a
TH
1185fail_alloc:
1186 /*
1187 * Allocation failed presumably due to memory. Undo anything we
1188 * might have messed up.
1189 *
1190 * Allocating task should really be put onto the front of the wait
1191 * queue, but this is pretty rare.
1192 */
1193 spin_lock_irq(q->queue_lock);
5b788ce3 1194 freed_request(rl, rw_flags);
b679281a
TH
1195
1196 /*
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
1201 * READ and WRITE
1202 */
1203rq_starved:
1204 if (unlikely(rl->count[is_sync] == 0))
1205 rl->starved[is_sync] = 1;
a492f075 1206 return ERR_PTR(-ENOMEM);
1da177e4
LT
1207}
1208
da8303c6 1209/**
a06e05e6 1210 * get_request - get a free request
da8303c6
TH
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)
a06e05e6 1214 * @gfp_mask: allocation mask
da8303c6 1215 *
d0164adc
MG
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.
d6344532 1218 *
da3dae54 1219 * Must be called with @q->queue_lock held and,
a492f075
JL
1220 * Returns ERR_PTR on failure, with @q->queue_lock held.
1221 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1222 */
a06e05e6
TH
1223static struct request *get_request(struct request_queue *q, int rw_flags,
1224 struct bio *bio, gfp_t gfp_mask)
1da177e4 1225{
1faa16d2 1226 const bool is_sync = rw_is_sync(rw_flags) != 0;
a06e05e6 1227 DEFINE_WAIT(wait);
a051661c 1228 struct request_list *rl;
1da177e4 1229 struct request *rq;
a051661c
TH
1230
1231 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
a06e05e6 1232retry:
a051661c 1233 rq = __get_request(rl, rw_flags, bio, gfp_mask);
a492f075 1234 if (!IS_ERR(rq))
a06e05e6 1235 return rq;
1da177e4 1236
d0164adc 1237 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
a051661c 1238 blk_put_rl(rl);
a492f075 1239 return rq;
a051661c 1240 }
1da177e4 1241
a06e05e6
TH
1242 /* wait on @rl and retry */
1243 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1244 TASK_UNINTERRUPTIBLE);
1da177e4 1245
a06e05e6 1246 trace_block_sleeprq(q, bio, rw_flags & 1);
1da177e4 1247
a06e05e6
TH
1248 spin_unlock_irq(q->queue_lock);
1249 io_schedule();
d6344532 1250
a06e05e6
TH
1251 /*
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
1255 */
a06e05e6 1256 ioc_set_batching(q, current->io_context);
05caf8db 1257
a06e05e6
TH
1258 spin_lock_irq(q->queue_lock);
1259 finish_wait(&rl->wait[is_sync], &wait);
1da177e4 1260
a06e05e6 1261 goto retry;
1da177e4
LT
1262}
1263
320ae51f
JA
1264static struct request *blk_old_get_request(struct request_queue *q, int rw,
1265 gfp_t gfp_mask)
1da177e4
LT
1266{
1267 struct request *rq;
1268
1269 BUG_ON(rw != READ && rw != WRITE);
1270
7f4b35d1
TH
1271 /* create ioc upfront */
1272 create_io_context(gfp_mask, q->node);
1273
d6344532 1274 spin_lock_irq(q->queue_lock);
a06e05e6 1275 rq = get_request(q, rw, NULL, gfp_mask);
a492f075 1276 if (IS_ERR(rq))
da8303c6 1277 spin_unlock_irq(q->queue_lock);
d6344532 1278 /* q->queue_lock is unlocked at this point */
1da177e4
LT
1279
1280 return rq;
1281}
320ae51f
JA
1282
1283struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1284{
1285 if (q->mq_ops)
3c92db6a
CH
1286 return blk_mq_alloc_request(q, rw,
1287 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1288 0 : BLK_MQ_REQ_NOWAIT);
320ae51f
JA
1289 else
1290 return blk_old_get_request(q, rw, gfp_mask);
1291}
1da177e4
LT
1292EXPORT_SYMBOL(blk_get_request);
1293
dc72ef4a 1294/**
79eb63e9 1295 * blk_make_request - given a bio, allocate a corresponding struct request.
8ebf9756 1296 * @q: target request queue
79eb63e9
BH
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.
8ebf9756 1299 * @gfp_mask: gfp flags to be used for memory allocation
dc72ef4a 1300 *
79eb63e9
BH
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
1304 * the I/O transfer.
dc72ef4a 1305 *
79eb63e9
BH
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)
1310 *
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
1314 * BUG.
53674ac5
JA
1315 *
1316 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
d0164adc
MG
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.
53674ac5
JA
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.
dc72ef4a 1324 */
79eb63e9
BH
1325struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1326 gfp_t gfp_mask)
dc72ef4a 1327{
79eb63e9
BH
1328 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1329
a492f075
JL
1330 if (IS_ERR(rq))
1331 return rq;
79eb63e9 1332
f27b087b
JA
1333 blk_rq_set_block_pc(rq);
1334
79eb63e9
BH
1335 for_each_bio(bio) {
1336 struct bio *bounce_bio = bio;
1337 int ret;
1338
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);
1344 }
1345 }
1346
1347 return rq;
dc72ef4a 1348}
79eb63e9 1349EXPORT_SYMBOL(blk_make_request);
dc72ef4a 1350
f27b087b 1351/**
da3dae54 1352 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
f27b087b
JA
1353 * @rq: request to be initialized
1354 *
1355 */
1356void blk_rq_set_block_pc(struct request *rq)
1357{
1358 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1359 rq->__data_len = 0;
1360 rq->__sector = (sector_t) -1;
1361 rq->bio = rq->biotail = NULL;
1362 memset(rq->__cmd, 0, sizeof(rq->__cmd));
f27b087b
JA
1363}
1364EXPORT_SYMBOL(blk_rq_set_block_pc);
1365
1da177e4
LT
1366/**
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
1370 *
1371 * Description:
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.
1375 */
165125e1 1376void blk_requeue_request(struct request_queue *q, struct request *rq)
1da177e4 1377{
242f9dcb
JA
1378 blk_delete_timer(rq);
1379 blk_clear_rq_complete(rq);
5f3ea37c 1380 trace_block_rq_requeue(q, rq);
2056a782 1381
125c99bc 1382 if (rq->cmd_flags & REQ_QUEUED)
1da177e4
LT
1383 blk_queue_end_tag(q, rq);
1384
ba396a6c
JB
1385 BUG_ON(blk_queued_rq(rq));
1386
1da177e4
LT
1387 elv_requeue_request(q, rq);
1388}
1da177e4
LT
1389EXPORT_SYMBOL(blk_requeue_request);
1390
73c10101
JA
1391static void add_acct_request(struct request_queue *q, struct request *rq,
1392 int where)
1393{
320ae51f 1394 blk_account_io_start(rq, true);
7eaceacc 1395 __elv_add_request(q, rq, where);
73c10101
JA
1396}
1397
074a7aca
TH
1398static void part_round_stats_single(int cpu, struct hd_struct *part,
1399 unsigned long now)
1400{
7276d02e
JA
1401 int inflight;
1402
074a7aca
TH
1403 if (now == part->stamp)
1404 return;
1405
7276d02e
JA
1406 inflight = part_in_flight(part);
1407 if (inflight) {
074a7aca 1408 __part_stat_add(cpu, part, time_in_queue,
7276d02e 1409 inflight * (now - part->stamp));
074a7aca
TH
1410 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1411 }
1412 part->stamp = now;
1413}
1414
1415/**
496aa8a9
RD
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
1da177e4
LT
1419 *
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.
1423 *
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.
1430 */
c9959059 1431void part_round_stats(int cpu, struct hd_struct *part)
6f2576af
JM
1432{
1433 unsigned long now = jiffies;
1434
074a7aca
TH
1435 if (part->partno)
1436 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1437 part_round_stats_single(cpu, part, now);
6f2576af 1438}
074a7aca 1439EXPORT_SYMBOL_GPL(part_round_stats);
6f2576af 1440
47fafbc7 1441#ifdef CONFIG_PM
c8158819
LM
1442static void blk_pm_put_request(struct request *rq)
1443{
1444 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1445 pm_runtime_mark_last_busy(rq->q->dev);
1446}
1447#else
1448static inline void blk_pm_put_request(struct request *rq) {}
1449#endif
1450
1da177e4
LT
1451/*
1452 * queue lock must be held
1453 */
165125e1 1454void __blk_put_request(struct request_queue *q, struct request *req)
1da177e4 1455{
1da177e4
LT
1456 if (unlikely(!q))
1457 return;
1da177e4 1458
6f5ba581
CH
1459 if (q->mq_ops) {
1460 blk_mq_free_request(req);
1461 return;
1462 }
1463
c8158819
LM
1464 blk_pm_put_request(req);
1465
8922e16c
TH
1466 elv_completed_request(q, req);
1467
1cd96c24
BH
1468 /* this is a bio leak */
1469 WARN_ON(req->bio != NULL);
1470
1da177e4
LT
1471 /*
1472 * Request may not have originated from ll_rw_blk. if not,
1473 * it didn't come out of our reserved rq pools
1474 */
49171e5c 1475 if (req->cmd_flags & REQ_ALLOCED) {
75eb6c37 1476 unsigned int flags = req->cmd_flags;
a051661c 1477 struct request_list *rl = blk_rq_rl(req);
1da177e4 1478
1da177e4 1479 BUG_ON(!list_empty(&req->queuelist));
360f92c2 1480 BUG_ON(ELV_ON_HASH(req));
1da177e4 1481
a051661c
TH
1482 blk_free_request(rl, req);
1483 freed_request(rl, flags);
1484 blk_put_rl(rl);
1da177e4
LT
1485 }
1486}
6e39b69e
MC
1487EXPORT_SYMBOL_GPL(__blk_put_request);
1488
1da177e4
LT
1489void blk_put_request(struct request *req)
1490{
165125e1 1491 struct request_queue *q = req->q;
8922e16c 1492
320ae51f
JA
1493 if (q->mq_ops)
1494 blk_mq_free_request(req);
1495 else {
1496 unsigned long flags;
1497
1498 spin_lock_irqsave(q->queue_lock, flags);
1499 __blk_put_request(q, req);
1500 spin_unlock_irqrestore(q->queue_lock, flags);
1501 }
1da177e4 1502}
1da177e4
LT
1503EXPORT_SYMBOL(blk_put_request);
1504
66ac0280
CH
1505/**
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.
1510 *
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
1513 * itself.
1514 *
1515 * Note that this is a quite horrible hack and nothing but handling of
1516 * discard requests should ever use it.
1517 */
1518void blk_add_request_payload(struct request *rq, struct page *page,
1519 unsigned int len)
1520{
1521 struct bio *bio = rq->bio;
1522
1523 bio->bi_io_vec->bv_page = page;
1524 bio->bi_io_vec->bv_offset = 0;
1525 bio->bi_io_vec->bv_len = len;
1526
4f024f37 1527 bio->bi_iter.bi_size = len;
66ac0280
CH
1528 bio->bi_vcnt = 1;
1529 bio->bi_phys_segments = 1;
1530
1531 rq->__data_len = rq->resid_len = len;
1532 rq->nr_phys_segments = 1;
66ac0280
CH
1533}
1534EXPORT_SYMBOL_GPL(blk_add_request_payload);
1535
320ae51f
JA
1536bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1537 struct bio *bio)
73c10101
JA
1538{
1539 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1540
73c10101
JA
1541 if (!ll_back_merge_fn(q, req, bio))
1542 return false;
1543
8c1cf6bb 1544 trace_block_bio_backmerge(q, req, bio);
73c10101
JA
1545
1546 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1547 blk_rq_set_mixed_merge(req);
1548
1549 req->biotail->bi_next = bio;
1550 req->biotail = bio;
4f024f37 1551 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1552 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1553
320ae51f 1554 blk_account_io_start(req, false);
73c10101
JA
1555 return true;
1556}
1557
320ae51f
JA
1558bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1559 struct bio *bio)
73c10101
JA
1560{
1561 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
73c10101 1562
73c10101
JA
1563 if (!ll_front_merge_fn(q, req, bio))
1564 return false;
1565
8c1cf6bb 1566 trace_block_bio_frontmerge(q, req, bio);
73c10101
JA
1567
1568 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1569 blk_rq_set_mixed_merge(req);
1570
73c10101
JA
1571 bio->bi_next = req->bio;
1572 req->bio = bio;
1573
4f024f37
KO
1574 req->__sector = bio->bi_iter.bi_sector;
1575 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1576 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1577
320ae51f 1578 blk_account_io_start(req, false);
73c10101
JA
1579 return true;
1580}
1581
bd87b589 1582/**
320ae51f 1583 * blk_attempt_plug_merge - try to merge with %current's plugged list
bd87b589
TH
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
ccc2600b
RD
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)
bd87b589
TH
1590 *
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,
1593 * otherwise %false.
1594 *
07c2bd37
TH
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.
da41a589
RE
1601 *
1602 * Caller must ensure !blk_queue_nomerges(q) beforehand.
73c10101 1603 */
320ae51f 1604bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
5b3f341f
SL
1605 unsigned int *request_count,
1606 struct request **same_queue_rq)
73c10101
JA
1607{
1608 struct blk_plug *plug;
1609 struct request *rq;
1610 bool ret = false;
92f399c7 1611 struct list_head *plug_list;
73c10101 1612
bd87b589 1613 plug = current->plug;
73c10101
JA
1614 if (!plug)
1615 goto out;
56ebdaf2 1616 *request_count = 0;
73c10101 1617
92f399c7
SL
1618 if (q->mq_ops)
1619 plug_list = &plug->mq_list;
1620 else
1621 plug_list = &plug->list;
1622
1623 list_for_each_entry_reverse(rq, plug_list, queuelist) {
73c10101
JA
1624 int el_ret;
1625
5b3f341f 1626 if (rq->q == q) {
1b2e19f1 1627 (*request_count)++;
5b3f341f
SL
1628 /*
1629 * Only blk-mq multiple hardware queues case checks the
1630 * rq in the same queue, there should be only one such
1631 * rq in a queue
1632 **/
1633 if (same_queue_rq)
1634 *same_queue_rq = rq;
1635 }
56ebdaf2 1636
07c2bd37 1637 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
73c10101
JA
1638 continue;
1639
050c8ea8 1640 el_ret = blk_try_merge(rq, bio);
73c10101
JA
1641 if (el_ret == ELEVATOR_BACK_MERGE) {
1642 ret = bio_attempt_back_merge(q, rq, bio);
1643 if (ret)
1644 break;
1645 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1646 ret = bio_attempt_front_merge(q, rq, bio);
1647 if (ret)
1648 break;
1649 }
1650 }
1651out:
1652 return ret;
1653}
1654
0809e3ac
JM
1655unsigned int blk_plug_queued_count(struct request_queue *q)
1656{
1657 struct blk_plug *plug;
1658 struct request *rq;
1659 struct list_head *plug_list;
1660 unsigned int ret = 0;
1661
1662 plug = current->plug;
1663 if (!plug)
1664 goto out;
1665
1666 if (q->mq_ops)
1667 plug_list = &plug->mq_list;
1668 else
1669 plug_list = &plug->list;
1670
1671 list_for_each_entry(rq, plug_list, queuelist) {
1672 if (rq->q == q)
1673 ret++;
1674 }
1675out:
1676 return ret;
1677}
1678
86db1e29 1679void init_request_from_bio(struct request *req, struct bio *bio)
52d9e675 1680{
4aff5e23 1681 req->cmd_type = REQ_TYPE_FS;
52d9e675 1682
7b6d91da
CH
1683 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1684 if (bio->bi_rw & REQ_RAHEAD)
a82afdfc 1685 req->cmd_flags |= REQ_FAILFAST_MASK;
b31dc66a 1686
52d9e675 1687 req->errors = 0;
4f024f37 1688 req->__sector = bio->bi_iter.bi_sector;
52d9e675 1689 req->ioprio = bio_prio(bio);
bc1c56fd 1690 blk_rq_bio_prep(req->q, req, bio);
52d9e675
TH
1691}
1692
dece1635 1693static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1da177e4 1694{
5e00d1b5 1695 const bool sync = !!(bio->bi_rw & REQ_SYNC);
73c10101
JA
1696 struct blk_plug *plug;
1697 int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1698 struct request *req;
56ebdaf2 1699 unsigned int request_count = 0;
1da177e4 1700
1da177e4
LT
1701 /*
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)
1705 */
1706 blk_queue_bounce(q, &bio);
1707
23688bf4
JN
1708 blk_queue_split(q, &bio, q->bio_split);
1709
ffecfd1a 1710 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
4246a0b6
CH
1711 bio->bi_error = -EIO;
1712 bio_endio(bio);
dece1635 1713 return BLK_QC_T_NONE;
ffecfd1a
DW
1714 }
1715
4fed947c 1716 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
73c10101 1717 spin_lock_irq(q->queue_lock);
ae1b1539 1718 where = ELEVATOR_INSERT_FLUSH;
28e7d184
TH
1719 goto get_rq;
1720 }
1721
73c10101
JA
1722 /*
1723 * Check if we can merge with the plugged list before grabbing
1724 * any locks.
1725 */
0809e3ac
JM
1726 if (!blk_queue_nomerges(q)) {
1727 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
dece1635 1728 return BLK_QC_T_NONE;
0809e3ac
JM
1729 } else
1730 request_count = blk_plug_queued_count(q);
1da177e4 1731
73c10101 1732 spin_lock_irq(q->queue_lock);
2056a782 1733
73c10101
JA
1734 el_ret = elv_merge(q, &req, bio);
1735 if (el_ret == ELEVATOR_BACK_MERGE) {
73c10101 1736 if (bio_attempt_back_merge(q, req, bio)) {
07c2bd37 1737 elv_bio_merged(q, req, bio);
73c10101
JA
1738 if (!attempt_back_merge(q, req))
1739 elv_merged_request(q, req, el_ret);
1740 goto out_unlock;
1741 }
1742 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
73c10101 1743 if (bio_attempt_front_merge(q, req, bio)) {
07c2bd37 1744 elv_bio_merged(q, req, bio);
73c10101
JA
1745 if (!attempt_front_merge(q, req))
1746 elv_merged_request(q, req, el_ret);
1747 goto out_unlock;
80a761fd 1748 }
1da177e4
LT
1749 }
1750
450991bc 1751get_rq:
7749a8d4
JA
1752 /*
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.
1756 */
1757 rw_flags = bio_data_dir(bio);
1758 if (sync)
7b6d91da 1759 rw_flags |= REQ_SYNC;
7749a8d4 1760
1da177e4 1761 /*
450991bc 1762 * Grab a free request. This is might sleep but can not fail.
d6344532 1763 * Returns with the queue unlocked.
450991bc 1764 */
a06e05e6 1765 req = get_request(q, rw_flags, bio, GFP_NOIO);
a492f075 1766 if (IS_ERR(req)) {
4246a0b6
CH
1767 bio->bi_error = PTR_ERR(req);
1768 bio_endio(bio);
da8303c6
TH
1769 goto out_unlock;
1770 }
d6344532 1771
450991bc
NP
1772 /*
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.
1da177e4 1777 */
52d9e675 1778 init_request_from_bio(req, bio);
1da177e4 1779
9562ad9a 1780 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
11ccf116 1781 req->cpu = raw_smp_processor_id();
73c10101
JA
1782
1783 plug = current->plug;
721a9602 1784 if (plug) {
dc6d36c9
JA
1785 /*
1786 * If this is the first request added after a plug, fire
7aef2e78 1787 * of a plug trace.
dc6d36c9 1788 */
7aef2e78 1789 if (!request_count)
dc6d36c9 1790 trace_block_plug(q);
3540d5e8 1791 else {
019ceb7d 1792 if (request_count >= BLK_MAX_REQUEST_COUNT) {
3540d5e8 1793 blk_flush_plug_list(plug, false);
019ceb7d
SL
1794 trace_block_plug(q);
1795 }
73c10101 1796 }
73c10101 1797 list_add_tail(&req->queuelist, &plug->list);
320ae51f 1798 blk_account_io_start(req, true);
73c10101
JA
1799 } else {
1800 spin_lock_irq(q->queue_lock);
1801 add_acct_request(q, req, where);
24ecfbe2 1802 __blk_run_queue(q);
73c10101
JA
1803out_unlock:
1804 spin_unlock_irq(q->queue_lock);
1805 }
dece1635
JA
1806
1807 return BLK_QC_T_NONE;
1da177e4
LT
1808}
1809
1810/*
1811 * If bio->bi_dev is a partition, remap the location
1812 */
1813static inline void blk_partition_remap(struct bio *bio)
1814{
1815 struct block_device *bdev = bio->bi_bdev;
1816
bf2de6f5 1817 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1da177e4
LT
1818 struct hd_struct *p = bdev->bd_part;
1819
4f024f37 1820 bio->bi_iter.bi_sector += p->start_sect;
1da177e4 1821 bio->bi_bdev = bdev->bd_contains;
c7149d6b 1822
d07335e5
MS
1823 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1824 bdev->bd_dev,
4f024f37 1825 bio->bi_iter.bi_sector - p->start_sect);
1da177e4
LT
1826 }
1827}
1828
1da177e4
LT
1829static void handle_bad_sector(struct bio *bio)
1830{
1831 char b[BDEVNAME_SIZE];
1832
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),
1836 bio->bi_rw,
f73a1c7d 1837 (unsigned long long)bio_end_sector(bio),
77304d2a 1838 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1da177e4
LT
1839}
1840
c17bb495
AM
1841#ifdef CONFIG_FAIL_MAKE_REQUEST
1842
1843static DECLARE_FAULT_ATTR(fail_make_request);
1844
1845static int __init setup_fail_make_request(char *str)
1846{
1847 return setup_fault_attr(&fail_make_request, str);
1848}
1849__setup("fail_make_request=", setup_fail_make_request);
1850
b2c9cd37 1851static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
c17bb495 1852{
b2c9cd37 1853 return part->make_it_fail && should_fail(&fail_make_request, bytes);
c17bb495
AM
1854}
1855
1856static int __init fail_make_request_debugfs(void)
1857{
dd48c085
AM
1858 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1859 NULL, &fail_make_request);
1860
21f9fcd8 1861 return PTR_ERR_OR_ZERO(dir);
c17bb495
AM
1862}
1863
1864late_initcall(fail_make_request_debugfs);
1865
1866#else /* CONFIG_FAIL_MAKE_REQUEST */
1867
b2c9cd37
AM
1868static inline bool should_fail_request(struct hd_struct *part,
1869 unsigned int bytes)
c17bb495 1870{
b2c9cd37 1871 return false;
c17bb495
AM
1872}
1873
1874#endif /* CONFIG_FAIL_MAKE_REQUEST */
1875
c07e2b41
JA
1876/*
1877 * Check whether this bio extends beyond the end of the device.
1878 */
1879static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1880{
1881 sector_t maxsector;
1882
1883 if (!nr_sectors)
1884 return 0;
1885
1886 /* Test device or partition size, when known. */
77304d2a 1887 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
c07e2b41 1888 if (maxsector) {
4f024f37 1889 sector_t sector = bio->bi_iter.bi_sector;
c07e2b41
JA
1890
1891 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1892 /*
1893 * This may well happen - the kernel calls bread()
1894 * without checking the size of the device, e.g., when
1895 * mounting a device.
1896 */
1897 handle_bad_sector(bio);
1898 return 1;
1899 }
1900 }
1901
1902 return 0;
1903}
1904
27a84d54
CH
1905static noinline_for_stack bool
1906generic_make_request_checks(struct bio *bio)
1da177e4 1907{
165125e1 1908 struct request_queue *q;
5a7bbad2 1909 int nr_sectors = bio_sectors(bio);
51fd77bd 1910 int err = -EIO;
5a7bbad2
CH
1911 char b[BDEVNAME_SIZE];
1912 struct hd_struct *part;
1da177e4
LT
1913
1914 might_sleep();
1da177e4 1915
c07e2b41
JA
1916 if (bio_check_eod(bio, nr_sectors))
1917 goto end_io;
1da177e4 1918
5a7bbad2
CH
1919 q = bdev_get_queue(bio->bi_bdev);
1920 if (unlikely(!q)) {
1921 printk(KERN_ERR
1922 "generic_make_request: Trying to access "
1923 "nonexistent block-device %s (%Lu)\n",
1924 bdevname(bio->bi_bdev, b),
4f024f37 1925 (long long) bio->bi_iter.bi_sector);
5a7bbad2
CH
1926 goto end_io;
1927 }
c17bb495 1928
5a7bbad2 1929 part = bio->bi_bdev->bd_part;
4f024f37 1930 if (should_fail_request(part, bio->bi_iter.bi_size) ||
5a7bbad2 1931 should_fail_request(&part_to_disk(part)->part0,
4f024f37 1932 bio->bi_iter.bi_size))
5a7bbad2 1933 goto end_io;
2056a782 1934
5a7bbad2
CH
1935 /*
1936 * If this device has partitions, remap block n
1937 * of partition p to block n+start(p) of the disk.
1938 */
1939 blk_partition_remap(bio);
2056a782 1940
5a7bbad2
CH
1941 if (bio_check_eod(bio, nr_sectors))
1942 goto end_io;
1e87901e 1943
5a7bbad2
CH
1944 /*
1945 * Filter flush bio's early so that make_request based
1946 * drivers without flush support don't have to worry
1947 * about them.
1948 */
1949 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1950 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1951 if (!nr_sectors) {
1952 err = 0;
51fd77bd
JA
1953 goto end_io;
1954 }
5a7bbad2 1955 }
5ddfe969 1956
5a7bbad2
CH
1957 if ((bio->bi_rw & REQ_DISCARD) &&
1958 (!blk_queue_discard(q) ||
e2a60da7 1959 ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
5a7bbad2
CH
1960 err = -EOPNOTSUPP;
1961 goto end_io;
1962 }
01edede4 1963
4363ac7c 1964 if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
5a7bbad2
CH
1965 err = -EOPNOTSUPP;
1966 goto end_io;
1967 }
01edede4 1968
7f4b35d1
TH
1969 /*
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.
1974 */
1975 create_io_context(GFP_ATOMIC, q->node);
1976
ae118896
TH
1977 if (!blkcg_bio_issue_check(q, bio))
1978 return false;
27a84d54 1979
5a7bbad2 1980 trace_block_bio_queue(q, bio);
27a84d54 1981 return true;
a7384677
TH
1982
1983end_io:
4246a0b6
CH
1984 bio->bi_error = err;
1985 bio_endio(bio);
27a84d54 1986 return false;
1da177e4
LT
1987}
1988
27a84d54
CH
1989/**
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.
1992 *
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
1995 * to be done.
1996 *
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.
2001 *
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.
2007 *
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.
d89d8796 2012 */
dece1635 2013blk_qc_t generic_make_request(struct bio *bio)
d89d8796 2014{
0adeb9aa
N
2015 /*
2016 * bio_list_on_stack[0] contains bios submitted by the current
2017 * make_request_fn.
2018 * bio_list_on_stack[1] contains bios that were submitted before
2019 * the current make_request_fn, but that haven't been processed
2020 * yet.
2021 */
2022 struct bio_list bio_list_on_stack[2];
dece1635 2023 blk_qc_t ret = BLK_QC_T_NONE;
bddd87c7 2024
27a84d54 2025 if (!generic_make_request_checks(bio))
dece1635 2026 goto out;
27a84d54
CH
2027
2028 /*
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
2037 */
bddd87c7 2038 if (current->bio_list) {
0adeb9aa 2039 bio_list_add(&current->bio_list[0], bio);
dece1635 2040 goto out;
d89d8796 2041 }
27a84d54 2042
d89d8796
NB
2043 /* following loop may be a bit non-obvious, and so deserves some
2044 * explanation.
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
bddd87c7
AM
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
27a84d54 2050 * added. ->make_request() may indeed add some more bios
d89d8796
NB
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
bddd87c7 2054 * of the top of the list (no pretending) and so remove it from
27a84d54 2055 * bio_list, and call into ->make_request() again.
d89d8796
NB
2056 */
2057 BUG_ON(bio->bi_next);
0adeb9aa
N
2058 bio_list_init(&bio_list_on_stack[0]);
2059 current->bio_list = bio_list_on_stack;
d89d8796 2060 do {
27a84d54
CH
2061 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2062
3c92db6a 2063 if (likely(blk_queue_enter(q, false) == 0)) {
0adeb9aa 2064 struct bio_list lower, same;
edc89b19
N
2065
2066 /* Create a fresh bio_list for all subordinate requests */
0adeb9aa
N
2067 bio_list_on_stack[1] = bio_list_on_stack[0];
2068 bio_list_init(&bio_list_on_stack[0]);
edc89b19 2069
dece1635 2070 ret = q->make_request_fn(q, bio);
3ef28e83
DW
2071
2072 blk_queue_exit(q);
27a84d54 2073
edc89b19
N
2074 /* sort new bios into those for a lower level
2075 * and those for the same level
2076 */
2077 bio_list_init(&lower);
2078 bio_list_init(&same);
0adeb9aa 2079 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
edc89b19
N
2080 if (q == bdev_get_queue(bio->bi_bdev))
2081 bio_list_add(&same, bio);
2082 else
2083 bio_list_add(&lower, bio);
2084 /* now assemble so we handle the lowest level first */
0adeb9aa
N
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]);
3ef28e83 2088 } else {
3ef28e83 2089 bio_io_error(bio);
3ef28e83 2090 }
0adeb9aa 2091 bio = bio_list_pop(&bio_list_on_stack[0]);
d89d8796 2092 } while (bio);
bddd87c7 2093 current->bio_list = NULL; /* deactivate */
dece1635
JA
2094
2095out:
2096 return ret;
d89d8796 2097}
1da177e4
LT
2098EXPORT_SYMBOL(generic_make_request);
2099
2100/**
710027a4 2101 * submit_bio - submit a bio to the block device layer for I/O
1da177e4
LT
2102 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2103 * @bio: The &struct bio which describes the I/O
2104 *
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
710027a4 2107 * interfaces; @bio must be presetup and ready for I/O.
1da177e4
LT
2108 *
2109 */
dece1635 2110blk_qc_t submit_bio(int rw, struct bio *bio)
1da177e4 2111{
22e2c507 2112 bio->bi_rw |= rw;
1da177e4 2113
bf2de6f5
JA
2114 /*
2115 * If it's a regular read/write or a barrier with data attached,
2116 * go through the normal accounting stuff before submission.
2117 */
e2a60da7 2118 if (bio_has_data(bio)) {
4363ac7c
MP
2119 unsigned int count;
2120
2121 if (unlikely(rw & REQ_WRITE_SAME))
2122 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2123 else
2124 count = bio_sectors(bio);
2125
bf2de6f5
JA
2126 if (rw & WRITE) {
2127 count_vm_events(PGPGOUT, count);
2128 } else {
4f024f37 2129 task_io_account_read(bio->bi_iter.bi_size);
bf2de6f5
JA
2130 count_vm_events(PGPGIN, count);
2131 }
2132
2133 if (unlikely(block_dump)) {
2134 char b[BDEVNAME_SIZE];
8dcbdc74 2135 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
ba25f9dc 2136 current->comm, task_pid_nr(current),
bf2de6f5 2137 (rw & WRITE) ? "WRITE" : "READ",
4f024f37 2138 (unsigned long long)bio->bi_iter.bi_sector,
8dcbdc74
SM
2139 bdevname(bio->bi_bdev, b),
2140 count);
bf2de6f5 2141 }
1da177e4
LT
2142 }
2143
dece1635 2144 return generic_make_request(bio);
1da177e4 2145}
1da177e4
LT
2146EXPORT_SYMBOL(submit_bio);
2147
82124d60 2148/**
bf4e6b4e
HR
2149 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2150 * for new the queue limits
82124d60
KU
2151 * @q: the queue
2152 * @rq: the request being checked
2153 *
2154 * Description:
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.
2160 *
82124d60 2161 * Request stacking drivers like request-based dm may change the queue
bf4e6b4e
HR
2162 * limits when retrying requests on other queues. Those requests need
2163 * to be checked against the new queue limits again during dispatch.
82124d60 2164 */
bf4e6b4e
HR
2165static int blk_cloned_rq_check_limits(struct request_queue *q,
2166 struct request *rq)
82124d60 2167{
f31dc1cd 2168 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
82124d60
KU
2169 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2170 return -EIO;
2171 }
2172
2173 /*
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
2177 * limitation.
2178 */
2179 blk_recalc_rq_segments(rq);
8a78362c 2180 if (rq->nr_phys_segments > queue_max_segments(q)) {
82124d60
KU
2181 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2182 return -EIO;
2183 }
2184
2185 return 0;
2186}
82124d60
KU
2187
2188/**
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
2192 */
2193int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2194{
2195 unsigned long flags;
4853abaa 2196 int where = ELEVATOR_INSERT_BACK;
82124d60 2197
bf4e6b4e 2198 if (blk_cloned_rq_check_limits(q, rq))
82124d60
KU
2199 return -EIO;
2200
b2c9cd37
AM
2201 if (rq->rq_disk &&
2202 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
82124d60 2203 return -EIO;
82124d60 2204
7fb4898e
KB
2205 if (q->mq_ops) {
2206 if (blk_queue_io_stat(q))
2207 blk_account_io_start(rq, true);
4328241d 2208 blk_mq_insert_request(rq, false, true, false);
7fb4898e
KB
2209 return 0;
2210 }
2211
82124d60 2212 spin_lock_irqsave(q->queue_lock, flags);
3f3299d5 2213 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
2214 spin_unlock_irqrestore(q->queue_lock, flags);
2215 return -ENODEV;
2216 }
82124d60
KU
2217
2218 /*
2219 * Submitting request must be dequeued before calling this function
2220 * because it will be linked to another request_queue
2221 */
2222 BUG_ON(blk_queued_rq(rq));
2223
4853abaa
JM
2224 if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
2225 where = ELEVATOR_INSERT_FLUSH;
2226
2227 add_acct_request(q, rq, where);
e67b77c7
JM
2228 if (where == ELEVATOR_INSERT_FLUSH)
2229 __blk_run_queue(q);
82124d60
KU
2230 spin_unlock_irqrestore(q->queue_lock, flags);
2231
2232 return 0;
2233}
2234EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2235
80a761fd
TH
2236/**
2237 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2238 * @rq: request to examine
2239 *
2240 * Description:
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.
2245 *
2246 * Return:
2247 * The number of bytes to fail.
2248 *
2249 * Context:
2250 * queue_lock must be held.
2251 */
2252unsigned int blk_rq_err_bytes(const struct request *rq)
2253{
2254 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2255 unsigned int bytes = 0;
2256 struct bio *bio;
2257
2258 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2259 return blk_rq_bytes(rq);
2260
2261 /*
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
2266 * one.
2267 */
2268 for (bio = rq->bio; bio; bio = bio->bi_next) {
2269 if ((bio->bi_rw & ff) != ff)
2270 break;
4f024f37 2271 bytes += bio->bi_iter.bi_size;
80a761fd
TH
2272 }
2273
2274 /* this could lead to infinite loop */
2275 BUG_ON(blk_rq_bytes(rq) && !bytes);
2276 return bytes;
2277}
2278EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2279
320ae51f 2280void blk_account_io_completion(struct request *req, unsigned int bytes)
bc58ba94 2281{
c2553b58 2282 if (blk_do_io_stat(req)) {
bc58ba94
JA
2283 const int rw = rq_data_dir(req);
2284 struct hd_struct *part;
2285 int cpu;
2286
2287 cpu = part_stat_lock();
09e099d4 2288 part = req->part;
bc58ba94
JA
2289 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2290 part_stat_unlock();
2291 }
2292}
2293
320ae51f 2294void blk_account_io_done(struct request *req)
bc58ba94 2295{
bc58ba94 2296 /*
dd4c133f
TH
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.
bc58ba94 2300 */
414b4ff5 2301 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
bc58ba94
JA
2302 unsigned long duration = jiffies - req->start_time;
2303 const int rw = rq_data_dir(req);
2304 struct hd_struct *part;
2305 int cpu;
2306
2307 cpu = part_stat_lock();
09e099d4 2308 part = req->part;
bc58ba94
JA
2309
2310 part_stat_inc(cpu, part, ios[rw]);
2311 part_stat_add(cpu, part, ticks[rw], duration);
2312 part_round_stats(cpu, part);
316d315b 2313 part_dec_in_flight(part, rw);
bc58ba94 2314
6c23a968 2315 hd_struct_put(part);
bc58ba94
JA
2316 part_stat_unlock();
2317 }
2318}
2319
47fafbc7 2320#ifdef CONFIG_PM
c8158819
LM
2321/*
2322 * Don't process normal requests when queue is suspended
2323 * or in the process of suspending/resuming
2324 */
2325static struct request *blk_pm_peek_request(struct request_queue *q,
2326 struct request *rq)
2327{
2328 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2329 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2330 return NULL;
2331 else
2332 return rq;
2333}
2334#else
2335static inline struct request *blk_pm_peek_request(struct request_queue *q,
2336 struct request *rq)
2337{
2338 return rq;
2339}
2340#endif
2341
320ae51f
JA
2342void blk_account_io_start(struct request *rq, bool new_io)
2343{
2344 struct hd_struct *part;
2345 int rw = rq_data_dir(rq);
2346 int cpu;
2347
2348 if (!blk_do_io_stat(rq))
2349 return;
2350
2351 cpu = part_stat_lock();
2352
2353 if (!new_io) {
2354 part = rq->part;
2355 part_stat_inc(cpu, part, merges[rw]);
2356 } else {
2357 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2358 if (!hd_struct_try_get(part)) {
2359 /*
2360 * The partition is already being removed,
2361 * the request will be accounted on the disk only
2362 *
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.
2366 */
2367 part = &rq->rq_disk->part0;
2368 hd_struct_get(part);
2369 }
2370 part_round_stats(cpu, part);
2371 part_inc_in_flight(part, rw);
2372 rq->part = part;
2373 }
2374
2375 part_stat_unlock();
2376}
2377
3bcddeac 2378/**
9934c8c0
TH
2379 * blk_peek_request - peek at the top of a request queue
2380 * @q: request queue to peek at
2381 *
2382 * Description:
2383 * Return the request at the top of @q. The returned request
2384 * should be started using blk_start_request() before LLD starts
2385 * processing it.
2386 *
2387 * Return:
2388 * Pointer to the request at the top of @q if available. Null
2389 * otherwise.
2390 *
2391 * Context:
2392 * queue_lock must be held.
2393 */
2394struct request *blk_peek_request(struct request_queue *q)
158dbda0
TH
2395{
2396 struct request *rq;
2397 int ret;
2398
2399 while ((rq = __elv_next_request(q)) != NULL) {
c8158819
LM
2400
2401 rq = blk_pm_peek_request(q, rq);
2402 if (!rq)
2403 break;
2404
158dbda0
TH
2405 if (!(rq->cmd_flags & REQ_STARTED)) {
2406 /*
2407 * This is the first time the device driver
2408 * sees this request (possibly after
2409 * requeueing). Notify IO scheduler.
2410 */
33659ebb 2411 if (rq->cmd_flags & REQ_SORTED)
158dbda0
TH
2412 elv_activate_rq(q, rq);
2413
2414 /*
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
2418 */
2419 rq->cmd_flags |= REQ_STARTED;
2420 trace_block_rq_issue(q, rq);
2421 }
2422
2423 if (!q->boundary_rq || q->boundary_rq == rq) {
2424 q->end_sector = rq_end_sector(rq);
2425 q->boundary_rq = NULL;
2426 }
2427
2428 if (rq->cmd_flags & REQ_DONTPREP)
2429 break;
2430
2e46e8b2 2431 if (q->dma_drain_size && blk_rq_bytes(rq)) {
158dbda0
TH
2432 /*
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
2436 * device can handle
2437 */
2438 rq->nr_phys_segments++;
2439 }
2440
2441 if (!q->prep_rq_fn)
2442 break;
2443
2444 ret = q->prep_rq_fn(q, rq);
2445 if (ret == BLKPREP_OK) {
2446 break;
2447 } else if (ret == BLKPREP_DEFER) {
2448 /*
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.
2453 */
2e46e8b2 2454 if (q->dma_drain_size && blk_rq_bytes(rq) &&
158dbda0
TH
2455 !(rq->cmd_flags & REQ_DONTPREP)) {
2456 /*
2457 * remove the space for the drain we added
2458 * so that we don't add it again
2459 */
2460 --rq->nr_phys_segments;
2461 }
2462
2463 rq = NULL;
2464 break;
2465 } else if (ret == BLKPREP_KILL) {
2466 rq->cmd_flags |= REQ_QUIET;
c143dc90
JB
2467 /*
2468 * Mark this request as started so we don't trigger
2469 * any debug logic in the end I/O path.
2470 */
2471 blk_start_request(rq);
40cbbb78 2472 __blk_end_request_all(rq, -EIO);
158dbda0
TH
2473 } else {
2474 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2475 break;
2476 }
2477 }
2478
2479 return rq;
2480}
9934c8c0 2481EXPORT_SYMBOL(blk_peek_request);
158dbda0 2482
9934c8c0 2483void blk_dequeue_request(struct request *rq)
158dbda0 2484{
9934c8c0
TH
2485 struct request_queue *q = rq->q;
2486
158dbda0
TH
2487 BUG_ON(list_empty(&rq->queuelist));
2488 BUG_ON(ELV_ON_HASH(rq));
2489
2490 list_del_init(&rq->queuelist);
2491
2492 /*
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
2495 * the driver side.
2496 */
9195291e 2497 if (blk_account_rq(rq)) {
0a7ae2ff 2498 q->in_flight[rq_is_sync(rq)]++;
9195291e
DS
2499 set_io_start_time_ns(rq);
2500 }
158dbda0
TH
2501}
2502
9934c8c0
TH
2503/**
2504 * blk_start_request - start request processing on the driver
2505 * @req: request to dequeue
2506 *
2507 * Description:
2508 * Dequeue @req and start timeout timer on it. This hands off the
2509 * request to the driver.
2510 *
2511 * Block internal functions which don't want to start timer should
2512 * call blk_dequeue_request().
2513 *
2514 * Context:
2515 * queue_lock must be held.
2516 */
2517void blk_start_request(struct request *req)
2518{
2519 blk_dequeue_request(req);
2520
2521 /*
5f49f631
TH
2522 * We are now handing the request to the hardware, initialize
2523 * resid_len to full count and add the timeout handler.
9934c8c0 2524 */
5f49f631 2525 req->resid_len = blk_rq_bytes(req);
dbb66c4b
FT
2526 if (unlikely(blk_bidi_rq(req)))
2527 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2528
4912aa6c 2529 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
9934c8c0
TH
2530 blk_add_timer(req);
2531}
2532EXPORT_SYMBOL(blk_start_request);
2533
2534/**
2535 * blk_fetch_request - fetch a request from a request queue
2536 * @q: request queue to fetch a request from
2537 *
2538 * Description:
2539 * Return the request at the top of @q. The request is started on
2540 * return and LLD can start processing it immediately.
2541 *
2542 * Return:
2543 * Pointer to the request at the top of @q if available. Null
2544 * otherwise.
2545 *
2546 * Context:
2547 * queue_lock must be held.
2548 */
2549struct request *blk_fetch_request(struct request_queue *q)
2550{
2551 struct request *rq;
2552
2553 rq = blk_peek_request(q);
2554 if (rq)
2555 blk_start_request(rq);
2556 return rq;
2557}
2558EXPORT_SYMBOL(blk_fetch_request);
2559
3bcddeac 2560/**
2e60e022 2561 * blk_update_request - Special helper function for request stacking drivers
8ebf9756 2562 * @req: the request being processed
710027a4 2563 * @error: %0 for success, < %0 for error
8ebf9756 2564 * @nr_bytes: number of bytes to complete @req
3bcddeac
KU
2565 *
2566 * Description:
8ebf9756
RD
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.
2e60e022
TH
2570 *
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.
2574 *
2575 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2576 * %false return from this function.
3bcddeac
KU
2577 *
2578 * Return:
2e60e022
TH
2579 * %false - this request doesn't have any more data
2580 * %true - this request has more data
3bcddeac 2581 **/
2e60e022 2582bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
1da177e4 2583{
f79ea416 2584 int total_bytes;
1da177e4 2585
4a0efdc9
HR
2586 trace_block_rq_complete(req->q, req, nr_bytes);
2587
2e60e022
TH
2588 if (!req->bio)
2589 return false;
2590
1da177e4 2591 /*
6f41469c
TH
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.
2595 *
2596 * TODO: tj: This is too subtle. It would be better to let
2597 * low level drivers do what they see fit.
1da177e4 2598 */
33659ebb 2599 if (req->cmd_type == REQ_TYPE_FS)
1da177e4
LT
2600 req->errors = 0;
2601
33659ebb
CH
2602 if (error && req->cmd_type == REQ_TYPE_FS &&
2603 !(req->cmd_flags & REQ_QUIET)) {
79775567
HR
2604 char *error_type;
2605
2606 switch (error) {
2607 case -ENOLINK:
2608 error_type = "recoverable transport";
2609 break;
2610 case -EREMOTEIO:
2611 error_type = "critical target";
2612 break;
2613 case -EBADE:
2614 error_type = "critical nexus";
2615 break;
d1ffc1f8
HR
2616 case -ETIMEDOUT:
2617 error_type = "timeout";
2618 break;
a9d6ceb8
HR
2619 case -ENOSPC:
2620 error_type = "critical space allocation";
2621 break;
7e782af5
HR
2622 case -ENODATA:
2623 error_type = "critical medium";
2624 break;
79775567
HR
2625 case -EIO:
2626 default:
2627 error_type = "I/O";
2628 break;
2629 }
ef3ecb66
RE
2630 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2631 __func__, error_type, req->rq_disk ?
37d7b34f
YZ
2632 req->rq_disk->disk_name : "?",
2633 (unsigned long long)blk_rq_pos(req));
2634
1da177e4
LT
2635 }
2636
bc58ba94 2637 blk_account_io_completion(req, nr_bytes);
d72d904a 2638
f79ea416
KO
2639 total_bytes = 0;
2640 while (req->bio) {
2641 struct bio *bio = req->bio;
4f024f37 2642 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
1da177e4 2643
4f024f37 2644 if (bio_bytes == bio->bi_iter.bi_size)
1da177e4 2645 req->bio = bio->bi_next;
1da177e4 2646
f79ea416 2647 req_bio_endio(req, bio, bio_bytes, error);
1da177e4 2648
f79ea416
KO
2649 total_bytes += bio_bytes;
2650 nr_bytes -= bio_bytes;
1da177e4 2651
f79ea416
KO
2652 if (!nr_bytes)
2653 break;
1da177e4
LT
2654 }
2655
2656 /*
2657 * completely done
2658 */
2e60e022
TH
2659 if (!req->bio) {
2660 /*
2661 * Reset counters so that the request stacking driver
2662 * can find how many bytes remain in the request
2663 * later.
2664 */
a2dec7b3 2665 req->__data_len = 0;
2e60e022
TH
2666 return false;
2667 }
1da177e4 2668
a2dec7b3 2669 req->__data_len -= total_bytes;
2e46e8b2
TH
2670
2671 /* update sector only for requests with clear definition of sector */
e2a60da7 2672 if (req->cmd_type == REQ_TYPE_FS)
a2dec7b3 2673 req->__sector += total_bytes >> 9;
2e46e8b2 2674
80a761fd
TH
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;
2679 }
2680
2e46e8b2
TH
2681 /*
2682 * If total number of sectors is less than the first segment
2683 * size, something has gone terribly wrong.
2684 */
2685 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
8182924b 2686 blk_dump_rq_flags(req, "request botched");
a2dec7b3 2687 req->__data_len = blk_rq_cur_bytes(req);
2e46e8b2
TH
2688 }
2689
2690 /* recalculate the number of segments */
1da177e4 2691 blk_recalc_rq_segments(req);
2e46e8b2 2692
2e60e022 2693 return true;
1da177e4 2694}
2e60e022 2695EXPORT_SYMBOL_GPL(blk_update_request);
1da177e4 2696
2e60e022
TH
2697static bool blk_update_bidi_request(struct request *rq, int error,
2698 unsigned int nr_bytes,
2699 unsigned int bidi_bytes)
5efccd17 2700{
2e60e022
TH
2701 if (blk_update_request(rq, error, nr_bytes))
2702 return true;
5efccd17 2703
2e60e022
TH
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))
2707 return true;
5efccd17 2708
e2e1a148
JA
2709 if (blk_queue_add_random(rq->q))
2710 add_disk_randomness(rq->rq_disk);
2e60e022
TH
2711
2712 return false;
1da177e4
LT
2713}
2714
28018c24
JB
2715/**
2716 * blk_unprep_request - unprepare a request
2717 * @req: the request
2718 *
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.
2724 */
2725void blk_unprep_request(struct request *req)
2726{
2727 struct request_queue *q = req->q;
2728
2729 req->cmd_flags &= ~REQ_DONTPREP;
2730 if (q->unprep_rq_fn)
2731 q->unprep_rq_fn(q, req);
2732}
2733EXPORT_SYMBOL_GPL(blk_unprep_request);
2734
1da177e4
LT
2735/*
2736 * queue lock must be held
2737 */
12120077 2738void blk_finish_request(struct request *req, int error)
1da177e4 2739{
125c99bc 2740 if (req->cmd_flags & REQ_QUEUED)
b8286239
KU
2741 blk_queue_end_tag(req->q, req);
2742
ba396a6c 2743 BUG_ON(blk_queued_rq(req));
1da177e4 2744
33659ebb 2745 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
f53624d5 2746 laptop_io_completion(req->q->backing_dev_info);
1da177e4 2747
e78042e5
MA
2748 blk_delete_timer(req);
2749
28018c24
JB
2750 if (req->cmd_flags & REQ_DONTPREP)
2751 blk_unprep_request(req);
2752
bc58ba94 2753 blk_account_io_done(req);
b8286239 2754
1da177e4 2755 if (req->end_io)
8ffdc655 2756 req->end_io(req, error);
b8286239
KU
2757 else {
2758 if (blk_bidi_rq(req))
2759 __blk_put_request(req->next_rq->q, req->next_rq);
2760
1da177e4 2761 __blk_put_request(req->q, req);
b8286239 2762 }
1da177e4 2763}
12120077 2764EXPORT_SYMBOL(blk_finish_request);
1da177e4 2765
3b11313a 2766/**
2e60e022
TH
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
a0cd1285
JA
2772 *
2773 * Description:
e3a04fe3 2774 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2e60e022
TH
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
2777 * just ignored.
336cdb40
KU
2778 *
2779 * Return:
2e60e022
TH
2780 * %false - we are done with this request
2781 * %true - still buffers pending for this request
a0cd1285 2782 **/
b1f74493 2783static bool blk_end_bidi_request(struct request *rq, int error,
32fab448
KU
2784 unsigned int nr_bytes, unsigned int bidi_bytes)
2785{
336cdb40 2786 struct request_queue *q = rq->q;
2e60e022 2787 unsigned long flags;
32fab448 2788
2e60e022
TH
2789 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2790 return true;
32fab448 2791
336cdb40 2792 spin_lock_irqsave(q->queue_lock, flags);
2e60e022 2793 blk_finish_request(rq, error);
336cdb40
KU
2794 spin_unlock_irqrestore(q->queue_lock, flags);
2795
2e60e022 2796 return false;
32fab448
KU
2797}
2798
336cdb40 2799/**
2e60e022
TH
2800 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2801 * @rq: the request to complete
710027a4 2802 * @error: %0 for success, < %0 for error
e3a04fe3
KU
2803 * @nr_bytes: number of bytes to complete @rq
2804 * @bidi_bytes: number of bytes to complete @rq->next_rq
336cdb40
KU
2805 *
2806 * Description:
2e60e022
TH
2807 * Identical to blk_end_bidi_request() except that queue lock is
2808 * assumed to be locked on entry and remains so on return.
336cdb40
KU
2809 *
2810 * Return:
2e60e022
TH
2811 * %false - we are done with this request
2812 * %true - still buffers pending for this request
336cdb40 2813 **/
4853abaa 2814bool __blk_end_bidi_request(struct request *rq, int error,
b1f74493 2815 unsigned int nr_bytes, unsigned int bidi_bytes)
336cdb40 2816{
2e60e022
TH
2817 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2818 return true;
336cdb40 2819
2e60e022 2820 blk_finish_request(rq, error);
336cdb40 2821
2e60e022 2822 return false;
336cdb40 2823}
e19a3ab0
KU
2824
2825/**
2826 * blk_end_request - Helper function for drivers to complete the request.
2827 * @rq: the request being processed
710027a4 2828 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2829 * @nr_bytes: number of bytes to complete
2830 *
2831 * Description:
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.
2834 *
2835 * Return:
b1f74493
FT
2836 * %false - we are done with this request
2837 * %true - still buffers pending for this request
e19a3ab0 2838 **/
b1f74493 2839bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e19a3ab0 2840{
b1f74493 2841 return blk_end_bidi_request(rq, error, nr_bytes, 0);
e19a3ab0 2842}
56ad1740 2843EXPORT_SYMBOL(blk_end_request);
336cdb40
KU
2844
2845/**
b1f74493
FT
2846 * blk_end_request_all - Helper function for drives to finish the request.
2847 * @rq: the request to finish
8ebf9756 2848 * @error: %0 for success, < %0 for error
336cdb40
KU
2849 *
2850 * Description:
b1f74493
FT
2851 * Completely finish @rq.
2852 */
2853void blk_end_request_all(struct request *rq, int error)
336cdb40 2854{
b1f74493
FT
2855 bool pending;
2856 unsigned int bidi_bytes = 0;
336cdb40 2857
b1f74493
FT
2858 if (unlikely(blk_bidi_rq(rq)))
2859 bidi_bytes = blk_rq_bytes(rq->next_rq);
336cdb40 2860
b1f74493
FT
2861 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2862 BUG_ON(pending);
2863}
56ad1740 2864EXPORT_SYMBOL(blk_end_request_all);
336cdb40 2865
b1f74493
FT
2866/**
2867 * blk_end_request_cur - Helper function to finish the current request chunk.
2868 * @rq: the request to finish the current chunk for
8ebf9756 2869 * @error: %0 for success, < %0 for error
b1f74493
FT
2870 *
2871 * Description:
2872 * Complete the current consecutively mapped chunk from @rq.
2873 *
2874 * Return:
2875 * %false - we are done with this request
2876 * %true - still buffers pending for this request
2877 */
2878bool blk_end_request_cur(struct request *rq, int error)
2879{
2880 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
336cdb40 2881}
56ad1740 2882EXPORT_SYMBOL(blk_end_request_cur);
336cdb40 2883
80a761fd
TH
2884/**
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
2888 *
2889 * Description:
2890 * Complete @rq till the next failure boundary.
2891 *
2892 * Return:
2893 * %false - we are done with this request
2894 * %true - still buffers pending for this request
2895 */
2896bool blk_end_request_err(struct request *rq, int error)
2897{
2898 WARN_ON(error >= 0);
2899 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2900}
2901EXPORT_SYMBOL_GPL(blk_end_request_err);
2902
e3a04fe3 2903/**
b1f74493
FT
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
e3a04fe3
KU
2908 *
2909 * Description:
b1f74493 2910 * Must be called with queue lock held unlike blk_end_request().
e3a04fe3
KU
2911 *
2912 * Return:
b1f74493
FT
2913 * %false - we are done with this request
2914 * %true - still buffers pending for this request
e3a04fe3 2915 **/
b1f74493 2916bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e3a04fe3 2917{
b1f74493 2918 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
e3a04fe3 2919}
56ad1740 2920EXPORT_SYMBOL(__blk_end_request);
e3a04fe3 2921
32fab448 2922/**
b1f74493
FT
2923 * __blk_end_request_all - Helper function for drives to finish the request.
2924 * @rq: the request to finish
8ebf9756 2925 * @error: %0 for success, < %0 for error
32fab448
KU
2926 *
2927 * Description:
b1f74493 2928 * Completely finish @rq. Must be called with queue lock held.
32fab448 2929 */
b1f74493 2930void __blk_end_request_all(struct request *rq, int error)
32fab448 2931{
b1f74493
FT
2932 bool pending;
2933 unsigned int bidi_bytes = 0;
2934
2935 if (unlikely(blk_bidi_rq(rq)))
2936 bidi_bytes = blk_rq_bytes(rq->next_rq);
2937
2938 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2939 BUG_ON(pending);
32fab448 2940}
56ad1740 2941EXPORT_SYMBOL(__blk_end_request_all);
32fab448 2942
e19a3ab0 2943/**
b1f74493
FT
2944 * __blk_end_request_cur - Helper function to finish the current request chunk.
2945 * @rq: the request to finish the current chunk for
8ebf9756 2946 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2947 *
2948 * Description:
b1f74493
FT
2949 * Complete the current consecutively mapped chunk from @rq. Must
2950 * be called with queue lock held.
e19a3ab0
KU
2951 *
2952 * Return:
b1f74493
FT
2953 * %false - we are done with this request
2954 * %true - still buffers pending for this request
2955 */
2956bool __blk_end_request_cur(struct request *rq, int error)
e19a3ab0 2957{
b1f74493 2958 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
e19a3ab0 2959}
56ad1740 2960EXPORT_SYMBOL(__blk_end_request_cur);
e19a3ab0 2961
80a761fd
TH
2962/**
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
2966 *
2967 * Description:
2968 * Complete @rq till the next failure boundary. Must be called
2969 * with queue lock held.
2970 *
2971 * Return:
2972 * %false - we are done with this request
2973 * %true - still buffers pending for this request
2974 */
2975bool __blk_end_request_err(struct request *rq, int error)
2976{
2977 WARN_ON(error >= 0);
2978 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2979}
2980EXPORT_SYMBOL_GPL(__blk_end_request_err);
2981
86db1e29
JA
2982void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2983 struct bio *bio)
1da177e4 2984{
a82afdfc 2985 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
7b6d91da 2986 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
1da177e4 2987
b4f42e28 2988 if (bio_has_data(bio))
fb2dce86 2989 rq->nr_phys_segments = bio_phys_segments(q, bio);
b4f42e28 2990
4f024f37 2991 rq->__data_len = bio->bi_iter.bi_size;
1da177e4 2992 rq->bio = rq->biotail = bio;
1da177e4 2993
66846572
N
2994 if (bio->bi_bdev)
2995 rq->rq_disk = bio->bi_bdev->bd_disk;
2996}
1da177e4 2997
2d4dc890
IL
2998#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2999/**
3000 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3001 * @rq: the request to be flushed
3002 *
3003 * Description:
3004 * Flush all pages in @rq.
3005 */
3006void rq_flush_dcache_pages(struct request *rq)
3007{
3008 struct req_iterator iter;
7988613b 3009 struct bio_vec bvec;
2d4dc890
IL
3010
3011 rq_for_each_segment(bvec, rq, iter)
7988613b 3012 flush_dcache_page(bvec.bv_page);
2d4dc890
IL
3013}
3014EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3015#endif
3016
ef9e3fac
KU
3017/**
3018 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3019 * @q : the queue of the device being checked
3020 *
3021 * Description:
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.
3025 *
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.
3031 *
3032 * Return:
3033 * 0 - Not busy (The request stacking driver should dispatch request)
3034 * 1 - Busy (The request stacking driver should stop dispatching request)
3035 */
3036int blk_lld_busy(struct request_queue *q)
3037{
3038 if (q->lld_busy_fn)
3039 return q->lld_busy_fn(q);
3040
3041 return 0;
3042}
3043EXPORT_SYMBOL_GPL(blk_lld_busy);
3044
78d8e58a
MS
3045/**
3046 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3047 * @rq: the clone request to be cleaned up
3048 *
3049 * Description:
3050 * Free all bios in @rq for a cloned request.
3051 */
3052void blk_rq_unprep_clone(struct request *rq)
3053{
3054 struct bio *bio;
3055
3056 while ((bio = rq->bio) != NULL) {
3057 rq->bio = bio->bi_next;
3058
3059 bio_put(bio);
3060 }
3061}
3062EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3063
3064/*
3065 * Copy attributes of the original request to the clone request.
3066 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3067 */
3068static void __blk_rq_prep_clone(struct request *dst, struct request *src)
b0fd271d
KU
3069{
3070 dst->cpu = src->cpu;
78d8e58a 3071 dst->cmd_flags |= (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
b0fd271d
KU
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;
78d8e58a
MS
3078}
3079
3080/**
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
3089 *
3090 * Description:
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.
3098 */
3099int 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 *),
3102 void *data)
3103{
3104 struct bio *bio, *bio_src;
3105
3106 if (!bs)
3107 bs = fs_bio_set;
3108
3109 __rq_for_each_bio(bio_src, rq_src) {
3110 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3111 if (!bio)
3112 goto free_and_out;
3113
3114 if (bio_ctr && bio_ctr(bio, bio_src, data))
3115 goto free_and_out;
3116
3117 if (rq->bio) {
3118 rq->biotail->bi_next = bio;
3119 rq->biotail = bio;
3120 } else
3121 rq->bio = rq->biotail = bio;
3122 }
3123
3124 __blk_rq_prep_clone(rq, rq_src);
3125
3126 return 0;
3127
3128free_and_out:
3129 if (bio)
3130 bio_put(bio);
3131 blk_rq_unprep_clone(rq);
3132
3133 return -ENOMEM;
b0fd271d
KU
3134}
3135EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3136
59c3d45e 3137int kblockd_schedule_work(struct work_struct *work)
1da177e4
LT
3138{
3139 return queue_work(kblockd_workqueue, work);
3140}
1da177e4
LT
3141EXPORT_SYMBOL(kblockd_schedule_work);
3142
59c3d45e
JA
3143int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3144 unsigned long delay)
e43473b7
VG
3145{
3146 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3147}
3148EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3149
8ab14595
JA
3150int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3151 unsigned long delay)
3152{
3153 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3154}
3155EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3156
75df7136
SJ
3157/**
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
3160 *
3161 * Description:
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.
3170 */
73c10101
JA
3171void blk_start_plug(struct blk_plug *plug)
3172{
3173 struct task_struct *tsk = current;
3174
dd6cf3e1
SL
3175 /*
3176 * If this is a nested plug, don't actually assign it.
3177 */
3178 if (tsk->plug)
3179 return;
3180
73c10101 3181 INIT_LIST_HEAD(&plug->list);
320ae51f 3182 INIT_LIST_HEAD(&plug->mq_list);
048c9374 3183 INIT_LIST_HEAD(&plug->cb_list);
73c10101 3184 /*
dd6cf3e1
SL
3185 * Store ordering should not be needed here, since a potential
3186 * preempt will imply a full memory barrier
73c10101 3187 */
dd6cf3e1 3188 tsk->plug = plug;
73c10101
JA
3189}
3190EXPORT_SYMBOL(blk_start_plug);
3191
3192static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3193{
3194 struct request *rqa = container_of(a, struct request, queuelist);
3195 struct request *rqb = container_of(b, struct request, queuelist);
3196
975927b9
JM
3197 return !(rqa->q < rqb->q ||
3198 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
73c10101
JA
3199}
3200
49cac01e
JA
3201/*
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.
3206 */
f6603783 3207static void queue_unplugged(struct request_queue *q, unsigned int depth,
49cac01e 3208 bool from_schedule)
99e22598 3209 __releases(q->queue_lock)
94b5eb28 3210{
49cac01e 3211 trace_block_unplug(q, depth, !from_schedule);
99e22598 3212
70460571 3213 if (from_schedule)
24ecfbe2 3214 blk_run_queue_async(q);
70460571 3215 else
24ecfbe2 3216 __blk_run_queue(q);
70460571 3217 spin_unlock(q->queue_lock);
94b5eb28
JA
3218}
3219
74018dc3 3220static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
048c9374
N
3221{
3222 LIST_HEAD(callbacks);
3223
2a7d5559
SL
3224 while (!list_empty(&plug->cb_list)) {
3225 list_splice_init(&plug->cb_list, &callbacks);
048c9374 3226
2a7d5559
SL
3227 while (!list_empty(&callbacks)) {
3228 struct blk_plug_cb *cb = list_first_entry(&callbacks,
048c9374
N
3229 struct blk_plug_cb,
3230 list);
2a7d5559 3231 list_del(&cb->list);
74018dc3 3232 cb->callback(cb, from_schedule);
2a7d5559 3233 }
048c9374
N
3234 }
3235}
3236
9cbb1750
N
3237struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3238 int size)
3239{
3240 struct blk_plug *plug = current->plug;
3241 struct blk_plug_cb *cb;
3242
3243 if (!plug)
3244 return NULL;
3245
3246 list_for_each_entry(cb, &plug->cb_list, list)
3247 if (cb->callback == unplug && cb->data == data)
3248 return cb;
3249
3250 /* Not currently on the callback list */
3251 BUG_ON(size < sizeof(*cb));
3252 cb = kzalloc(size, GFP_ATOMIC);
3253 if (cb) {
3254 cb->data = data;
3255 cb->callback = unplug;
3256 list_add(&cb->list, &plug->cb_list);
3257 }
3258 return cb;
3259}
3260EXPORT_SYMBOL(blk_check_plugged);
3261
49cac01e 3262void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
73c10101
JA
3263{
3264 struct request_queue *q;
3265 unsigned long flags;
3266 struct request *rq;
109b8129 3267 LIST_HEAD(list);
94b5eb28 3268 unsigned int depth;
73c10101 3269
74018dc3 3270 flush_plug_callbacks(plug, from_schedule);
320ae51f
JA
3271
3272 if (!list_empty(&plug->mq_list))
3273 blk_mq_flush_plug_list(plug, from_schedule);
3274
73c10101
JA
3275 if (list_empty(&plug->list))
3276 return;
3277
109b8129
N
3278 list_splice_init(&plug->list, &list);
3279
422765c2 3280 list_sort(NULL, &list, plug_rq_cmp);
73c10101
JA
3281
3282 q = NULL;
94b5eb28 3283 depth = 0;
18811272
JA
3284
3285 /*
3286 * Save and disable interrupts here, to avoid doing it for every
3287 * queue lock we have to take.
3288 */
73c10101 3289 local_irq_save(flags);
109b8129
N
3290 while (!list_empty(&list)) {
3291 rq = list_entry_rq(list.next);
73c10101 3292 list_del_init(&rq->queuelist);
73c10101
JA
3293 BUG_ON(!rq->q);
3294 if (rq->q != q) {
99e22598
JA
3295 /*
3296 * This drops the queue lock
3297 */
3298 if (q)
49cac01e 3299 queue_unplugged(q, depth, from_schedule);
73c10101 3300 q = rq->q;
94b5eb28 3301 depth = 0;
73c10101
JA
3302 spin_lock(q->queue_lock);
3303 }
8ba61435
TH
3304
3305 /*
3306 * Short-circuit if @q is dead
3307 */
3f3299d5 3308 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
3309 __blk_end_request_all(rq, -ENODEV);
3310 continue;
3311 }
3312
73c10101
JA
3313 /*
3314 * rq is already accounted, so use raw insert
3315 */
401a18e9
JA
3316 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3317 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3318 else
3319 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
94b5eb28
JA
3320
3321 depth++;
73c10101
JA
3322 }
3323
99e22598
JA
3324 /*
3325 * This drops the queue lock
3326 */
3327 if (q)
49cac01e 3328 queue_unplugged(q, depth, from_schedule);
73c10101 3329
73c10101
JA
3330 local_irq_restore(flags);
3331}
73c10101
JA
3332
3333void blk_finish_plug(struct blk_plug *plug)
3334{
dd6cf3e1
SL
3335 if (plug != current->plug)
3336 return;
f6603783 3337 blk_flush_plug_list(plug, false);
73c10101 3338
dd6cf3e1 3339 current->plug = NULL;
73c10101 3340}
88b996cd 3341EXPORT_SYMBOL(blk_finish_plug);
73c10101 3342
05229bee
JA
3343bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3344{
3345 struct blk_plug *plug;
3346 long state;
3347
3348 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3349 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3350 return false;
3351
3352 plug = current->plug;
3353 if (plug)
3354 blk_flush_plug_list(plug, false);
3355
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];
3360 int ret;
3361
3362 hctx->poll_invoked++;
3363
3364 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3365 if (ret > 0) {
3366 hctx->poll_success++;
3367 set_current_state(TASK_RUNNING);
3368 return true;
3369 }
3370
3371 if (signal_pending_state(state, current))
3372 set_current_state(TASK_RUNNING);
3373
3374 if (current->state == TASK_RUNNING)
3375 return true;
3376 if (ret < 0)
3377 break;
3378 cpu_relax();
3379 }
3380
3381 return false;
3382}
3383
47fafbc7 3384#ifdef CONFIG_PM
6c954667
LM
3385/**
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
3389 *
3390 * Description:
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.
3397 *
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.
3402 *
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.
3405 */
3406void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3407{
3408 q->dev = dev;
3409 q->rpm_status = RPM_ACTIVE;
3410 pm_runtime_set_autosuspend_delay(q->dev, -1);
3411 pm_runtime_use_autosuspend(q->dev);
3412}
3413EXPORT_SYMBOL(blk_pm_runtime_init);
3414
3415/**
3416 * blk_pre_runtime_suspend - Pre runtime suspend check
3417 * @q: the queue of the device
3418 *
3419 * Description:
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.
3425 *
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.
3428 *
3429 * This function should be called near the start of the device's
3430 * runtime_suspend callback.
3431 *
3432 * Return:
3433 * 0 - OK to runtime suspend the device
3434 * -EBUSY - Device should not be runtime suspended
3435 */
3436int blk_pre_runtime_suspend(struct request_queue *q)
3437{
3438 int ret = 0;
3439
4fd41a85
KX
3440 if (!q->dev)
3441 return ret;
3442
6c954667
LM
3443 spin_lock_irq(q->queue_lock);
3444 if (q->nr_pending) {
3445 ret = -EBUSY;
3446 pm_runtime_mark_last_busy(q->dev);
3447 } else {
3448 q->rpm_status = RPM_SUSPENDING;
3449 }
3450 spin_unlock_irq(q->queue_lock);
3451 return ret;
3452}
3453EXPORT_SYMBOL(blk_pre_runtime_suspend);
3454
3455/**
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
3459 *
3460 * Description:
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.
3464 *
3465 * This function should be called near the end of the device's
3466 * runtime_suspend callback.
3467 */
3468void blk_post_runtime_suspend(struct request_queue *q, int err)
3469{
4fd41a85
KX
3470 if (!q->dev)
3471 return;
3472
6c954667
LM
3473 spin_lock_irq(q->queue_lock);
3474 if (!err) {
3475 q->rpm_status = RPM_SUSPENDED;
3476 } else {
3477 q->rpm_status = RPM_ACTIVE;
3478 pm_runtime_mark_last_busy(q->dev);
3479 }
3480 spin_unlock_irq(q->queue_lock);
3481}
3482EXPORT_SYMBOL(blk_post_runtime_suspend);
3483
3484/**
3485 * blk_pre_runtime_resume - Pre runtime resume processing
3486 * @q: the queue of the device
3487 *
3488 * Description:
3489 * Update the queue's runtime status to RESUMING in preparation for the
3490 * runtime resume of the device.
3491 *
3492 * This function should be called near the start of the device's
3493 * runtime_resume callback.
3494 */
3495void blk_pre_runtime_resume(struct request_queue *q)
3496{
4fd41a85
KX
3497 if (!q->dev)
3498 return;
3499
6c954667
LM
3500 spin_lock_irq(q->queue_lock);
3501 q->rpm_status = RPM_RESUMING;
3502 spin_unlock_irq(q->queue_lock);
3503}
3504EXPORT_SYMBOL(blk_pre_runtime_resume);
3505
3506/**
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
3510 *
3511 * Description:
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.
3516 *
3517 * This function should be called near the end of the device's
3518 * runtime_resume callback.
3519 */
3520void blk_post_runtime_resume(struct request_queue *q, int err)
3521{
4fd41a85
KX
3522 if (!q->dev)
3523 return;
3524
6c954667
LM
3525 spin_lock_irq(q->queue_lock);
3526 if (!err) {
3527 q->rpm_status = RPM_ACTIVE;
3528 __blk_run_queue(q);
3529 pm_runtime_mark_last_busy(q->dev);
c60855cd 3530 pm_request_autosuspend(q->dev);
6c954667
LM
3531 } else {
3532 q->rpm_status = RPM_SUSPENDED;
3533 }
3534 spin_unlock_irq(q->queue_lock);
3535}
3536EXPORT_SYMBOL(blk_post_runtime_resume);
3537#endif
3538
1da177e4
LT
3539int __init blk_dev_init(void)
3540{
9eb55b03 3541 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
0762b23d 3542 FIELD_SIZEOF(struct request, cmd_flags));
9eb55b03 3543
89b90be2
TH
3544 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3545 kblockd_workqueue = alloc_workqueue("kblockd",
28747fcd 3546 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1da177e4
LT
3547 if (!kblockd_workqueue)
3548 panic("Failed to create kblockd\n");
3549
3550 request_cachep = kmem_cache_create("blkdev_requests",
20c2df83 3551 sizeof(struct request), 0, SLAB_PANIC, NULL);
1da177e4 3552
8324aa91 3553 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
165125e1 3554 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1da177e4 3555
d38ecf93 3556 return 0;
1da177e4 3557}