]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - block/blk-core.c
block: kill legacy parts of timeout handling
[mirror_ubuntu-hirsute-kernel.git] / block / blk-core.c
CommitLineData
1da177e4 1/*
1da177e4
LT
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6728cb0e
JA
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7 * - July2000
1da177e4
LT
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9 */
10
11/*
12 * This handles all read/write requests to block devices
13 */
1da177e4
LT
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/backing-dev.h>
17#include <linux/bio.h>
18#include <linux/blkdev.h>
320ae51f 19#include <linux/blk-mq.h>
1da177e4
LT
20#include <linux/highmem.h>
21#include <linux/mm.h>
22#include <linux/kernel_stat.h>
23#include <linux/string.h>
24#include <linux/init.h>
1da177e4
LT
25#include <linux/completion.h>
26#include <linux/slab.h>
27#include <linux/swap.h>
28#include <linux/writeback.h>
faccbd4b 29#include <linux/task_io_accounting_ops.h>
c17bb495 30#include <linux/fault-inject.h>
73c10101 31#include <linux/list_sort.h>
e3c78ca5 32#include <linux/delay.h>
aaf7c680 33#include <linux/ratelimit.h>
6c954667 34#include <linux/pm_runtime.h>
eea8f41c 35#include <linux/blk-cgroup.h>
18fbda91 36#include <linux/debugfs.h>
30abb3a6 37#include <linux/bpf.h>
55782138
LZ
38
39#define CREATE_TRACE_POINTS
40#include <trace/events/block.h>
1da177e4 41
8324aa91 42#include "blk.h"
43a5e4e2 43#include "blk-mq.h"
bd166ef1 44#include "blk-mq-sched.h"
bca6b067 45#include "blk-pm.h"
c1c80384 46#include "blk-rq-qos.h"
8324aa91 47
18fbda91
OS
48#ifdef CONFIG_DEBUG_FS
49struct dentry *blk_debugfs_root;
50#endif
51
d07335e5 52EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
b0da3f0d 53EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
0a82a8d1 54EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
3291fa57 55EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
cbae8d45 56EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
0bfc2455 57
a73f730d
TH
58DEFINE_IDA(blk_queue_ida);
59
1da177e4
LT
60/*
61 * For the allocated request tables
62 */
d674d414 63struct kmem_cache *request_cachep;
1da177e4
LT
64
65/*
66 * For queue allocation
67 */
6728cb0e 68struct kmem_cache *blk_requestq_cachep;
1da177e4 69
1da177e4
LT
70/*
71 * Controlling structure to kblockd
72 */
ff856bad 73static struct workqueue_struct *kblockd_workqueue;
1da177e4 74
8814ce8a
BVA
75/**
76 * blk_queue_flag_set - atomically set a queue flag
77 * @flag: flag to be set
78 * @q: request queue
79 */
80void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
81{
82 unsigned long flags;
83
84 spin_lock_irqsave(q->queue_lock, flags);
85 queue_flag_set(flag, q);
86 spin_unlock_irqrestore(q->queue_lock, flags);
87}
88EXPORT_SYMBOL(blk_queue_flag_set);
89
90/**
91 * blk_queue_flag_clear - atomically clear a queue flag
92 * @flag: flag to be cleared
93 * @q: request queue
94 */
95void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
96{
97 unsigned long flags;
98
99 spin_lock_irqsave(q->queue_lock, flags);
100 queue_flag_clear(flag, q);
101 spin_unlock_irqrestore(q->queue_lock, flags);
102}
103EXPORT_SYMBOL(blk_queue_flag_clear);
104
105/**
106 * blk_queue_flag_test_and_set - atomically test and set a queue flag
107 * @flag: flag to be set
108 * @q: request queue
109 *
110 * Returns the previous value of @flag - 0 if the flag was not set and 1 if
111 * the flag was already set.
112 */
113bool blk_queue_flag_test_and_set(unsigned int flag, struct request_queue *q)
114{
115 unsigned long flags;
116 bool res;
117
118 spin_lock_irqsave(q->queue_lock, flags);
119 res = queue_flag_test_and_set(flag, q);
120 spin_unlock_irqrestore(q->queue_lock, flags);
121
122 return res;
123}
124EXPORT_SYMBOL_GPL(blk_queue_flag_test_and_set);
125
126/**
127 * blk_queue_flag_test_and_clear - atomically test and clear a queue flag
128 * @flag: flag to be cleared
129 * @q: request queue
130 *
131 * Returns the previous value of @flag - 0 if the flag was not set and 1 if
132 * the flag was set.
133 */
134bool blk_queue_flag_test_and_clear(unsigned int flag, struct request_queue *q)
135{
136 unsigned long flags;
137 bool res;
138
139 spin_lock_irqsave(q->queue_lock, flags);
140 res = queue_flag_test_and_clear(flag, q);
141 spin_unlock_irqrestore(q->queue_lock, flags);
142
143 return res;
144}
145EXPORT_SYMBOL_GPL(blk_queue_flag_test_and_clear);
146
2a4aa30c 147void blk_rq_init(struct request_queue *q, struct request *rq)
1da177e4 148{
1afb20f3
FT
149 memset(rq, 0, sizeof(*rq));
150
1da177e4 151 INIT_LIST_HEAD(&rq->queuelist);
242f9dcb 152 INIT_LIST_HEAD(&rq->timeout_list);
c7c22e4d 153 rq->cpu = -1;
63a71386 154 rq->q = q;
a2dec7b3 155 rq->__sector = (sector_t) -1;
2e662b65
JA
156 INIT_HLIST_NODE(&rq->hash);
157 RB_CLEAR_NODE(&rq->rb_node);
63a71386 158 rq->tag = -1;
bd166ef1 159 rq->internal_tag = -1;
522a7775 160 rq->start_time_ns = ktime_get_ns();
09e099d4 161 rq->part = NULL;
1da177e4 162}
2a4aa30c 163EXPORT_SYMBOL(blk_rq_init);
1da177e4 164
2a842aca
CH
165static const struct {
166 int errno;
167 const char *name;
168} blk_errors[] = {
169 [BLK_STS_OK] = { 0, "" },
170 [BLK_STS_NOTSUPP] = { -EOPNOTSUPP, "operation not supported" },
171 [BLK_STS_TIMEOUT] = { -ETIMEDOUT, "timeout" },
172 [BLK_STS_NOSPC] = { -ENOSPC, "critical space allocation" },
173 [BLK_STS_TRANSPORT] = { -ENOLINK, "recoverable transport" },
174 [BLK_STS_TARGET] = { -EREMOTEIO, "critical target" },
175 [BLK_STS_NEXUS] = { -EBADE, "critical nexus" },
176 [BLK_STS_MEDIUM] = { -ENODATA, "critical medium" },
177 [BLK_STS_PROTECTION] = { -EILSEQ, "protection" },
178 [BLK_STS_RESOURCE] = { -ENOMEM, "kernel resource" },
86ff7c2a 179 [BLK_STS_DEV_RESOURCE] = { -EBUSY, "device resource" },
03a07c92 180 [BLK_STS_AGAIN] = { -EAGAIN, "nonblocking retry" },
2a842aca 181
4e4cbee9
CH
182 /* device mapper special case, should not leak out: */
183 [BLK_STS_DM_REQUEUE] = { -EREMCHG, "dm internal retry" },
184
2a842aca
CH
185 /* everything else not covered above: */
186 [BLK_STS_IOERR] = { -EIO, "I/O" },
187};
188
189blk_status_t errno_to_blk_status(int errno)
190{
191 int i;
192
193 for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
194 if (blk_errors[i].errno == errno)
195 return (__force blk_status_t)i;
196 }
197
198 return BLK_STS_IOERR;
199}
200EXPORT_SYMBOL_GPL(errno_to_blk_status);
201
202int blk_status_to_errno(blk_status_t status)
203{
204 int idx = (__force int)status;
205
34bd9c1c 206 if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
2a842aca
CH
207 return -EIO;
208 return blk_errors[idx].errno;
209}
210EXPORT_SYMBOL_GPL(blk_status_to_errno);
211
212static void print_req_error(struct request *req, blk_status_t status)
213{
214 int idx = (__force int)status;
215
34bd9c1c 216 if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
2a842aca
CH
217 return;
218
219 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
220 __func__, blk_errors[idx].name, req->rq_disk ?
221 req->rq_disk->disk_name : "?",
222 (unsigned long long)blk_rq_pos(req));
223}
224
5bb23a68 225static void req_bio_endio(struct request *rq, struct bio *bio,
2a842aca 226 unsigned int nbytes, blk_status_t error)
1da177e4 227{
78d8e58a 228 if (error)
4e4cbee9 229 bio->bi_status = error;
797e7dbb 230
e8064021 231 if (unlikely(rq->rq_flags & RQF_QUIET))
b7c44ed9 232 bio_set_flag(bio, BIO_QUIET);
08bafc03 233
f79ea416 234 bio_advance(bio, nbytes);
7ba1ba12 235
143a87f4 236 /* don't actually finish bio if it's part of flush sequence */
e8064021 237 if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
4246a0b6 238 bio_endio(bio);
1da177e4 239}
1da177e4 240
1da177e4
LT
241void blk_dump_rq_flags(struct request *rq, char *msg)
242{
aebf526b
CH
243 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
244 rq->rq_disk ? rq->rq_disk->disk_name : "?",
5953316d 245 (unsigned long long) rq->cmd_flags);
1da177e4 246
83096ebf
TH
247 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
248 (unsigned long long)blk_rq_pos(rq),
249 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
b4f42e28
JA
250 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
251 rq->bio, rq->biotail, blk_rq_bytes(rq));
1da177e4 252}
1da177e4
LT
253EXPORT_SYMBOL(blk_dump_rq_flags);
254
1da177e4
LT
255/**
256 * blk_sync_queue - cancel any pending callbacks on a queue
257 * @q: the queue
258 *
259 * Description:
260 * The block layer may perform asynchronous callback activity
261 * on a queue, such as calling the unplug function after a timeout.
262 * A block device may call blk_sync_queue to ensure that any
263 * such activity is cancelled, thus allowing it to release resources
59c51591 264 * that the callbacks might use. The caller must already have made sure
1da177e4
LT
265 * that its ->make_request_fn will not re-add plugging prior to calling
266 * this function.
267 *
da527770 268 * This function does not cancel any asynchronous activity arising
da3dae54 269 * out of elevator or throttling code. That would require elevator_exit()
5efd6113 270 * and blkcg_exit_queue() to be called with queue lock initialized.
da527770 271 *
1da177e4
LT
272 */
273void blk_sync_queue(struct request_queue *q)
274{
70ed28b9 275 del_timer_sync(&q->timeout);
4e9b6f20 276 cancel_work_sync(&q->timeout_work);
f04c1fe7
ML
277
278 if (q->mq_ops) {
279 struct blk_mq_hw_ctx *hctx;
280 int i;
281
aba7afc5 282 cancel_delayed_work_sync(&q->requeue_work);
21c6e939 283 queue_for_each_hw_ctx(q, hctx, i)
9f993737 284 cancel_delayed_work_sync(&hctx->run_work);
f04c1fe7 285 }
1da177e4
LT
286}
287EXPORT_SYMBOL(blk_sync_queue);
288
c9254f2d 289/**
cd84a62e 290 * blk_set_pm_only - increment pm_only counter
c9254f2d 291 * @q: request queue pointer
c9254f2d 292 */
cd84a62e 293void blk_set_pm_only(struct request_queue *q)
c9254f2d 294{
cd84a62e 295 atomic_inc(&q->pm_only);
c9254f2d 296}
cd84a62e 297EXPORT_SYMBOL_GPL(blk_set_pm_only);
c9254f2d 298
cd84a62e 299void blk_clear_pm_only(struct request_queue *q)
c9254f2d 300{
cd84a62e
BVA
301 int pm_only;
302
303 pm_only = atomic_dec_return(&q->pm_only);
304 WARN_ON_ONCE(pm_only < 0);
305 if (pm_only == 0)
306 wake_up_all(&q->mq_freeze_wq);
c9254f2d 307}
cd84a62e 308EXPORT_SYMBOL_GPL(blk_clear_pm_only);
c9254f2d 309
165125e1 310void blk_put_queue(struct request_queue *q)
483f4afc
AV
311{
312 kobject_put(&q->kobj);
313}
d86e0e83 314EXPORT_SYMBOL(blk_put_queue);
483f4afc 315
aed3ea94
JA
316void blk_set_queue_dying(struct request_queue *q)
317{
8814ce8a 318 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
aed3ea94 319
d3cfb2a0
ML
320 /*
321 * When queue DYING flag is set, we need to block new req
322 * entering queue, so we call blk_freeze_queue_start() to
323 * prevent I/O from crossing blk_queue_enter().
324 */
325 blk_freeze_queue_start(q);
326
aed3ea94
JA
327 if (q->mq_ops)
328 blk_mq_wake_waiters(q);
055f6e18
ML
329
330 /* Make blk_queue_enter() reexamine the DYING flag. */
331 wake_up_all(&q->mq_freeze_wq);
aed3ea94
JA
332}
333EXPORT_SYMBOL_GPL(blk_set_queue_dying);
334
4cf6324b
BVA
335/* Unconfigure the I/O scheduler and dissociate from the cgroup controller. */
336void blk_exit_queue(struct request_queue *q)
337{
338 /*
339 * Since the I/O scheduler exit code may access cgroup information,
340 * perform I/O scheduler exit before disassociating from the block
341 * cgroup controller.
342 */
343 if (q->elevator) {
344 ioc_clear_queue(q);
345 elevator_exit(q, q->elevator);
346 q->elevator = NULL;
347 }
348
349 /*
350 * Remove all references to @q from the block cgroup controller before
351 * restoring @q->queue_lock to avoid that restoring this pointer causes
352 * e.g. blkcg_print_blkgs() to crash.
353 */
354 blkcg_exit_queue(q);
355
356 /*
357 * Since the cgroup code may dereference the @q->backing_dev_info
358 * pointer, only decrease its reference count after having removed the
359 * association with the block cgroup controller.
360 */
361 bdi_put(q->backing_dev_info);
362}
363
c9a929dd
TH
364/**
365 * blk_cleanup_queue - shutdown a request queue
366 * @q: request queue to shutdown
367 *
c246e80d
BVA
368 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
369 * put it. All future requests will be failed immediately with -ENODEV.
c94a96ac 370 */
6728cb0e 371void blk_cleanup_queue(struct request_queue *q)
483f4afc 372{
c9a929dd 373 spinlock_t *lock = q->queue_lock;
e3335de9 374
3f3299d5 375 /* mark @q DYING, no new request or merges will be allowed afterwards */
483f4afc 376 mutex_lock(&q->sysfs_lock);
aed3ea94 377 blk_set_queue_dying(q);
c9a929dd 378 spin_lock_irq(lock);
6ecf23af 379
80fd9979 380 /*
3f3299d5 381 * A dying queue is permanently in bypass mode till released. Note
80fd9979
TH
382 * that, unlike blk_queue_bypass_start(), we aren't performing
383 * synchronize_rcu() after entering bypass mode to avoid the delay
384 * as some drivers create and destroy a lot of queues while
385 * probing. This is still safe because blk_release_queue() will be
386 * called only after the queue refcnt drops to zero and nothing,
387 * RCU or not, would be traversing the queue by then.
388 */
6ecf23af
TH
389 q->bypass_depth++;
390 queue_flag_set(QUEUE_FLAG_BYPASS, q);
391
c9a929dd
TH
392 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
393 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
3f3299d5 394 queue_flag_set(QUEUE_FLAG_DYING, q);
c9a929dd
TH
395 spin_unlock_irq(lock);
396 mutex_unlock(&q->sysfs_lock);
397
c246e80d
BVA
398 /*
399 * Drain all requests queued before DYING marking. Set DEAD flag to
400 * prevent that q->request_fn() gets invoked after draining finished.
401 */
3ef28e83 402 blk_freeze_queue(q);
c57cdf7a
ML
403
404 rq_qos_exit(q);
405
9c1051aa 406 spin_lock_irq(lock);
c246e80d 407 queue_flag_set(QUEUE_FLAG_DEAD, q);
807592a4 408 spin_unlock_irq(lock);
c9a929dd 409
c2856ae2
ML
410 /*
411 * make sure all in-progress dispatch are completed because
412 * blk_freeze_queue() can only complete all requests, and
413 * dispatch may still be in-progress since we dispatch requests
1311326c
ML
414 * from more than one contexts.
415 *
416 * No need to quiesce queue if it isn't initialized yet since
417 * blk_freeze_queue() should be enough for cases of passthrough
418 * request.
c2856ae2 419 */
1311326c 420 if (q->mq_ops && blk_queue_init_done(q))
c2856ae2
ML
421 blk_mq_quiesce_queue(q);
422
5a48fc14
DW
423 /* for synchronous bio-based driver finish in-flight integrity i/o */
424 blk_flush_integrity();
425
c9a929dd 426 /* @q won't process any more request, flush async actions */
dc3b17cc 427 del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
c9a929dd
TH
428 blk_sync_queue(q);
429
a063057d
BVA
430 /*
431 * I/O scheduler exit is only safe after the sysfs scheduler attribute
432 * has been removed.
433 */
434 WARN_ON_ONCE(q->kobj.state_in_sysfs);
435
4cf6324b 436 blk_exit_queue(q);
a063057d 437
45a9c9d9
BVA
438 if (q->mq_ops)
439 blk_mq_free_queue(q);
a1ce35fa 440
3ef28e83 441 percpu_ref_exit(&q->q_usage_counter);
45a9c9d9 442
5e5cfac0
AH
443 spin_lock_irq(lock);
444 if (q->queue_lock != &q->__queue_lock)
445 q->queue_lock = &q->__queue_lock;
446 spin_unlock_irq(lock);
447
c9a929dd 448 /* @q is and will stay empty, shutdown and put */
483f4afc
AV
449 blk_put_queue(q);
450}
1da177e4
LT
451EXPORT_SYMBOL(blk_cleanup_queue);
452
271508db 453/* Allocate memory local to the request queue */
6d247d7f 454static void *alloc_request_simple(gfp_t gfp_mask, void *data)
271508db 455{
6d247d7f
CH
456 struct request_queue *q = data;
457
458 return kmem_cache_alloc_node(request_cachep, gfp_mask, q->node);
271508db
DR
459}
460
6d247d7f 461static void free_request_simple(void *element, void *data)
271508db
DR
462{
463 kmem_cache_free(request_cachep, element);
464}
465
6d247d7f
CH
466static void *alloc_request_size(gfp_t gfp_mask, void *data)
467{
468 struct request_queue *q = data;
469 struct request *rq;
470
471 rq = kmalloc_node(sizeof(struct request) + q->cmd_size, gfp_mask,
472 q->node);
473 if (rq && q->init_rq_fn && q->init_rq_fn(q, rq, gfp_mask) < 0) {
474 kfree(rq);
475 rq = NULL;
476 }
477 return rq;
478}
479
480static void free_request_size(void *element, void *data)
481{
482 struct request_queue *q = data;
483
484 if (q->exit_rq_fn)
485 q->exit_rq_fn(q, element);
486 kfree(element);
487}
488
5b788ce3
TH
489int blk_init_rl(struct request_list *rl, struct request_queue *q,
490 gfp_t gfp_mask)
1da177e4 491{
85acb3ba 492 if (unlikely(rl->rq_pool) || q->mq_ops)
1abec4fd
MS
493 return 0;
494
5b788ce3 495 rl->q = q;
1faa16d2
JA
496 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
497 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
1faa16d2
JA
498 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
499 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
1da177e4 500
6d247d7f
CH
501 if (q->cmd_size) {
502 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
503 alloc_request_size, free_request_size,
504 q, gfp_mask, q->node);
505 } else {
506 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
507 alloc_request_simple, free_request_simple,
508 q, gfp_mask, q->node);
509 }
1da177e4
LT
510 if (!rl->rq_pool)
511 return -ENOMEM;
512
b425e504
BVA
513 if (rl != &q->root_rl)
514 WARN_ON_ONCE(!blk_get_queue(q));
515
1da177e4
LT
516 return 0;
517}
518
b425e504 519void blk_exit_rl(struct request_queue *q, struct request_list *rl)
5b788ce3 520{
b425e504 521 if (rl->rq_pool) {
5b788ce3 522 mempool_destroy(rl->rq_pool);
b425e504
BVA
523 if (rl != &q->root_rl)
524 blk_put_queue(q);
525 }
5b788ce3
TH
526}
527
165125e1 528struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
1da177e4 529{
5ee0524b 530 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE, NULL);
1946089a
CL
531}
532EXPORT_SYMBOL(blk_alloc_queue);
1da177e4 533
3a0a5299
BVA
534/**
535 * blk_queue_enter() - try to increase q->q_usage_counter
536 * @q: request queue pointer
537 * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PREEMPT
538 */
9a95e4ef 539int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
3ef28e83 540{
cd84a62e 541 const bool pm = flags & BLK_MQ_REQ_PREEMPT;
3a0a5299 542
3ef28e83 543 while (true) {
3a0a5299 544 bool success = false;
3ef28e83 545
818e0fa2 546 rcu_read_lock();
3a0a5299
BVA
547 if (percpu_ref_tryget_live(&q->q_usage_counter)) {
548 /*
cd84a62e
BVA
549 * The code that increments the pm_only counter is
550 * responsible for ensuring that that counter is
551 * globally visible before the queue is unfrozen.
3a0a5299 552 */
cd84a62e 553 if (pm || !blk_queue_pm_only(q)) {
3a0a5299
BVA
554 success = true;
555 } else {
556 percpu_ref_put(&q->q_usage_counter);
557 }
558 }
818e0fa2 559 rcu_read_unlock();
3a0a5299
BVA
560
561 if (success)
3ef28e83
DW
562 return 0;
563
3a0a5299 564 if (flags & BLK_MQ_REQ_NOWAIT)
3ef28e83
DW
565 return -EBUSY;
566
5ed61d3f 567 /*
1671d522 568 * read pair of barrier in blk_freeze_queue_start(),
5ed61d3f 569 * we need to order reading __PERCPU_REF_DEAD flag of
d3cfb2a0
ML
570 * .q_usage_counter and reading .mq_freeze_depth or
571 * queue dying flag, otherwise the following wait may
572 * never return if the two reads are reordered.
5ed61d3f
ML
573 */
574 smp_rmb();
575
1dc3039b
AJ
576 wait_event(q->mq_freeze_wq,
577 (atomic_read(&q->mq_freeze_depth) == 0 &&
0d25bd07
BVA
578 (pm || (blk_pm_request_resume(q),
579 !blk_queue_pm_only(q)))) ||
1dc3039b 580 blk_queue_dying(q));
3ef28e83
DW
581 if (blk_queue_dying(q))
582 return -ENODEV;
3ef28e83
DW
583 }
584}
585
586void blk_queue_exit(struct request_queue *q)
587{
588 percpu_ref_put(&q->q_usage_counter);
589}
590
591static void blk_queue_usage_counter_release(struct percpu_ref *ref)
592{
593 struct request_queue *q =
594 container_of(ref, struct request_queue, q_usage_counter);
595
596 wake_up_all(&q->mq_freeze_wq);
597}
598
bca237a5 599static void blk_rq_timed_out_timer(struct timer_list *t)
287922eb 600{
bca237a5 601 struct request_queue *q = from_timer(q, t, timeout);
287922eb
CH
602
603 kblockd_schedule_work(&q->timeout_work);
604}
605
498f6650
BVA
606/**
607 * blk_alloc_queue_node - allocate a request queue
608 * @gfp_mask: memory allocation flags
609 * @node_id: NUMA node to allocate memory from
610 * @lock: For legacy queues, pointer to a spinlock that will be used to e.g.
611 * serialize calls to the legacy .request_fn() callback. Ignored for
612 * blk-mq request queues.
613 *
614 * Note: pass the queue lock as the third argument to this function instead of
615 * setting the queue lock pointer explicitly to avoid triggering a sporadic
616 * crash in the blkcg code. This function namely calls blkcg_init_queue() and
617 * the queue lock pointer must be set before blkcg_init_queue() is called.
618 */
5ee0524b
BVA
619struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id,
620 spinlock_t *lock)
1946089a 621{
165125e1 622 struct request_queue *q;
338aa96d 623 int ret;
1946089a 624
8324aa91 625 q = kmem_cache_alloc_node(blk_requestq_cachep,
94f6030c 626 gfp_mask | __GFP_ZERO, node_id);
1da177e4
LT
627 if (!q)
628 return NULL;
629
cbf62af3
CH
630 INIT_LIST_HEAD(&q->queue_head);
631 q->last_merge = NULL;
cbf62af3 632
00380a40 633 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
a73f730d 634 if (q->id < 0)
3d2936f4 635 goto fail_q;
a73f730d 636
338aa96d
KO
637 ret = bioset_init(&q->bio_split, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
638 if (ret)
54efd50b
KO
639 goto fail_id;
640
d03f6cdc
JK
641 q->backing_dev_info = bdi_alloc_node(gfp_mask, node_id);
642 if (!q->backing_dev_info)
643 goto fail_split;
644
a83b576c
JA
645 q->stats = blk_alloc_queue_stats();
646 if (!q->stats)
647 goto fail_stats;
648
dc3b17cc 649 q->backing_dev_info->ra_pages =
09cbfeaf 650 (VM_MAX_READAHEAD * 1024) / PAGE_SIZE;
dc3b17cc
JK
651 q->backing_dev_info->capabilities = BDI_CAP_CGROUP_WRITEBACK;
652 q->backing_dev_info->name = "block";
5151412d 653 q->node = node_id;
0989a025 654
bca237a5
KC
655 timer_setup(&q->backing_dev_info->laptop_mode_wb_timer,
656 laptop_mode_timer_fn, 0);
657 timer_setup(&q->timeout, blk_rq_timed_out_timer, 0);
4e9b6f20 658 INIT_WORK(&q->timeout_work, NULL);
a612fddf 659 INIT_LIST_HEAD(&q->icq_list);
4eef3049 660#ifdef CONFIG_BLK_CGROUP
e8989fae 661 INIT_LIST_HEAD(&q->blkg_list);
4eef3049 662#endif
483f4afc 663
8324aa91 664 kobject_init(&q->kobj, &blk_queue_ktype);
1da177e4 665
5acb3cc2
WL
666#ifdef CONFIG_BLK_DEV_IO_TRACE
667 mutex_init(&q->blk_trace_mutex);
668#endif
483f4afc 669 mutex_init(&q->sysfs_lock);
e7e72bf6 670 spin_lock_init(&q->__queue_lock);
483f4afc 671
5e27891e 672 q->queue_lock = lock ? : &q->__queue_lock;
c94a96ac 673
b82d4b19
TH
674 /*
675 * A queue starts its life with bypass turned on to avoid
676 * unnecessary bypass on/off overhead and nasty surprises during
749fefe6
TH
677 * init. The initial bypass will be finished when the queue is
678 * registered by blk_register_queue().
b82d4b19
TH
679 */
680 q->bypass_depth = 1;
f78bac2c 681 queue_flag_set_unlocked(QUEUE_FLAG_BYPASS, q);
b82d4b19 682
320ae51f
JA
683 init_waitqueue_head(&q->mq_freeze_wq);
684
3ef28e83
DW
685 /*
686 * Init percpu_ref in atomic mode so that it's faster to shutdown.
687 * See blk_register_queue() for details.
688 */
689 if (percpu_ref_init(&q->q_usage_counter,
690 blk_queue_usage_counter_release,
691 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
fff4996b 692 goto fail_bdi;
f51b802c 693
3ef28e83
DW
694 if (blkcg_init_queue(q))
695 goto fail_ref;
696
1da177e4 697 return q;
a73f730d 698
3ef28e83
DW
699fail_ref:
700 percpu_ref_exit(&q->q_usage_counter);
fff4996b 701fail_bdi:
a83b576c
JA
702 blk_free_queue_stats(q->stats);
703fail_stats:
d03f6cdc 704 bdi_put(q->backing_dev_info);
54efd50b 705fail_split:
338aa96d 706 bioset_exit(&q->bio_split);
a73f730d
TH
707fail_id:
708 ida_simple_remove(&blk_queue_ida, q->id);
709fail_q:
710 kmem_cache_free(blk_requestq_cachep, q);
711 return NULL;
1da177e4 712}
1946089a 713EXPORT_SYMBOL(blk_alloc_queue_node);
1da177e4 714
09ac46c4 715bool blk_get_queue(struct request_queue *q)
1da177e4 716{
3f3299d5 717 if (likely(!blk_queue_dying(q))) {
09ac46c4
TH
718 __blk_get_queue(q);
719 return true;
1da177e4
LT
720 }
721
09ac46c4 722 return false;
1da177e4 723}
d86e0e83 724EXPORT_SYMBOL(blk_get_queue);
1da177e4 725
a1ce35fa
JA
726/**
727 * blk_get_request - allocate a request
728 * @q: request queue to allocate a request for
729 * @op: operation (REQ_OP_*) and REQ_* flags, e.g. REQ_SYNC.
730 * @flags: BLK_MQ_REQ_* flags, e.g. BLK_MQ_REQ_NOWAIT.
1da177e4 731 */
a1ce35fa
JA
732struct request *blk_get_request(struct request_queue *q, unsigned int op,
733 blk_mq_req_flags_t flags)
1da177e4 734{
a1ce35fa 735 struct request *req;
1da177e4 736
a1ce35fa
JA
737 WARN_ON_ONCE(op & REQ_NOWAIT);
738 WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PREEMPT));
1da177e4 739
a1ce35fa
JA
740 req = blk_mq_alloc_request(q, op, flags);
741 if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn)
742 q->mq_ops->initialize_rq_fn(req);
1da177e4 743
a1ce35fa 744 return req;
1da177e4 745}
a1ce35fa 746EXPORT_SYMBOL(blk_get_request);
1da177e4 747
a1ce35fa
JA
748static void part_round_stats_single(struct request_queue *q, int cpu,
749 struct hd_struct *part, unsigned long now,
750 unsigned int inflight)
1da177e4 751{
a1ce35fa
JA
752 if (inflight) {
753 __part_stat_add(cpu, part, time_in_queue,
754 inflight * (now - part->stamp));
755 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1da177e4 756 }
a1ce35fa 757 part->stamp = now;
074a7aca
TH
758}
759
760/**
496aa8a9 761 * part_round_stats() - Round off the performance stats on a struct disk_stats.
d62e26b3 762 * @q: target block queue
496aa8a9
RD
763 * @cpu: cpu number for stats access
764 * @part: target partition
1da177e4
LT
765 *
766 * The average IO queue length and utilisation statistics are maintained
767 * by observing the current state of the queue length and the amount of
768 * time it has been in this state for.
769 *
770 * Normally, that accounting is done on IO completion, but that can result
771 * in more than a second's worth of IO being accounted for within any one
772 * second, leading to >100% utilisation. To deal with that, we call this
773 * function to do a round-off before returning the results when reading
774 * /proc/diskstats. This accounts immediately for all queue usage up to
775 * the current jiffies and restarts the counters again.
776 */
d62e26b3 777void part_round_stats(struct request_queue *q, int cpu, struct hd_struct *part)
6f2576af 778{
b8d62b3a 779 struct hd_struct *part2 = NULL;
6f2576af 780 unsigned long now = jiffies;
b8d62b3a
JA
781 unsigned int inflight[2];
782 int stats = 0;
783
784 if (part->stamp != now)
785 stats |= 1;
786
787 if (part->partno) {
788 part2 = &part_to_disk(part)->part0;
789 if (part2->stamp != now)
790 stats |= 2;
791 }
792
793 if (!stats)
794 return;
795
796 part_in_flight(q, part, inflight);
6f2576af 797
b8d62b3a
JA
798 if (stats & 2)
799 part_round_stats_single(q, cpu, part2, now, inflight[1]);
800 if (stats & 1)
801 part_round_stats_single(q, cpu, part, now, inflight[0]);
6f2576af 802}
074a7aca 803EXPORT_SYMBOL_GPL(part_round_stats);
6f2576af 804
1da177e4
LT
805void blk_put_request(struct request *req)
806{
a1ce35fa 807 blk_mq_free_request(req);
1da177e4 808}
1da177e4
LT
809EXPORT_SYMBOL(blk_put_request);
810
320ae51f
JA
811bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
812 struct bio *bio)
73c10101 813{
1eff9d32 814 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
73c10101 815
73c10101
JA
816 if (!ll_back_merge_fn(q, req, bio))
817 return false;
818
8c1cf6bb 819 trace_block_bio_backmerge(q, req, bio);
73c10101
JA
820
821 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
822 blk_rq_set_mixed_merge(req);
823
824 req->biotail->bi_next = bio;
825 req->biotail = bio;
4f024f37 826 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
827 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
828
320ae51f 829 blk_account_io_start(req, false);
73c10101
JA
830 return true;
831}
832
320ae51f
JA
833bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
834 struct bio *bio)
73c10101 835{
1eff9d32 836 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
73c10101 837
73c10101
JA
838 if (!ll_front_merge_fn(q, req, bio))
839 return false;
840
8c1cf6bb 841 trace_block_bio_frontmerge(q, req, bio);
73c10101
JA
842
843 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
844 blk_rq_set_mixed_merge(req);
845
73c10101
JA
846 bio->bi_next = req->bio;
847 req->bio = bio;
848
4f024f37
KO
849 req->__sector = bio->bi_iter.bi_sector;
850 req->__data_len += bio->bi_iter.bi_size;
73c10101
JA
851 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
852
320ae51f 853 blk_account_io_start(req, false);
73c10101
JA
854 return true;
855}
856
1e739730
CH
857bool bio_attempt_discard_merge(struct request_queue *q, struct request *req,
858 struct bio *bio)
859{
860 unsigned short segments = blk_rq_nr_discard_segments(req);
861
862 if (segments >= queue_max_discard_segments(q))
863 goto no_merge;
864 if (blk_rq_sectors(req) + bio_sectors(bio) >
865 blk_rq_get_max_sectors(req, blk_rq_pos(req)))
866 goto no_merge;
867
868 req->biotail->bi_next = bio;
869 req->biotail = bio;
870 req->__data_len += bio->bi_iter.bi_size;
871 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
872 req->nr_phys_segments = segments + 1;
873
874 blk_account_io_start(req, false);
875 return true;
876no_merge:
877 req_set_nomerge(q, req);
878 return false;
879}
880
bd87b589 881/**
320ae51f 882 * blk_attempt_plug_merge - try to merge with %current's plugged list
bd87b589
TH
883 * @q: request_queue new bio is being queued at
884 * @bio: new bio being queued
885 * @request_count: out parameter for number of traversed plugged requests
ccc2600b
RD
886 * @same_queue_rq: pointer to &struct request that gets filled in when
887 * another request associated with @q is found on the plug list
888 * (optional, may be %NULL)
bd87b589
TH
889 *
890 * Determine whether @bio being queued on @q can be merged with a request
891 * on %current's plugged list. Returns %true if merge was successful,
892 * otherwise %false.
893 *
07c2bd37
TH
894 * Plugging coalesces IOs from the same issuer for the same purpose without
895 * going through @q->queue_lock. As such it's more of an issuing mechanism
896 * than scheduling, and the request, while may have elvpriv data, is not
897 * added on the elevator at this point. In addition, we don't have
898 * reliable access to the elevator outside queue lock. Only check basic
899 * merging parameters without querying the elevator.
da41a589
RE
900 *
901 * Caller must ensure !blk_queue_nomerges(q) beforehand.
73c10101 902 */
320ae51f 903bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
5b3f341f
SL
904 unsigned int *request_count,
905 struct request **same_queue_rq)
73c10101
JA
906{
907 struct blk_plug *plug;
908 struct request *rq;
92f399c7 909 struct list_head *plug_list;
73c10101 910
bd87b589 911 plug = current->plug;
73c10101 912 if (!plug)
34fe7c05 913 return false;
56ebdaf2 914 *request_count = 0;
73c10101 915
a1ce35fa 916 plug_list = &plug->mq_list;
92f399c7
SL
917
918 list_for_each_entry_reverse(rq, plug_list, queuelist) {
34fe7c05 919 bool merged = false;
73c10101 920
5b3f341f 921 if (rq->q == q) {
1b2e19f1 922 (*request_count)++;
5b3f341f
SL
923 /*
924 * Only blk-mq multiple hardware queues case checks the
925 * rq in the same queue, there should be only one such
926 * rq in a queue
927 **/
928 if (same_queue_rq)
929 *same_queue_rq = rq;
930 }
56ebdaf2 931
07c2bd37 932 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
73c10101
JA
933 continue;
934
34fe7c05
CH
935 switch (blk_try_merge(rq, bio)) {
936 case ELEVATOR_BACK_MERGE:
937 merged = bio_attempt_back_merge(q, rq, bio);
938 break;
939 case ELEVATOR_FRONT_MERGE:
940 merged = bio_attempt_front_merge(q, rq, bio);
941 break;
1e739730
CH
942 case ELEVATOR_DISCARD_MERGE:
943 merged = bio_attempt_discard_merge(q, rq, bio);
944 break;
34fe7c05
CH
945 default:
946 break;
73c10101 947 }
34fe7c05
CH
948
949 if (merged)
950 return true;
73c10101 951 }
34fe7c05
CH
952
953 return false;
73c10101
JA
954}
955
0809e3ac
JM
956unsigned int blk_plug_queued_count(struct request_queue *q)
957{
958 struct blk_plug *plug;
959 struct request *rq;
960 struct list_head *plug_list;
961 unsigned int ret = 0;
962
963 plug = current->plug;
964 if (!plug)
965 goto out;
966
a1ce35fa 967 plug_list = &plug->mq_list;
0809e3ac
JM
968 list_for_each_entry(rq, plug_list, queuelist) {
969 if (rq->q == q)
970 ret++;
971 }
972out:
973 return ret;
974}
975
da8d7f07 976void blk_init_request_from_bio(struct request *req, struct bio *bio)
52d9e675 977{
0be0dee6
BVA
978 struct io_context *ioc = rq_ioc(bio);
979
1eff9d32 980 if (bio->bi_opf & REQ_RAHEAD)
a82afdfc 981 req->cmd_flags |= REQ_FAILFAST_MASK;
b31dc66a 982
4f024f37 983 req->__sector = bio->bi_iter.bi_sector;
5dc8b362
AM
984 if (ioprio_valid(bio_prio(bio)))
985 req->ioprio = bio_prio(bio);
0be0dee6
BVA
986 else if (ioc)
987 req->ioprio = ioc->ioprio;
988 else
989 req->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
cb6934f8 990 req->write_hint = bio->bi_write_hint;
bc1c56fd 991 blk_rq_bio_prep(req->q, req, bio);
52d9e675 992}
da8d7f07 993EXPORT_SYMBOL_GPL(blk_init_request_from_bio);
52d9e675 994
52c5e62d 995static void handle_bad_sector(struct bio *bio, sector_t maxsector)
1da177e4
LT
996{
997 char b[BDEVNAME_SIZE];
998
999 printk(KERN_INFO "attempt to access beyond end of device\n");
6296b960 1000 printk(KERN_INFO "%s: rw=%d, want=%Lu, limit=%Lu\n",
74d46992 1001 bio_devname(bio, b), bio->bi_opf,
f73a1c7d 1002 (unsigned long long)bio_end_sector(bio),
52c5e62d 1003 (long long)maxsector);
1da177e4
LT
1004}
1005
c17bb495
AM
1006#ifdef CONFIG_FAIL_MAKE_REQUEST
1007
1008static DECLARE_FAULT_ATTR(fail_make_request);
1009
1010static int __init setup_fail_make_request(char *str)
1011{
1012 return setup_fault_attr(&fail_make_request, str);
1013}
1014__setup("fail_make_request=", setup_fail_make_request);
1015
b2c9cd37 1016static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
c17bb495 1017{
b2c9cd37 1018 return part->make_it_fail && should_fail(&fail_make_request, bytes);
c17bb495
AM
1019}
1020
1021static int __init fail_make_request_debugfs(void)
1022{
dd48c085
AM
1023 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1024 NULL, &fail_make_request);
1025
21f9fcd8 1026 return PTR_ERR_OR_ZERO(dir);
c17bb495
AM
1027}
1028
1029late_initcall(fail_make_request_debugfs);
1030
1031#else /* CONFIG_FAIL_MAKE_REQUEST */
1032
b2c9cd37
AM
1033static inline bool should_fail_request(struct hd_struct *part,
1034 unsigned int bytes)
c17bb495 1035{
b2c9cd37 1036 return false;
c17bb495
AM
1037}
1038
1039#endif /* CONFIG_FAIL_MAKE_REQUEST */
1040
721c7fc7
ID
1041static inline bool bio_check_ro(struct bio *bio, struct hd_struct *part)
1042{
b089cfd9
JA
1043 const int op = bio_op(bio);
1044
8b2ded1c 1045 if (part->policy && op_is_write(op)) {
721c7fc7
ID
1046 char b[BDEVNAME_SIZE];
1047
8b2ded1c
MP
1048 if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
1049 return false;
1050
a32e236e 1051 WARN_ONCE(1,
721c7fc7
ID
1052 "generic_make_request: Trying to write "
1053 "to read-only block-device %s (partno %d)\n",
1054 bio_devname(bio, b), part->partno);
a32e236e
LT
1055 /* Older lvm-tools actually trigger this */
1056 return false;
721c7fc7
ID
1057 }
1058
1059 return false;
1060}
1061
30abb3a6
HM
1062static noinline int should_fail_bio(struct bio *bio)
1063{
1064 if (should_fail_request(&bio->bi_disk->part0, bio->bi_iter.bi_size))
1065 return -EIO;
1066 return 0;
1067}
1068ALLOW_ERROR_INJECTION(should_fail_bio, ERRNO);
1069
52c5e62d
CH
1070/*
1071 * Check whether this bio extends beyond the end of the device or partition.
1072 * This may well happen - the kernel calls bread() without checking the size of
1073 * the device, e.g., when mounting a file system.
1074 */
1075static inline int bio_check_eod(struct bio *bio, sector_t maxsector)
1076{
1077 unsigned int nr_sectors = bio_sectors(bio);
1078
1079 if (nr_sectors && maxsector &&
1080 (nr_sectors > maxsector ||
1081 bio->bi_iter.bi_sector > maxsector - nr_sectors)) {
1082 handle_bad_sector(bio, maxsector);
1083 return -EIO;
1084 }
1085 return 0;
1086}
1087
74d46992
CH
1088/*
1089 * Remap block n of partition p to block n+start(p) of the disk.
1090 */
1091static inline int blk_partition_remap(struct bio *bio)
1092{
1093 struct hd_struct *p;
52c5e62d 1094 int ret = -EIO;
74d46992 1095
721c7fc7
ID
1096 rcu_read_lock();
1097 p = __disk_get_part(bio->bi_disk, bio->bi_partno);
52c5e62d
CH
1098 if (unlikely(!p))
1099 goto out;
1100 if (unlikely(should_fail_request(p, bio->bi_iter.bi_size)))
1101 goto out;
1102 if (unlikely(bio_check_ro(bio, p)))
721c7fc7 1103 goto out;
721c7fc7 1104
74d46992
CH
1105 /*
1106 * Zone reset does not include bi_size so bio_sectors() is always 0.
1107 * Include a test for the reset op code and perform the remap if needed.
1108 */
52c5e62d
CH
1109 if (bio_sectors(bio) || bio_op(bio) == REQ_OP_ZONE_RESET) {
1110 if (bio_check_eod(bio, part_nr_sects_read(p)))
1111 goto out;
1112 bio->bi_iter.bi_sector += p->start_sect;
52c5e62d
CH
1113 trace_block_bio_remap(bio->bi_disk->queue, bio, part_devt(p),
1114 bio->bi_iter.bi_sector - p->start_sect);
1115 }
c04fa44b 1116 bio->bi_partno = 0;
52c5e62d 1117 ret = 0;
721c7fc7
ID
1118out:
1119 rcu_read_unlock();
74d46992
CH
1120 return ret;
1121}
1122
27a84d54
CH
1123static noinline_for_stack bool
1124generic_make_request_checks(struct bio *bio)
1da177e4 1125{
165125e1 1126 struct request_queue *q;
5a7bbad2 1127 int nr_sectors = bio_sectors(bio);
4e4cbee9 1128 blk_status_t status = BLK_STS_IOERR;
5a7bbad2 1129 char b[BDEVNAME_SIZE];
1da177e4
LT
1130
1131 might_sleep();
1da177e4 1132
74d46992 1133 q = bio->bi_disk->queue;
5a7bbad2
CH
1134 if (unlikely(!q)) {
1135 printk(KERN_ERR
1136 "generic_make_request: Trying to access "
1137 "nonexistent block-device %s (%Lu)\n",
74d46992 1138 bio_devname(bio, b), (long long)bio->bi_iter.bi_sector);
5a7bbad2
CH
1139 goto end_io;
1140 }
c17bb495 1141
03a07c92
GR
1142 /*
1143 * For a REQ_NOWAIT based request, return -EOPNOTSUPP
1144 * if queue is not a request based queue.
1145 */
03a07c92
GR
1146 if ((bio->bi_opf & REQ_NOWAIT) && !queue_is_rq_based(q))
1147 goto not_supported;
1148
30abb3a6 1149 if (should_fail_bio(bio))
5a7bbad2 1150 goto end_io;
2056a782 1151
52c5e62d
CH
1152 if (bio->bi_partno) {
1153 if (unlikely(blk_partition_remap(bio)))
721c7fc7
ID
1154 goto end_io;
1155 } else {
52c5e62d
CH
1156 if (unlikely(bio_check_ro(bio, &bio->bi_disk->part0)))
1157 goto end_io;
1158 if (unlikely(bio_check_eod(bio, get_capacity(bio->bi_disk))))
721c7fc7
ID
1159 goto end_io;
1160 }
2056a782 1161
5a7bbad2
CH
1162 /*
1163 * Filter flush bio's early so that make_request based
1164 * drivers without flush support don't have to worry
1165 * about them.
1166 */
f3a8ab7d 1167 if (op_is_flush(bio->bi_opf) &&
c888a8f9 1168 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
1eff9d32 1169 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
5a7bbad2 1170 if (!nr_sectors) {
4e4cbee9 1171 status = BLK_STS_OK;
51fd77bd
JA
1172 goto end_io;
1173 }
5a7bbad2 1174 }
5ddfe969 1175
288dab8a
CH
1176 switch (bio_op(bio)) {
1177 case REQ_OP_DISCARD:
1178 if (!blk_queue_discard(q))
1179 goto not_supported;
1180 break;
1181 case REQ_OP_SECURE_ERASE:
1182 if (!blk_queue_secure_erase(q))
1183 goto not_supported;
1184 break;
1185 case REQ_OP_WRITE_SAME:
74d46992 1186 if (!q->limits.max_write_same_sectors)
288dab8a 1187 goto not_supported;
58886785 1188 break;
2d253440 1189 case REQ_OP_ZONE_RESET:
74d46992 1190 if (!blk_queue_is_zoned(q))
2d253440 1191 goto not_supported;
288dab8a 1192 break;
a6f0788e 1193 case REQ_OP_WRITE_ZEROES:
74d46992 1194 if (!q->limits.max_write_zeroes_sectors)
a6f0788e
CK
1195 goto not_supported;
1196 break;
288dab8a
CH
1197 default:
1198 break;
5a7bbad2 1199 }
01edede4 1200
7f4b35d1
TH
1201 /*
1202 * Various block parts want %current->io_context and lazy ioc
1203 * allocation ends up trading a lot of pain for a small amount of
1204 * memory. Just allocate it upfront. This may fail and block
1205 * layer knows how to live with it.
1206 */
1207 create_io_context(GFP_ATOMIC, q->node);
1208
ae118896
TH
1209 if (!blkcg_bio_issue_check(q, bio))
1210 return false;
27a84d54 1211
fbbaf700
N
1212 if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
1213 trace_block_bio_queue(q, bio);
1214 /* Now that enqueuing has been traced, we need to trace
1215 * completion as well.
1216 */
1217 bio_set_flag(bio, BIO_TRACE_COMPLETION);
1218 }
27a84d54 1219 return true;
a7384677 1220
288dab8a 1221not_supported:
4e4cbee9 1222 status = BLK_STS_NOTSUPP;
a7384677 1223end_io:
4e4cbee9 1224 bio->bi_status = status;
4246a0b6 1225 bio_endio(bio);
27a84d54 1226 return false;
1da177e4
LT
1227}
1228
27a84d54
CH
1229/**
1230 * generic_make_request - hand a buffer to its device driver for I/O
1231 * @bio: The bio describing the location in memory and on the device.
1232 *
1233 * generic_make_request() is used to make I/O requests of block
1234 * devices. It is passed a &struct bio, which describes the I/O that needs
1235 * to be done.
1236 *
1237 * generic_make_request() does not return any status. The
1238 * success/failure status of the request, along with notification of
1239 * completion, is delivered asynchronously through the bio->bi_end_io
1240 * function described (one day) else where.
1241 *
1242 * The caller of generic_make_request must make sure that bi_io_vec
1243 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1244 * set to describe the device address, and the
1245 * bi_end_io and optionally bi_private are set to describe how
1246 * completion notification should be signaled.
1247 *
1248 * generic_make_request and the drivers it calls may use bi_next if this
1249 * bio happens to be merged with someone else, and may resubmit the bio to
1250 * a lower device by calling into generic_make_request recursively, which
1251 * means the bio should NOT be touched after the call to ->make_request_fn.
d89d8796 1252 */
dece1635 1253blk_qc_t generic_make_request(struct bio *bio)
d89d8796 1254{
f5fe1b51
N
1255 /*
1256 * bio_list_on_stack[0] contains bios submitted by the current
1257 * make_request_fn.
1258 * bio_list_on_stack[1] contains bios that were submitted before
1259 * the current make_request_fn, but that haven't been processed
1260 * yet.
1261 */
1262 struct bio_list bio_list_on_stack[2];
37f9579f
BVA
1263 blk_mq_req_flags_t flags = 0;
1264 struct request_queue *q = bio->bi_disk->queue;
dece1635 1265 blk_qc_t ret = BLK_QC_T_NONE;
bddd87c7 1266
37f9579f
BVA
1267 if (bio->bi_opf & REQ_NOWAIT)
1268 flags = BLK_MQ_REQ_NOWAIT;
cd4a4ae4
JA
1269 if (bio_flagged(bio, BIO_QUEUE_ENTERED))
1270 blk_queue_enter_live(q);
1271 else if (blk_queue_enter(q, flags) < 0) {
37f9579f
BVA
1272 if (!blk_queue_dying(q) && (bio->bi_opf & REQ_NOWAIT))
1273 bio_wouldblock_error(bio);
1274 else
1275 bio_io_error(bio);
1276 return ret;
1277 }
1278
27a84d54 1279 if (!generic_make_request_checks(bio))
dece1635 1280 goto out;
27a84d54
CH
1281
1282 /*
1283 * We only want one ->make_request_fn to be active at a time, else
1284 * stack usage with stacked devices could be a problem. So use
1285 * current->bio_list to keep a list of requests submited by a
1286 * make_request_fn function. current->bio_list is also used as a
1287 * flag to say if generic_make_request is currently active in this
1288 * task or not. If it is NULL, then no make_request is active. If
1289 * it is non-NULL, then a make_request is active, and new requests
1290 * should be added at the tail
1291 */
bddd87c7 1292 if (current->bio_list) {
f5fe1b51 1293 bio_list_add(&current->bio_list[0], bio);
dece1635 1294 goto out;
d89d8796 1295 }
27a84d54 1296
d89d8796
NB
1297 /* following loop may be a bit non-obvious, and so deserves some
1298 * explanation.
1299 * Before entering the loop, bio->bi_next is NULL (as all callers
1300 * ensure that) so we have a list with a single bio.
1301 * We pretend that we have just taken it off a longer list, so
bddd87c7
AM
1302 * we assign bio_list to a pointer to the bio_list_on_stack,
1303 * thus initialising the bio_list of new bios to be
27a84d54 1304 * added. ->make_request() may indeed add some more bios
d89d8796
NB
1305 * through a recursive call to generic_make_request. If it
1306 * did, we find a non-NULL value in bio_list and re-enter the loop
1307 * from the top. In this case we really did just take the bio
bddd87c7 1308 * of the top of the list (no pretending) and so remove it from
27a84d54 1309 * bio_list, and call into ->make_request() again.
d89d8796
NB
1310 */
1311 BUG_ON(bio->bi_next);
f5fe1b51
N
1312 bio_list_init(&bio_list_on_stack[0]);
1313 current->bio_list = bio_list_on_stack;
d89d8796 1314 do {
37f9579f
BVA
1315 bool enter_succeeded = true;
1316
1317 if (unlikely(q != bio->bi_disk->queue)) {
1318 if (q)
1319 blk_queue_exit(q);
1320 q = bio->bi_disk->queue;
1321 flags = 0;
1322 if (bio->bi_opf & REQ_NOWAIT)
1323 flags = BLK_MQ_REQ_NOWAIT;
1324 if (blk_queue_enter(q, flags) < 0) {
1325 enter_succeeded = false;
1326 q = NULL;
1327 }
1328 }
27a84d54 1329
37f9579f 1330 if (enter_succeeded) {
79bd9959
N
1331 struct bio_list lower, same;
1332
1333 /* Create a fresh bio_list for all subordinate requests */
f5fe1b51
N
1334 bio_list_on_stack[1] = bio_list_on_stack[0];
1335 bio_list_init(&bio_list_on_stack[0]);
dece1635 1336 ret = q->make_request_fn(q, bio);
3ef28e83 1337
79bd9959
N
1338 /* sort new bios into those for a lower level
1339 * and those for the same level
1340 */
1341 bio_list_init(&lower);
1342 bio_list_init(&same);
f5fe1b51 1343 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
74d46992 1344 if (q == bio->bi_disk->queue)
79bd9959
N
1345 bio_list_add(&same, bio);
1346 else
1347 bio_list_add(&lower, bio);
1348 /* now assemble so we handle the lowest level first */
f5fe1b51
N
1349 bio_list_merge(&bio_list_on_stack[0], &lower);
1350 bio_list_merge(&bio_list_on_stack[0], &same);
1351 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
3ef28e83 1352 } else {
03a07c92
GR
1353 if (unlikely(!blk_queue_dying(q) &&
1354 (bio->bi_opf & REQ_NOWAIT)))
1355 bio_wouldblock_error(bio);
1356 else
1357 bio_io_error(bio);
3ef28e83 1358 }
f5fe1b51 1359 bio = bio_list_pop(&bio_list_on_stack[0]);
d89d8796 1360 } while (bio);
bddd87c7 1361 current->bio_list = NULL; /* deactivate */
dece1635
JA
1362
1363out:
37f9579f
BVA
1364 if (q)
1365 blk_queue_exit(q);
dece1635 1366 return ret;
d89d8796 1367}
1da177e4
LT
1368EXPORT_SYMBOL(generic_make_request);
1369
f421e1d9
CH
1370/**
1371 * direct_make_request - hand a buffer directly to its device driver for I/O
1372 * @bio: The bio describing the location in memory and on the device.
1373 *
1374 * This function behaves like generic_make_request(), but does not protect
1375 * against recursion. Must only be used if the called driver is known
1376 * to not call generic_make_request (or direct_make_request) again from
1377 * its make_request function. (Calling direct_make_request again from
1378 * a workqueue is perfectly fine as that doesn't recurse).
1379 */
1380blk_qc_t direct_make_request(struct bio *bio)
1381{
1382 struct request_queue *q = bio->bi_disk->queue;
1383 bool nowait = bio->bi_opf & REQ_NOWAIT;
1384 blk_qc_t ret;
1385
1386 if (!generic_make_request_checks(bio))
1387 return BLK_QC_T_NONE;
1388
3a0a5299 1389 if (unlikely(blk_queue_enter(q, nowait ? BLK_MQ_REQ_NOWAIT : 0))) {
f421e1d9
CH
1390 if (nowait && !blk_queue_dying(q))
1391 bio->bi_status = BLK_STS_AGAIN;
1392 else
1393 bio->bi_status = BLK_STS_IOERR;
1394 bio_endio(bio);
1395 return BLK_QC_T_NONE;
1396 }
1397
1398 ret = q->make_request_fn(q, bio);
1399 blk_queue_exit(q);
1400 return ret;
1401}
1402EXPORT_SYMBOL_GPL(direct_make_request);
1403
1da177e4 1404/**
710027a4 1405 * submit_bio - submit a bio to the block device layer for I/O
1da177e4
LT
1406 * @bio: The &struct bio which describes the I/O
1407 *
1408 * submit_bio() is very similar in purpose to generic_make_request(), and
1409 * uses that function to do most of the work. Both are fairly rough
710027a4 1410 * interfaces; @bio must be presetup and ready for I/O.
1da177e4
LT
1411 *
1412 */
4e49ea4a 1413blk_qc_t submit_bio(struct bio *bio)
1da177e4 1414{
bf2de6f5
JA
1415 /*
1416 * If it's a regular read/write or a barrier with data attached,
1417 * go through the normal accounting stuff before submission.
1418 */
e2a60da7 1419 if (bio_has_data(bio)) {
4363ac7c
MP
1420 unsigned int count;
1421
95fe6c1a 1422 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
7c5a0dcf 1423 count = queue_logical_block_size(bio->bi_disk->queue) >> 9;
4363ac7c
MP
1424 else
1425 count = bio_sectors(bio);
1426
a8ebb056 1427 if (op_is_write(bio_op(bio))) {
bf2de6f5
JA
1428 count_vm_events(PGPGOUT, count);
1429 } else {
4f024f37 1430 task_io_account_read(bio->bi_iter.bi_size);
bf2de6f5
JA
1431 count_vm_events(PGPGIN, count);
1432 }
1433
1434 if (unlikely(block_dump)) {
1435 char b[BDEVNAME_SIZE];
8dcbdc74 1436 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
ba25f9dc 1437 current->comm, task_pid_nr(current),
a8ebb056 1438 op_is_write(bio_op(bio)) ? "WRITE" : "READ",
4f024f37 1439 (unsigned long long)bio->bi_iter.bi_sector,
74d46992 1440 bio_devname(bio, b), count);
bf2de6f5 1441 }
1da177e4
LT
1442 }
1443
dece1635 1444 return generic_make_request(bio);
1da177e4 1445}
1da177e4
LT
1446EXPORT_SYMBOL(submit_bio);
1447
ea435e1b
CH
1448bool blk_poll(struct request_queue *q, blk_qc_t cookie)
1449{
1450 if (!q->poll_fn || !blk_qc_t_valid(cookie))
1451 return false;
1452
1453 if (current->plug)
1454 blk_flush_plug_list(current->plug, false);
1455 return q->poll_fn(q, cookie);
1456}
1457EXPORT_SYMBOL_GPL(blk_poll);
1458
82124d60 1459/**
bf4e6b4e
HR
1460 * blk_cloned_rq_check_limits - Helper function to check a cloned request
1461 * for new the queue limits
82124d60
KU
1462 * @q: the queue
1463 * @rq: the request being checked
1464 *
1465 * Description:
1466 * @rq may have been made based on weaker limitations of upper-level queues
1467 * in request stacking drivers, and it may violate the limitation of @q.
1468 * Since the block layer and the underlying device driver trust @rq
1469 * after it is inserted to @q, it should be checked against @q before
1470 * the insertion using this generic function.
1471 *
82124d60 1472 * Request stacking drivers like request-based dm may change the queue
bf4e6b4e
HR
1473 * limits when retrying requests on other queues. Those requests need
1474 * to be checked against the new queue limits again during dispatch.
82124d60 1475 */
bf4e6b4e
HR
1476static int blk_cloned_rq_check_limits(struct request_queue *q,
1477 struct request *rq)
82124d60 1478{
8fe0d473 1479 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) {
82124d60
KU
1480 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1481 return -EIO;
1482 }
1483
1484 /*
1485 * queue's settings related to segment counting like q->bounce_pfn
1486 * may differ from that of other stacking queues.
1487 * Recalculate it to check the request correctly on this queue's
1488 * limitation.
1489 */
1490 blk_recalc_rq_segments(rq);
8a78362c 1491 if (rq->nr_phys_segments > queue_max_segments(q)) {
82124d60
KU
1492 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1493 return -EIO;
1494 }
1495
1496 return 0;
1497}
82124d60
KU
1498
1499/**
1500 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1501 * @q: the queue to submit the request
1502 * @rq: the request being queued
1503 */
2a842aca 1504blk_status_t blk_insert_cloned_request(struct request_queue *q, struct request *rq)
82124d60 1505{
bf4e6b4e 1506 if (blk_cloned_rq_check_limits(q, rq))
2a842aca 1507 return BLK_STS_IOERR;
82124d60 1508
b2c9cd37
AM
1509 if (rq->rq_disk &&
1510 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2a842aca 1511 return BLK_STS_IOERR;
82124d60 1512
a1ce35fa
JA
1513 if (blk_queue_io_stat(q))
1514 blk_account_io_start(rq, true);
82124d60
KU
1515
1516 /*
a1ce35fa
JA
1517 * Since we have a scheduler attached on the top device,
1518 * bypass a potential scheduler on the bottom device for
1519 * insert.
82124d60 1520 */
a1ce35fa 1521 return blk_mq_request_issue_directly(rq);
82124d60
KU
1522}
1523EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1524
80a761fd
TH
1525/**
1526 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1527 * @rq: request to examine
1528 *
1529 * Description:
1530 * A request could be merge of IOs which require different failure
1531 * handling. This function determines the number of bytes which
1532 * can be failed from the beginning of the request without
1533 * crossing into area which need to be retried further.
1534 *
1535 * Return:
1536 * The number of bytes to fail.
80a761fd
TH
1537 */
1538unsigned int blk_rq_err_bytes(const struct request *rq)
1539{
1540 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
1541 unsigned int bytes = 0;
1542 struct bio *bio;
1543
e8064021 1544 if (!(rq->rq_flags & RQF_MIXED_MERGE))
80a761fd
TH
1545 return blk_rq_bytes(rq);
1546
1547 /*
1548 * Currently the only 'mixing' which can happen is between
1549 * different fastfail types. We can safely fail portions
1550 * which have all the failfast bits that the first one has -
1551 * the ones which are at least as eager to fail as the first
1552 * one.
1553 */
1554 for (bio = rq->bio; bio; bio = bio->bi_next) {
1eff9d32 1555 if ((bio->bi_opf & ff) != ff)
80a761fd 1556 break;
4f024f37 1557 bytes += bio->bi_iter.bi_size;
80a761fd
TH
1558 }
1559
1560 /* this could lead to infinite loop */
1561 BUG_ON(blk_rq_bytes(rq) && !bytes);
1562 return bytes;
1563}
1564EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
1565
320ae51f 1566void blk_account_io_completion(struct request *req, unsigned int bytes)
bc58ba94 1567{
c2553b58 1568 if (blk_do_io_stat(req)) {
ddcf35d3 1569 const int sgrp = op_stat_group(req_op(req));
bc58ba94
JA
1570 struct hd_struct *part;
1571 int cpu;
1572
1573 cpu = part_stat_lock();
09e099d4 1574 part = req->part;
ddcf35d3 1575 part_stat_add(cpu, part, sectors[sgrp], bytes >> 9);
bc58ba94
JA
1576 part_stat_unlock();
1577 }
1578}
1579
522a7775 1580void blk_account_io_done(struct request *req, u64 now)
bc58ba94 1581{
bc58ba94 1582 /*
dd4c133f
TH
1583 * Account IO completion. flush_rq isn't accounted as a
1584 * normal IO on queueing nor completion. Accounting the
1585 * containing request is enough.
bc58ba94 1586 */
e8064021 1587 if (blk_do_io_stat(req) && !(req->rq_flags & RQF_FLUSH_SEQ)) {
ddcf35d3 1588 const int sgrp = op_stat_group(req_op(req));
bc58ba94
JA
1589 struct hd_struct *part;
1590 int cpu;
1591
1592 cpu = part_stat_lock();
09e099d4 1593 part = req->part;
bc58ba94 1594
ddcf35d3 1595 part_stat_inc(cpu, part, ios[sgrp]);
b57e99b4 1596 part_stat_add(cpu, part, nsecs[sgrp], now - req->start_time_ns);
d62e26b3 1597 part_round_stats(req->q, cpu, part);
ddcf35d3 1598 part_dec_in_flight(req->q, part, rq_data_dir(req));
bc58ba94 1599
6c23a968 1600 hd_struct_put(part);
bc58ba94
JA
1601 part_stat_unlock();
1602 }
1603}
1604
320ae51f
JA
1605void blk_account_io_start(struct request *rq, bool new_io)
1606{
1607 struct hd_struct *part;
1608 int rw = rq_data_dir(rq);
1609 int cpu;
1610
1611 if (!blk_do_io_stat(rq))
1612 return;
1613
1614 cpu = part_stat_lock();
1615
1616 if (!new_io) {
1617 part = rq->part;
1618 part_stat_inc(cpu, part, merges[rw]);
1619 } else {
1620 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
1621 if (!hd_struct_try_get(part)) {
1622 /*
1623 * The partition is already being removed,
1624 * the request will be accounted on the disk only
1625 *
1626 * We take a reference on disk->part0 although that
1627 * partition will never be deleted, so we can treat
1628 * it as any other partition.
1629 */
1630 part = &rq->rq_disk->part0;
1631 hd_struct_get(part);
1632 }
d62e26b3
JA
1633 part_round_stats(rq->q, cpu, part);
1634 part_inc_in_flight(rq->q, part, rw);
320ae51f
JA
1635 rq->part = part;
1636 }
1637
1638 part_stat_unlock();
1639}
1640
ef71de8b
CH
1641/*
1642 * Steal bios from a request and add them to a bio list.
1643 * The request must not have been partially completed before.
1644 */
1645void blk_steal_bios(struct bio_list *list, struct request *rq)
1646{
1647 if (rq->bio) {
1648 if (list->tail)
1649 list->tail->bi_next = rq->bio;
1650 else
1651 list->head = rq->bio;
1652 list->tail = rq->biotail;
1653
1654 rq->bio = NULL;
1655 rq->biotail = NULL;
1656 }
1657
1658 rq->__data_len = 0;
1659}
1660EXPORT_SYMBOL_GPL(blk_steal_bios);
1661
3bcddeac 1662/**
2e60e022 1663 * blk_update_request - Special helper function for request stacking drivers
8ebf9756 1664 * @req: the request being processed
2a842aca 1665 * @error: block status code
8ebf9756 1666 * @nr_bytes: number of bytes to complete @req
3bcddeac
KU
1667 *
1668 * Description:
8ebf9756
RD
1669 * Ends I/O on a number of bytes attached to @req, but doesn't complete
1670 * the request structure even if @req doesn't have leftover.
1671 * If @req has leftover, sets it up for the next range of segments.
2e60e022
TH
1672 *
1673 * This special helper function is only for request stacking drivers
1674 * (e.g. request-based dm) so that they can handle partial completion.
1675 * Actual device drivers should use blk_end_request instead.
1676 *
1677 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
1678 * %false return from this function.
3bcddeac 1679 *
1954e9a9
BVA
1680 * Note:
1681 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in both
1682 * blk_rq_bytes() and in blk_update_request().
1683 *
3bcddeac 1684 * Return:
2e60e022
TH
1685 * %false - this request doesn't have any more data
1686 * %true - this request has more data
3bcddeac 1687 **/
2a842aca
CH
1688bool blk_update_request(struct request *req, blk_status_t error,
1689 unsigned int nr_bytes)
1da177e4 1690{
f79ea416 1691 int total_bytes;
1da177e4 1692
2a842aca 1693 trace_block_rq_complete(req, blk_status_to_errno(error), nr_bytes);
4a0efdc9 1694
2e60e022
TH
1695 if (!req->bio)
1696 return false;
1697
2a842aca
CH
1698 if (unlikely(error && !blk_rq_is_passthrough(req) &&
1699 !(req->rq_flags & RQF_QUIET)))
1700 print_req_error(req, error);
1da177e4 1701
bc58ba94 1702 blk_account_io_completion(req, nr_bytes);
d72d904a 1703
f79ea416
KO
1704 total_bytes = 0;
1705 while (req->bio) {
1706 struct bio *bio = req->bio;
4f024f37 1707 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
1da177e4 1708
9c24c10a 1709 if (bio_bytes == bio->bi_iter.bi_size)
1da177e4 1710 req->bio = bio->bi_next;
1da177e4 1711
fbbaf700
N
1712 /* Completion has already been traced */
1713 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
f79ea416 1714 req_bio_endio(req, bio, bio_bytes, error);
1da177e4 1715
f79ea416
KO
1716 total_bytes += bio_bytes;
1717 nr_bytes -= bio_bytes;
1da177e4 1718
f79ea416
KO
1719 if (!nr_bytes)
1720 break;
1da177e4
LT
1721 }
1722
1723 /*
1724 * completely done
1725 */
2e60e022
TH
1726 if (!req->bio) {
1727 /*
1728 * Reset counters so that the request stacking driver
1729 * can find how many bytes remain in the request
1730 * later.
1731 */
a2dec7b3 1732 req->__data_len = 0;
2e60e022
TH
1733 return false;
1734 }
1da177e4 1735
a2dec7b3 1736 req->__data_len -= total_bytes;
2e46e8b2
TH
1737
1738 /* update sector only for requests with clear definition of sector */
57292b58 1739 if (!blk_rq_is_passthrough(req))
a2dec7b3 1740 req->__sector += total_bytes >> 9;
2e46e8b2 1741
80a761fd 1742 /* mixed attributes always follow the first bio */
e8064021 1743 if (req->rq_flags & RQF_MIXED_MERGE) {
80a761fd 1744 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1eff9d32 1745 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
80a761fd
TH
1746 }
1747
ed6565e7
CH
1748 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1749 /*
1750 * If total number of sectors is less than the first segment
1751 * size, something has gone terribly wrong.
1752 */
1753 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1754 blk_dump_rq_flags(req, "request botched");
1755 req->__data_len = blk_rq_cur_bytes(req);
1756 }
2e46e8b2 1757
ed6565e7
CH
1758 /* recalculate the number of segments */
1759 blk_recalc_rq_segments(req);
1760 }
2e46e8b2 1761
2e60e022 1762 return true;
1da177e4 1763}
2e60e022 1764EXPORT_SYMBOL_GPL(blk_update_request);
1da177e4 1765
86db1e29
JA
1766void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
1767 struct bio *bio)
1da177e4 1768{
b4f42e28 1769 if (bio_has_data(bio))
fb2dce86 1770 rq->nr_phys_segments = bio_phys_segments(q, bio);
445251d0
JA
1771 else if (bio_op(bio) == REQ_OP_DISCARD)
1772 rq->nr_phys_segments = 1;
b4f42e28 1773
4f024f37 1774 rq->__data_len = bio->bi_iter.bi_size;
1da177e4 1775 rq->bio = rq->biotail = bio;
1da177e4 1776
74d46992
CH
1777 if (bio->bi_disk)
1778 rq->rq_disk = bio->bi_disk;
66846572 1779}
1da177e4 1780
2d4dc890
IL
1781#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
1782/**
1783 * rq_flush_dcache_pages - Helper function to flush all pages in a request
1784 * @rq: the request to be flushed
1785 *
1786 * Description:
1787 * Flush all pages in @rq.
1788 */
1789void rq_flush_dcache_pages(struct request *rq)
1790{
1791 struct req_iterator iter;
7988613b 1792 struct bio_vec bvec;
2d4dc890
IL
1793
1794 rq_for_each_segment(bvec, rq, iter)
7988613b 1795 flush_dcache_page(bvec.bv_page);
2d4dc890
IL
1796}
1797EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
1798#endif
1799
ef9e3fac
KU
1800/**
1801 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
1802 * @q : the queue of the device being checked
1803 *
1804 * Description:
1805 * Check if underlying low-level drivers of a device are busy.
1806 * If the drivers want to export their busy state, they must set own
1807 * exporting function using blk_queue_lld_busy() first.
1808 *
1809 * Basically, this function is used only by request stacking drivers
1810 * to stop dispatching requests to underlying devices when underlying
1811 * devices are busy. This behavior helps more I/O merging on the queue
1812 * of the request stacking driver and prevents I/O throughput regression
1813 * on burst I/O load.
1814 *
1815 * Return:
1816 * 0 - Not busy (The request stacking driver should dispatch request)
1817 * 1 - Busy (The request stacking driver should stop dispatching request)
1818 */
1819int blk_lld_busy(struct request_queue *q)
1820{
9ba20527
JA
1821 if (q->mq_ops && q->mq_ops->busy)
1822 return q->mq_ops->busy(q);
ef9e3fac
KU
1823
1824 return 0;
1825}
1826EXPORT_SYMBOL_GPL(blk_lld_busy);
1827
78d8e58a
MS
1828/**
1829 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
1830 * @rq: the clone request to be cleaned up
1831 *
1832 * Description:
1833 * Free all bios in @rq for a cloned request.
1834 */
1835void blk_rq_unprep_clone(struct request *rq)
1836{
1837 struct bio *bio;
1838
1839 while ((bio = rq->bio) != NULL) {
1840 rq->bio = bio->bi_next;
1841
1842 bio_put(bio);
1843 }
1844}
1845EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
1846
1847/*
1848 * Copy attributes of the original request to the clone request.
1849 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
1850 */
1851static void __blk_rq_prep_clone(struct request *dst, struct request *src)
b0fd271d
KU
1852{
1853 dst->cpu = src->cpu;
b0fd271d
KU
1854 dst->__sector = blk_rq_pos(src);
1855 dst->__data_len = blk_rq_bytes(src);
297ba57d
BVA
1856 if (src->rq_flags & RQF_SPECIAL_PAYLOAD) {
1857 dst->rq_flags |= RQF_SPECIAL_PAYLOAD;
1858 dst->special_vec = src->special_vec;
1859 }
b0fd271d
KU
1860 dst->nr_phys_segments = src->nr_phys_segments;
1861 dst->ioprio = src->ioprio;
1862 dst->extra_len = src->extra_len;
78d8e58a
MS
1863}
1864
1865/**
1866 * blk_rq_prep_clone - Helper function to setup clone request
1867 * @rq: the request to be setup
1868 * @rq_src: original request to be cloned
1869 * @bs: bio_set that bios for clone are allocated from
1870 * @gfp_mask: memory allocation mask for bio
1871 * @bio_ctr: setup function to be called for each clone bio.
1872 * Returns %0 for success, non %0 for failure.
1873 * @data: private data to be passed to @bio_ctr
1874 *
1875 * Description:
1876 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
1877 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
1878 * are not copied, and copying such parts is the caller's responsibility.
1879 * Also, pages which the original bios are pointing to are not copied
1880 * and the cloned bios just point same pages.
1881 * So cloned bios must be completed before original bios, which means
1882 * the caller must complete @rq before @rq_src.
1883 */
1884int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
1885 struct bio_set *bs, gfp_t gfp_mask,
1886 int (*bio_ctr)(struct bio *, struct bio *, void *),
1887 void *data)
1888{
1889 struct bio *bio, *bio_src;
1890
1891 if (!bs)
f4f8154a 1892 bs = &fs_bio_set;
78d8e58a
MS
1893
1894 __rq_for_each_bio(bio_src, rq_src) {
1895 bio = bio_clone_fast(bio_src, gfp_mask, bs);
1896 if (!bio)
1897 goto free_and_out;
1898
1899 if (bio_ctr && bio_ctr(bio, bio_src, data))
1900 goto free_and_out;
1901
1902 if (rq->bio) {
1903 rq->biotail->bi_next = bio;
1904 rq->biotail = bio;
1905 } else
1906 rq->bio = rq->biotail = bio;
1907 }
1908
1909 __blk_rq_prep_clone(rq, rq_src);
1910
1911 return 0;
1912
1913free_and_out:
1914 if (bio)
1915 bio_put(bio);
1916 blk_rq_unprep_clone(rq);
1917
1918 return -ENOMEM;
b0fd271d
KU
1919}
1920EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
1921
59c3d45e 1922int kblockd_schedule_work(struct work_struct *work)
1da177e4
LT
1923{
1924 return queue_work(kblockd_workqueue, work);
1925}
1da177e4
LT
1926EXPORT_SYMBOL(kblockd_schedule_work);
1927
ee63cfa7
JA
1928int kblockd_schedule_work_on(int cpu, struct work_struct *work)
1929{
1930 return queue_work_on(cpu, kblockd_workqueue, work);
1931}
1932EXPORT_SYMBOL(kblockd_schedule_work_on);
1933
818cd1cb
JA
1934int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
1935 unsigned long delay)
1936{
1937 return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
1938}
1939EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
1940
75df7136
SJ
1941/**
1942 * blk_start_plug - initialize blk_plug and track it inside the task_struct
1943 * @plug: The &struct blk_plug that needs to be initialized
1944 *
1945 * Description:
1946 * Tracking blk_plug inside the task_struct will help with auto-flushing the
1947 * pending I/O should the task end up blocking between blk_start_plug() and
1948 * blk_finish_plug(). This is important from a performance perspective, but
1949 * also ensures that we don't deadlock. For instance, if the task is blocking
1950 * for a memory allocation, memory reclaim could end up wanting to free a
1951 * page belonging to that request that is currently residing in our private
1952 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
1953 * this kind of deadlock.
1954 */
73c10101
JA
1955void blk_start_plug(struct blk_plug *plug)
1956{
1957 struct task_struct *tsk = current;
1958
dd6cf3e1
SL
1959 /*
1960 * If this is a nested plug, don't actually assign it.
1961 */
1962 if (tsk->plug)
1963 return;
1964
320ae51f 1965 INIT_LIST_HEAD(&plug->mq_list);
048c9374 1966 INIT_LIST_HEAD(&plug->cb_list);
73c10101 1967 /*
dd6cf3e1
SL
1968 * Store ordering should not be needed here, since a potential
1969 * preempt will imply a full memory barrier
73c10101 1970 */
dd6cf3e1 1971 tsk->plug = plug;
73c10101
JA
1972}
1973EXPORT_SYMBOL(blk_start_plug);
1974
74018dc3 1975static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
048c9374
N
1976{
1977 LIST_HEAD(callbacks);
1978
2a7d5559
SL
1979 while (!list_empty(&plug->cb_list)) {
1980 list_splice_init(&plug->cb_list, &callbacks);
048c9374 1981
2a7d5559
SL
1982 while (!list_empty(&callbacks)) {
1983 struct blk_plug_cb *cb = list_first_entry(&callbacks,
048c9374
N
1984 struct blk_plug_cb,
1985 list);
2a7d5559 1986 list_del(&cb->list);
74018dc3 1987 cb->callback(cb, from_schedule);
2a7d5559 1988 }
048c9374
N
1989 }
1990}
1991
9cbb1750
N
1992struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
1993 int size)
1994{
1995 struct blk_plug *plug = current->plug;
1996 struct blk_plug_cb *cb;
1997
1998 if (!plug)
1999 return NULL;
2000
2001 list_for_each_entry(cb, &plug->cb_list, list)
2002 if (cb->callback == unplug && cb->data == data)
2003 return cb;
2004
2005 /* Not currently on the callback list */
2006 BUG_ON(size < sizeof(*cb));
2007 cb = kzalloc(size, GFP_ATOMIC);
2008 if (cb) {
2009 cb->data = data;
2010 cb->callback = unplug;
2011 list_add(&cb->list, &plug->cb_list);
2012 }
2013 return cb;
2014}
2015EXPORT_SYMBOL(blk_check_plugged);
2016
49cac01e 2017void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
73c10101 2018{
74018dc3 2019 flush_plug_callbacks(plug, from_schedule);
320ae51f
JA
2020
2021 if (!list_empty(&plug->mq_list))
2022 blk_mq_flush_plug_list(plug, from_schedule);
73c10101 2023}
73c10101
JA
2024
2025void blk_finish_plug(struct blk_plug *plug)
2026{
dd6cf3e1
SL
2027 if (plug != current->plug)
2028 return;
f6603783 2029 blk_flush_plug_list(plug, false);
73c10101 2030
dd6cf3e1 2031 current->plug = NULL;
73c10101 2032}
88b996cd 2033EXPORT_SYMBOL(blk_finish_plug);
73c10101 2034
1da177e4
LT
2035int __init blk_dev_init(void)
2036{
ef295ecf
CH
2037 BUILD_BUG_ON(REQ_OP_LAST >= (1 << REQ_OP_BITS));
2038 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
0762b23d 2039 FIELD_SIZEOF(struct request, cmd_flags));
ef295ecf
CH
2040 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
2041 FIELD_SIZEOF(struct bio, bi_opf));
9eb55b03 2042
89b90be2
TH
2043 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
2044 kblockd_workqueue = alloc_workqueue("kblockd",
28747fcd 2045 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1da177e4
LT
2046 if (!kblockd_workqueue)
2047 panic("Failed to create kblockd\n");
2048
2049 request_cachep = kmem_cache_create("blkdev_requests",
20c2df83 2050 sizeof(struct request), 0, SLAB_PANIC, NULL);
1da177e4 2051
c2789bd4 2052 blk_requestq_cachep = kmem_cache_create("request_queue",
165125e1 2053 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1da177e4 2054
18fbda91
OS
2055#ifdef CONFIG_DEBUG_FS
2056 blk_debugfs_root = debugfs_create_dir("block", NULL);
2057#endif
2058
d38ecf93 2059 return 0;
1da177e4 2060}