usb: gadget: f_mtp: Avoid race between mtp_read and mtp_function_disable
[GitHub/exynos8895/android_kernel_samsung_universal8895.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
65733da1
MS
43#include <linux/math64.h>
44
d07335e5 45EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
b0da3f0d 46EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
0a82a8d1 47EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
3291fa57 48EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
cbae8d45 49EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
0bfc2455 50
a73f730d
TH
51DEFINE_IDA(blk_queue_ida);
52
1da177e4
LT
53/*
54 * For the allocated request tables
55 */
320ae51f 56struct kmem_cache *request_cachep = NULL;
1da177e4
LT
57
58/*
59 * For queue allocation
60 */
6728cb0e 61struct kmem_cache *blk_requestq_cachep;
1da177e4 62
1da177e4
LT
63/*
64 * Controlling structure to kblockd
65 */
ff856bad 66static struct workqueue_struct *kblockd_workqueue;
1da177e4 67
d40f75a0
TH
68static void blk_clear_congested(struct request_list *rl, int sync)
69{
d40f75a0
TH
70#ifdef CONFIG_CGROUP_WRITEBACK
71 clear_wb_congested(rl->blkg->wb_congested, sync);
72#else
482cf79c
TH
73 /*
74 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
75 * flip its congestion state for events on other blkcgs.
76 */
77 if (rl == &rl->q->root_rl)
78 clear_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
d40f75a0
TH
79#endif
80}
81
82static void blk_set_congested(struct request_list *rl, int sync)
83{
d40f75a0
TH
84#ifdef CONFIG_CGROUP_WRITEBACK
85 set_wb_congested(rl->blkg->wb_congested, sync);
86#else
482cf79c
TH
87 /* see blk_clear_congested() */
88 if (rl == &rl->q->root_rl)
89 set_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
d40f75a0
TH
90#endif
91}
92
8324aa91 93void blk_queue_congestion_threshold(struct request_queue *q)
1da177e4
LT
94{
95 int nr;
96
97 nr = q->nr_requests - (q->nr_requests / 8) + 1;
98 if (nr > q->nr_requests)
99 nr = q->nr_requests;
100 q->nr_congestion_on = nr;
101
102 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
103 if (nr < 1)
104 nr = 1;
105 q->nr_congestion_off = nr;
106}
107
1da177e4
LT
108/**
109 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
110 * @bdev: device
111 *
112 * Locates the passed device's request queue and returns the address of its
1cac41cb
MB
113 * backing_dev_info. This function can only be called while there is an
114 * active reference against the parent gendisk.
1da177e4
LT
115 */
116struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
117{
165125e1 118 struct request_queue *q = bdev_get_queue(bdev);
1da177e4 119
ff9ea323 120 return &q->backing_dev_info;
1da177e4 121}
1da177e4
LT
122EXPORT_SYMBOL(blk_get_backing_dev_info);
123
2a4aa30c 124void blk_rq_init(struct request_queue *q, struct request *rq)
1da177e4 125{
1afb20f3
FT
126 memset(rq, 0, sizeof(*rq));
127
1da177e4 128 INIT_LIST_HEAD(&rq->queuelist);
242f9dcb 129 INIT_LIST_HEAD(&rq->timeout_list);
c7c22e4d 130 rq->cpu = -1;
63a71386 131 rq->q = q;
a2dec7b3 132 rq->__sector = (sector_t) -1;
2e662b65
JA
133 INIT_HLIST_NODE(&rq->hash);
134 RB_CLEAR_NODE(&rq->rb_node);
d7e3c324 135 rq->cmd = rq->__cmd;
e2494e1b 136 rq->cmd_len = BLK_MAX_CDB;
63a71386 137 rq->tag = -1;
b243ddcb 138 rq->start_time = jiffies;
9195291e 139 set_start_time_ns(rq);
09e099d4 140 rq->part = NULL;
1da177e4 141}
2a4aa30c 142EXPORT_SYMBOL(blk_rq_init);
1da177e4 143
5bb23a68
N
144static void req_bio_endio(struct request *rq, struct bio *bio,
145 unsigned int nbytes, int error)
1da177e4 146{
78d8e58a 147 if (error)
4246a0b6 148 bio->bi_error = error;
797e7dbb 149
143a87f4 150 if (unlikely(rq->cmd_flags & REQ_QUIET))
b7c44ed9 151 bio_set_flag(bio, BIO_QUIET);
08bafc03 152
f79ea416 153 bio_advance(bio, nbytes);
7ba1ba12 154
143a87f4 155 /* don't actually finish bio if it's part of flush sequence */
78d8e58a 156 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
4246a0b6 157 bio_endio(bio);
1da177e4 158}
1da177e4 159
1da177e4
LT
160void blk_dump_rq_flags(struct request *rq, char *msg)
161{
162 int bit;
163
5953316d 164 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
4aff5e23 165 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
5953316d 166 (unsigned long long) rq->cmd_flags);
1da177e4 167
83096ebf
TH
168 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
169 (unsigned long long)blk_rq_pos(rq),
170 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
b4f42e28
JA
171 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
172 rq->bio, rq->biotail, blk_rq_bytes(rq));
1da177e4 173
33659ebb 174 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
6728cb0e 175 printk(KERN_INFO " cdb: ");
d34c87e4 176 for (bit = 0; bit < BLK_MAX_CDB; bit++)
1da177e4
LT
177 printk("%02x ", rq->cmd[bit]);
178 printk("\n");
179 }
180}
1da177e4
LT
181EXPORT_SYMBOL(blk_dump_rq_flags);
182
3cca6dc1 183static void blk_delay_work(struct work_struct *work)
1da177e4 184{
3cca6dc1 185 struct request_queue *q;
1da177e4 186
3cca6dc1
JA
187 q = container_of(work, struct request_queue, delay_work.work);
188 spin_lock_irq(q->queue_lock);
24ecfbe2 189 __blk_run_queue(q);
3cca6dc1 190 spin_unlock_irq(q->queue_lock);
1da177e4 191}
1da177e4
LT
192
193/**
3cca6dc1
JA
194 * blk_delay_queue - restart queueing after defined interval
195 * @q: The &struct request_queue in question
196 * @msecs: Delay in msecs
1da177e4
LT
197 *
198 * Description:
3cca6dc1
JA
199 * Sometimes queueing needs to be postponed for a little while, to allow
200 * resources to come back. This function will make sure that queueing is
70460571 201 * restarted around the specified time. Queue lock must be held.
3cca6dc1
JA
202 */
203void blk_delay_queue(struct request_queue *q, unsigned long msecs)
2ad8b1ef 204{
70460571
BVA
205 if (likely(!blk_queue_dead(q)))
206 queue_delayed_work(kblockd_workqueue, &q->delay_work,
207 msecs_to_jiffies(msecs));
2ad8b1ef 208}
3cca6dc1 209EXPORT_SYMBOL(blk_delay_queue);
2ad8b1ef 210
21491412
JA
211/**
212 * blk_start_queue_async - asynchronously restart a previously stopped queue
213 * @q: The &struct request_queue in question
214 *
215 * Description:
216 * blk_start_queue_async() will clear the stop flag on the queue, and
217 * ensure that the request_fn for the queue is run from an async
218 * context.
219 **/
220void blk_start_queue_async(struct request_queue *q)
221{
222 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
223 blk_run_queue_async(q);
224}
225EXPORT_SYMBOL(blk_start_queue_async);
226
1da177e4
LT
227/**
228 * blk_start_queue - restart a previously stopped queue
165125e1 229 * @q: The &struct request_queue in question
1da177e4
LT
230 *
231 * Description:
232 * blk_start_queue() will clear the stop flag on the queue, and call
233 * the request_fn for the queue if it was in a stopped state when
234 * entered. Also see blk_stop_queue(). Queue lock must be held.
235 **/
165125e1 236void blk_start_queue(struct request_queue *q)
1da177e4 237{
30e81e7f 238 WARN_ON(!in_interrupt() && !irqs_disabled());
a038e253 239
75ad23bc 240 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
24ecfbe2 241 __blk_run_queue(q);
1da177e4 242}
1da177e4
LT
243EXPORT_SYMBOL(blk_start_queue);
244
245/**
246 * blk_stop_queue - stop a queue
165125e1 247 * @q: The &struct request_queue in question
1da177e4
LT
248 *
249 * Description:
250 * The Linux block layer assumes that a block driver will consume all
251 * entries on the request queue when the request_fn strategy is called.
252 * Often this will not happen, because of hardware limitations (queue
253 * depth settings). If a device driver gets a 'queue full' response,
254 * or if it simply chooses not to queue more I/O at one point, it can
255 * call this function to prevent the request_fn from being called until
256 * the driver has signalled it's ready to go again. This happens by calling
257 * blk_start_queue() to restart queue operations. Queue lock must be held.
258 **/
165125e1 259void blk_stop_queue(struct request_queue *q)
1da177e4 260{
136b5721 261 cancel_delayed_work(&q->delay_work);
75ad23bc 262 queue_flag_set(QUEUE_FLAG_STOPPED, q);
1da177e4
LT
263}
264EXPORT_SYMBOL(blk_stop_queue);
265
266/**
267 * blk_sync_queue - cancel any pending callbacks on a queue
268 * @q: the queue
269 *
270 * Description:
271 * The block layer may perform asynchronous callback activity
272 * on a queue, such as calling the unplug function after a timeout.
273 * A block device may call blk_sync_queue to ensure that any
274 * such activity is cancelled, thus allowing it to release resources
59c51591 275 * that the callbacks might use. The caller must already have made sure
1da177e4
LT
276 * that its ->make_request_fn will not re-add plugging prior to calling
277 * this function.
278 *
da527770 279 * This function does not cancel any asynchronous activity arising
da3dae54 280 * out of elevator or throttling code. That would require elevator_exit()
5efd6113 281 * and blkcg_exit_queue() to be called with queue lock initialized.
da527770 282 *
1da177e4
LT
283 */
284void blk_sync_queue(struct request_queue *q)
285{
70ed28b9 286 del_timer_sync(&q->timeout);
f04c1fe7
ML
287
288 if (q->mq_ops) {
289 struct blk_mq_hw_ctx *hctx;
290 int i;
291
70f4db63
CH
292 queue_for_each_hw_ctx(q, hctx, i) {
293 cancel_delayed_work_sync(&hctx->run_work);
294 cancel_delayed_work_sync(&hctx->delay_work);
295 }
f04c1fe7
ML
296 } else {
297 cancel_delayed_work_sync(&q->delay_work);
298 }
1da177e4
LT
299}
300EXPORT_SYMBOL(blk_sync_queue);
301
c246e80d
BVA
302/**
303 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
304 * @q: The queue to run
305 *
306 * Description:
307 * Invoke request handling on a queue if there are any pending requests.
308 * May be used to restart request handling after a request has completed.
309 * This variant runs the queue whether or not the queue has been
310 * stopped. Must be called with the queue lock held and interrupts
311 * disabled. See also @blk_run_queue.
312 */
313inline void __blk_run_queue_uncond(struct request_queue *q)
314{
315 if (unlikely(blk_queue_dead(q)))
316 return;
317
24faf6f6
BVA
318 /*
319 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
320 * the queue lock internally. As a result multiple threads may be
321 * running such a request function concurrently. Keep track of the
322 * number of active request_fn invocations such that blk_drain_queue()
323 * can wait until all these request_fn calls have finished.
324 */
325 q->request_fn_active++;
c246e80d 326 q->request_fn(q);
24faf6f6 327 q->request_fn_active--;
c246e80d 328}
a7928c15 329EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
c246e80d 330
1da177e4 331/**
80a4b58e 332 * __blk_run_queue - run a single device queue
1da177e4 333 * @q: The queue to run
80a4b58e
JA
334 *
335 * Description:
336 * See @blk_run_queue. This variant must be called with the queue lock
24ecfbe2 337 * held and interrupts disabled.
1da177e4 338 */
24ecfbe2 339void __blk_run_queue(struct request_queue *q)
1da177e4 340{
a538cd03
TH
341 if (unlikely(blk_queue_stopped(q)))
342 return;
343
c246e80d 344 __blk_run_queue_uncond(q);
75ad23bc
NP
345}
346EXPORT_SYMBOL(__blk_run_queue);
dac07ec1 347
24ecfbe2
CH
348/**
349 * blk_run_queue_async - run a single device queue in workqueue context
350 * @q: The queue to run
351 *
352 * Description:
353 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
70460571 354 * of us. The caller must hold the queue lock.
24ecfbe2
CH
355 */
356void blk_run_queue_async(struct request_queue *q)
357{
70460571 358 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
e7c2f967 359 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
24ecfbe2 360}
c21e6beb 361EXPORT_SYMBOL(blk_run_queue_async);
24ecfbe2 362
75ad23bc
NP
363/**
364 * blk_run_queue - run a single device queue
365 * @q: The queue to run
80a4b58e
JA
366 *
367 * Description:
368 * Invoke request handling on this queue, if it has pending work to do.
a7f55792 369 * May be used to restart queueing when a request has completed.
75ad23bc
NP
370 */
371void blk_run_queue(struct request_queue *q)
372{
373 unsigned long flags;
374
375 spin_lock_irqsave(q->queue_lock, flags);
24ecfbe2 376 __blk_run_queue(q);
1da177e4
LT
377 spin_unlock_irqrestore(q->queue_lock, flags);
378}
379EXPORT_SYMBOL(blk_run_queue);
380
165125e1 381void blk_put_queue(struct request_queue *q)
483f4afc
AV
382{
383 kobject_put(&q->kobj);
384}
d86e0e83 385EXPORT_SYMBOL(blk_put_queue);
483f4afc 386
e3c78ca5 387/**
807592a4 388 * __blk_drain_queue - drain requests from request_queue
e3c78ca5 389 * @q: queue to drain
c9a929dd 390 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
e3c78ca5 391 *
c9a929dd
TH
392 * Drain requests from @q. If @drain_all is set, all requests are drained.
393 * If not, only ELVPRIV requests are drained. The caller is responsible
394 * for ensuring that no new requests which need to be drained are queued.
e3c78ca5 395 */
1cac41cb 396void __blk_drain_queue(struct request_queue *q, bool drain_all)
807592a4
BVA
397 __releases(q->queue_lock)
398 __acquires(q->queue_lock)
e3c78ca5 399{
458f27a9
AH
400 int i;
401
807592a4
BVA
402 lockdep_assert_held(q->queue_lock);
403
e3c78ca5 404 while (true) {
481a7d64 405 bool drain = false;
e3c78ca5 406
b855b04a
TH
407 /*
408 * The caller might be trying to drain @q before its
409 * elevator is initialized.
410 */
411 if (q->elevator)
412 elv_drain_elevator(q);
413
5efd6113 414 blkcg_drain_queue(q);
e3c78ca5 415
4eabc941
TH
416 /*
417 * This function might be called on a queue which failed
b855b04a
TH
418 * driver init after queue creation or is not yet fully
419 * active yet. Some drivers (e.g. fd and loop) get unhappy
420 * in such cases. Kick queue iff dispatch queue has
421 * something on it and @q has request_fn set.
4eabc941 422 */
b855b04a 423 if (!list_empty(&q->queue_head) && q->request_fn)
4eabc941 424 __blk_run_queue(q);
c9a929dd 425
8a5ecdd4 426 drain |= q->nr_rqs_elvpriv;
24faf6f6 427 drain |= q->request_fn_active;
481a7d64
TH
428
429 /*
430 * Unfortunately, requests are queued at and tracked from
431 * multiple places and there's no single counter which can
432 * be drained. Check all the queues and counters.
433 */
434 if (drain_all) {
e97c293c 435 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
481a7d64
TH
436 drain |= !list_empty(&q->queue_head);
437 for (i = 0; i < 2; i++) {
8a5ecdd4 438 drain |= q->nr_rqs[i];
481a7d64 439 drain |= q->in_flight[i];
7c94e1c1
ML
440 if (fq)
441 drain |= !list_empty(&fq->flush_queue[i]);
481a7d64
TH
442 }
443 }
e3c78ca5 444
481a7d64 445 if (!drain)
e3c78ca5 446 break;
807592a4
BVA
447
448 spin_unlock_irq(q->queue_lock);
449
e3c78ca5 450 msleep(10);
807592a4
BVA
451
452 spin_lock_irq(q->queue_lock);
e3c78ca5 453 }
458f27a9
AH
454
455 /*
456 * With queue marked dead, any woken up waiter will fail the
457 * allocation path, so the wakeup chaining is lost and we're
458 * left with hung waiters. We need to wake up those waiters.
459 */
460 if (q->request_fn) {
a051661c
TH
461 struct request_list *rl;
462
a051661c
TH
463 blk_queue_for_each_rl(rl, q)
464 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
465 wake_up_all(&rl->wait[i]);
458f27a9 466 }
e3c78ca5
TH
467}
468
d732580b
TH
469/**
470 * blk_queue_bypass_start - enter queue bypass mode
471 * @q: queue of interest
472 *
473 * In bypass mode, only the dispatch FIFO queue of @q is used. This
474 * function makes @q enter bypass mode and drains all requests which were
6ecf23af 475 * throttled or issued before. On return, it's guaranteed that no request
80fd9979
TH
476 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
477 * inside queue or RCU read lock.
d732580b
TH
478 */
479void blk_queue_bypass_start(struct request_queue *q)
480{
481 spin_lock_irq(q->queue_lock);
776687bc 482 q->bypass_depth++;
d732580b
TH
483 queue_flag_set(QUEUE_FLAG_BYPASS, q);
484 spin_unlock_irq(q->queue_lock);
485
776687bc
TH
486 /*
487 * Queues start drained. Skip actual draining till init is
488 * complete. This avoids lenghty delays during queue init which
489 * can happen many times during boot.
490 */
491 if (blk_queue_init_done(q)) {
807592a4
BVA
492 spin_lock_irq(q->queue_lock);
493 __blk_drain_queue(q, false);
494 spin_unlock_irq(q->queue_lock);
495
b82d4b19
TH
496 /* ensure blk_queue_bypass() is %true inside RCU read lock */
497 synchronize_rcu();
498 }
d732580b
TH
499}
500EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
501
502/**
503 * blk_queue_bypass_end - leave queue bypass mode
504 * @q: queue of interest
505 *
506 * Leave bypass mode and restore the normal queueing behavior.
507 */
508void blk_queue_bypass_end(struct request_queue *q)
509{
510 spin_lock_irq(q->queue_lock);
511 if (!--q->bypass_depth)
512 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
513 WARN_ON_ONCE(q->bypass_depth < 0);
514 spin_unlock_irq(q->queue_lock);
515}
516EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
517
aed3ea94
JA
518void blk_set_queue_dying(struct request_queue *q)
519{
d3a6bd7b
BVA
520 spin_lock_irq(q->queue_lock);
521 queue_flag_set(QUEUE_FLAG_DYING, q);
522 spin_unlock_irq(q->queue_lock);
aed3ea94
JA
523
524 if (q->mq_ops)
525 blk_mq_wake_waiters(q);
526 else {
527 struct request_list *rl;
528
529 blk_queue_for_each_rl(rl, q) {
530 if (rl->rq_pool) {
7b99b00c
ML
531 wake_up_all(&rl->wait[BLK_RW_SYNC]);
532 wake_up_all(&rl->wait[BLK_RW_ASYNC]);
aed3ea94
JA
533 }
534 }
535 }
536}
537EXPORT_SYMBOL_GPL(blk_set_queue_dying);
538
c9a929dd
TH
539/**
540 * blk_cleanup_queue - shutdown a request queue
541 * @q: request queue to shutdown
542 *
c246e80d
BVA
543 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
544 * put it. All future requests will be failed immediately with -ENODEV.
c94a96ac 545 */
6728cb0e 546void blk_cleanup_queue(struct request_queue *q)
483f4afc 547{
c9a929dd 548 spinlock_t *lock = q->queue_lock;
e3335de9 549
3f3299d5 550 /* mark @q DYING, no new request or merges will be allowed afterwards */
483f4afc 551 mutex_lock(&q->sysfs_lock);
aed3ea94 552 blk_set_queue_dying(q);
c9a929dd 553 spin_lock_irq(lock);
6ecf23af 554
80fd9979 555 /*
3f3299d5 556 * A dying queue is permanently in bypass mode till released. Note
80fd9979
TH
557 * that, unlike blk_queue_bypass_start(), we aren't performing
558 * synchronize_rcu() after entering bypass mode to avoid the delay
559 * as some drivers create and destroy a lot of queues while
560 * probing. This is still safe because blk_release_queue() will be
561 * called only after the queue refcnt drops to zero and nothing,
562 * RCU or not, would be traversing the queue by then.
563 */
6ecf23af
TH
564 q->bypass_depth++;
565 queue_flag_set(QUEUE_FLAG_BYPASS, q);
566
c9a929dd
TH
567 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
568 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
3f3299d5 569 queue_flag_set(QUEUE_FLAG_DYING, q);
c9a929dd
TH
570 spin_unlock_irq(lock);
571 mutex_unlock(&q->sysfs_lock);
572
c246e80d
BVA
573 /*
574 * Drain all requests queued before DYING marking. Set DEAD flag to
575 * prevent that q->request_fn() gets invoked after draining finished.
576 */
3ef28e83
DW
577 blk_freeze_queue(q);
578 spin_lock_irq(lock);
579 if (!q->mq_ops)
43a5e4e2 580 __blk_drain_queue(q, true);
c246e80d 581 queue_flag_set(QUEUE_FLAG_DEAD, q);
807592a4 582 spin_unlock_irq(lock);
c9a929dd 583
5a48fc14
DW
584 /* for synchronous bio-based driver finish in-flight integrity i/o */
585 blk_flush_integrity();
586
c9a929dd
TH
587 /* @q won't process any more request, flush async actions */
588 del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
589 blk_sync_queue(q);
590
45a9c9d9
BVA
591 if (q->mq_ops)
592 blk_mq_free_queue(q);
3ef28e83 593 percpu_ref_exit(&q->q_usage_counter);
45a9c9d9 594
5e5cfac0
AH
595 spin_lock_irq(lock);
596 if (q->queue_lock != &q->__queue_lock)
597 q->queue_lock = &q->__queue_lock;
598 spin_unlock_irq(lock);
599
b02176f3 600 bdi_unregister(&q->backing_dev_info);
6cd18e71 601
c9a929dd 602 /* @q is and will stay empty, shutdown and put */
483f4afc
AV
603 blk_put_queue(q);
604}
1da177e4
LT
605EXPORT_SYMBOL(blk_cleanup_queue);
606
271508db
DR
607/* Allocate memory local to the request queue */
608static void *alloc_request_struct(gfp_t gfp_mask, void *data)
609{
610 int nid = (int)(long)data;
611 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
612}
613
614static void free_request_struct(void *element, void *unused)
615{
616 kmem_cache_free(request_cachep, element);
617}
618
5b788ce3
TH
619int blk_init_rl(struct request_list *rl, struct request_queue *q,
620 gfp_t gfp_mask)
1da177e4 621{
1abec4fd
MS
622 if (unlikely(rl->rq_pool))
623 return 0;
624
5b788ce3 625 rl->q = q;
1faa16d2
JA
626 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
627 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
1faa16d2
JA
628 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
629 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
1da177e4 630
271508db
DR
631 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
632 free_request_struct,
633 (void *)(long)q->node, gfp_mask,
634 q->node);
1da177e4
LT
635 if (!rl->rq_pool)
636 return -ENOMEM;
637
638 return 0;
639}
640
5b788ce3
TH
641void blk_exit_rl(struct request_list *rl)
642{
643 if (rl->rq_pool)
644 mempool_destroy(rl->rq_pool);
645}
646
165125e1 647struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
1da177e4 648{
c304a51b 649 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
1946089a
CL
650}
651EXPORT_SYMBOL(blk_alloc_queue);
1da177e4 652
3ef28e83
DW
653int blk_queue_enter(struct request_queue *q, gfp_t gfp)
654{
655 while (true) {
656 int ret;
657
658 if (percpu_ref_tryget_live(&q->q_usage_counter))
659 return 0;
660
71baba4b 661 if (!gfpflags_allow_blocking(gfp))
3ef28e83
DW
662 return -EBUSY;
663
664 ret = wait_event_interruptible(q->mq_freeze_wq,
665 !atomic_read(&q->mq_freeze_depth) ||
666 blk_queue_dying(q));
667 if (blk_queue_dying(q))
668 return -ENODEV;
669 if (ret)
670 return ret;
671 }
672}
673
674void blk_queue_exit(struct request_queue *q)
675{
676 percpu_ref_put(&q->q_usage_counter);
677}
678
679static void blk_queue_usage_counter_release(struct percpu_ref *ref)
680{
681 struct request_queue *q =
682 container_of(ref, struct request_queue, q_usage_counter);
683
684 wake_up_all(&q->mq_freeze_wq);
685}
686
165125e1 687struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
1946089a 688{
165125e1 689 struct request_queue *q;
e0bf68dd 690 int err;
1946089a 691
8324aa91 692 q = kmem_cache_alloc_node(blk_requestq_cachep,
94f6030c 693 gfp_mask | __GFP_ZERO, node_id);
1da177e4
LT
694 if (!q)
695 return NULL;
696
00380a40 697 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
a73f730d 698 if (q->id < 0)
3d2936f4 699 goto fail_q;
a73f730d 700
54efd50b
KO
701 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
702 if (!q->bio_split)
703 goto fail_id;
704
0989a025
JA
705 q->backing_dev_info.ra_pages =
706 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
89e9b9e0 707 q->backing_dev_info.capabilities = BDI_CAP_CGROUP_WRITEBACK;
d993831f 708 q->backing_dev_info.name = "block";
5151412d 709 q->node = node_id;
0989a025 710
e0bf68dd 711 err = bdi_init(&q->backing_dev_info);
a73f730d 712 if (err)
54efd50b 713 goto fail_split;
e0bf68dd 714
31373d09
MG
715 setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
716 laptop_mode_timer_fn, (unsigned long) q);
242f9dcb 717 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
b855b04a 718 INIT_LIST_HEAD(&q->queue_head);
242f9dcb 719 INIT_LIST_HEAD(&q->timeout_list);
a612fddf 720 INIT_LIST_HEAD(&q->icq_list);
4eef3049 721#ifdef CONFIG_BLK_CGROUP
e8989fae 722 INIT_LIST_HEAD(&q->blkg_list);
4eef3049 723#endif
3cca6dc1 724 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
483f4afc 725
8324aa91 726 kobject_init(&q->kobj, &blk_queue_ktype);
1da177e4 727
483f4afc 728 mutex_init(&q->sysfs_lock);
e7e72bf6 729 spin_lock_init(&q->__queue_lock);
483f4afc 730
c94a96ac
VG
731 /*
732 * By default initialize queue_lock to internal lock and driver can
733 * override it later if need be.
734 */
735 q->queue_lock = &q->__queue_lock;
736
b82d4b19
TH
737 /*
738 * A queue starts its life with bypass turned on to avoid
739 * unnecessary bypass on/off overhead and nasty surprises during
749fefe6
TH
740 * init. The initial bypass will be finished when the queue is
741 * registered by blk_register_queue().
b82d4b19
TH
742 */
743 q->bypass_depth = 1;
744 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
745
320ae51f
JA
746 init_waitqueue_head(&q->mq_freeze_wq);
747
3ef28e83
DW
748 /*
749 * Init percpu_ref in atomic mode so that it's faster to shutdown.
750 * See blk_register_queue() for details.
751 */
752 if (percpu_ref_init(&q->q_usage_counter,
753 blk_queue_usage_counter_release,
754 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
fff4996b 755 goto fail_bdi;
f51b802c 756
3ef28e83
DW
757 if (blkcg_init_queue(q))
758 goto fail_ref;
759
1da177e4 760 return q;
a73f730d 761
3ef28e83
DW
762fail_ref:
763 percpu_ref_exit(&q->q_usage_counter);
fff4996b
MP
764fail_bdi:
765 bdi_destroy(&q->backing_dev_info);
54efd50b
KO
766fail_split:
767 bioset_free(q->bio_split);
a73f730d
TH
768fail_id:
769 ida_simple_remove(&blk_queue_ida, q->id);
770fail_q:
771 kmem_cache_free(blk_requestq_cachep, q);
772 return NULL;
1da177e4 773}
1946089a 774EXPORT_SYMBOL(blk_alloc_queue_node);
1da177e4
LT
775
776/**
777 * blk_init_queue - prepare a request queue for use with a block device
778 * @rfn: The function to be called to process requests that have been
779 * placed on the queue.
780 * @lock: Request queue spin lock
781 *
782 * Description:
783 * If a block device wishes to use the standard request handling procedures,
784 * which sorts requests and coalesces adjacent requests, then it must
785 * call blk_init_queue(). The function @rfn will be called when there
786 * are requests on the queue that need to be processed. If the device
787 * supports plugging, then @rfn may not be called immediately when requests
788 * are available on the queue, but may be called at some time later instead.
789 * Plugged queues are generally unplugged when a buffer belonging to one
790 * of the requests on the queue is needed, or due to memory pressure.
791 *
792 * @rfn is not required, or even expected, to remove all requests off the
793 * queue, but only as many as it can handle at a time. If it does leave
794 * requests on the queue, it is responsible for arranging that the requests
795 * get dealt with eventually.
796 *
797 * The queue spin lock must be held while manipulating the requests on the
a038e253
PBG
798 * request queue; this lock will be taken also from interrupt context, so irq
799 * disabling is needed for it.
1da177e4 800 *
710027a4 801 * Function returns a pointer to the initialized request queue, or %NULL if
1da177e4
LT
802 * it didn't succeed.
803 *
804 * Note:
805 * blk_init_queue() must be paired with a blk_cleanup_queue() call
806 * when the block device is deactivated (such as at module unload).
807 **/
1946089a 808
165125e1 809struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
1da177e4 810{
c304a51b 811 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
1946089a
CL
812}
813EXPORT_SYMBOL(blk_init_queue);
814
165125e1 815struct request_queue *
1946089a
CL
816blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
817{
c86d1b8a 818 struct request_queue *uninit_q, *q;
1da177e4 819
c86d1b8a
MS
820 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
821 if (!uninit_q)
822 return NULL;
823
5151412d 824 q = blk_init_allocated_queue(uninit_q, rfn, lock);
c86d1b8a 825 if (!q)
7982e90c 826 blk_cleanup_queue(uninit_q);
18741986 827
7982e90c 828 return q;
01effb0d
MS
829}
830EXPORT_SYMBOL(blk_init_queue_node);
831
dece1635 832static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
336b7e1f 833
01effb0d
MS
834struct request_queue *
835blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
836 spinlock_t *lock)
01effb0d 837{
1da177e4
LT
838 if (!q)
839 return NULL;
840
f70ced09 841 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
ba483388 842 if (!q->fq)
7982e90c
MS
843 return NULL;
844
a051661c 845 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
708f04d2 846 goto fail;
1da177e4
LT
847
848 q->request_fn = rfn;
1da177e4 849 q->prep_rq_fn = NULL;
28018c24 850 q->unprep_rq_fn = NULL;
60ea8226 851 q->queue_flags |= QUEUE_FLAG_DEFAULT;
c94a96ac
VG
852
853 /* Override internal queue lock with supplied lock pointer */
854 if (lock)
855 q->queue_lock = lock;
1da177e4 856
f3b144aa
JA
857 /*
858 * This also sets hw/phys segments, boundary and size
859 */
c20e8de2 860 blk_queue_make_request(q, blk_queue_bio);
1da177e4 861
44ec9542
AS
862 q->sg_reserved_size = INT_MAX;
863
eb1c160b
TS
864 /* Protect q->elevator from elevator_change */
865 mutex_lock(&q->sysfs_lock);
866
b82d4b19 867 /* init elevator */
eb1c160b
TS
868 if (elevator_init(q, NULL)) {
869 mutex_unlock(&q->sysfs_lock);
708f04d2 870 goto fail;
eb1c160b
TS
871 }
872
873 mutex_unlock(&q->sysfs_lock);
874
b82d4b19 875 return q;
708f04d2
DJ
876
877fail:
ba483388 878 blk_free_flush_queue(q->fq);
708f04d2 879 return NULL;
1da177e4 880}
5151412d 881EXPORT_SYMBOL(blk_init_allocated_queue);
1da177e4 882
09ac46c4 883bool blk_get_queue(struct request_queue *q)
1da177e4 884{
3f3299d5 885 if (likely(!blk_queue_dying(q))) {
09ac46c4
TH
886 __blk_get_queue(q);
887 return true;
1da177e4
LT
888 }
889
09ac46c4 890 return false;
1da177e4 891}
d86e0e83 892EXPORT_SYMBOL(blk_get_queue);
1da177e4 893
5b788ce3 894static inline void blk_free_request(struct request_list *rl, struct request *rq)
1da177e4 895{
f1f8cc94 896 if (rq->cmd_flags & REQ_ELVPRIV) {
5b788ce3 897 elv_put_request(rl->q, rq);
f1f8cc94 898 if (rq->elv.icq)
11a3122f 899 put_io_context(rq->elv.icq->ioc);
f1f8cc94
TH
900 }
901
5b788ce3 902 mempool_free(rq, rl->rq_pool);
1da177e4
LT
903}
904
1da177e4
LT
905/*
906 * ioc_batching returns true if the ioc is a valid batching request and
907 * should be given priority access to a request.
908 */
165125e1 909static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
910{
911 if (!ioc)
912 return 0;
913
914 /*
915 * Make sure the process is able to allocate at least 1 request
916 * even if the batch times out, otherwise we could theoretically
917 * lose wakeups.
918 */
919 return ioc->nr_batch_requests == q->nr_batching ||
920 (ioc->nr_batch_requests > 0
921 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
922}
923
924/*
925 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
926 * will cause the process to be a "batcher" on all queues in the system. This
927 * is the behaviour we want though - once it gets a wakeup it should be given
928 * a nice run.
929 */
165125e1 930static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1da177e4
LT
931{
932 if (!ioc || ioc_batching(q, ioc))
933 return;
934
935 ioc->nr_batch_requests = q->nr_batching;
936 ioc->last_waited = jiffies;
937}
938
5b788ce3 939static void __freed_request(struct request_list *rl, int sync)
1da177e4 940{
5b788ce3 941 struct request_queue *q = rl->q;
1da177e4 942
d40f75a0
TH
943 if (rl->count[sync] < queue_congestion_off_threshold(q))
944 blk_clear_congested(rl, sync);
1da177e4 945
1faa16d2
JA
946 if (rl->count[sync] + 1 <= q->nr_requests) {
947 if (waitqueue_active(&rl->wait[sync]))
948 wake_up(&rl->wait[sync]);
1da177e4 949
5b788ce3 950 blk_clear_rl_full(rl, sync);
1da177e4
LT
951 }
952}
953
954/*
955 * A request has just been released. Account for it, update the full and
956 * congestion status, wake up any waiters. Called under q->queue_lock.
957 */
5b788ce3 958static void freed_request(struct request_list *rl, unsigned int flags)
1da177e4 959{
5b788ce3 960 struct request_queue *q = rl->q;
75eb6c37 961 int sync = rw_is_sync(flags);
1da177e4 962
8a5ecdd4 963 q->nr_rqs[sync]--;
1faa16d2 964 rl->count[sync]--;
75eb6c37 965 if (flags & REQ_ELVPRIV)
8a5ecdd4 966 q->nr_rqs_elvpriv--;
1da177e4 967
5b788ce3 968 __freed_request(rl, sync);
1da177e4 969
1faa16d2 970 if (unlikely(rl->starved[sync ^ 1]))
5b788ce3 971 __freed_request(rl, sync ^ 1);
1da177e4
LT
972}
973
e3a2b3f9
JA
974int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
975{
976 struct request_list *rl;
d40f75a0 977 int on_thresh, off_thresh;
e3a2b3f9
JA
978
979 spin_lock_irq(q->queue_lock);
980 q->nr_requests = nr;
981 blk_queue_congestion_threshold(q);
d40f75a0
TH
982 on_thresh = queue_congestion_on_threshold(q);
983 off_thresh = queue_congestion_off_threshold(q);
e3a2b3f9 984
d40f75a0
TH
985 blk_queue_for_each_rl(rl, q) {
986 if (rl->count[BLK_RW_SYNC] >= on_thresh)
987 blk_set_congested(rl, BLK_RW_SYNC);
988 else if (rl->count[BLK_RW_SYNC] < off_thresh)
989 blk_clear_congested(rl, BLK_RW_SYNC);
e3a2b3f9 990
d40f75a0
TH
991 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
992 blk_set_congested(rl, BLK_RW_ASYNC);
993 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
994 blk_clear_congested(rl, BLK_RW_ASYNC);
e3a2b3f9 995
e3a2b3f9
JA
996 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
997 blk_set_rl_full(rl, BLK_RW_SYNC);
998 } else {
999 blk_clear_rl_full(rl, BLK_RW_SYNC);
1000 wake_up(&rl->wait[BLK_RW_SYNC]);
1001 }
1002
1003 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1004 blk_set_rl_full(rl, BLK_RW_ASYNC);
1005 } else {
1006 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1007 wake_up(&rl->wait[BLK_RW_ASYNC]);
1008 }
1009 }
1010
1011 spin_unlock_irq(q->queue_lock);
1012 return 0;
1013}
1014
9d5a4e94
MS
1015/*
1016 * Determine if elevator data should be initialized when allocating the
1017 * request associated with @bio.
1018 */
1019static bool blk_rq_should_init_elevator(struct bio *bio)
1020{
1021 if (!bio)
1022 return true;
1023
1024 /*
1025 * Flush requests do not use the elevator so skip initialization.
1026 * This allows a request to share the flush and elevator data.
1027 */
1028 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
1029 return false;
1030
1031 return true;
1032}
1033
852c788f
TH
1034/**
1035 * rq_ioc - determine io_context for request allocation
1036 * @bio: request being allocated is for this bio (can be %NULL)
1037 *
1038 * Determine io_context to use for request allocation for @bio. May return
1039 * %NULL if %current->io_context doesn't exist.
1040 */
1041static struct io_context *rq_ioc(struct bio *bio)
1042{
1043#ifdef CONFIG_BLK_CGROUP
1044 if (bio && bio->bi_ioc)
1045 return bio->bi_ioc;
1046#endif
1047 return current->io_context;
1048}
1049
da8303c6 1050/**
a06e05e6 1051 * __get_request - get a free request
5b788ce3 1052 * @rl: request list to allocate from
da8303c6
TH
1053 * @rw_flags: RW and SYNC flags
1054 * @bio: bio to allocate request for (can be %NULL)
1055 * @gfp_mask: allocation mask
1056 *
1057 * Get a free request from @q. This function may fail under memory
1058 * pressure or if @q is dead.
1059 *
da3dae54 1060 * Must be called with @q->queue_lock held and,
a492f075
JL
1061 * Returns ERR_PTR on failure, with @q->queue_lock held.
1062 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1063 */
5b788ce3 1064static struct request *__get_request(struct request_list *rl, int rw_flags,
a06e05e6 1065 struct bio *bio, gfp_t gfp_mask)
1da177e4 1066{
5b788ce3 1067 struct request_queue *q = rl->q;
b679281a 1068 struct request *rq;
7f4b35d1
TH
1069 struct elevator_type *et = q->elevator->type;
1070 struct io_context *ioc = rq_ioc(bio);
f1f8cc94 1071 struct io_cq *icq = NULL;
1faa16d2 1072 const bool is_sync = rw_is_sync(rw_flags) != 0;
75eb6c37 1073 int may_queue;
88ee5ef1 1074
3f3299d5 1075 if (unlikely(blk_queue_dying(q)))
a492f075 1076 return ERR_PTR(-ENODEV);
da8303c6 1077
7749a8d4 1078 may_queue = elv_may_queue(q, rw_flags);
88ee5ef1
JA
1079 if (may_queue == ELV_MQUEUE_NO)
1080 goto rq_starved;
1081
1faa16d2
JA
1082 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1083 if (rl->count[is_sync]+1 >= q->nr_requests) {
88ee5ef1
JA
1084 /*
1085 * The queue will fill after this allocation, so set
1086 * it as full, and mark this process as "batching".
1087 * This process will be allowed to complete a batch of
1088 * requests, others will be blocked.
1089 */
5b788ce3 1090 if (!blk_rl_full(rl, is_sync)) {
88ee5ef1 1091 ioc_set_batching(q, ioc);
5b788ce3 1092 blk_set_rl_full(rl, is_sync);
88ee5ef1
JA
1093 } else {
1094 if (may_queue != ELV_MQUEUE_MUST
1095 && !ioc_batching(q, ioc)) {
1096 /*
1097 * The queue is full and the allocating
1098 * process is not a "batcher", and not
1099 * exempted by the IO scheduler
1100 */
a492f075 1101 return ERR_PTR(-ENOMEM);
88ee5ef1
JA
1102 }
1103 }
1da177e4 1104 }
d40f75a0 1105 blk_set_congested(rl, is_sync);
1da177e4
LT
1106 }
1107
082cf69e
JA
1108 /*
1109 * Only allow batching queuers to allocate up to 50% over the defined
1110 * limit of requests, otherwise we could have thousands of requests
1111 * allocated with any setting of ->nr_requests
1112 */
1faa16d2 1113 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
a492f075 1114 return ERR_PTR(-ENOMEM);
fd782a4a 1115
8a5ecdd4 1116 q->nr_rqs[is_sync]++;
1faa16d2
JA
1117 rl->count[is_sync]++;
1118 rl->starved[is_sync] = 0;
cb98fc8b 1119
f1f8cc94
TH
1120 /*
1121 * Decide whether the new request will be managed by elevator. If
1122 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
1123 * prevent the current elevator from being destroyed until the new
1124 * request is freed. This guarantees icq's won't be destroyed and
1125 * makes creating new ones safe.
1126 *
1127 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1128 * it will be created after releasing queue_lock.
1129 */
d732580b 1130 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
75eb6c37 1131 rw_flags |= REQ_ELVPRIV;
8a5ecdd4 1132 q->nr_rqs_elvpriv++;
f1f8cc94
TH
1133 if (et->icq_cache && ioc)
1134 icq = ioc_lookup_icq(ioc, q);
9d5a4e94 1135 }
cb98fc8b 1136
f253b86b
JA
1137 if (blk_queue_io_stat(q))
1138 rw_flags |= REQ_IO_STAT;
1da177e4
LT
1139 spin_unlock_irq(q->queue_lock);
1140
29e2b09a 1141 /* allocate and init request */
5b788ce3 1142 rq = mempool_alloc(rl->rq_pool, gfp_mask);
29e2b09a 1143 if (!rq)
b679281a 1144 goto fail_alloc;
1da177e4 1145
29e2b09a 1146 blk_rq_init(q, rq);
a051661c 1147 blk_rq_set_rl(rq, rl);
29e2b09a
TH
1148 rq->cmd_flags = rw_flags | REQ_ALLOCED;
1149
aaf7c680 1150 /* init elvpriv */
29e2b09a 1151 if (rw_flags & REQ_ELVPRIV) {
aaf7c680 1152 if (unlikely(et->icq_cache && !icq)) {
7f4b35d1
TH
1153 if (ioc)
1154 icq = ioc_create_icq(ioc, q, gfp_mask);
aaf7c680
TH
1155 if (!icq)
1156 goto fail_elvpriv;
29e2b09a 1157 }
aaf7c680
TH
1158
1159 rq->elv.icq = icq;
1160 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1161 goto fail_elvpriv;
1162
1163 /* @rq->elv.icq holds io_context until @rq is freed */
29e2b09a
TH
1164 if (icq)
1165 get_io_context(icq->ioc);
1166 }
aaf7c680 1167out:
88ee5ef1
JA
1168 /*
1169 * ioc may be NULL here, and ioc_batching will be false. That's
1170 * OK, if the queue is under the request limit then requests need
1171 * not count toward the nr_batch_requests limit. There will always
1172 * be some limit enforced by BLK_BATCH_TIME.
1173 */
1da177e4
LT
1174 if (ioc_batching(q, ioc))
1175 ioc->nr_batch_requests--;
6728cb0e 1176
1faa16d2 1177 trace_block_getrq(q, bio, rw_flags & 1);
1da177e4 1178 return rq;
b679281a 1179
aaf7c680
TH
1180fail_elvpriv:
1181 /*
1182 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1183 * and may fail indefinitely under memory pressure and thus
1184 * shouldn't stall IO. Treat this request as !elvpriv. This will
1185 * disturb iosched and blkcg but weird is bettern than dead.
1186 */
7b2b10e0
RE
1187 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1188 __func__, dev_name(q->backing_dev_info.dev));
aaf7c680
TH
1189
1190 rq->cmd_flags &= ~REQ_ELVPRIV;
1191 rq->elv.icq = NULL;
1192
1193 spin_lock_irq(q->queue_lock);
8a5ecdd4 1194 q->nr_rqs_elvpriv--;
aaf7c680
TH
1195 spin_unlock_irq(q->queue_lock);
1196 goto out;
1197
b679281a
TH
1198fail_alloc:
1199 /*
1200 * Allocation failed presumably due to memory. Undo anything we
1201 * might have messed up.
1202 *
1203 * Allocating task should really be put onto the front of the wait
1204 * queue, but this is pretty rare.
1205 */
1206 spin_lock_irq(q->queue_lock);
5b788ce3 1207 freed_request(rl, rw_flags);
b679281a
TH
1208
1209 /*
1210 * in the very unlikely event that allocation failed and no
1211 * requests for this direction was pending, mark us starved so that
1212 * freeing of a request in the other direction will notice
1213 * us. another possible fix would be to split the rq mempool into
1214 * READ and WRITE
1215 */
1216rq_starved:
1217 if (unlikely(rl->count[is_sync] == 0))
1218 rl->starved[is_sync] = 1;
a492f075 1219 return ERR_PTR(-ENOMEM);
1da177e4
LT
1220}
1221
da8303c6 1222/**
a06e05e6 1223 * get_request - get a free request
da8303c6
TH
1224 * @q: request_queue to allocate request from
1225 * @rw_flags: RW and SYNC flags
1226 * @bio: bio to allocate request for (can be %NULL)
a06e05e6 1227 * @gfp_mask: allocation mask
da8303c6 1228 *
d0164adc
MG
1229 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1230 * this function keeps retrying under memory pressure and fails iff @q is dead.
d6344532 1231 *
da3dae54 1232 * Must be called with @q->queue_lock held and,
a492f075
JL
1233 * Returns ERR_PTR on failure, with @q->queue_lock held.
1234 * Returns request pointer on success, with @q->queue_lock *not held*.
1da177e4 1235 */
a06e05e6
TH
1236static struct request *get_request(struct request_queue *q, int rw_flags,
1237 struct bio *bio, gfp_t gfp_mask)
1da177e4 1238{
1faa16d2 1239 const bool is_sync = rw_is_sync(rw_flags) != 0;
a06e05e6 1240 DEFINE_WAIT(wait);
a051661c 1241 struct request_list *rl;
1da177e4 1242 struct request *rq;
a051661c
TH
1243
1244 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
a06e05e6 1245retry:
a051661c 1246 rq = __get_request(rl, rw_flags, bio, gfp_mask);
a492f075 1247 if (!IS_ERR(rq))
a06e05e6 1248 return rq;
1da177e4 1249
d0164adc 1250 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
a051661c 1251 blk_put_rl(rl);
a492f075 1252 return rq;
a051661c 1253 }
1da177e4 1254
a06e05e6
TH
1255 /* wait on @rl and retry */
1256 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1257 TASK_UNINTERRUPTIBLE);
1da177e4 1258
a06e05e6 1259 trace_block_sleeprq(q, bio, rw_flags & 1);
1da177e4 1260
a06e05e6
TH
1261 spin_unlock_irq(q->queue_lock);
1262 io_schedule();
d6344532 1263
a06e05e6
TH
1264 /*
1265 * After sleeping, we become a "batching" process and will be able
1266 * to allocate at least one request, and up to a big batch of them
1267 * for a small period time. See ioc_batching, ioc_set_batching
1268 */
a06e05e6 1269 ioc_set_batching(q, current->io_context);
05caf8db 1270
a06e05e6
TH
1271 spin_lock_irq(q->queue_lock);
1272 finish_wait(&rl->wait[is_sync], &wait);
1da177e4 1273
a06e05e6 1274 goto retry;
1da177e4
LT
1275}
1276
320ae51f
JA
1277static struct request *blk_old_get_request(struct request_queue *q, int rw,
1278 gfp_t gfp_mask)
1da177e4
LT
1279{
1280 struct request *rq;
1281
1282 BUG_ON(rw != READ && rw != WRITE);
1283
7f4b35d1
TH
1284 /* create ioc upfront */
1285 create_io_context(gfp_mask, q->node);
1286
d6344532 1287 spin_lock_irq(q->queue_lock);
a06e05e6 1288 rq = get_request(q, rw, NULL, gfp_mask);
a492f075 1289 if (IS_ERR(rq))
da8303c6 1290 spin_unlock_irq(q->queue_lock);
d6344532 1291 /* q->queue_lock is unlocked at this point */
1da177e4
LT
1292
1293 return rq;
1294}
320ae51f
JA
1295
1296struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1297{
1298 if (q->mq_ops)
4ce01dd1 1299 return blk_mq_alloc_request(q, rw, gfp_mask, false);
320ae51f
JA
1300 else
1301 return blk_old_get_request(q, rw, gfp_mask);
1302}
1da177e4
LT
1303EXPORT_SYMBOL(blk_get_request);
1304
dc72ef4a 1305/**
79eb63e9 1306 * blk_make_request - given a bio, allocate a corresponding struct request.
8ebf9756 1307 * @q: target request queue
79eb63e9
BH
1308 * @bio: The bio describing the memory mappings that will be submitted for IO.
1309 * It may be a chained-bio properly constructed by block/bio layer.
8ebf9756 1310 * @gfp_mask: gfp flags to be used for memory allocation
dc72ef4a 1311 *
79eb63e9
BH
1312 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1313 * type commands. Where the struct request needs to be farther initialized by
1314 * the caller. It is passed a &struct bio, which describes the memory info of
1315 * the I/O transfer.
dc72ef4a 1316 *
79eb63e9
BH
1317 * The caller of blk_make_request must make sure that bi_io_vec
1318 * are set to describe the memory buffers. That bio_data_dir() will return
1319 * the needed direction of the request. (And all bio's in the passed bio-chain
1320 * are properly set accordingly)
1321 *
1322 * If called under none-sleepable conditions, mapped bio buffers must not
1323 * need bouncing, by calling the appropriate masked or flagged allocator,
1324 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1325 * BUG.
53674ac5
JA
1326 *
1327 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
d0164adc
MG
1328 * given to how you allocate bios. In particular, you cannot use
1329 * __GFP_DIRECT_RECLAIM for anything but the first bio in the chain. Otherwise
1330 * you risk waiting for IO completion of a bio that hasn't been submitted yet,
1331 * thus resulting in a deadlock. Alternatively bios should be allocated using
1332 * bio_kmalloc() instead of bio_alloc(), as that avoids the mempool deadlock.
53674ac5
JA
1333 * If possible a big IO should be split into smaller parts when allocation
1334 * fails. Partial allocation should not be an error, or you risk a live-lock.
dc72ef4a 1335 */
79eb63e9
BH
1336struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1337 gfp_t gfp_mask)
dc72ef4a 1338{
79eb63e9
BH
1339 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1340
a492f075
JL
1341 if (IS_ERR(rq))
1342 return rq;
79eb63e9 1343
f27b087b
JA
1344 blk_rq_set_block_pc(rq);
1345
79eb63e9
BH
1346 for_each_bio(bio) {
1347 struct bio *bounce_bio = bio;
1348 int ret;
1349
1350 blk_queue_bounce(q, &bounce_bio);
1351 ret = blk_rq_append_bio(q, rq, bounce_bio);
1352 if (unlikely(ret)) {
1353 blk_put_request(rq);
1354 return ERR_PTR(ret);
1355 }
1356 }
1357
1358 return rq;
dc72ef4a 1359}
79eb63e9 1360EXPORT_SYMBOL(blk_make_request);
dc72ef4a 1361
f27b087b 1362/**
da3dae54 1363 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
f27b087b
JA
1364 * @rq: request to be initialized
1365 *
1366 */
1367void blk_rq_set_block_pc(struct request *rq)
1368{
1369 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1370 rq->__data_len = 0;
1371 rq->__sector = (sector_t) -1;
1372 rq->bio = rq->biotail = NULL;
1373 memset(rq->__cmd, 0, sizeof(rq->__cmd));
f27b087b
JA
1374}
1375EXPORT_SYMBOL(blk_rq_set_block_pc);
1376
1da177e4
LT
1377/**
1378 * blk_requeue_request - put a request back on queue
1379 * @q: request queue where request should be inserted
1380 * @rq: request to be inserted
1381 *
1382 * Description:
1383 * Drivers often keep queueing requests until the hardware cannot accept
1384 * more, when that condition happens we need to put the request back
1385 * on the queue. Must be called with queue lock held.
1386 */
165125e1 1387void blk_requeue_request(struct request_queue *q, struct request *rq)
1da177e4 1388{
242f9dcb
JA
1389 blk_delete_timer(rq);
1390 blk_clear_rq_complete(rq);
5f3ea37c 1391 trace_block_rq_requeue(q, rq);
2056a782 1392
125c99bc 1393 if (rq->cmd_flags & REQ_QUEUED)
1da177e4
LT
1394 blk_queue_end_tag(q, rq);
1395
ba396a6c
JB
1396 BUG_ON(blk_queued_rq(rq));
1397
1da177e4
LT
1398 elv_requeue_request(q, rq);
1399}
1da177e4
LT
1400EXPORT_SYMBOL(blk_requeue_request);
1401
73c10101
JA
1402static void add_acct_request(struct request_queue *q, struct request *rq,
1403 int where)
1404{
320ae51f 1405 blk_account_io_start(rq, true);
7eaceacc 1406 __elv_add_request(q, rq, where);
73c10101
JA
1407}
1408
074a7aca
TH
1409static void part_round_stats_single(int cpu, struct hd_struct *part,
1410 unsigned long now)
1411{
7276d02e
JA
1412 int inflight;
1413
074a7aca
TH
1414 if (now == part->stamp)
1415 return;
1416
7276d02e
JA
1417 inflight = part_in_flight(part);
1418 if (inflight) {
074a7aca 1419 __part_stat_add(cpu, part, time_in_queue,
7276d02e 1420 inflight * (now - part->stamp));
074a7aca
TH
1421 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1422 }
1423 part->stamp = now;
1424}
1425
1426/**
496aa8a9
RD
1427 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1428 * @cpu: cpu number for stats access
1429 * @part: target partition
1da177e4
LT
1430 *
1431 * The average IO queue length and utilisation statistics are maintained
1432 * by observing the current state of the queue length and the amount of
1433 * time it has been in this state for.
1434 *
1435 * Normally, that accounting is done on IO completion, but that can result
1436 * in more than a second's worth of IO being accounted for within any one
1437 * second, leading to >100% utilisation. To deal with that, we call this
1438 * function to do a round-off before returning the results when reading
1439 * /proc/diskstats. This accounts immediately for all queue usage up to
1440 * the current jiffies and restarts the counters again.
1441 */
c9959059 1442void part_round_stats(int cpu, struct hd_struct *part)
6f2576af
JM
1443{
1444 unsigned long now = jiffies;
1445
074a7aca
TH
1446 if (part->partno)
1447 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1448 part_round_stats_single(cpu, part, now);
6f2576af 1449}
074a7aca 1450EXPORT_SYMBOL_GPL(part_round_stats);
6f2576af 1451
47fafbc7 1452#ifdef CONFIG_PM
c8158819
LM
1453static void blk_pm_put_request(struct request *rq)
1454{
1455 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1456 pm_runtime_mark_last_busy(rq->q->dev);
1457}
1458#else
1459static inline void blk_pm_put_request(struct request *rq) {}
1460#endif
1461
1da177e4
LT
1462/*
1463 * queue lock must be held
1464 */
165125e1 1465void __blk_put_request(struct request_queue *q, struct request *req)
1da177e4 1466{
1da177e4
LT
1467 if (unlikely(!q))
1468 return;
1da177e4 1469
6f5ba581
CH
1470 if (q->mq_ops) {
1471 blk_mq_free_request(req);
1472 return;
1473 }
1474
c8158819
LM
1475 blk_pm_put_request(req);
1476
8922e16c
TH
1477 elv_completed_request(q, req);
1478
1cd96c24
BH
1479 /* this is a bio leak */
1480 WARN_ON(req->bio != NULL);
1481
1da177e4
LT
1482 /*
1483 * Request may not have originated from ll_rw_blk. if not,
1484 * it didn't come out of our reserved rq pools
1485 */
49171e5c 1486 if (req->cmd_flags & REQ_ALLOCED) {
75eb6c37 1487 unsigned int flags = req->cmd_flags;
a051661c 1488 struct request_list *rl = blk_rq_rl(req);
1da177e4 1489
1da177e4 1490 BUG_ON(!list_empty(&req->queuelist));
360f92c2 1491 BUG_ON(ELV_ON_HASH(req));
1da177e4 1492
a051661c
TH
1493 blk_free_request(rl, req);
1494 freed_request(rl, flags);
1495 blk_put_rl(rl);
1da177e4
LT
1496 }
1497}
6e39b69e
MC
1498EXPORT_SYMBOL_GPL(__blk_put_request);
1499
1da177e4
LT
1500void blk_put_request(struct request *req)
1501{
165125e1 1502 struct request_queue *q = req->q;
8922e16c 1503
320ae51f
JA
1504 if (q->mq_ops)
1505 blk_mq_free_request(req);
1506 else {
1507 unsigned long flags;
1508
1509 spin_lock_irqsave(q->queue_lock, flags);
1510 __blk_put_request(q, req);
1511 spin_unlock_irqrestore(q->queue_lock, flags);
1512 }
1da177e4 1513}
1da177e4
LT
1514EXPORT_SYMBOL(blk_put_request);
1515
66ac0280
CH
1516/**
1517 * blk_add_request_payload - add a payload to a request
1518 * @rq: request to update
1519 * @page: page backing the payload
1520 * @len: length of the payload.
1521 *
1522 * This allows to later add a payload to an already submitted request by
1523 * a block driver. The driver needs to take care of freeing the payload
1524 * itself.
1525 *
1526 * Note that this is a quite horrible hack and nothing but handling of
1527 * discard requests should ever use it.
1528 */
1529void blk_add_request_payload(struct request *rq, struct page *page,
1530 unsigned int len)
1531{
1532 struct bio *bio = rq->bio;
1533
1534 bio->bi_io_vec->bv_page = page;
1535 bio->bi_io_vec->bv_offset = 0;
1536 bio->bi_io_vec->bv_len = len;
1537
4f024f37 1538 bio->bi_iter.bi_size = len;
66ac0280
CH
1539 bio->bi_vcnt = 1;
1540 bio->bi_phys_segments = 1;
1541
1542 rq->__data_len = rq->resid_len = len;
1543 rq->nr_phys_segments = 1;
66ac0280
CH
1544}
1545EXPORT_SYMBOL_GPL(blk_add_request_payload);
1546
320ae51f
JA
1547bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1548 struct bio *bio)
73c10101
JA
1549{
1550 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1551
73c10101
JA
1552 if (!ll_back_merge_fn(q, req, bio))
1553 return false;
1554
8c1cf6bb 1555 trace_block_bio_backmerge(q, req, bio);
73c10101
JA
1556
1557 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1558 blk_rq_set_mixed_merge(req);
1559
1560 req->biotail->bi_next = bio;
1561 req->biotail = bio;
4f024f37 1562 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1563 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1564
320ae51f 1565 blk_account_io_start(req, false);
73c10101
JA
1566 return true;
1567}
1568
320ae51f
JA
1569bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1570 struct bio *bio)
73c10101
JA
1571{
1572 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
73c10101 1573
73c10101
JA
1574 if (!ll_front_merge_fn(q, req, bio))
1575 return false;
1576
8c1cf6bb 1577 trace_block_bio_frontmerge(q, req, bio);
73c10101
JA
1578
1579 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1580 blk_rq_set_mixed_merge(req);
1581
73c10101
JA
1582 bio->bi_next = req->bio;
1583 req->bio = bio;
1584
4f024f37
KO
1585 req->__sector = bio->bi_iter.bi_sector;
1586 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
1587 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1588
320ae51f 1589 blk_account_io_start(req, false);
73c10101
JA
1590 return true;
1591}
1592
bd87b589 1593/**
320ae51f 1594 * blk_attempt_plug_merge - try to merge with %current's plugged list
bd87b589
TH
1595 * @q: request_queue new bio is being queued at
1596 * @bio: new bio being queued
1597 * @request_count: out parameter for number of traversed plugged requests
ccc2600b
RD
1598 * @same_queue_rq: pointer to &struct request that gets filled in when
1599 * another request associated with @q is found on the plug list
1600 * (optional, may be %NULL)
bd87b589
TH
1601 *
1602 * Determine whether @bio being queued on @q can be merged with a request
1603 * on %current's plugged list. Returns %true if merge was successful,
1604 * otherwise %false.
1605 *
07c2bd37
TH
1606 * Plugging coalesces IOs from the same issuer for the same purpose without
1607 * going through @q->queue_lock. As such it's more of an issuing mechanism
1608 * than scheduling, and the request, while may have elvpriv data, is not
1609 * added on the elevator at this point. In addition, we don't have
1610 * reliable access to the elevator outside queue lock. Only check basic
1611 * merging parameters without querying the elevator.
da41a589
RE
1612 *
1613 * Caller must ensure !blk_queue_nomerges(q) beforehand.
73c10101 1614 */
320ae51f 1615bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
5b3f341f
SL
1616 unsigned int *request_count,
1617 struct request **same_queue_rq)
73c10101
JA
1618{
1619 struct blk_plug *plug;
1620 struct request *rq;
1621 bool ret = false;
92f399c7 1622 struct list_head *plug_list;
73c10101 1623
bd87b589 1624 plug = current->plug;
73c10101
JA
1625 if (!plug)
1626 goto out;
56ebdaf2 1627 *request_count = 0;
73c10101 1628
92f399c7
SL
1629 if (q->mq_ops)
1630 plug_list = &plug->mq_list;
1631 else
1632 plug_list = &plug->list;
1633
1634 list_for_each_entry_reverse(rq, plug_list, queuelist) {
73c10101
JA
1635 int el_ret;
1636
5b3f341f 1637 if (rq->q == q) {
1b2e19f1 1638 (*request_count)++;
5b3f341f
SL
1639 /*
1640 * Only blk-mq multiple hardware queues case checks the
1641 * rq in the same queue, there should be only one such
1642 * rq in a queue
1643 **/
1644 if (same_queue_rq)
1645 *same_queue_rq = rq;
1646 }
56ebdaf2 1647
07c2bd37 1648 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
73c10101
JA
1649 continue;
1650
050c8ea8 1651 el_ret = blk_try_merge(rq, bio);
73c10101
JA
1652 if (el_ret == ELEVATOR_BACK_MERGE) {
1653 ret = bio_attempt_back_merge(q, rq, bio);
1654 if (ret)
1655 break;
1656 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1657 ret = bio_attempt_front_merge(q, rq, bio);
1658 if (ret)
1659 break;
1660 }
1661 }
1662out:
1663 return ret;
1664}
1665
0809e3ac
JM
1666unsigned int blk_plug_queued_count(struct request_queue *q)
1667{
1668 struct blk_plug *plug;
1669 struct request *rq;
1670 struct list_head *plug_list;
1671 unsigned int ret = 0;
1672
1673 plug = current->plug;
1674 if (!plug)
1675 goto out;
1676
1677 if (q->mq_ops)
1678 plug_list = &plug->mq_list;
1679 else
1680 plug_list = &plug->list;
1681
1682 list_for_each_entry(rq, plug_list, queuelist) {
1683 if (rq->q == q)
1684 ret++;
1685 }
1686out:
1687 return ret;
1688}
1689
86db1e29 1690void init_request_from_bio(struct request *req, struct bio *bio)
52d9e675 1691{
4aff5e23 1692 req->cmd_type = REQ_TYPE_FS;
52d9e675 1693
7b6d91da
CH
1694 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1695 if (bio->bi_rw & REQ_RAHEAD)
a82afdfc 1696 req->cmd_flags |= REQ_FAILFAST_MASK;
b31dc66a 1697
1cac41cb
MB
1698#ifdef CONFIG_JOURNAL_DATA_TAG
1699 if (bio_flagged(bio, BIO_JMETA) || bio_flagged(bio, BIO_JOURNAL))
1700 req->cmd_flags |= REQ_META;
1701#endif
1702
52d9e675 1703 req->errors = 0;
4f024f37 1704 req->__sector = bio->bi_iter.bi_sector;
52d9e675 1705 req->ioprio = bio_prio(bio);
bc1c56fd 1706 blk_rq_bio_prep(req->q, req, bio);
52d9e675
TH
1707}
1708
dece1635 1709static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1da177e4 1710{
5e00d1b5 1711 const bool sync = !!(bio->bi_rw & REQ_SYNC);
73c10101
JA
1712 struct blk_plug *plug;
1713 int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1714 struct request *req;
56ebdaf2 1715 unsigned int request_count = 0;
1da177e4 1716
1da177e4
LT
1717 /*
1718 * low level driver can indicate that it wants pages above a
1719 * certain limit bounced to low memory (ie for highmem, or even
1720 * ISA dma in theory)
1721 */
1722 blk_queue_bounce(q, &bio);
1723
23688bf4
JN
1724 blk_queue_split(q, &bio, q->bio_split);
1725
ffecfd1a 1726 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
4246a0b6
CH
1727 bio->bi_error = -EIO;
1728 bio_endio(bio);
dece1635 1729 return BLK_QC_T_NONE;
ffecfd1a
DW
1730 }
1731
4fed947c 1732 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
73c10101 1733 spin_lock_irq(q->queue_lock);
ae1b1539 1734 where = ELEVATOR_INSERT_FLUSH;
28e7d184
TH
1735 goto get_rq;
1736 }
1737
73c10101
JA
1738 /*
1739 * Check if we can merge with the plugged list before grabbing
1740 * any locks.
1741 */
0809e3ac
JM
1742 if (!blk_queue_nomerges(q)) {
1743 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
dece1635 1744 return BLK_QC_T_NONE;
0809e3ac
JM
1745 } else
1746 request_count = blk_plug_queued_count(q);
1da177e4 1747
73c10101 1748 spin_lock_irq(q->queue_lock);
2056a782 1749
73c10101
JA
1750 el_ret = elv_merge(q, &req, bio);
1751 if (el_ret == ELEVATOR_BACK_MERGE) {
73c10101 1752 if (bio_attempt_back_merge(q, req, bio)) {
07c2bd37 1753 elv_bio_merged(q, req, bio);
73c10101
JA
1754 if (!attempt_back_merge(q, req))
1755 elv_merged_request(q, req, el_ret);
1756 goto out_unlock;
1757 }
1758 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
73c10101 1759 if (bio_attempt_front_merge(q, req, bio)) {
07c2bd37 1760 elv_bio_merged(q, req, bio);
73c10101
JA
1761 if (!attempt_front_merge(q, req))
1762 elv_merged_request(q, req, el_ret);
1763 goto out_unlock;
80a761fd 1764 }
1da177e4
LT
1765 }
1766
450991bc 1767get_rq:
7749a8d4
JA
1768 /*
1769 * This sync check and mask will be re-done in init_request_from_bio(),
1770 * but we need to set it earlier to expose the sync flag to the
1771 * rq allocator and io schedulers.
1772 */
1773 rw_flags = bio_data_dir(bio);
1774 if (sync)
7b6d91da 1775 rw_flags |= REQ_SYNC;
7749a8d4 1776
1da177e4 1777 /*
450991bc 1778 * Grab a free request. This is might sleep but can not fail.
d6344532 1779 * Returns with the queue unlocked.
450991bc 1780 */
a06e05e6 1781 req = get_request(q, rw_flags, bio, GFP_NOIO);
a492f075 1782 if (IS_ERR(req)) {
4246a0b6
CH
1783 bio->bi_error = PTR_ERR(req);
1784 bio_endio(bio);
da8303c6
TH
1785 goto out_unlock;
1786 }
d6344532 1787
450991bc
NP
1788 /*
1789 * After dropping the lock and possibly sleeping here, our request
1790 * may now be mergeable after it had proven unmergeable (above).
1791 * We don't worry about that case for efficiency. It won't happen
1792 * often, and the elevators are able to handle it.
1da177e4 1793 */
52d9e675 1794 init_request_from_bio(req, bio);
1da177e4 1795
9562ad9a 1796 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
11ccf116 1797 req->cpu = raw_smp_processor_id();
73c10101
JA
1798
1799 plug = current->plug;
721a9602 1800 if (plug) {
dc6d36c9
JA
1801 /*
1802 * If this is the first request added after a plug, fire
7aef2e78 1803 * of a plug trace.
dc6d36c9 1804 */
7aef2e78 1805 if (!request_count)
dc6d36c9 1806 trace_block_plug(q);
3540d5e8 1807 else {
019ceb7d 1808 if (request_count >= BLK_MAX_REQUEST_COUNT) {
3540d5e8 1809 blk_flush_plug_list(plug, false);
019ceb7d
SL
1810 trace_block_plug(q);
1811 }
73c10101 1812 }
73c10101 1813 list_add_tail(&req->queuelist, &plug->list);
320ae51f 1814 blk_account_io_start(req, true);
73c10101
JA
1815 } else {
1816 spin_lock_irq(q->queue_lock);
1817 add_acct_request(q, req, where);
24ecfbe2 1818 __blk_run_queue(q);
73c10101
JA
1819out_unlock:
1820 spin_unlock_irq(q->queue_lock);
1821 }
dece1635
JA
1822
1823 return BLK_QC_T_NONE;
1da177e4
LT
1824}
1825
1826/*
1827 * If bio->bi_dev is a partition, remap the location
1828 */
1829static inline void blk_partition_remap(struct bio *bio)
1830{
1831 struct block_device *bdev = bio->bi_bdev;
1832
bf2de6f5 1833 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1da177e4
LT
1834 struct hd_struct *p = bdev->bd_part;
1835
4f024f37 1836 bio->bi_iter.bi_sector += p->start_sect;
1da177e4 1837 bio->bi_bdev = bdev->bd_contains;
c7149d6b 1838
d07335e5
MS
1839 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1840 bdev->bd_dev,
4f024f37 1841 bio->bi_iter.bi_sector - p->start_sect);
1da177e4
LT
1842 }
1843}
1844
1da177e4
LT
1845static void handle_bad_sector(struct bio *bio)
1846{
1847 char b[BDEVNAME_SIZE];
1848
1849 printk(KERN_INFO "attempt to access beyond end of device\n");
1850 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1851 bdevname(bio->bi_bdev, b),
1852 bio->bi_rw,
f73a1c7d 1853 (unsigned long long)bio_end_sector(bio),
77304d2a 1854 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1da177e4
LT
1855}
1856
c17bb495
AM
1857#ifdef CONFIG_FAIL_MAKE_REQUEST
1858
1859static DECLARE_FAULT_ATTR(fail_make_request);
1860
1861static int __init setup_fail_make_request(char *str)
1862{
1863 return setup_fault_attr(&fail_make_request, str);
1864}
1865__setup("fail_make_request=", setup_fail_make_request);
1866
b2c9cd37 1867static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
c17bb495 1868{
b2c9cd37 1869 return part->make_it_fail && should_fail(&fail_make_request, bytes);
c17bb495
AM
1870}
1871
1872static int __init fail_make_request_debugfs(void)
1873{
dd48c085
AM
1874 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1875 NULL, &fail_make_request);
1876
21f9fcd8 1877 return PTR_ERR_OR_ZERO(dir);
c17bb495
AM
1878}
1879
1880late_initcall(fail_make_request_debugfs);
1881
1882#else /* CONFIG_FAIL_MAKE_REQUEST */
1883
b2c9cd37
AM
1884static inline bool should_fail_request(struct hd_struct *part,
1885 unsigned int bytes)
c17bb495 1886{
b2c9cd37 1887 return false;
c17bb495
AM
1888}
1889
1890#endif /* CONFIG_FAIL_MAKE_REQUEST */
1891
c07e2b41
JA
1892/*
1893 * Check whether this bio extends beyond the end of the device.
1894 */
1895static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1896{
1897 sector_t maxsector;
1898
1899 if (!nr_sectors)
1900 return 0;
1901
1902 /* Test device or partition size, when known. */
77304d2a 1903 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
c07e2b41 1904 if (maxsector) {
4f024f37 1905 sector_t sector = bio->bi_iter.bi_sector;
c07e2b41
JA
1906
1907 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1908 /*
1909 * This may well happen - the kernel calls bread()
1910 * without checking the size of the device, e.g., when
1911 * mounting a device.
1912 */
1913 handle_bad_sector(bio);
1914 return 1;
1915 }
1916 }
1917
1918 return 0;
1919}
1920
27a84d54
CH
1921static noinline_for_stack bool
1922generic_make_request_checks(struct bio *bio)
1da177e4 1923{
165125e1 1924 struct request_queue *q;
5a7bbad2 1925 int nr_sectors = bio_sectors(bio);
51fd77bd 1926 int err = -EIO;
5a7bbad2
CH
1927 char b[BDEVNAME_SIZE];
1928 struct hd_struct *part;
1da177e4
LT
1929
1930 might_sleep();
1da177e4 1931
c07e2b41
JA
1932 if (bio_check_eod(bio, nr_sectors))
1933 goto end_io;
1da177e4 1934
5a7bbad2
CH
1935 q = bdev_get_queue(bio->bi_bdev);
1936 if (unlikely(!q)) {
1937 printk(KERN_ERR
1938 "generic_make_request: Trying to access "
1939 "nonexistent block-device %s (%Lu)\n",
1940 bdevname(bio->bi_bdev, b),
4f024f37 1941 (long long) bio->bi_iter.bi_sector);
5a7bbad2
CH
1942 goto end_io;
1943 }
c17bb495 1944
5a7bbad2 1945 part = bio->bi_bdev->bd_part;
4f024f37 1946 if (should_fail_request(part, bio->bi_iter.bi_size) ||
5a7bbad2 1947 should_fail_request(&part_to_disk(part)->part0,
4f024f37 1948 bio->bi_iter.bi_size))
5a7bbad2 1949 goto end_io;
2056a782 1950
5a7bbad2
CH
1951 /*
1952 * If this device has partitions, remap block n
1953 * of partition p to block n+start(p) of the disk.
1954 */
1955 blk_partition_remap(bio);
2056a782 1956
5a7bbad2
CH
1957 if (bio_check_eod(bio, nr_sectors))
1958 goto end_io;
1e87901e 1959
5a7bbad2
CH
1960 /*
1961 * Filter flush bio's early so that make_request based
1962 * drivers without flush support don't have to worry
1963 * about them.
1964 */
1965 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1966 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1967 if (!nr_sectors) {
1968 err = 0;
51fd77bd
JA
1969 goto end_io;
1970 }
5a7bbad2 1971 }
5ddfe969 1972
5a7bbad2
CH
1973 if ((bio->bi_rw & REQ_DISCARD) &&
1974 (!blk_queue_discard(q) ||
e2a60da7 1975 ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
5a7bbad2
CH
1976 err = -EOPNOTSUPP;
1977 goto end_io;
1978 }
01edede4 1979
4363ac7c 1980 if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
5a7bbad2
CH
1981 err = -EOPNOTSUPP;
1982 goto end_io;
1983 }
01edede4 1984
7f4b35d1
TH
1985 /*
1986 * Various block parts want %current->io_context and lazy ioc
1987 * allocation ends up trading a lot of pain for a small amount of
1988 * memory. Just allocate it upfront. This may fail and block
1989 * layer knows how to live with it.
1990 */
1991 create_io_context(GFP_ATOMIC, q->node);
1992
ae118896
TH
1993 if (!blkcg_bio_issue_check(q, bio))
1994 return false;
27a84d54 1995
5a7bbad2 1996 trace_block_bio_queue(q, bio);
27a84d54 1997 return true;
a7384677
TH
1998
1999end_io:
4246a0b6
CH
2000 bio->bi_error = err;
2001 bio_endio(bio);
27a84d54 2002 return false;
1da177e4
LT
2003}
2004
27a84d54
CH
2005/**
2006 * generic_make_request - hand a buffer to its device driver for I/O
2007 * @bio: The bio describing the location in memory and on the device.
2008 *
2009 * generic_make_request() is used to make I/O requests of block
2010 * devices. It is passed a &struct bio, which describes the I/O that needs
2011 * to be done.
2012 *
2013 * generic_make_request() does not return any status. The
2014 * success/failure status of the request, along with notification of
2015 * completion, is delivered asynchronously through the bio->bi_end_io
2016 * function described (one day) else where.
2017 *
2018 * The caller of generic_make_request must make sure that bi_io_vec
2019 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2020 * set to describe the device address, and the
2021 * bi_end_io and optionally bi_private are set to describe how
2022 * completion notification should be signaled.
2023 *
2024 * generic_make_request and the drivers it calls may use bi_next if this
2025 * bio happens to be merged with someone else, and may resubmit the bio to
2026 * a lower device by calling into generic_make_request recursively, which
2027 * means the bio should NOT be touched after the call to ->make_request_fn.
d89d8796 2028 */
dece1635 2029blk_qc_t generic_make_request(struct bio *bio)
d89d8796 2030{
5cca175b
N
2031 /*
2032 * bio_list_on_stack[0] contains bios submitted by the current
2033 * make_request_fn.
2034 * bio_list_on_stack[1] contains bios that were submitted before
2035 * the current make_request_fn, but that haven't been processed
2036 * yet.
2037 */
2038 struct bio_list bio_list_on_stack[2];
dece1635 2039 blk_qc_t ret = BLK_QC_T_NONE;
bddd87c7 2040
27a84d54 2041 if (!generic_make_request_checks(bio))
dece1635 2042 goto out;
27a84d54
CH
2043
2044 /*
2045 * We only want one ->make_request_fn to be active at a time, else
2046 * stack usage with stacked devices could be a problem. So use
2047 * current->bio_list to keep a list of requests submited by a
2048 * make_request_fn function. current->bio_list is also used as a
2049 * flag to say if generic_make_request is currently active in this
2050 * task or not. If it is NULL, then no make_request is active. If
2051 * it is non-NULL, then a make_request is active, and new requests
2052 * should be added at the tail
2053 */
bddd87c7 2054 if (current->bio_list) {
5cca175b 2055 bio_list_add(&current->bio_list[0], bio);
dece1635 2056 goto out;
d89d8796 2057 }
27a84d54 2058
d89d8796
NB
2059 /* following loop may be a bit non-obvious, and so deserves some
2060 * explanation.
2061 * Before entering the loop, bio->bi_next is NULL (as all callers
2062 * ensure that) so we have a list with a single bio.
2063 * We pretend that we have just taken it off a longer list, so
bddd87c7
AM
2064 * we assign bio_list to a pointer to the bio_list_on_stack,
2065 * thus initialising the bio_list of new bios to be
27a84d54 2066 * added. ->make_request() may indeed add some more bios
d89d8796
NB
2067 * through a recursive call to generic_make_request. If it
2068 * did, we find a non-NULL value in bio_list and re-enter the loop
2069 * from the top. In this case we really did just take the bio
bddd87c7 2070 * of the top of the list (no pretending) and so remove it from
27a84d54 2071 * bio_list, and call into ->make_request() again.
d89d8796
NB
2072 */
2073 BUG_ON(bio->bi_next);
5cca175b
N
2074 bio_list_init(&bio_list_on_stack[0]);
2075 current->bio_list = bio_list_on_stack;
d89d8796 2076 do {
27a84d54
CH
2077 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2078
71baba4b 2079 if (likely(blk_queue_enter(q, __GFP_DIRECT_RECLAIM) == 0)) {
5cca175b 2080 struct bio_list lower, same;
2cbd78f4
N
2081
2082 /* Create a fresh bio_list for all subordinate requests */
5cca175b
N
2083 bio_list_on_stack[1] = bio_list_on_stack[0];
2084 bio_list_init(&bio_list_on_stack[0]);
3ef28e83 2085
dece1635 2086 ret = q->make_request_fn(q, bio);
3ef28e83
DW
2087
2088 blk_queue_exit(q);
2cbd78f4
N
2089 /* sort new bios into those for a lower level
2090 * and those for the same level
2091 */
2092 bio_list_init(&lower);
2093 bio_list_init(&same);
5cca175b 2094 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2cbd78f4
N
2095 if (q == bdev_get_queue(bio->bi_bdev))
2096 bio_list_add(&same, bio);
2097 else
2098 bio_list_add(&lower, bio);
2099 /* now assemble so we handle the lowest level first */
5cca175b
N
2100 bio_list_merge(&bio_list_on_stack[0], &lower);
2101 bio_list_merge(&bio_list_on_stack[0], &same);
2102 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
3ef28e83 2103 } else {
3ef28e83 2104 bio_io_error(bio);
3ef28e83 2105 }
5cca175b 2106 bio = bio_list_pop(&bio_list_on_stack[0]);
d89d8796 2107 } while (bio);
bddd87c7 2108 current->bio_list = NULL; /* deactivate */
dece1635
JA
2109
2110out:
2111 return ret;
d89d8796 2112}
1da177e4
LT
2113EXPORT_SYMBOL(generic_make_request);
2114
2115/**
710027a4 2116 * submit_bio - submit a bio to the block device layer for I/O
1da177e4
LT
2117 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2118 * @bio: The &struct bio which describes the I/O
2119 *
2120 * submit_bio() is very similar in purpose to generic_make_request(), and
2121 * uses that function to do most of the work. Both are fairly rough
710027a4 2122 * interfaces; @bio must be presetup and ready for I/O.
1da177e4
LT
2123 *
2124 */
dece1635 2125blk_qc_t submit_bio(int rw, struct bio *bio)
1da177e4 2126{
22e2c507 2127 bio->bi_rw |= rw;
1da177e4 2128
bf2de6f5
JA
2129 /*
2130 * If it's a regular read/write or a barrier with data attached,
2131 * go through the normal accounting stuff before submission.
2132 */
e2a60da7 2133 if (bio_has_data(bio)) {
4363ac7c
MP
2134 unsigned int count;
2135
2136 if (unlikely(rw & REQ_WRITE_SAME))
2137 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2138 else
2139 count = bio_sectors(bio);
2140
bf2de6f5
JA
2141 if (rw & WRITE) {
2142 count_vm_events(PGPGOUT, count);
2143 } else {
4f024f37 2144 task_io_account_read(bio->bi_iter.bi_size);
bf2de6f5
JA
2145 count_vm_events(PGPGIN, count);
2146 }
2147
2148 if (unlikely(block_dump)) {
2149 char b[BDEVNAME_SIZE];
8dcbdc74 2150 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
ba25f9dc 2151 current->comm, task_pid_nr(current),
bf2de6f5 2152 (rw & WRITE) ? "WRITE" : "READ",
4f024f37 2153 (unsigned long long)bio->bi_iter.bi_sector,
8dcbdc74
SM
2154 bdevname(bio->bi_bdev, b),
2155 count);
bf2de6f5 2156 }
1da177e4
LT
2157 }
2158
dece1635 2159 return generic_make_request(bio);
1da177e4 2160}
1da177e4
LT
2161EXPORT_SYMBOL(submit_bio);
2162
82124d60 2163/**
bf4e6b4e
HR
2164 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2165 * for new the queue limits
82124d60
KU
2166 * @q: the queue
2167 * @rq: the request being checked
2168 *
2169 * Description:
2170 * @rq may have been made based on weaker limitations of upper-level queues
2171 * in request stacking drivers, and it may violate the limitation of @q.
2172 * Since the block layer and the underlying device driver trust @rq
2173 * after it is inserted to @q, it should be checked against @q before
2174 * the insertion using this generic function.
2175 *
82124d60 2176 * Request stacking drivers like request-based dm may change the queue
bf4e6b4e
HR
2177 * limits when retrying requests on other queues. Those requests need
2178 * to be checked against the new queue limits again during dispatch.
82124d60 2179 */
bf4e6b4e
HR
2180static int blk_cloned_rq_check_limits(struct request_queue *q,
2181 struct request *rq)
82124d60 2182{
f31dc1cd 2183 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
82124d60
KU
2184 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2185 return -EIO;
2186 }
2187
2188 /*
2189 * queue's settings related to segment counting like q->bounce_pfn
2190 * may differ from that of other stacking queues.
2191 * Recalculate it to check the request correctly on this queue's
2192 * limitation.
2193 */
2194 blk_recalc_rq_segments(rq);
8a78362c 2195 if (rq->nr_phys_segments > queue_max_segments(q)) {
82124d60
KU
2196 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2197 return -EIO;
2198 }
2199
2200 return 0;
2201}
82124d60
KU
2202
2203/**
2204 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2205 * @q: the queue to submit the request
2206 * @rq: the request being queued
2207 */
2208int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2209{
2210 unsigned long flags;
4853abaa 2211 int where = ELEVATOR_INSERT_BACK;
82124d60 2212
bf4e6b4e 2213 if (blk_cloned_rq_check_limits(q, rq))
82124d60
KU
2214 return -EIO;
2215
b2c9cd37
AM
2216 if (rq->rq_disk &&
2217 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
82124d60 2218 return -EIO;
82124d60 2219
7fb4898e
KB
2220 if (q->mq_ops) {
2221 if (blk_queue_io_stat(q))
2222 blk_account_io_start(rq, true);
5504a470 2223 blk_mq_insert_request(rq, false, true, false);
7fb4898e
KB
2224 return 0;
2225 }
2226
82124d60 2227 spin_lock_irqsave(q->queue_lock, flags);
3f3299d5 2228 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
2229 spin_unlock_irqrestore(q->queue_lock, flags);
2230 return -ENODEV;
2231 }
82124d60
KU
2232
2233 /*
2234 * Submitting request must be dequeued before calling this function
2235 * because it will be linked to another request_queue
2236 */
2237 BUG_ON(blk_queued_rq(rq));
2238
4853abaa
JM
2239 if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
2240 where = ELEVATOR_INSERT_FLUSH;
2241
2242 add_acct_request(q, rq, where);
e67b77c7
JM
2243 if (where == ELEVATOR_INSERT_FLUSH)
2244 __blk_run_queue(q);
82124d60
KU
2245 spin_unlock_irqrestore(q->queue_lock, flags);
2246
2247 return 0;
2248}
2249EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2250
80a761fd
TH
2251/**
2252 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2253 * @rq: request to examine
2254 *
2255 * Description:
2256 * A request could be merge of IOs which require different failure
2257 * handling. This function determines the number of bytes which
2258 * can be failed from the beginning of the request without
2259 * crossing into area which need to be retried further.
2260 *
2261 * Return:
2262 * The number of bytes to fail.
2263 *
2264 * Context:
2265 * queue_lock must be held.
2266 */
2267unsigned int blk_rq_err_bytes(const struct request *rq)
2268{
2269 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2270 unsigned int bytes = 0;
2271 struct bio *bio;
2272
2273 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2274 return blk_rq_bytes(rq);
2275
2276 /*
2277 * Currently the only 'mixing' which can happen is between
2278 * different fastfail types. We can safely fail portions
2279 * which have all the failfast bits that the first one has -
2280 * the ones which are at least as eager to fail as the first
2281 * one.
2282 */
2283 for (bio = rq->bio; bio; bio = bio->bi_next) {
2284 if ((bio->bi_rw & ff) != ff)
2285 break;
4f024f37 2286 bytes += bio->bi_iter.bi_size;
80a761fd
TH
2287 }
2288
2289 /* this could lead to infinite loop */
2290 BUG_ON(blk_rq_bytes(rq) && !bytes);
2291 return bytes;
2292}
2293EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2294
320ae51f 2295void blk_account_io_completion(struct request *req, unsigned int bytes)
bc58ba94 2296{
c2553b58 2297 if (blk_do_io_stat(req)) {
bc58ba94
JA
2298 const int rw = rq_data_dir(req);
2299 struct hd_struct *part;
2300 int cpu;
2301
2302 cpu = part_stat_lock();
09e099d4 2303 part = req->part;
bc58ba94 2304 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
1cac41cb
MB
2305 if (req->cmd_flags & REQ_DISCARD)
2306 part_stat_add(cpu, part, discard_sectors, bytes >> 9);
bc58ba94
JA
2307 part_stat_unlock();
2308 }
2309}
2310
320ae51f 2311void blk_account_io_done(struct request *req)
bc58ba94 2312{
bc58ba94 2313 /*
dd4c133f
TH
2314 * Account IO completion. flush_rq isn't accounted as a
2315 * normal IO on queueing nor completion. Accounting the
2316 * containing request is enough.
bc58ba94 2317 */
414b4ff5 2318 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
bc58ba94
JA
2319 unsigned long duration = jiffies - req->start_time;
2320 const int rw = rq_data_dir(req);
2321 struct hd_struct *part;
2322 int cpu;
2323
2324 cpu = part_stat_lock();
09e099d4 2325 part = req->part;
bc58ba94
JA
2326
2327 part_stat_inc(cpu, part, ios[rw]);
2328 part_stat_add(cpu, part, ticks[rw], duration);
2329 part_round_stats(cpu, part);
316d315b 2330 part_dec_in_flight(part, rw);
1cac41cb
MB
2331 if (req->cmd_flags & REQ_DISCARD)
2332 part_stat_inc(cpu, part, discard_ios);
2333 if (!(req->cmd_flags & REQ_STARTED))
2334 part_stat_inc(cpu, part, flush_ios);
bc58ba94 2335
6c23a968 2336 hd_struct_put(part);
bc58ba94
JA
2337 part_stat_unlock();
2338 }
1cac41cb
MB
2339
2340 if (req->cmd_flags & REQ_FLUSH_SEQ)
2341 req->q->flush_ios++;
bc58ba94
JA
2342}
2343
47fafbc7 2344#ifdef CONFIG_PM
c8158819
LM
2345/*
2346 * Don't process normal requests when queue is suspended
2347 * or in the process of suspending/resuming
2348 */
2349static struct request *blk_pm_peek_request(struct request_queue *q,
2350 struct request *rq)
2351{
2352 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2353 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2354 return NULL;
2355 else
2356 return rq;
2357}
2358#else
2359static inline struct request *blk_pm_peek_request(struct request_queue *q,
2360 struct request *rq)
2361{
2362 return rq;
2363}
2364#endif
2365
320ae51f
JA
2366void blk_account_io_start(struct request *rq, bool new_io)
2367{
2368 struct hd_struct *part;
2369 int rw = rq_data_dir(rq);
2370 int cpu;
2371
2372 if (!blk_do_io_stat(rq))
2373 return;
2374
2375 cpu = part_stat_lock();
2376
2377 if (!new_io) {
2378 part = rq->part;
2379 part_stat_inc(cpu, part, merges[rw]);
2380 } else {
2381 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2382 if (!hd_struct_try_get(part)) {
2383 /*
2384 * The partition is already being removed,
2385 * the request will be accounted on the disk only
2386 *
2387 * We take a reference on disk->part0 although that
2388 * partition will never be deleted, so we can treat
2389 * it as any other partition.
2390 */
2391 part = &rq->rq_disk->part0;
2392 hd_struct_get(part);
2393 }
2394 part_round_stats(cpu, part);
2395 part_inc_in_flight(part, rw);
2396 rq->part = part;
2397 }
2398
2399 part_stat_unlock();
2400}
2401
3bcddeac 2402/**
9934c8c0
TH
2403 * blk_peek_request - peek at the top of a request queue
2404 * @q: request queue to peek at
2405 *
2406 * Description:
2407 * Return the request at the top of @q. The returned request
2408 * should be started using blk_start_request() before LLD starts
2409 * processing it.
2410 *
2411 * Return:
2412 * Pointer to the request at the top of @q if available. Null
2413 * otherwise.
2414 *
2415 * Context:
2416 * queue_lock must be held.
2417 */
2418struct request *blk_peek_request(struct request_queue *q)
158dbda0
TH
2419{
2420 struct request *rq;
2421 int ret;
2422
2423 while ((rq = __elv_next_request(q)) != NULL) {
c8158819
LM
2424
2425 rq = blk_pm_peek_request(q, rq);
2426 if (!rq)
2427 break;
2428
158dbda0
TH
2429 if (!(rq->cmd_flags & REQ_STARTED)) {
2430 /*
2431 * This is the first time the device driver
2432 * sees this request (possibly after
2433 * requeueing). Notify IO scheduler.
2434 */
33659ebb 2435 if (rq->cmd_flags & REQ_SORTED)
158dbda0
TH
2436 elv_activate_rq(q, rq);
2437
2438 /*
2439 * just mark as started even if we don't start
2440 * it, a request that has been delayed should
2441 * not be passed by new incoming requests
2442 */
2443 rq->cmd_flags |= REQ_STARTED;
2444 trace_block_rq_issue(q, rq);
2445 }
2446
2447 if (!q->boundary_rq || q->boundary_rq == rq) {
2448 q->end_sector = rq_end_sector(rq);
2449 q->boundary_rq = NULL;
2450 }
2451
2452 if (rq->cmd_flags & REQ_DONTPREP)
2453 break;
2454
2e46e8b2 2455 if (q->dma_drain_size && blk_rq_bytes(rq)) {
158dbda0
TH
2456 /*
2457 * make sure space for the drain appears we
2458 * know we can do this because max_hw_segments
2459 * has been adjusted to be one fewer than the
2460 * device can handle
2461 */
2462 rq->nr_phys_segments++;
2463 }
2464
2465 if (!q->prep_rq_fn)
2466 break;
2467
2468 ret = q->prep_rq_fn(q, rq);
2469 if (ret == BLKPREP_OK) {
2470 break;
2471 } else if (ret == BLKPREP_DEFER) {
2472 /*
2473 * the request may have been (partially) prepped.
2474 * we need to keep this request in the front to
2475 * avoid resource deadlock. REQ_STARTED will
2476 * prevent other fs requests from passing this one.
2477 */
2e46e8b2 2478 if (q->dma_drain_size && blk_rq_bytes(rq) &&
158dbda0
TH
2479 !(rq->cmd_flags & REQ_DONTPREP)) {
2480 /*
2481 * remove the space for the drain we added
2482 * so that we don't add it again
2483 */
2484 --rq->nr_phys_segments;
2485 }
2486
2487 rq = NULL;
2488 break;
2489 } else if (ret == BLKPREP_KILL) {
2490 rq->cmd_flags |= REQ_QUIET;
c143dc90
JB
2491 /*
2492 * Mark this request as started so we don't trigger
2493 * any debug logic in the end I/O path.
2494 */
2495 blk_start_request(rq);
40cbbb78 2496 __blk_end_request_all(rq, -EIO);
158dbda0
TH
2497 } else {
2498 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2499 break;
2500 }
2501 }
2502
2503 return rq;
2504}
9934c8c0 2505EXPORT_SYMBOL(blk_peek_request);
158dbda0 2506
9934c8c0 2507void blk_dequeue_request(struct request *rq)
158dbda0 2508{
9934c8c0
TH
2509 struct request_queue *q = rq->q;
2510
158dbda0
TH
2511 BUG_ON(list_empty(&rq->queuelist));
2512 BUG_ON(ELV_ON_HASH(rq));
2513
2514 list_del_init(&rq->queuelist);
2515
2516 /*
2517 * the time frame between a request being removed from the lists
2518 * and to it is freed is accounted as io that is in progress at
2519 * the driver side.
2520 */
9195291e 2521 if (blk_account_rq(rq)) {
1cac41cb
MB
2522 if (!queue_in_flight(q))
2523 q->in_flight_stamp = ktime_get();
0a7ae2ff 2524 q->in_flight[rq_is_sync(rq)]++;
9195291e
DS
2525 set_io_start_time_ns(rq);
2526 }
158dbda0
TH
2527}
2528
9934c8c0
TH
2529/**
2530 * blk_start_request - start request processing on the driver
2531 * @req: request to dequeue
2532 *
2533 * Description:
2534 * Dequeue @req and start timeout timer on it. This hands off the
2535 * request to the driver.
2536 *
2537 * Block internal functions which don't want to start timer should
2538 * call blk_dequeue_request().
2539 *
2540 * Context:
2541 * queue_lock must be held.
2542 */
2543void blk_start_request(struct request *req)
2544{
2545 blk_dequeue_request(req);
2546
2547 /*
5f49f631
TH
2548 * We are now handing the request to the hardware, initialize
2549 * resid_len to full count and add the timeout handler.
9934c8c0 2550 */
5f49f631 2551 req->resid_len = blk_rq_bytes(req);
dbb66c4b
FT
2552 if (unlikely(blk_bidi_rq(req)))
2553 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2554
4912aa6c 2555 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
9934c8c0
TH
2556 blk_add_timer(req);
2557}
2558EXPORT_SYMBOL(blk_start_request);
2559
2560/**
2561 * blk_fetch_request - fetch a request from a request queue
2562 * @q: request queue to fetch a request from
2563 *
2564 * Description:
2565 * Return the request at the top of @q. The request is started on
2566 * return and LLD can start processing it immediately.
2567 *
2568 * Return:
2569 * Pointer to the request at the top of @q if available. Null
2570 * otherwise.
2571 *
2572 * Context:
2573 * queue_lock must be held.
2574 */
2575struct request *blk_fetch_request(struct request_queue *q)
2576{
2577 struct request *rq;
2578
2579 rq = blk_peek_request(q);
2580 if (rq)
2581 blk_start_request(rq);
2582 return rq;
2583}
2584EXPORT_SYMBOL(blk_fetch_request);
2585
3bcddeac 2586/**
2e60e022 2587 * blk_update_request - Special helper function for request stacking drivers
8ebf9756 2588 * @req: the request being processed
710027a4 2589 * @error: %0 for success, < %0 for error
8ebf9756 2590 * @nr_bytes: number of bytes to complete @req
3bcddeac
KU
2591 *
2592 * Description:
8ebf9756
RD
2593 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2594 * the request structure even if @req doesn't have leftover.
2595 * If @req has leftover, sets it up for the next range of segments.
2e60e022
TH
2596 *
2597 * This special helper function is only for request stacking drivers
2598 * (e.g. request-based dm) so that they can handle partial completion.
2599 * Actual device drivers should use blk_end_request instead.
2600 *
2601 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2602 * %false return from this function.
3bcddeac
KU
2603 *
2604 * Return:
2e60e022
TH
2605 * %false - this request doesn't have any more data
2606 * %true - this request has more data
3bcddeac 2607 **/
2e60e022 2608bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
1da177e4 2609{
f79ea416 2610 int total_bytes;
1da177e4 2611
4a0efdc9
HR
2612 trace_block_rq_complete(req->q, req, nr_bytes);
2613
2e60e022
TH
2614 if (!req->bio)
2615 return false;
2616
1da177e4 2617 /*
6f41469c
TH
2618 * For fs requests, rq is just carrier of independent bio's
2619 * and each partial completion should be handled separately.
2620 * Reset per-request error on each partial completion.
2621 *
2622 * TODO: tj: This is too subtle. It would be better to let
2623 * low level drivers do what they see fit.
1da177e4 2624 */
33659ebb 2625 if (req->cmd_type == REQ_TYPE_FS)
1da177e4
LT
2626 req->errors = 0;
2627
33659ebb
CH
2628 if (error && req->cmd_type == REQ_TYPE_FS &&
2629 !(req->cmd_flags & REQ_QUIET)) {
79775567
HR
2630 char *error_type;
2631
2632 switch (error) {
2633 case -ENOLINK:
2634 error_type = "recoverable transport";
2635 break;
2636 case -EREMOTEIO:
2637 error_type = "critical target";
2638 break;
2639 case -EBADE:
2640 error_type = "critical nexus";
2641 break;
d1ffc1f8
HR
2642 case -ETIMEDOUT:
2643 error_type = "timeout";
2644 break;
a9d6ceb8
HR
2645 case -ENOSPC:
2646 error_type = "critical space allocation";
2647 break;
7e782af5
HR
2648 case -ENODATA:
2649 error_type = "critical medium";
2650 break;
79775567
HR
2651 case -EIO:
2652 default:
2653 error_type = "I/O";
2654 break;
2655 }
ef3ecb66
RE
2656 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2657 __func__, error_type, req->rq_disk ?
37d7b34f
YZ
2658 req->rq_disk->disk_name : "?",
2659 (unsigned long long)blk_rq_pos(req));
2660
1da177e4
LT
2661 }
2662
bc58ba94 2663 blk_account_io_completion(req, nr_bytes);
d72d904a 2664
f79ea416
KO
2665 total_bytes = 0;
2666 while (req->bio) {
2667 struct bio *bio = req->bio;
4f024f37 2668 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
1da177e4 2669
4f024f37 2670 if (bio_bytes == bio->bi_iter.bi_size)
1da177e4 2671 req->bio = bio->bi_next;
1da177e4 2672
f79ea416 2673 req_bio_endio(req, bio, bio_bytes, error);
1da177e4 2674
f79ea416
KO
2675 total_bytes += bio_bytes;
2676 nr_bytes -= bio_bytes;
1da177e4 2677
f79ea416
KO
2678 if (!nr_bytes)
2679 break;
1da177e4
LT
2680 }
2681
2682 /*
2683 * completely done
2684 */
2e60e022
TH
2685 if (!req->bio) {
2686 /*
2687 * Reset counters so that the request stacking driver
2688 * can find how many bytes remain in the request
2689 * later.
2690 */
a2dec7b3 2691 req->__data_len = 0;
2e60e022
TH
2692 return false;
2693 }
1da177e4 2694
a2dec7b3 2695 req->__data_len -= total_bytes;
2e46e8b2
TH
2696
2697 /* update sector only for requests with clear definition of sector */
e2a60da7 2698 if (req->cmd_type == REQ_TYPE_FS)
a2dec7b3 2699 req->__sector += total_bytes >> 9;
2e46e8b2 2700
80a761fd
TH
2701 /* mixed attributes always follow the first bio */
2702 if (req->cmd_flags & REQ_MIXED_MERGE) {
2703 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2704 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2705 }
2706
2e46e8b2
TH
2707 /*
2708 * If total number of sectors is less than the first segment
2709 * size, something has gone terribly wrong.
2710 */
2711 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
8182924b 2712 blk_dump_rq_flags(req, "request botched");
a2dec7b3 2713 req->__data_len = blk_rq_cur_bytes(req);
2e46e8b2
TH
2714 }
2715
2716 /* recalculate the number of segments */
1da177e4 2717 blk_recalc_rq_segments(req);
2e46e8b2 2718
2e60e022 2719 return true;
1da177e4 2720}
2e60e022 2721EXPORT_SYMBOL_GPL(blk_update_request);
1da177e4 2722
2e60e022
TH
2723static bool blk_update_bidi_request(struct request *rq, int error,
2724 unsigned int nr_bytes,
2725 unsigned int bidi_bytes)
5efccd17 2726{
2e60e022
TH
2727 if (blk_update_request(rq, error, nr_bytes))
2728 return true;
5efccd17 2729
2e60e022
TH
2730 /* Bidi request must be completed as a whole */
2731 if (unlikely(blk_bidi_rq(rq)) &&
2732 blk_update_request(rq->next_rq, error, bidi_bytes))
2733 return true;
5efccd17 2734
e2e1a148
JA
2735 if (blk_queue_add_random(rq->q))
2736 add_disk_randomness(rq->rq_disk);
2e60e022
TH
2737
2738 return false;
1da177e4
LT
2739}
2740
28018c24
JB
2741/**
2742 * blk_unprep_request - unprepare a request
2743 * @req: the request
2744 *
2745 * This function makes a request ready for complete resubmission (or
2746 * completion). It happens only after all error handling is complete,
2747 * so represents the appropriate moment to deallocate any resources
2748 * that were allocated to the request in the prep_rq_fn. The queue
2749 * lock is held when calling this.
2750 */
2751void blk_unprep_request(struct request *req)
2752{
2753 struct request_queue *q = req->q;
2754
2755 req->cmd_flags &= ~REQ_DONTPREP;
2756 if (q->unprep_rq_fn)
2757 q->unprep_rq_fn(q, req);
2758}
2759EXPORT_SYMBOL_GPL(blk_unprep_request);
2760
1da177e4
LT
2761/*
2762 * queue lock must be held
2763 */
12120077 2764void blk_finish_request(struct request *req, int error)
1da177e4 2765{
125c99bc 2766 if (req->cmd_flags & REQ_QUEUED)
b8286239
KU
2767 blk_queue_end_tag(req->q, req);
2768
ba396a6c 2769 BUG_ON(blk_queued_rq(req));
1da177e4 2770
33659ebb 2771 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
31373d09 2772 laptop_io_completion(&req->q->backing_dev_info);
1da177e4 2773
e78042e5
MA
2774 blk_delete_timer(req);
2775
28018c24
JB
2776 if (req->cmd_flags & REQ_DONTPREP)
2777 blk_unprep_request(req);
2778
bc58ba94 2779 blk_account_io_done(req);
b8286239 2780
1da177e4 2781 if (req->end_io)
8ffdc655 2782 req->end_io(req, error);
b8286239
KU
2783 else {
2784 if (blk_bidi_rq(req))
2785 __blk_put_request(req->next_rq->q, req->next_rq);
2786
1da177e4 2787 __blk_put_request(req->q, req);
b8286239 2788 }
1da177e4 2789}
12120077 2790EXPORT_SYMBOL(blk_finish_request);
1da177e4 2791
3b11313a 2792/**
2e60e022
TH
2793 * blk_end_bidi_request - Complete a bidi request
2794 * @rq: the request to complete
2795 * @error: %0 for success, < %0 for error
2796 * @nr_bytes: number of bytes to complete @rq
2797 * @bidi_bytes: number of bytes to complete @rq->next_rq
a0cd1285
JA
2798 *
2799 * Description:
e3a04fe3 2800 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2e60e022
TH
2801 * Drivers that supports bidi can safely call this member for any
2802 * type of request, bidi or uni. In the later case @bidi_bytes is
2803 * just ignored.
336cdb40
KU
2804 *
2805 * Return:
2e60e022
TH
2806 * %false - we are done with this request
2807 * %true - still buffers pending for this request
a0cd1285 2808 **/
b1f74493 2809static bool blk_end_bidi_request(struct request *rq, int error,
32fab448
KU
2810 unsigned int nr_bytes, unsigned int bidi_bytes)
2811{
336cdb40 2812 struct request_queue *q = rq->q;
2e60e022 2813 unsigned long flags;
32fab448 2814
2e60e022
TH
2815 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2816 return true;
32fab448 2817
336cdb40 2818 spin_lock_irqsave(q->queue_lock, flags);
2e60e022 2819 blk_finish_request(rq, error);
336cdb40
KU
2820 spin_unlock_irqrestore(q->queue_lock, flags);
2821
2e60e022 2822 return false;
32fab448
KU
2823}
2824
336cdb40 2825/**
2e60e022
TH
2826 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2827 * @rq: the request to complete
710027a4 2828 * @error: %0 for success, < %0 for error
e3a04fe3
KU
2829 * @nr_bytes: number of bytes to complete @rq
2830 * @bidi_bytes: number of bytes to complete @rq->next_rq
336cdb40
KU
2831 *
2832 * Description:
2e60e022
TH
2833 * Identical to blk_end_bidi_request() except that queue lock is
2834 * assumed to be locked on entry and remains so on return.
336cdb40
KU
2835 *
2836 * Return:
2e60e022
TH
2837 * %false - we are done with this request
2838 * %true - still buffers pending for this request
336cdb40 2839 **/
4853abaa 2840bool __blk_end_bidi_request(struct request *rq, int error,
b1f74493 2841 unsigned int nr_bytes, unsigned int bidi_bytes)
336cdb40 2842{
2e60e022
TH
2843 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2844 return true;
336cdb40 2845
2e60e022 2846 blk_finish_request(rq, error);
336cdb40 2847
2e60e022 2848 return false;
336cdb40 2849}
e19a3ab0
KU
2850
2851/**
2852 * blk_end_request - Helper function for drivers to complete the request.
2853 * @rq: the request being processed
710027a4 2854 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2855 * @nr_bytes: number of bytes to complete
2856 *
2857 * Description:
2858 * Ends I/O on a number of bytes attached to @rq.
2859 * If @rq has leftover, sets it up for the next range of segments.
2860 *
2861 * Return:
b1f74493
FT
2862 * %false - we are done with this request
2863 * %true - still buffers pending for this request
e19a3ab0 2864 **/
b1f74493 2865bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e19a3ab0 2866{
b1f74493 2867 return blk_end_bidi_request(rq, error, nr_bytes, 0);
e19a3ab0 2868}
56ad1740 2869EXPORT_SYMBOL(blk_end_request);
336cdb40
KU
2870
2871/**
b1f74493
FT
2872 * blk_end_request_all - Helper function for drives to finish the request.
2873 * @rq: the request to finish
8ebf9756 2874 * @error: %0 for success, < %0 for error
336cdb40
KU
2875 *
2876 * Description:
b1f74493
FT
2877 * Completely finish @rq.
2878 */
2879void blk_end_request_all(struct request *rq, int error)
336cdb40 2880{
b1f74493
FT
2881 bool pending;
2882 unsigned int bidi_bytes = 0;
336cdb40 2883
b1f74493
FT
2884 if (unlikely(blk_bidi_rq(rq)))
2885 bidi_bytes = blk_rq_bytes(rq->next_rq);
336cdb40 2886
b1f74493
FT
2887 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2888 BUG_ON(pending);
2889}
56ad1740 2890EXPORT_SYMBOL(blk_end_request_all);
336cdb40 2891
b1f74493
FT
2892/**
2893 * blk_end_request_cur - Helper function to finish the current request chunk.
2894 * @rq: the request to finish the current chunk for
8ebf9756 2895 * @error: %0 for success, < %0 for error
b1f74493
FT
2896 *
2897 * Description:
2898 * Complete the current consecutively mapped chunk from @rq.
2899 *
2900 * Return:
2901 * %false - we are done with this request
2902 * %true - still buffers pending for this request
2903 */
2904bool blk_end_request_cur(struct request *rq, int error)
2905{
2906 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
336cdb40 2907}
56ad1740 2908EXPORT_SYMBOL(blk_end_request_cur);
336cdb40 2909
80a761fd
TH
2910/**
2911 * blk_end_request_err - Finish a request till the next failure boundary.
2912 * @rq: the request to finish till the next failure boundary for
2913 * @error: must be negative errno
2914 *
2915 * Description:
2916 * Complete @rq till the next failure boundary.
2917 *
2918 * Return:
2919 * %false - we are done with this request
2920 * %true - still buffers pending for this request
2921 */
2922bool blk_end_request_err(struct request *rq, int error)
2923{
2924 WARN_ON(error >= 0);
2925 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2926}
2927EXPORT_SYMBOL_GPL(blk_end_request_err);
2928
e3a04fe3 2929/**
b1f74493
FT
2930 * __blk_end_request - Helper function for drivers to complete the request.
2931 * @rq: the request being processed
2932 * @error: %0 for success, < %0 for error
2933 * @nr_bytes: number of bytes to complete
e3a04fe3
KU
2934 *
2935 * Description:
b1f74493 2936 * Must be called with queue lock held unlike blk_end_request().
e3a04fe3
KU
2937 *
2938 * Return:
b1f74493
FT
2939 * %false - we are done with this request
2940 * %true - still buffers pending for this request
e3a04fe3 2941 **/
b1f74493 2942bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
e3a04fe3 2943{
b1f74493 2944 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
e3a04fe3 2945}
56ad1740 2946EXPORT_SYMBOL(__blk_end_request);
e3a04fe3 2947
32fab448 2948/**
b1f74493
FT
2949 * __blk_end_request_all - Helper function for drives to finish the request.
2950 * @rq: the request to finish
8ebf9756 2951 * @error: %0 for success, < %0 for error
32fab448
KU
2952 *
2953 * Description:
b1f74493 2954 * Completely finish @rq. Must be called with queue lock held.
32fab448 2955 */
b1f74493 2956void __blk_end_request_all(struct request *rq, int error)
32fab448 2957{
b1f74493
FT
2958 bool pending;
2959 unsigned int bidi_bytes = 0;
2960
2961 if (unlikely(blk_bidi_rq(rq)))
2962 bidi_bytes = blk_rq_bytes(rq->next_rq);
2963
2964 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2965 BUG_ON(pending);
32fab448 2966}
56ad1740 2967EXPORT_SYMBOL(__blk_end_request_all);
32fab448 2968
e19a3ab0 2969/**
b1f74493
FT
2970 * __blk_end_request_cur - Helper function to finish the current request chunk.
2971 * @rq: the request to finish the current chunk for
8ebf9756 2972 * @error: %0 for success, < %0 for error
e19a3ab0
KU
2973 *
2974 * Description:
b1f74493
FT
2975 * Complete the current consecutively mapped chunk from @rq. Must
2976 * be called with queue lock held.
e19a3ab0
KU
2977 *
2978 * Return:
b1f74493
FT
2979 * %false - we are done with this request
2980 * %true - still buffers pending for this request
2981 */
2982bool __blk_end_request_cur(struct request *rq, int error)
e19a3ab0 2983{
b1f74493 2984 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
e19a3ab0 2985}
56ad1740 2986EXPORT_SYMBOL(__blk_end_request_cur);
e19a3ab0 2987
80a761fd
TH
2988/**
2989 * __blk_end_request_err - Finish a request till the next failure boundary.
2990 * @rq: the request to finish till the next failure boundary for
2991 * @error: must be negative errno
2992 *
2993 * Description:
2994 * Complete @rq till the next failure boundary. Must be called
2995 * with queue lock held.
2996 *
2997 * Return:
2998 * %false - we are done with this request
2999 * %true - still buffers pending for this request
3000 */
3001bool __blk_end_request_err(struct request *rq, int error)
3002{
3003 WARN_ON(error >= 0);
3004 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
3005}
3006EXPORT_SYMBOL_GPL(__blk_end_request_err);
3007
86db1e29
JA
3008void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
3009 struct bio *bio)
1da177e4 3010{
a82afdfc 3011 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
7b6d91da 3012 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
1da177e4 3013
b4f42e28 3014 if (bio_has_data(bio))
fb2dce86 3015 rq->nr_phys_segments = bio_phys_segments(q, bio);
b4f42e28 3016
4f024f37 3017 rq->__data_len = bio->bi_iter.bi_size;
1da177e4 3018 rq->bio = rq->biotail = bio;
1da177e4 3019
66846572
N
3020 if (bio->bi_bdev)
3021 rq->rq_disk = bio->bi_bdev->bd_disk;
3022}
1da177e4 3023
2d4dc890
IL
3024#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
3025/**
3026 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3027 * @rq: the request to be flushed
3028 *
3029 * Description:
3030 * Flush all pages in @rq.
3031 */
3032void rq_flush_dcache_pages(struct request *rq)
3033{
3034 struct req_iterator iter;
7988613b 3035 struct bio_vec bvec;
2d4dc890
IL
3036
3037 rq_for_each_segment(bvec, rq, iter)
7988613b 3038 flush_dcache_page(bvec.bv_page);
2d4dc890
IL
3039}
3040EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3041#endif
3042
ef9e3fac
KU
3043/**
3044 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3045 * @q : the queue of the device being checked
3046 *
3047 * Description:
3048 * Check if underlying low-level drivers of a device are busy.
3049 * If the drivers want to export their busy state, they must set own
3050 * exporting function using blk_queue_lld_busy() first.
3051 *
3052 * Basically, this function is used only by request stacking drivers
3053 * to stop dispatching requests to underlying devices when underlying
3054 * devices are busy. This behavior helps more I/O merging on the queue
3055 * of the request stacking driver and prevents I/O throughput regression
3056 * on burst I/O load.
3057 *
3058 * Return:
3059 * 0 - Not busy (The request stacking driver should dispatch request)
3060 * 1 - Busy (The request stacking driver should stop dispatching request)
3061 */
3062int blk_lld_busy(struct request_queue *q)
3063{
3064 if (q->lld_busy_fn)
3065 return q->lld_busy_fn(q);
3066
3067 return 0;
3068}
3069EXPORT_SYMBOL_GPL(blk_lld_busy);
3070
78d8e58a
MS
3071/**
3072 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3073 * @rq: the clone request to be cleaned up
3074 *
3075 * Description:
3076 * Free all bios in @rq for a cloned request.
3077 */
3078void blk_rq_unprep_clone(struct request *rq)
3079{
3080 struct bio *bio;
3081
3082 while ((bio = rq->bio) != NULL) {
3083 rq->bio = bio->bi_next;
3084
3085 bio_put(bio);
3086 }
3087}
3088EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3089
3090/*
3091 * Copy attributes of the original request to the clone request.
3092 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3093 */
3094static void __blk_rq_prep_clone(struct request *dst, struct request *src)
b0fd271d
KU
3095{
3096 dst->cpu = src->cpu;
78d8e58a 3097 dst->cmd_flags |= (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
b0fd271d
KU
3098 dst->cmd_type = src->cmd_type;
3099 dst->__sector = blk_rq_pos(src);
3100 dst->__data_len = blk_rq_bytes(src);
3101 dst->nr_phys_segments = src->nr_phys_segments;
3102 dst->ioprio = src->ioprio;
3103 dst->extra_len = src->extra_len;
78d8e58a
MS
3104}
3105
3106/**
3107 * blk_rq_prep_clone - Helper function to setup clone request
3108 * @rq: the request to be setup
3109 * @rq_src: original request to be cloned
3110 * @bs: bio_set that bios for clone are allocated from
3111 * @gfp_mask: memory allocation mask for bio
3112 * @bio_ctr: setup function to be called for each clone bio.
3113 * Returns %0 for success, non %0 for failure.
3114 * @data: private data to be passed to @bio_ctr
3115 *
3116 * Description:
3117 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3118 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3119 * are not copied, and copying such parts is the caller's responsibility.
3120 * Also, pages which the original bios are pointing to are not copied
3121 * and the cloned bios just point same pages.
3122 * So cloned bios must be completed before original bios, which means
3123 * the caller must complete @rq before @rq_src.
3124 */
3125int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3126 struct bio_set *bs, gfp_t gfp_mask,
3127 int (*bio_ctr)(struct bio *, struct bio *, void *),
3128 void *data)
3129{
3130 struct bio *bio, *bio_src;
3131
3132 if (!bs)
3133 bs = fs_bio_set;
3134
3135 __rq_for_each_bio(bio_src, rq_src) {
3136 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3137 if (!bio)
3138 goto free_and_out;
3139
3140 if (bio_ctr && bio_ctr(bio, bio_src, data))
3141 goto free_and_out;
3142
3143 if (rq->bio) {
3144 rq->biotail->bi_next = bio;
3145 rq->biotail = bio;
3146 } else
3147 rq->bio = rq->biotail = bio;
3148 }
3149
3150 __blk_rq_prep_clone(rq, rq_src);
3151
3152 return 0;
3153
3154free_and_out:
3155 if (bio)
3156 bio_put(bio);
3157 blk_rq_unprep_clone(rq);
3158
3159 return -ENOMEM;
b0fd271d
KU
3160}
3161EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3162
59c3d45e 3163int kblockd_schedule_work(struct work_struct *work)
1da177e4
LT
3164{
3165 return queue_work(kblockd_workqueue, work);
3166}
1da177e4
LT
3167EXPORT_SYMBOL(kblockd_schedule_work);
3168
59c3d45e
JA
3169int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3170 unsigned long delay)
e43473b7
VG
3171{
3172 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3173}
3174EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3175
8ab14595
JA
3176int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3177 unsigned long delay)
3178{
3179 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3180}
3181EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3182
75df7136
SJ
3183/**
3184 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3185 * @plug: The &struct blk_plug that needs to be initialized
3186 *
3187 * Description:
3188 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3189 * pending I/O should the task end up blocking between blk_start_plug() and
3190 * blk_finish_plug(). This is important from a performance perspective, but
3191 * also ensures that we don't deadlock. For instance, if the task is blocking
3192 * for a memory allocation, memory reclaim could end up wanting to free a
3193 * page belonging to that request that is currently residing in our private
3194 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3195 * this kind of deadlock.
3196 */
73c10101
JA
3197void blk_start_plug(struct blk_plug *plug)
3198{
3199 struct task_struct *tsk = current;
3200
dd6cf3e1
SL
3201 /*
3202 * If this is a nested plug, don't actually assign it.
3203 */
3204 if (tsk->plug)
3205 return;
3206
73c10101 3207 INIT_LIST_HEAD(&plug->list);
320ae51f 3208 INIT_LIST_HEAD(&plug->mq_list);
048c9374 3209 INIT_LIST_HEAD(&plug->cb_list);
73c10101 3210 /*
dd6cf3e1
SL
3211 * Store ordering should not be needed here, since a potential
3212 * preempt will imply a full memory barrier
73c10101 3213 */
dd6cf3e1 3214 tsk->plug = plug;
73c10101
JA
3215}
3216EXPORT_SYMBOL(blk_start_plug);
3217
3218static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3219{
3220 struct request *rqa = container_of(a, struct request, queuelist);
3221 struct request *rqb = container_of(b, struct request, queuelist);
3222
975927b9
JM
3223 return !(rqa->q < rqb->q ||
3224 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
73c10101
JA
3225}
3226
49cac01e
JA
3227/*
3228 * If 'from_schedule' is true, then postpone the dispatch of requests
3229 * until a safe kblockd context. We due this to avoid accidental big
3230 * additional stack usage in driver dispatch, in places where the originally
3231 * plugger did not intend it.
3232 */
f6603783 3233static void queue_unplugged(struct request_queue *q, unsigned int depth,
49cac01e 3234 bool from_schedule)
99e22598 3235 __releases(q->queue_lock)
94b5eb28 3236{
49cac01e 3237 trace_block_unplug(q, depth, !from_schedule);
99e22598 3238
70460571 3239 if (from_schedule)
24ecfbe2 3240 blk_run_queue_async(q);
70460571 3241 else
24ecfbe2 3242 __blk_run_queue(q);
70460571 3243 spin_unlock(q->queue_lock);
94b5eb28
JA
3244}
3245
74018dc3 3246static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
048c9374
N
3247{
3248 LIST_HEAD(callbacks);
3249
2a7d5559
SL
3250 while (!list_empty(&plug->cb_list)) {
3251 list_splice_init(&plug->cb_list, &callbacks);
048c9374 3252
2a7d5559
SL
3253 while (!list_empty(&callbacks)) {
3254 struct blk_plug_cb *cb = list_first_entry(&callbacks,
048c9374
N
3255 struct blk_plug_cb,
3256 list);
2a7d5559 3257 list_del(&cb->list);
74018dc3 3258 cb->callback(cb, from_schedule);
2a7d5559 3259 }
048c9374
N
3260 }
3261}
3262
9cbb1750
N
3263struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3264 int size)
3265{
3266 struct blk_plug *plug = current->plug;
3267 struct blk_plug_cb *cb;
3268
3269 if (!plug)
3270 return NULL;
3271
3272 list_for_each_entry(cb, &plug->cb_list, list)
3273 if (cb->callback == unplug && cb->data == data)
3274 return cb;
3275
3276 /* Not currently on the callback list */
3277 BUG_ON(size < sizeof(*cb));
3278 cb = kzalloc(size, GFP_ATOMIC);
3279 if (cb) {
3280 cb->data = data;
3281 cb->callback = unplug;
3282 list_add(&cb->list, &plug->cb_list);
3283 }
3284 return cb;
3285}
3286EXPORT_SYMBOL(blk_check_plugged);
3287
49cac01e 3288void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
73c10101
JA
3289{
3290 struct request_queue *q;
3291 unsigned long flags;
3292 struct request *rq;
109b8129 3293 LIST_HEAD(list);
94b5eb28 3294 unsigned int depth;
73c10101 3295
74018dc3 3296 flush_plug_callbacks(plug, from_schedule);
320ae51f
JA
3297
3298 if (!list_empty(&plug->mq_list))
3299 blk_mq_flush_plug_list(plug, from_schedule);
3300
73c10101
JA
3301 if (list_empty(&plug->list))
3302 return;
3303
109b8129
N
3304 list_splice_init(&plug->list, &list);
3305
422765c2 3306 list_sort(NULL, &list, plug_rq_cmp);
73c10101
JA
3307
3308 q = NULL;
94b5eb28 3309 depth = 0;
18811272
JA
3310
3311 /*
3312 * Save and disable interrupts here, to avoid doing it for every
3313 * queue lock we have to take.
3314 */
73c10101 3315 local_irq_save(flags);
109b8129
N
3316 while (!list_empty(&list)) {
3317 rq = list_entry_rq(list.next);
73c10101 3318 list_del_init(&rq->queuelist);
73c10101
JA
3319 BUG_ON(!rq->q);
3320 if (rq->q != q) {
99e22598
JA
3321 /*
3322 * This drops the queue lock
3323 */
3324 if (q)
49cac01e 3325 queue_unplugged(q, depth, from_schedule);
73c10101 3326 q = rq->q;
94b5eb28 3327 depth = 0;
73c10101
JA
3328 spin_lock(q->queue_lock);
3329 }
8ba61435
TH
3330
3331 /*
3332 * Short-circuit if @q is dead
3333 */
3f3299d5 3334 if (unlikely(blk_queue_dying(q))) {
8ba61435
TH
3335 __blk_end_request_all(rq, -ENODEV);
3336 continue;
3337 }
3338
73c10101
JA
3339 /*
3340 * rq is already accounted, so use raw insert
3341 */
401a18e9
JA
3342 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3343 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3344 else
3345 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
94b5eb28
JA
3346
3347 depth++;
73c10101
JA
3348 }
3349
99e22598
JA
3350 /*
3351 * This drops the queue lock
3352 */
3353 if (q)
49cac01e 3354 queue_unplugged(q, depth, from_schedule);
73c10101 3355
73c10101
JA
3356 local_irq_restore(flags);
3357}
73c10101
JA
3358
3359void blk_finish_plug(struct blk_plug *plug)
3360{
dd6cf3e1
SL
3361 if (plug != current->plug)
3362 return;
f6603783 3363 blk_flush_plug_list(plug, false);
73c10101 3364
dd6cf3e1 3365 current->plug = NULL;
73c10101 3366}
88b996cd 3367EXPORT_SYMBOL(blk_finish_plug);
73c10101 3368
05229bee
JA
3369bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3370{
3371 struct blk_plug *plug;
3372 long state;
3373
3374 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3375 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3376 return false;
3377
3378 plug = current->plug;
3379 if (plug)
3380 blk_flush_plug_list(plug, false);
3381
3382 state = current->state;
3383 while (!need_resched()) {
3384 unsigned int queue_num = blk_qc_t_to_queue_num(cookie);
3385 struct blk_mq_hw_ctx *hctx = q->queue_hw_ctx[queue_num];
3386 int ret;
3387
3388 hctx->poll_invoked++;
3389
3390 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3391 if (ret > 0) {
3392 hctx->poll_success++;
3393 set_current_state(TASK_RUNNING);
3394 return true;
3395 }
3396
3397 if (signal_pending_state(state, current))
3398 set_current_state(TASK_RUNNING);
3399
3400 if (current->state == TASK_RUNNING)
3401 return true;
3402 if (ret < 0)
3403 break;
3404 cpu_relax();
3405 }
3406
3407 return false;
3408}
3409
47fafbc7 3410#ifdef CONFIG_PM
6c954667
LM
3411/**
3412 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3413 * @q: the queue of the device
3414 * @dev: the device the queue belongs to
3415 *
3416 * Description:
3417 * Initialize runtime-PM-related fields for @q and start auto suspend for
3418 * @dev. Drivers that want to take advantage of request-based runtime PM
3419 * should call this function after @dev has been initialized, and its
3420 * request queue @q has been allocated, and runtime PM for it can not happen
3421 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3422 * cases, driver should call this function before any I/O has taken place.
3423 *
3424 * This function takes care of setting up using auto suspend for the device,
3425 * the autosuspend delay is set to -1 to make runtime suspend impossible
3426 * until an updated value is either set by user or by driver. Drivers do
3427 * not need to touch other autosuspend settings.
3428 *
3429 * The block layer runtime PM is request based, so only works for drivers
3430 * that use request as their IO unit instead of those directly use bio's.
3431 */
3432void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3433{
3434 q->dev = dev;
3435 q->rpm_status = RPM_ACTIVE;
3436 pm_runtime_set_autosuspend_delay(q->dev, -1);
3437 pm_runtime_use_autosuspend(q->dev);
3438}
3439EXPORT_SYMBOL(blk_pm_runtime_init);
3440
3441/**
3442 * blk_pre_runtime_suspend - Pre runtime suspend check
3443 * @q: the queue of the device
3444 *
3445 * Description:
3446 * This function will check if runtime suspend is allowed for the device
3447 * by examining if there are any requests pending in the queue. If there
3448 * are requests pending, the device can not be runtime suspended; otherwise,
3449 * the queue's status will be updated to SUSPENDING and the driver can
3450 * proceed to suspend the device.
3451 *
3452 * For the not allowed case, we mark last busy for the device so that
3453 * runtime PM core will try to autosuspend it some time later.
3454 *
3455 * This function should be called near the start of the device's
3456 * runtime_suspend callback.
3457 *
3458 * Return:
3459 * 0 - OK to runtime suspend the device
3460 * -EBUSY - Device should not be runtime suspended
3461 */
3462int blk_pre_runtime_suspend(struct request_queue *q)
3463{
3464 int ret = 0;
3465
4fd41a85
KX
3466 if (!q->dev)
3467 return ret;
3468
6c954667
LM
3469 spin_lock_irq(q->queue_lock);
3470 if (q->nr_pending) {
3471 ret = -EBUSY;
3472 pm_runtime_mark_last_busy(q->dev);
3473 } else {
3474 q->rpm_status = RPM_SUSPENDING;
3475 }
3476 spin_unlock_irq(q->queue_lock);
3477 return ret;
3478}
3479EXPORT_SYMBOL(blk_pre_runtime_suspend);
3480
3481/**
3482 * blk_post_runtime_suspend - Post runtime suspend processing
3483 * @q: the queue of the device
3484 * @err: return value of the device's runtime_suspend function
3485 *
3486 * Description:
3487 * Update the queue's runtime status according to the return value of the
3488 * device's runtime suspend function and mark last busy for the device so
3489 * that PM core will try to auto suspend the device at a later time.
3490 *
3491 * This function should be called near the end of the device's
3492 * runtime_suspend callback.
3493 */
3494void blk_post_runtime_suspend(struct request_queue *q, int err)
3495{
4fd41a85
KX
3496 if (!q->dev)
3497 return;
3498
6c954667
LM
3499 spin_lock_irq(q->queue_lock);
3500 if (!err) {
3501 q->rpm_status = RPM_SUSPENDED;
3502 } else {
3503 q->rpm_status = RPM_ACTIVE;
3504 pm_runtime_mark_last_busy(q->dev);
3505 }
3506 spin_unlock_irq(q->queue_lock);
3507}
3508EXPORT_SYMBOL(blk_post_runtime_suspend);
3509
3510/**
3511 * blk_pre_runtime_resume - Pre runtime resume processing
3512 * @q: the queue of the device
3513 *
3514 * Description:
3515 * Update the queue's runtime status to RESUMING in preparation for the
3516 * runtime resume of the device.
3517 *
3518 * This function should be called near the start of the device's
3519 * runtime_resume callback.
3520 */
3521void blk_pre_runtime_resume(struct request_queue *q)
3522{
4fd41a85
KX
3523 if (!q->dev)
3524 return;
3525
6c954667
LM
3526 spin_lock_irq(q->queue_lock);
3527 q->rpm_status = RPM_RESUMING;
3528 spin_unlock_irq(q->queue_lock);
3529}
3530EXPORT_SYMBOL(blk_pre_runtime_resume);
3531
3532/**
3533 * blk_post_runtime_resume - Post runtime resume processing
3534 * @q: the queue of the device
3535 * @err: return value of the device's runtime_resume function
3536 *
3537 * Description:
3538 * Update the queue's runtime status according to the return value of the
3539 * device's runtime_resume function. If it is successfully resumed, process
3540 * the requests that are queued into the device's queue when it is resuming
3541 * and then mark last busy and initiate autosuspend for it.
3542 *
3543 * This function should be called near the end of the device's
3544 * runtime_resume callback.
3545 */
3546void blk_post_runtime_resume(struct request_queue *q, int err)
3547{
4fd41a85
KX
3548 if (!q->dev)
3549 return;
3550
6c954667
LM
3551 spin_lock_irq(q->queue_lock);
3552 if (!err) {
3553 q->rpm_status = RPM_ACTIVE;
3554 __blk_run_queue(q);
3555 pm_runtime_mark_last_busy(q->dev);
c60855cd 3556 pm_request_autosuspend(q->dev);
6c954667
LM
3557 } else {
3558 q->rpm_status = RPM_SUSPENDED;
3559 }
3560 spin_unlock_irq(q->queue_lock);
3561}
3562EXPORT_SYMBOL(blk_post_runtime_resume);
3563#endif
3564
1cac41cb
MB
3565#if !defined(CONFIG_SAMSUNG_PRODUCT_SHIP)
3566/*********************************
3567 * debugfs functions
3568 **********************************/
3569#ifdef CONFIG_DEBUG_FS
3570#include <linux/debugfs.h>
3571
3572#define DBGFS_FUNC_DECL(name) \
3573static int sio_open_##name(struct inode *inode, struct file *file) \
3574{ \
3575 return single_open(file, sio_show_##name, inode->i_private); \
3576} \
3577static const struct file_operations sio_fops_##name = { \
3578 .owner = THIS_MODULE, \
3579 .open = sio_open_##name, \
3580 .llseek = seq_lseek, \
3581 .read = seq_read, \
3582 .release = single_release, \
3583}
3584
3585static int sio_show_patches(struct seq_file *s, void *p)
3586{
3587 extern char *__start_sio_patches;
3588 extern char *__stop_sio_patches;
3589 char **p_version_str;
3590
3591 for (p_version_str = &__start_sio_patches; p_version_str < &__stop_sio_patches; ++p_version_str)
3592 seq_printf(s, "%s\n", *p_version_str);
3593
3594 return 0;
3595}
3596
3597static struct dentry *sio_debugfs_root;
3598
3599DBGFS_FUNC_DECL(patches);
3600
3601SIO_PATCH_VERSION(SIO_patch_manager, 1, 0, "");
3602
3603static int __init sio_debugfs_init(void)
3604{
3605 if (!debugfs_initialized())
3606 return -ENODEV;
3607
3608 sio_debugfs_root = debugfs_create_dir("sio", NULL);
3609 if (!sio_debugfs_root)
3610 return -ENOMEM;
3611
3612 debugfs_create_file("patches", 0400, sio_debugfs_root, NULL, &sio_fops_patches);
3613
3614 return 0;
3615}
3616
3617static void __exit sio_debugfs_exit(void)
3618{
3619 debugfs_remove_recursive(sio_debugfs_root);
3620}
3621#else
3622static int __init sio_debugfs_init(void)
3623{
3624 return 0;
3625}
3626
3627static void __exit sio_debugfs_exit(void) { }
3628#endif
3629#endif
3630
1da177e4
LT
3631int __init blk_dev_init(void)
3632{
9eb55b03 3633 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
0762b23d 3634 FIELD_SIZEOF(struct request, cmd_flags));
9eb55b03 3635
89b90be2
TH
3636 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3637 kblockd_workqueue = alloc_workqueue("kblockd",
28747fcd 3638 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1da177e4
LT
3639 if (!kblockd_workqueue)
3640 panic("Failed to create kblockd\n");
3641
3642 request_cachep = kmem_cache_create("blkdev_requests",
20c2df83 3643 sizeof(struct request), 0, SLAB_PANIC, NULL);
1da177e4 3644
8324aa91 3645 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
165125e1 3646 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1da177e4 3647
1cac41cb
MB
3648#if !defined(CONFIG_SAMSUNG_PRODUCT_SHIP)
3649 sio_debugfs_init();
3650#endif
3651
d38ecf93 3652 return 0;
1da177e4 3653}
65733da1
MS
3654
3655/*
3656 * Blk IO latency support. We want this to be as cheap as possible, so doing
3657 * this lockless (and avoiding atomics), a few off by a few errors in this
3658 * code is not harmful, and we don't want to do anything that is
3659 * perf-impactful.
3660 * TODO : If necessary, we can make the histograms per-cpu and aggregate
3661 * them when printing them out.
3662 */
3663void
3664blk_zero_latency_hist(struct io_latency_state *s)
3665{
3666 memset(s->latency_y_axis_read, 0,
3667 sizeof(s->latency_y_axis_read));
3668 memset(s->latency_y_axis_write, 0,
3669 sizeof(s->latency_y_axis_write));
3670 s->latency_reads_elems = 0;
3671 s->latency_writes_elems = 0;
3672}
65a2cd6d 3673EXPORT_SYMBOL(blk_zero_latency_hist);
65733da1
MS
3674
3675ssize_t
3676blk_latency_hist_show(struct io_latency_state *s, char *buf)
3677{
3678 int i;
3679 int bytes_written = 0;
3680 u_int64_t num_elem, elem;
3681 int pct;
3682
3683 num_elem = s->latency_reads_elems;
3684 if (num_elem > 0) {
3685 bytes_written += scnprintf(buf + bytes_written,
3686 PAGE_SIZE - bytes_written,
3687 "IO svc_time Read Latency Histogram (n = %llu):\n",
3688 num_elem);
3689 for (i = 0;
3690 i < ARRAY_SIZE(latency_x_axis_us);
3691 i++) {
3692 elem = s->latency_y_axis_read[i];
3693 pct = div64_u64(elem * 100, num_elem);
3694 bytes_written += scnprintf(buf + bytes_written,
3695 PAGE_SIZE - bytes_written,
3696 "\t< %5lluus%15llu%15d%%\n",
3697 latency_x_axis_us[i],
3698 elem, pct);
3699 }
3700 /* Last element in y-axis table is overflow */
3701 elem = s->latency_y_axis_read[i];
3702 pct = div64_u64(elem * 100, num_elem);
3703 bytes_written += scnprintf(buf + bytes_written,
3704 PAGE_SIZE - bytes_written,
3705 "\t> %5dms%15llu%15d%%\n", 10,
3706 elem, pct);
3707 }
3708 num_elem = s->latency_writes_elems;
3709 if (num_elem > 0) {
3710 bytes_written += scnprintf(buf + bytes_written,
3711 PAGE_SIZE - bytes_written,
3712 "IO svc_time Write Latency Histogram (n = %llu):\n",
3713 num_elem);
3714 for (i = 0;
3715 i < ARRAY_SIZE(latency_x_axis_us);
3716 i++) {
3717 elem = s->latency_y_axis_write[i];
3718 pct = div64_u64(elem * 100, num_elem);
3719 bytes_written += scnprintf(buf + bytes_written,
3720 PAGE_SIZE - bytes_written,
3721 "\t< %5lluus%15llu%15d%%\n",
3722 latency_x_axis_us[i],
3723 elem, pct);
3724 }
3725 /* Last element in y-axis table is overflow */
3726 elem = s->latency_y_axis_write[i];
3727 pct = div64_u64(elem * 100, num_elem);
3728 bytes_written += scnprintf(buf + bytes_written,
3729 PAGE_SIZE - bytes_written,
3730 "\t> %5dms%15llu%15d%%\n", 10,
3731 elem, pct);
3732 }
3733 return bytes_written;
3734}
65a2cd6d 3735EXPORT_SYMBOL(blk_latency_hist_show);