block: Rename BLKDEV_MAX_RQ -> BLKDEV_DEFAULT_RQ
[linux-block.git] / block / blk-mq.c
CommitLineData
3dcf60bc 1// SPDX-License-Identifier: GPL-2.0
75bb4625
JA
2/*
3 * Block multiqueue core code
4 *
5 * Copyright (C) 2013-2014 Jens Axboe
6 * Copyright (C) 2013-2014 Christoph Hellwig
7 */
320ae51f
JA
8#include <linux/kernel.h>
9#include <linux/module.h>
10#include <linux/backing-dev.h>
11#include <linux/bio.h>
12#include <linux/blkdev.h>
fe45e630 13#include <linux/blk-integrity.h>
f75782e4 14#include <linux/kmemleak.h>
320ae51f
JA
15#include <linux/mm.h>
16#include <linux/init.h>
17#include <linux/slab.h>
18#include <linux/workqueue.h>
19#include <linux/smp.h>
e41d12f5 20#include <linux/interrupt.h>
320ae51f
JA
21#include <linux/llist.h>
22#include <linux/list_sort.h>
23#include <linux/cpu.h>
24#include <linux/cache.h>
25#include <linux/sched/sysctl.h>
105ab3d8 26#include <linux/sched/topology.h>
174cd4b1 27#include <linux/sched/signal.h>
320ae51f 28#include <linux/delay.h>
aedcd72f 29#include <linux/crash_dump.h>
88c7b2b7 30#include <linux/prefetch.h>
a892c8d5 31#include <linux/blk-crypto.h>
320ae51f
JA
32
33#include <trace/events/block.h>
34
35#include <linux/blk-mq.h>
54d4e6ab 36#include <linux/t10-pi.h>
320ae51f
JA
37#include "blk.h"
38#include "blk-mq.h"
9c1051aa 39#include "blk-mq-debugfs.h"
320ae51f 40#include "blk-mq-tag.h"
986d413b 41#include "blk-pm.h"
cf43e6be 42#include "blk-stat.h"
bd166ef1 43#include "blk-mq-sched.h"
c1c80384 44#include "blk-rq-qos.h"
320ae51f 45
f9ab4918 46static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
c3077b5d 47
34dbad5d
OS
48static void blk_mq_poll_stats_start(struct request_queue *q);
49static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
50
720b8ccc
SB
51static int blk_mq_poll_stats_bkt(const struct request *rq)
52{
3d244306 53 int ddir, sectors, bucket;
720b8ccc 54
99c749a4 55 ddir = rq_data_dir(rq);
3d244306 56 sectors = blk_rq_stats_sectors(rq);
720b8ccc 57
3d244306 58 bucket = ddir + 2 * ilog2(sectors);
720b8ccc
SB
59
60 if (bucket < 0)
61 return -1;
62 else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
63 return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
64
65 return bucket;
66}
67
320ae51f 68/*
85fae294
YY
69 * Check if any of the ctx, dispatch list or elevator
70 * have pending work in this hardware queue.
320ae51f 71 */
79f720a7 72static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
320ae51f 73{
79f720a7
JA
74 return !list_empty_careful(&hctx->dispatch) ||
75 sbitmap_any_bit_set(&hctx->ctx_map) ||
bd166ef1 76 blk_mq_sched_has_work(hctx);
1429d7c9
JA
77}
78
320ae51f
JA
79/*
80 * Mark this ctx as having pending work in this hardware queue
81 */
82static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
83 struct blk_mq_ctx *ctx)
84{
f31967f0
JA
85 const int bit = ctx->index_hw[hctx->type];
86
87 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
88 sbitmap_set_bit(&hctx->ctx_map, bit);
1429d7c9
JA
89}
90
91static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
92 struct blk_mq_ctx *ctx)
93{
f31967f0
JA
94 const int bit = ctx->index_hw[hctx->type];
95
96 sbitmap_clear_bit(&hctx->ctx_map, bit);
320ae51f
JA
97}
98
f299b7c7 99struct mq_inflight {
8446fe92 100 struct block_device *part;
a2e80f6f 101 unsigned int inflight[2];
f299b7c7
JA
102};
103
7baa8572 104static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
f299b7c7
JA
105 struct request *rq, void *priv,
106 bool reserved)
107{
108 struct mq_inflight *mi = priv;
109
b0d97557
JX
110 if ((!mi->part->bd_partno || rq->part == mi->part) &&
111 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
bb4e6b14 112 mi->inflight[rq_data_dir(rq)]++;
7baa8572
JA
113
114 return true;
f299b7c7
JA
115}
116
8446fe92
CH
117unsigned int blk_mq_in_flight(struct request_queue *q,
118 struct block_device *part)
f299b7c7 119{
a2e80f6f 120 struct mq_inflight mi = { .part = part };
f299b7c7 121
f299b7c7 122 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
e016b782 123
a2e80f6f 124 return mi.inflight[0] + mi.inflight[1];
bf0ddaba
OS
125}
126
8446fe92
CH
127void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
128 unsigned int inflight[2])
bf0ddaba 129{
a2e80f6f 130 struct mq_inflight mi = { .part = part };
bf0ddaba 131
bb4e6b14 132 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
a2e80f6f
PB
133 inflight[0] = mi.inflight[0];
134 inflight[1] = mi.inflight[1];
bf0ddaba
OS
135}
136
1671d522 137void blk_freeze_queue_start(struct request_queue *q)
43a5e4e2 138{
7996a8b5
BL
139 mutex_lock(&q->mq_freeze_lock);
140 if (++q->mq_freeze_depth == 1) {
3ef28e83 141 percpu_ref_kill(&q->q_usage_counter);
7996a8b5 142 mutex_unlock(&q->mq_freeze_lock);
344e9ffc 143 if (queue_is_mq(q))
055f6e18 144 blk_mq_run_hw_queues(q, false);
7996a8b5
BL
145 } else {
146 mutex_unlock(&q->mq_freeze_lock);
cddd5d17 147 }
f3af020b 148}
1671d522 149EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
f3af020b 150
6bae363e 151void blk_mq_freeze_queue_wait(struct request_queue *q)
f3af020b 152{
3ef28e83 153 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
43a5e4e2 154}
6bae363e 155EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
43a5e4e2 156
f91328c4
KB
157int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
158 unsigned long timeout)
159{
160 return wait_event_timeout(q->mq_freeze_wq,
161 percpu_ref_is_zero(&q->q_usage_counter),
162 timeout);
163}
164EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
43a5e4e2 165
f3af020b
TH
166/*
167 * Guarantee no request is in use, so we can change any data structure of
168 * the queue afterward.
169 */
3ef28e83 170void blk_freeze_queue(struct request_queue *q)
f3af020b 171{
3ef28e83
DW
172 /*
173 * In the !blk_mq case we are only calling this to kill the
174 * q_usage_counter, otherwise this increases the freeze depth
175 * and waits for it to return to zero. For this reason there is
176 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
177 * exported to drivers as the only user for unfreeze is blk_mq.
178 */
1671d522 179 blk_freeze_queue_start(q);
f3af020b
TH
180 blk_mq_freeze_queue_wait(q);
181}
3ef28e83
DW
182
183void blk_mq_freeze_queue(struct request_queue *q)
184{
185 /*
186 * ...just an alias to keep freeze and unfreeze actions balanced
187 * in the blk_mq_* namespace
188 */
189 blk_freeze_queue(q);
190}
c761d96b 191EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
f3af020b 192
aec89dc5 193void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
320ae51f 194{
7996a8b5 195 mutex_lock(&q->mq_freeze_lock);
aec89dc5
CH
196 if (force_atomic)
197 q->q_usage_counter.data->force_atomic = true;
7996a8b5
BL
198 q->mq_freeze_depth--;
199 WARN_ON_ONCE(q->mq_freeze_depth < 0);
200 if (!q->mq_freeze_depth) {
bdd63160 201 percpu_ref_resurrect(&q->q_usage_counter);
320ae51f 202 wake_up_all(&q->mq_freeze_wq);
add703fd 203 }
7996a8b5 204 mutex_unlock(&q->mq_freeze_lock);
320ae51f 205}
aec89dc5
CH
206
207void blk_mq_unfreeze_queue(struct request_queue *q)
208{
209 __blk_mq_unfreeze_queue(q, false);
210}
b4c6a028 211EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
320ae51f 212
852ec809
BVA
213/*
214 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
215 * mpt3sas driver such that this function can be removed.
216 */
217void blk_mq_quiesce_queue_nowait(struct request_queue *q)
218{
8814ce8a 219 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
852ec809
BVA
220}
221EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
222
6a83e74d 223/**
69e07c4a 224 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
6a83e74d
BVA
225 * @q: request queue.
226 *
227 * Note: this function does not prevent that the struct request end_io()
69e07c4a
ML
228 * callback function is invoked. Once this function is returned, we make
229 * sure no dispatch can happen until the queue is unquiesced via
230 * blk_mq_unquiesce_queue().
6a83e74d
BVA
231 */
232void blk_mq_quiesce_queue(struct request_queue *q)
233{
234 struct blk_mq_hw_ctx *hctx;
235 unsigned int i;
236 bool rcu = false;
237
1d9e9bc6 238 blk_mq_quiesce_queue_nowait(q);
f4560ffe 239
6a83e74d
BVA
240 queue_for_each_hw_ctx(q, hctx, i) {
241 if (hctx->flags & BLK_MQ_F_BLOCKING)
05707b64 242 synchronize_srcu(hctx->srcu);
6a83e74d
BVA
243 else
244 rcu = true;
245 }
246 if (rcu)
247 synchronize_rcu();
248}
249EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
250
e4e73913
ML
251/*
252 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
253 * @q: request queue.
254 *
255 * This function recovers queue into the state before quiescing
256 * which is done by blk_mq_quiesce_queue.
257 */
258void blk_mq_unquiesce_queue(struct request_queue *q)
259{
8814ce8a 260 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
f4560ffe 261
1d9e9bc6
ML
262 /* dispatch requests which are inserted during quiescing */
263 blk_mq_run_hw_queues(q, true);
e4e73913
ML
264}
265EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
266
aed3ea94
JA
267void blk_mq_wake_waiters(struct request_queue *q)
268{
269 struct blk_mq_hw_ctx *hctx;
270 unsigned int i;
271
272 queue_for_each_hw_ctx(q, hctx, i)
273 if (blk_mq_hw_queue_mapped(hctx))
274 blk_mq_tag_wakeup_all(hctx->tags, true);
275}
276
fe1f4526 277/*
9a91b05b
HT
278 * Only need start/end time stamping if we have iostat or
279 * blk stats enabled, or using an IO scheduler.
fe1f4526
JA
280 */
281static inline bool blk_mq_need_time_stamp(struct request *rq)
282{
9a91b05b 283 return (rq->rq_flags & (RQF_IO_STAT | RQF_STATS)) || rq->q->elevator;
fe1f4526
JA
284}
285
e4cdf1a1 286static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
7ea4d8a4 287 unsigned int tag, u64 alloc_time_ns)
320ae51f 288{
e4cdf1a1
CH
289 struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
290 struct request *rq = tags->static_rqs[tag];
c3a148d2 291
42fdc5e4 292 if (data->q->elevator) {
76647368 293 rq->tag = BLK_MQ_NO_TAG;
e4cdf1a1
CH
294 rq->internal_tag = tag;
295 } else {
e4cdf1a1 296 rq->tag = tag;
76647368 297 rq->internal_tag = BLK_MQ_NO_TAG;
e4cdf1a1
CH
298 }
299
af76e555 300 /* csd/requeue_work/fifo_time is initialized before use */
e4cdf1a1
CH
301 rq->q = data->q;
302 rq->mq_ctx = data->ctx;
ea4f995e 303 rq->mq_hctx = data->hctx;
568f2700 304 rq->rq_flags = 0;
7ea4d8a4 305 rq->cmd_flags = data->cmd_flags;
0854bcdc
BVA
306 if (data->flags & BLK_MQ_REQ_PM)
307 rq->rq_flags |= RQF_PM;
e4cdf1a1 308 if (blk_queue_io_stat(data->q))
e8064021 309 rq->rq_flags |= RQF_IO_STAT;
7c3fb70f 310 INIT_LIST_HEAD(&rq->queuelist);
af76e555
CH
311 INIT_HLIST_NODE(&rq->hash);
312 RB_CLEAR_NODE(&rq->rb_node);
af76e555
CH
313 rq->rq_disk = NULL;
314 rq->part = NULL;
6f816b4b
TH
315#ifdef CONFIG_BLK_RQ_ALLOC_TIME
316 rq->alloc_time_ns = alloc_time_ns;
317#endif
fe1f4526
JA
318 if (blk_mq_need_time_stamp(rq))
319 rq->start_time_ns = ktime_get_ns();
320 else
321 rq->start_time_ns = 0;
544ccc8d 322 rq->io_start_time_ns = 0;
3d244306 323 rq->stats_sectors = 0;
af76e555
CH
324 rq->nr_phys_segments = 0;
325#if defined(CONFIG_BLK_DEV_INTEGRITY)
326 rq->nr_integrity_segments = 0;
327#endif
a892c8d5 328 blk_crypto_rq_set_defaults(rq);
af76e555 329 /* tag was already set */
079076b3 330 WRITE_ONCE(rq->deadline, 0);
af76e555 331
f6be4fb4
JA
332 rq->timeout = 0;
333
af76e555
CH
334 rq->end_io = NULL;
335 rq->end_io_data = NULL;
af76e555 336
7ea4d8a4 337 data->ctx->rq_dispatched[op_is_sync(data->cmd_flags)]++;
12f5b931 338 refcount_set(&rq->ref, 1);
7ea4d8a4
CH
339
340 if (!op_is_flush(data->cmd_flags)) {
341 struct elevator_queue *e = data->q->elevator;
342
343 rq->elv.icq = NULL;
344 if (e && e->type->ops.prepare_request) {
345 if (e->type->icq_cache)
346 blk_mq_sched_assign_ioc(rq);
347
348 e->type->ops.prepare_request(rq);
349 rq->rq_flags |= RQF_ELVPRIV;
350 }
351 }
352
353 data->hctx->queued++;
e4cdf1a1 354 return rq;
5dee8577
CH
355}
356
e6e7abff 357static struct request *__blk_mq_alloc_request(struct blk_mq_alloc_data *data)
d2c0d383 358{
e6e7abff 359 struct request_queue *q = data->q;
d2c0d383 360 struct elevator_queue *e = q->elevator;
6f816b4b 361 u64 alloc_time_ns = 0;
600c3b0c 362 unsigned int tag;
d2c0d383 363
6f816b4b
TH
364 /* alloc_time includes depth and tag waits */
365 if (blk_queue_rq_alloc_time(q))
366 alloc_time_ns = ktime_get_ns();
367
f9afca4d 368 if (data->cmd_flags & REQ_NOWAIT)
03a07c92 369 data->flags |= BLK_MQ_REQ_NOWAIT;
d2c0d383
CH
370
371 if (e) {
d2c0d383 372 /*
8d663f34 373 * Flush/passthrough requests are special and go directly to the
17a51199
JA
374 * dispatch list. Don't include reserved tags in the
375 * limiting, as it isn't useful.
d2c0d383 376 */
f9afca4d 377 if (!op_is_flush(data->cmd_flags) &&
8d663f34 378 !blk_op_is_passthrough(data->cmd_flags) &&
f9afca4d 379 e->type->ops.limit_depth &&
17a51199 380 !(data->flags & BLK_MQ_REQ_RESERVED))
f9afca4d 381 e->type->ops.limit_depth(data->cmd_flags, data);
d2c0d383
CH
382 }
383
bf0beec0 384retry:
600c3b0c
CH
385 data->ctx = blk_mq_get_ctx(q);
386 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
42fdc5e4 387 if (!e)
600c3b0c
CH
388 blk_mq_tag_busy(data->hctx);
389
bf0beec0
ML
390 /*
391 * Waiting allocations only fail because of an inactive hctx. In that
392 * case just retry the hctx assignment and tag allocation as CPU hotplug
393 * should have migrated us to an online CPU by now.
394 */
e4cdf1a1 395 tag = blk_mq_get_tag(data);
bf0beec0
ML
396 if (tag == BLK_MQ_NO_TAG) {
397 if (data->flags & BLK_MQ_REQ_NOWAIT)
398 return NULL;
399
400 /*
401 * Give up the CPU and sleep for a random short time to ensure
402 * that thread using a realtime scheduling class are migrated
70f15a4f 403 * off the CPU, and thus off the hctx that is going away.
bf0beec0
ML
404 */
405 msleep(3);
406 goto retry;
407 }
7ea4d8a4 408 return blk_mq_rq_ctx_init(data, tag, alloc_time_ns);
d2c0d383
CH
409}
410
cd6ce148 411struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
9a95e4ef 412 blk_mq_req_flags_t flags)
320ae51f 413{
e6e7abff
CH
414 struct blk_mq_alloc_data data = {
415 .q = q,
416 .flags = flags,
417 .cmd_flags = op,
418 };
bd166ef1 419 struct request *rq;
a492f075 420 int ret;
320ae51f 421
3a0a5299 422 ret = blk_queue_enter(q, flags);
a492f075
JL
423 if (ret)
424 return ERR_PTR(ret);
320ae51f 425
e6e7abff 426 rq = __blk_mq_alloc_request(&data);
bd166ef1 427 if (!rq)
a5ea5811 428 goto out_queue_exit;
0c4de0f3
CH
429 rq->__data_len = 0;
430 rq->__sector = (sector_t) -1;
431 rq->bio = rq->biotail = NULL;
320ae51f 432 return rq;
a5ea5811
CH
433out_queue_exit:
434 blk_queue_exit(q);
435 return ERR_PTR(-EWOULDBLOCK);
320ae51f 436}
4bb659b1 437EXPORT_SYMBOL(blk_mq_alloc_request);
320ae51f 438
cd6ce148 439struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
9a95e4ef 440 unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
1f5bd336 441{
e6e7abff
CH
442 struct blk_mq_alloc_data data = {
443 .q = q,
444 .flags = flags,
445 .cmd_flags = op,
446 };
600c3b0c 447 u64 alloc_time_ns = 0;
6d2809d5 448 unsigned int cpu;
600c3b0c 449 unsigned int tag;
1f5bd336
ML
450 int ret;
451
600c3b0c
CH
452 /* alloc_time includes depth and tag waits */
453 if (blk_queue_rq_alloc_time(q))
454 alloc_time_ns = ktime_get_ns();
455
1f5bd336
ML
456 /*
457 * If the tag allocator sleeps we could get an allocation for a
458 * different hardware context. No need to complicate the low level
459 * allocator for this for the rare use case of a command tied to
460 * a specific queue.
461 */
600c3b0c 462 if (WARN_ON_ONCE(!(flags & (BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED))))
1f5bd336
ML
463 return ERR_PTR(-EINVAL);
464
465 if (hctx_idx >= q->nr_hw_queues)
466 return ERR_PTR(-EIO);
467
3a0a5299 468 ret = blk_queue_enter(q, flags);
1f5bd336
ML
469 if (ret)
470 return ERR_PTR(ret);
471
c8712c6a
CH
472 /*
473 * Check if the hardware context is actually mapped to anything.
474 * If not tell the caller that it should skip this queue.
475 */
a5ea5811 476 ret = -EXDEV;
e6e7abff
CH
477 data.hctx = q->queue_hw_ctx[hctx_idx];
478 if (!blk_mq_hw_queue_mapped(data.hctx))
a5ea5811 479 goto out_queue_exit;
e6e7abff
CH
480 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
481 data.ctx = __blk_mq_get_ctx(q, cpu);
1f5bd336 482
42fdc5e4 483 if (!q->elevator)
600c3b0c
CH
484 blk_mq_tag_busy(data.hctx);
485
a5ea5811 486 ret = -EWOULDBLOCK;
600c3b0c
CH
487 tag = blk_mq_get_tag(&data);
488 if (tag == BLK_MQ_NO_TAG)
a5ea5811 489 goto out_queue_exit;
600c3b0c
CH
490 return blk_mq_rq_ctx_init(&data, tag, alloc_time_ns);
491
a5ea5811
CH
492out_queue_exit:
493 blk_queue_exit(q);
494 return ERR_PTR(ret);
1f5bd336
ML
495}
496EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
497
12f5b931
KB
498static void __blk_mq_free_request(struct request *rq)
499{
500 struct request_queue *q = rq->q;
501 struct blk_mq_ctx *ctx = rq->mq_ctx;
ea4f995e 502 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
12f5b931
KB
503 const int sched_tag = rq->internal_tag;
504
a892c8d5 505 blk_crypto_free_request(rq);
986d413b 506 blk_pm_mark_last_busy(rq);
ea4f995e 507 rq->mq_hctx = NULL;
76647368 508 if (rq->tag != BLK_MQ_NO_TAG)
cae740a0 509 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
76647368 510 if (sched_tag != BLK_MQ_NO_TAG)
cae740a0 511 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
12f5b931
KB
512 blk_mq_sched_restart(hctx);
513 blk_queue_exit(q);
514}
515
6af54051 516void blk_mq_free_request(struct request *rq)
320ae51f 517{
320ae51f 518 struct request_queue *q = rq->q;
6af54051
CH
519 struct elevator_queue *e = q->elevator;
520 struct blk_mq_ctx *ctx = rq->mq_ctx;
ea4f995e 521 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
6af54051 522
5bbf4e5a 523 if (rq->rq_flags & RQF_ELVPRIV) {
f9cd4bfe
JA
524 if (e && e->type->ops.finish_request)
525 e->type->ops.finish_request(rq);
6af54051
CH
526 if (rq->elv.icq) {
527 put_io_context(rq->elv.icq->ioc);
528 rq->elv.icq = NULL;
529 }
530 }
320ae51f 531
6af54051 532 ctx->rq_completed[rq_is_sync(rq)]++;
e8064021 533 if (rq->rq_flags & RQF_MQ_INFLIGHT)
bccf5e26 534 __blk_mq_dec_active_requests(hctx);
87760e5e 535
7beb2f84 536 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
d152c682 537 laptop_io_completion(q->disk->bdi);
7beb2f84 538
a7905043 539 rq_qos_done(q, rq);
0d2602ca 540
12f5b931
KB
541 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
542 if (refcount_dec_and_test(&rq->ref))
543 __blk_mq_free_request(rq);
320ae51f 544}
1a3b595a 545EXPORT_SYMBOL_GPL(blk_mq_free_request);
320ae51f 546
2a842aca 547inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
320ae51f 548{
fe1f4526
JA
549 u64 now = 0;
550
551 if (blk_mq_need_time_stamp(rq))
552 now = ktime_get_ns();
522a7775 553
4bc6339a
OS
554 if (rq->rq_flags & RQF_STATS) {
555 blk_mq_poll_stats_start(rq->q);
522a7775 556 blk_stat_add(rq, now);
4bc6339a
OS
557 }
558
87890092 559 blk_mq_sched_completed_request(rq, now);
ed88660a 560
522a7775 561 blk_account_io_done(rq, now);
0d11e6ac 562
91b63639 563 if (rq->end_io) {
a7905043 564 rq_qos_done(rq->q, rq);
320ae51f 565 rq->end_io(rq, error);
91b63639 566 } else {
320ae51f 567 blk_mq_free_request(rq);
91b63639 568 }
320ae51f 569}
c8a446ad 570EXPORT_SYMBOL(__blk_mq_end_request);
63151a44 571
2a842aca 572void blk_mq_end_request(struct request *rq, blk_status_t error)
63151a44
CH
573{
574 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
575 BUG();
c8a446ad 576 __blk_mq_end_request(rq, error);
63151a44 577}
c8a446ad 578EXPORT_SYMBOL(blk_mq_end_request);
320ae51f 579
f9ab4918 580static void blk_complete_reqs(struct llist_head *list)
320ae51f 581{
f9ab4918
SAS
582 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
583 struct request *rq, *next;
c3077b5d 584
f9ab4918 585 llist_for_each_entry_safe(rq, next, entry, ipi_list)
c3077b5d 586 rq->q->mq_ops->complete(rq);
320ae51f 587}
320ae51f 588
f9ab4918 589static __latent_entropy void blk_done_softirq(struct softirq_action *h)
320ae51f 590{
f9ab4918 591 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
115243f5
CH
592}
593
c3077b5d
CH
594static int blk_softirq_cpu_dead(unsigned int cpu)
595{
f9ab4918 596 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
c3077b5d
CH
597 return 0;
598}
599
40d09b53 600static void __blk_mq_complete_request_remote(void *data)
c3077b5d 601{
f9ab4918 602 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
c3077b5d
CH
603}
604
96339526
CH
605static inline bool blk_mq_complete_need_ipi(struct request *rq)
606{
607 int cpu = raw_smp_processor_id();
608
609 if (!IS_ENABLED(CONFIG_SMP) ||
610 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
611 return false;
71425189
SAS
612 /*
613 * With force threaded interrupts enabled, raising softirq from an SMP
614 * function call will always result in waking the ksoftirqd thread.
615 * This is probably worse than completing the request on a different
616 * cache domain.
617 */
91cc470e 618 if (force_irqthreads())
71425189 619 return false;
96339526
CH
620
621 /* same CPU or cache domain? Complete locally */
622 if (cpu == rq->mq_ctx->cpu ||
623 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
624 cpus_share_cache(cpu, rq->mq_ctx->cpu)))
625 return false;
626
627 /* don't try to IPI to an offline CPU */
628 return cpu_online(rq->mq_ctx->cpu);
629}
630
f9ab4918
SAS
631static void blk_mq_complete_send_ipi(struct request *rq)
632{
633 struct llist_head *list;
634 unsigned int cpu;
635
636 cpu = rq->mq_ctx->cpu;
637 list = &per_cpu(blk_cpu_done, cpu);
638 if (llist_add(&rq->ipi_list, list)) {
639 INIT_CSD(&rq->csd, __blk_mq_complete_request_remote, rq);
640 smp_call_function_single_async(cpu, &rq->csd);
641 }
642}
643
644static void blk_mq_raise_softirq(struct request *rq)
645{
646 struct llist_head *list;
647
648 preempt_disable();
649 list = this_cpu_ptr(&blk_cpu_done);
650 if (llist_add(&rq->ipi_list, list))
651 raise_softirq(BLOCK_SOFTIRQ);
652 preempt_enable();
653}
654
40d09b53 655bool blk_mq_complete_request_remote(struct request *rq)
320ae51f 656{
af78ff7c 657 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
36e76539 658
4ab32bf3
JA
659 /*
660 * For a polled request, always complete locallly, it's pointless
661 * to redirect the completion.
662 */
40d09b53
CH
663 if (rq->cmd_flags & REQ_HIPRI)
664 return false;
38535201 665
96339526 666 if (blk_mq_complete_need_ipi(rq)) {
f9ab4918
SAS
667 blk_mq_complete_send_ipi(rq);
668 return true;
3d6efbf6 669 }
40d09b53 670
f9ab4918
SAS
671 if (rq->q->nr_hw_queues == 1) {
672 blk_mq_raise_softirq(rq);
673 return true;
674 }
675 return false;
40d09b53
CH
676}
677EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
678
679/**
680 * blk_mq_complete_request - end I/O on a request
681 * @rq: the request being processed
682 *
683 * Description:
684 * Complete a request by scheduling the ->complete_rq operation.
685 **/
686void blk_mq_complete_request(struct request *rq)
687{
688 if (!blk_mq_complete_request_remote(rq))
689 rq->q->mq_ops->complete(rq);
320ae51f 690}
15f73f5b 691EXPORT_SYMBOL(blk_mq_complete_request);
30a91cb4 692
04ced159 693static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
b7435db8 694 __releases(hctx->srcu)
04ced159
JA
695{
696 if (!(hctx->flags & BLK_MQ_F_BLOCKING))
697 rcu_read_unlock();
698 else
05707b64 699 srcu_read_unlock(hctx->srcu, srcu_idx);
04ced159
JA
700}
701
702static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
b7435db8 703 __acquires(hctx->srcu)
04ced159 704{
08b5a6e2
JA
705 if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
706 /* shut up gcc false positive */
707 *srcu_idx = 0;
04ced159 708 rcu_read_lock();
08b5a6e2 709 } else
05707b64 710 *srcu_idx = srcu_read_lock(hctx->srcu);
04ced159
JA
711}
712
105663f7
AA
713/**
714 * blk_mq_start_request - Start processing a request
715 * @rq: Pointer to request to be started
716 *
717 * Function used by device drivers to notify the block layer that a request
718 * is going to be processed now, so blk layer can do proper initializations
719 * such as starting the timeout timer.
720 */
e2490073 721void blk_mq_start_request(struct request *rq)
320ae51f
JA
722{
723 struct request_queue *q = rq->q;
724
a54895fa 725 trace_block_rq_issue(rq);
320ae51f 726
cf43e6be 727 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
544ccc8d 728 rq->io_start_time_ns = ktime_get_ns();
3d244306 729 rq->stats_sectors = blk_rq_sectors(rq);
cf43e6be 730 rq->rq_flags |= RQF_STATS;
a7905043 731 rq_qos_issue(q, rq);
cf43e6be
JA
732 }
733
1d9bd516 734 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
538b7534 735
1d9bd516 736 blk_add_timer(rq);
12f5b931 737 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
49f5baa5 738
54d4e6ab
MG
739#ifdef CONFIG_BLK_DEV_INTEGRITY
740 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
741 q->integrity.profile->prepare_fn(rq);
742#endif
320ae51f 743}
e2490073 744EXPORT_SYMBOL(blk_mq_start_request);
320ae51f 745
ed0791b2 746static void __blk_mq_requeue_request(struct request *rq)
320ae51f
JA
747{
748 struct request_queue *q = rq->q;
749
923218f6
ML
750 blk_mq_put_driver_tag(rq);
751
a54895fa 752 trace_block_rq_requeue(rq);
a7905043 753 rq_qos_requeue(q, rq);
49f5baa5 754
12f5b931
KB
755 if (blk_mq_request_started(rq)) {
756 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
da661267 757 rq->rq_flags &= ~RQF_TIMED_OUT;
e2490073 758 }
320ae51f
JA
759}
760
2b053aca 761void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
ed0791b2 762{
ed0791b2 763 __blk_mq_requeue_request(rq);
ed0791b2 764
105976f5
ML
765 /* this request will be re-inserted to io scheduler queue */
766 blk_mq_sched_requeue_request(rq);
767
7d692330 768 BUG_ON(!list_empty(&rq->queuelist));
2b053aca 769 blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
ed0791b2
CH
770}
771EXPORT_SYMBOL(blk_mq_requeue_request);
772
6fca6a61
CH
773static void blk_mq_requeue_work(struct work_struct *work)
774{
775 struct request_queue *q =
2849450a 776 container_of(work, struct request_queue, requeue_work.work);
6fca6a61
CH
777 LIST_HEAD(rq_list);
778 struct request *rq, *next;
6fca6a61 779
18e9781d 780 spin_lock_irq(&q->requeue_lock);
6fca6a61 781 list_splice_init(&q->requeue_list, &rq_list);
18e9781d 782 spin_unlock_irq(&q->requeue_lock);
6fca6a61
CH
783
784 list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
aef1897c 785 if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
6fca6a61
CH
786 continue;
787
e8064021 788 rq->rq_flags &= ~RQF_SOFTBARRIER;
6fca6a61 789 list_del_init(&rq->queuelist);
aef1897c
JW
790 /*
791 * If RQF_DONTPREP, rq has contained some driver specific
792 * data, so insert it to hctx dispatch list to avoid any
793 * merge.
794 */
795 if (rq->rq_flags & RQF_DONTPREP)
01e99aec 796 blk_mq_request_bypass_insert(rq, false, false);
aef1897c
JW
797 else
798 blk_mq_sched_insert_request(rq, true, false, false);
6fca6a61
CH
799 }
800
801 while (!list_empty(&rq_list)) {
802 rq = list_entry(rq_list.next, struct request, queuelist);
803 list_del_init(&rq->queuelist);
9e97d295 804 blk_mq_sched_insert_request(rq, false, false, false);
6fca6a61
CH
805 }
806
52d7f1b5 807 blk_mq_run_hw_queues(q, false);
6fca6a61
CH
808}
809
2b053aca
BVA
810void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
811 bool kick_requeue_list)
6fca6a61
CH
812{
813 struct request_queue *q = rq->q;
814 unsigned long flags;
815
816 /*
817 * We abuse this flag that is otherwise used by the I/O scheduler to
ff821d27 818 * request head insertion from the workqueue.
6fca6a61 819 */
e8064021 820 BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
6fca6a61
CH
821
822 spin_lock_irqsave(&q->requeue_lock, flags);
823 if (at_head) {
e8064021 824 rq->rq_flags |= RQF_SOFTBARRIER;
6fca6a61
CH
825 list_add(&rq->queuelist, &q->requeue_list);
826 } else {
827 list_add_tail(&rq->queuelist, &q->requeue_list);
828 }
829 spin_unlock_irqrestore(&q->requeue_lock, flags);
2b053aca
BVA
830
831 if (kick_requeue_list)
832 blk_mq_kick_requeue_list(q);
6fca6a61 833}
6fca6a61
CH
834
835void blk_mq_kick_requeue_list(struct request_queue *q)
836{
ae943d20 837 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
6fca6a61
CH
838}
839EXPORT_SYMBOL(blk_mq_kick_requeue_list);
840
2849450a
MS
841void blk_mq_delay_kick_requeue_list(struct request_queue *q,
842 unsigned long msecs)
843{
d4acf365
BVA
844 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
845 msecs_to_jiffies(msecs));
2849450a
MS
846}
847EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
848
0e62f51f
JA
849struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
850{
88c7b2b7
JA
851 if (tag < tags->nr_tags) {
852 prefetch(tags->rqs[tag]);
4ee86bab 853 return tags->rqs[tag];
88c7b2b7 854 }
4ee86bab
HR
855
856 return NULL;
24d2f903
CH
857}
858EXPORT_SYMBOL(blk_mq_tag_to_rq);
859
3c94d83c
JA
860static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
861 void *priv, bool reserved)
ae879912
JA
862{
863 /*
05a4fed6 864 * If we find a request that isn't idle and the queue matches,
3c94d83c 865 * we know the queue is busy. Return false to stop the iteration.
ae879912 866 */
05a4fed6 867 if (blk_mq_request_started(rq) && rq->q == hctx->queue) {
ae879912
JA
868 bool *busy = priv;
869
870 *busy = true;
871 return false;
872 }
873
874 return true;
875}
876
3c94d83c 877bool blk_mq_queue_inflight(struct request_queue *q)
ae879912
JA
878{
879 bool busy = false;
880
3c94d83c 881 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
ae879912
JA
882 return busy;
883}
3c94d83c 884EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
ae879912 885
358f70da 886static void blk_mq_rq_timed_out(struct request *req, bool reserved)
320ae51f 887{
da661267 888 req->rq_flags |= RQF_TIMED_OUT;
d1210d5a
CH
889 if (req->q->mq_ops->timeout) {
890 enum blk_eh_timer_return ret;
891
892 ret = req->q->mq_ops->timeout(req, reserved);
893 if (ret == BLK_EH_DONE)
894 return;
895 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
46f92d42 896 }
d1210d5a
CH
897
898 blk_add_timer(req);
87ee7b11 899}
5b3f25fc 900
12f5b931 901static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
81481eb4 902{
12f5b931 903 unsigned long deadline;
87ee7b11 904
12f5b931
KB
905 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
906 return false;
da661267
CH
907 if (rq->rq_flags & RQF_TIMED_OUT)
908 return false;
a7af0af3 909
079076b3 910 deadline = READ_ONCE(rq->deadline);
12f5b931
KB
911 if (time_after_eq(jiffies, deadline))
912 return true;
a7af0af3 913
12f5b931
KB
914 if (*next == 0)
915 *next = deadline;
916 else if (time_after(*next, deadline))
917 *next = deadline;
918 return false;
87ee7b11
JA
919}
920
2e315dc0
ML
921void blk_mq_put_rq_ref(struct request *rq)
922{
a9ed27a7 923 if (is_flush_rq(rq))
2e315dc0
ML
924 rq->end_io(rq, 0);
925 else if (refcount_dec_and_test(&rq->ref))
926 __blk_mq_free_request(rq);
927}
928
7baa8572 929static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
1d9bd516
TH
930 struct request *rq, void *priv, bool reserved)
931{
12f5b931
KB
932 unsigned long *next = priv;
933
934 /*
c797b40c
ML
935 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
936 * be reallocated underneath the timeout handler's processing, then
937 * the expire check is reliable. If the request is not expired, then
938 * it was completed and reallocated as a new request after returning
939 * from blk_mq_check_expired().
1d9bd516 940 */
12f5b931 941 if (blk_mq_req_expired(rq, next))
1d9bd516 942 blk_mq_rq_timed_out(rq, reserved);
7baa8572 943 return true;
1d9bd516
TH
944}
945
287922eb 946static void blk_mq_timeout_work(struct work_struct *work)
320ae51f 947{
287922eb
CH
948 struct request_queue *q =
949 container_of(work, struct request_queue, timeout_work);
12f5b931 950 unsigned long next = 0;
1d9bd516 951 struct blk_mq_hw_ctx *hctx;
81481eb4 952 int i;
320ae51f 953
71f79fb3
GKB
954 /* A deadlock might occur if a request is stuck requiring a
955 * timeout at the same time a queue freeze is waiting
956 * completion, since the timeout code would not be able to
957 * acquire the queue reference here.
958 *
959 * That's why we don't use blk_queue_enter here; instead, we use
960 * percpu_ref_tryget directly, because we need to be able to
961 * obtain a reference even in the short window between the queue
962 * starting to freeze, by dropping the first reference in
1671d522 963 * blk_freeze_queue_start, and the moment the last request is
71f79fb3
GKB
964 * consumed, marked by the instant q_usage_counter reaches
965 * zero.
966 */
967 if (!percpu_ref_tryget(&q->q_usage_counter))
287922eb
CH
968 return;
969
12f5b931 970 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
320ae51f 971
12f5b931
KB
972 if (next != 0) {
973 mod_timer(&q->timeout, next);
0d2602ca 974 } else {
fcd36c36
BVA
975 /*
976 * Request timeouts are handled as a forward rolling timer. If
977 * we end up here it means that no requests are pending and
978 * also that no request has been pending for a while. Mark
979 * each hctx as idle.
980 */
f054b56c
ML
981 queue_for_each_hw_ctx(q, hctx, i) {
982 /* the hctx may be unmapped, so check it here */
983 if (blk_mq_hw_queue_mapped(hctx))
984 blk_mq_tag_idle(hctx);
985 }
0d2602ca 986 }
287922eb 987 blk_queue_exit(q);
320ae51f
JA
988}
989
88459642
OS
990struct flush_busy_ctx_data {
991 struct blk_mq_hw_ctx *hctx;
992 struct list_head *list;
993};
994
995static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
996{
997 struct flush_busy_ctx_data *flush_data = data;
998 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
999 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
c16d6b5a 1000 enum hctx_type type = hctx->type;
88459642 1001
88459642 1002 spin_lock(&ctx->lock);
c16d6b5a 1003 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
e9a99a63 1004 sbitmap_clear_bit(sb, bitnr);
88459642
OS
1005 spin_unlock(&ctx->lock);
1006 return true;
1007}
1008
1429d7c9
JA
1009/*
1010 * Process software queues that have been marked busy, splicing them
1011 * to the for-dispatch
1012 */
2c3ad667 1013void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1429d7c9 1014{
88459642
OS
1015 struct flush_busy_ctx_data data = {
1016 .hctx = hctx,
1017 .list = list,
1018 };
1429d7c9 1019
88459642 1020 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1429d7c9 1021}
2c3ad667 1022EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1429d7c9 1023
b347689f
ML
1024struct dispatch_rq_data {
1025 struct blk_mq_hw_ctx *hctx;
1026 struct request *rq;
1027};
1028
1029static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1030 void *data)
1031{
1032 struct dispatch_rq_data *dispatch_data = data;
1033 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1034 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
c16d6b5a 1035 enum hctx_type type = hctx->type;
b347689f
ML
1036
1037 spin_lock(&ctx->lock);
c16d6b5a
ML
1038 if (!list_empty(&ctx->rq_lists[type])) {
1039 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
b347689f 1040 list_del_init(&dispatch_data->rq->queuelist);
c16d6b5a 1041 if (list_empty(&ctx->rq_lists[type]))
b347689f
ML
1042 sbitmap_clear_bit(sb, bitnr);
1043 }
1044 spin_unlock(&ctx->lock);
1045
1046 return !dispatch_data->rq;
1047}
1048
1049struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1050 struct blk_mq_ctx *start)
1051{
f31967f0 1052 unsigned off = start ? start->index_hw[hctx->type] : 0;
b347689f
ML
1053 struct dispatch_rq_data data = {
1054 .hctx = hctx,
1055 .rq = NULL,
1056 };
1057
1058 __sbitmap_for_each_set(&hctx->ctx_map, off,
1059 dispatch_rq_from_ctx, &data);
1060
1061 return data.rq;
1062}
1063
703fd1c0
JA
1064static inline unsigned int queued_to_index(unsigned int queued)
1065{
1066 if (!queued)
1067 return 0;
1429d7c9 1068
703fd1c0 1069 return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
1429d7c9
JA
1070}
1071
570e9b73
ML
1072static bool __blk_mq_get_driver_tag(struct request *rq)
1073{
222a5ae0 1074 struct sbitmap_queue *bt = rq->mq_hctx->tags->bitmap_tags;
570e9b73 1075 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
570e9b73
ML
1076 int tag;
1077
568f2700
ML
1078 blk_mq_tag_busy(rq->mq_hctx);
1079
570e9b73 1080 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
222a5ae0 1081 bt = rq->mq_hctx->tags->breserved_tags;
570e9b73 1082 tag_offset = 0;
28500850
ML
1083 } else {
1084 if (!hctx_may_queue(rq->mq_hctx, bt))
1085 return false;
570e9b73
ML
1086 }
1087
570e9b73
ML
1088 tag = __sbitmap_queue_get(bt);
1089 if (tag == BLK_MQ_NO_TAG)
1090 return false;
1091
1092 rq->tag = tag + tag_offset;
570e9b73
ML
1093 return true;
1094}
1095
61347154 1096bool blk_mq_get_driver_tag(struct request *rq)
570e9b73 1097{
568f2700
ML
1098 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1099
1100 if (rq->tag == BLK_MQ_NO_TAG && !__blk_mq_get_driver_tag(rq))
1101 return false;
1102
51db1c37 1103 if ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
568f2700
ML
1104 !(rq->rq_flags & RQF_MQ_INFLIGHT)) {
1105 rq->rq_flags |= RQF_MQ_INFLIGHT;
bccf5e26 1106 __blk_mq_inc_active_requests(hctx);
568f2700
ML
1107 }
1108 hctx->tags->rqs[rq->tag] = rq;
1109 return true;
570e9b73
ML
1110}
1111
eb619fdb
JA
1112static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1113 int flags, void *key)
da55f2cc
OS
1114{
1115 struct blk_mq_hw_ctx *hctx;
1116
1117 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1118
5815839b 1119 spin_lock(&hctx->dispatch_wait_lock);
e8618575
JA
1120 if (!list_empty(&wait->entry)) {
1121 struct sbitmap_queue *sbq;
1122
1123 list_del_init(&wait->entry);
222a5ae0 1124 sbq = hctx->tags->bitmap_tags;
e8618575
JA
1125 atomic_dec(&sbq->ws_active);
1126 }
5815839b
ML
1127 spin_unlock(&hctx->dispatch_wait_lock);
1128
da55f2cc
OS
1129 blk_mq_run_hw_queue(hctx, true);
1130 return 1;
1131}
1132
f906a6a0
JA
1133/*
1134 * Mark us waiting for a tag. For shared tags, this involves hooking us into
ee3e4de5
BVA
1135 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1136 * restart. For both cases, take care to check the condition again after
f906a6a0
JA
1137 * marking us as waiting.
1138 */
2278d69f 1139static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
f906a6a0 1140 struct request *rq)
da55f2cc 1141{
222a5ae0 1142 struct sbitmap_queue *sbq = hctx->tags->bitmap_tags;
5815839b 1143 struct wait_queue_head *wq;
f906a6a0
JA
1144 wait_queue_entry_t *wait;
1145 bool ret;
da55f2cc 1146
51db1c37 1147 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
684b7324 1148 blk_mq_sched_mark_restart_hctx(hctx);
f906a6a0 1149
c27d53fb
BVA
1150 /*
1151 * It's possible that a tag was freed in the window between the
1152 * allocation failure and adding the hardware queue to the wait
1153 * queue.
1154 *
1155 * Don't clear RESTART here, someone else could have set it.
1156 * At most this will cost an extra queue run.
1157 */
8ab6bb9e 1158 return blk_mq_get_driver_tag(rq);
eb619fdb 1159 }
eb619fdb 1160
2278d69f 1161 wait = &hctx->dispatch_wait;
c27d53fb
BVA
1162 if (!list_empty_careful(&wait->entry))
1163 return false;
1164
e8618575 1165 wq = &bt_wait_ptr(sbq, hctx)->wait;
5815839b
ML
1166
1167 spin_lock_irq(&wq->lock);
1168 spin_lock(&hctx->dispatch_wait_lock);
c27d53fb 1169 if (!list_empty(&wait->entry)) {
5815839b
ML
1170 spin_unlock(&hctx->dispatch_wait_lock);
1171 spin_unlock_irq(&wq->lock);
c27d53fb 1172 return false;
eb619fdb
JA
1173 }
1174
e8618575 1175 atomic_inc(&sbq->ws_active);
5815839b
ML
1176 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1177 __add_wait_queue(wq, wait);
c27d53fb 1178
da55f2cc 1179 /*
eb619fdb
JA
1180 * It's possible that a tag was freed in the window between the
1181 * allocation failure and adding the hardware queue to the wait
1182 * queue.
da55f2cc 1183 */
8ab6bb9e 1184 ret = blk_mq_get_driver_tag(rq);
c27d53fb 1185 if (!ret) {
5815839b
ML
1186 spin_unlock(&hctx->dispatch_wait_lock);
1187 spin_unlock_irq(&wq->lock);
c27d53fb 1188 return false;
eb619fdb 1189 }
c27d53fb
BVA
1190
1191 /*
1192 * We got a tag, remove ourselves from the wait queue to ensure
1193 * someone else gets the wakeup.
1194 */
c27d53fb 1195 list_del_init(&wait->entry);
e8618575 1196 atomic_dec(&sbq->ws_active);
5815839b
ML
1197 spin_unlock(&hctx->dispatch_wait_lock);
1198 spin_unlock_irq(&wq->lock);
c27d53fb
BVA
1199
1200 return true;
da55f2cc
OS
1201}
1202
6e768717
ML
1203#define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1204#define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1205/*
1206 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1207 * - EWMA is one simple way to compute running average value
1208 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1209 * - take 4 as factor for avoiding to get too small(0) result, and this
1210 * factor doesn't matter because EWMA decreases exponentially
1211 */
1212static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1213{
1214 unsigned int ewma;
1215
6e768717
ML
1216 ewma = hctx->dispatch_busy;
1217
1218 if (!ewma && !busy)
1219 return;
1220
1221 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1222 if (busy)
1223 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1224 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1225
1226 hctx->dispatch_busy = ewma;
1227}
1228
86ff7c2a
ML
1229#define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1230
c92a4103
JT
1231static void blk_mq_handle_dev_resource(struct request *rq,
1232 struct list_head *list)
1233{
1234 struct request *next =
1235 list_first_entry_or_null(list, struct request, queuelist);
1236
1237 /*
1238 * If an I/O scheduler has been configured and we got a driver tag for
1239 * the next request already, free it.
1240 */
1241 if (next)
1242 blk_mq_put_driver_tag(next);
1243
1244 list_add(&rq->queuelist, list);
1245 __blk_mq_requeue_request(rq);
1246}
1247
0512a75b
KB
1248static void blk_mq_handle_zone_resource(struct request *rq,
1249 struct list_head *zone_list)
1250{
1251 /*
1252 * If we end up here it is because we cannot dispatch a request to a
1253 * specific zone due to LLD level zone-write locking or other zone
1254 * related resource not being available. In this case, set the request
1255 * aside in zone_list for retrying it later.
1256 */
1257 list_add(&rq->queuelist, zone_list);
1258 __blk_mq_requeue_request(rq);
1259}
1260
75383524
ML
1261enum prep_dispatch {
1262 PREP_DISPATCH_OK,
1263 PREP_DISPATCH_NO_TAG,
1264 PREP_DISPATCH_NO_BUDGET,
1265};
1266
1267static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
1268 bool need_budget)
1269{
1270 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2a5a24aa 1271 int budget_token = -1;
75383524 1272
2a5a24aa
ML
1273 if (need_budget) {
1274 budget_token = blk_mq_get_dispatch_budget(rq->q);
1275 if (budget_token < 0) {
1276 blk_mq_put_driver_tag(rq);
1277 return PREP_DISPATCH_NO_BUDGET;
1278 }
1279 blk_mq_set_rq_budget_token(rq, budget_token);
75383524
ML
1280 }
1281
1282 if (!blk_mq_get_driver_tag(rq)) {
1283 /*
1284 * The initial allocation attempt failed, so we need to
1285 * rerun the hardware queue when a tag is freed. The
1286 * waitqueue takes care of that. If the queue is run
1287 * before we add this entry back on the dispatch list,
1288 * we'll re-run it below.
1289 */
1290 if (!blk_mq_mark_tag_wait(hctx, rq)) {
1fd40b5e
ML
1291 /*
1292 * All budgets not got from this function will be put
1293 * together during handling partial dispatch
1294 */
1295 if (need_budget)
2a5a24aa 1296 blk_mq_put_dispatch_budget(rq->q, budget_token);
75383524
ML
1297 return PREP_DISPATCH_NO_TAG;
1298 }
1299 }
1300
1301 return PREP_DISPATCH_OK;
1302}
1303
1fd40b5e
ML
1304/* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
1305static void blk_mq_release_budgets(struct request_queue *q,
2a5a24aa 1306 struct list_head *list)
1fd40b5e 1307{
2a5a24aa 1308 struct request *rq;
1fd40b5e 1309
2a5a24aa
ML
1310 list_for_each_entry(rq, list, queuelist) {
1311 int budget_token = blk_mq_get_rq_budget_token(rq);
1fd40b5e 1312
2a5a24aa
ML
1313 if (budget_token >= 0)
1314 blk_mq_put_dispatch_budget(q, budget_token);
1315 }
1fd40b5e
ML
1316}
1317
1f57f8d4
JA
1318/*
1319 * Returns true if we did some work AND can potentially do more.
1320 */
445874e8 1321bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
1fd40b5e 1322 unsigned int nr_budgets)
320ae51f 1323{
75383524 1324 enum prep_dispatch prep;
445874e8 1325 struct request_queue *q = hctx->queue;
6d6f167c 1326 struct request *rq, *nxt;
fc17b653 1327 int errors, queued;
86ff7c2a 1328 blk_status_t ret = BLK_STS_OK;
0512a75b 1329 LIST_HEAD(zone_list);
320ae51f 1330
81380ca1
OS
1331 if (list_empty(list))
1332 return false;
1333
320ae51f
JA
1334 /*
1335 * Now process all the entries, sending them to the driver.
1336 */
93efe981 1337 errors = queued = 0;
81380ca1 1338 do {
74c45052 1339 struct blk_mq_queue_data bd;
320ae51f 1340
f04c3df3 1341 rq = list_first_entry(list, struct request, queuelist);
0bca799b 1342
445874e8 1343 WARN_ON_ONCE(hctx != rq->mq_hctx);
1fd40b5e 1344 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
75383524 1345 if (prep != PREP_DISPATCH_OK)
0bca799b 1346 break;
de148297 1347
320ae51f 1348 list_del_init(&rq->queuelist);
320ae51f 1349
74c45052 1350 bd.rq = rq;
113285b4
JA
1351
1352 /*
1353 * Flag last if we have no more requests, or if we have more
1354 * but can't assign a driver tag to it.
1355 */
1356 if (list_empty(list))
1357 bd.last = true;
1358 else {
113285b4 1359 nxt = list_first_entry(list, struct request, queuelist);
8ab6bb9e 1360 bd.last = !blk_mq_get_driver_tag(nxt);
113285b4 1361 }
74c45052 1362
1fd40b5e
ML
1363 /*
1364 * once the request is queued to lld, no need to cover the
1365 * budget any more
1366 */
1367 if (nr_budgets)
1368 nr_budgets--;
74c45052 1369 ret = q->mq_ops->queue_rq(hctx, &bd);
7bf13729
ML
1370 switch (ret) {
1371 case BLK_STS_OK:
1372 queued++;
320ae51f 1373 break;
7bf13729
ML
1374 case BLK_STS_RESOURCE:
1375 case BLK_STS_DEV_RESOURCE:
1376 blk_mq_handle_dev_resource(rq, list);
1377 goto out;
1378 case BLK_STS_ZONE_RESOURCE:
0512a75b
KB
1379 /*
1380 * Move the request to zone_list and keep going through
1381 * the dispatch list to find more requests the drive can
1382 * accept.
1383 */
1384 blk_mq_handle_zone_resource(rq, &zone_list);
7bf13729
ML
1385 break;
1386 default:
93efe981 1387 errors++;
e21ee5a6 1388 blk_mq_end_request(rq, ret);
320ae51f 1389 }
81380ca1 1390 } while (!list_empty(list));
7bf13729 1391out:
0512a75b
KB
1392 if (!list_empty(&zone_list))
1393 list_splice_tail_init(&zone_list, list);
1394
703fd1c0 1395 hctx->dispatched[queued_to_index(queued)]++;
320ae51f 1396
632bfb63 1397 /* If we didn't flush the entire list, we could have told the driver
1398 * there was more coming, but that turned out to be a lie.
1399 */
1400 if ((!list_empty(list) || errors) && q->mq_ops->commit_rqs && queued)
1401 q->mq_ops->commit_rqs(hctx);
320ae51f
JA
1402 /*
1403 * Any items that need requeuing? Stuff them into hctx->dispatch,
1404 * that is where we will continue on next queue run.
1405 */
f04c3df3 1406 if (!list_empty(list)) {
86ff7c2a 1407 bool needs_restart;
75383524
ML
1408 /* For non-shared tags, the RESTART check will suffice */
1409 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
51db1c37 1410 (hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED);
75383524 1411 bool no_budget_avail = prep == PREP_DISPATCH_NO_BUDGET;
86ff7c2a 1412
2a5a24aa
ML
1413 if (nr_budgets)
1414 blk_mq_release_budgets(q, list);
86ff7c2a 1415
320ae51f 1416 spin_lock(&hctx->lock);
01e99aec 1417 list_splice_tail_init(list, &hctx->dispatch);
320ae51f 1418 spin_unlock(&hctx->lock);
f04c3df3 1419
d7d8535f
ML
1420 /*
1421 * Order adding requests to hctx->dispatch and checking
1422 * SCHED_RESTART flag. The pair of this smp_mb() is the one
1423 * in blk_mq_sched_restart(). Avoid restart code path to
1424 * miss the new added requests to hctx->dispatch, meantime
1425 * SCHED_RESTART is observed here.
1426 */
1427 smp_mb();
1428
9ba52e58 1429 /*
710c785f
BVA
1430 * If SCHED_RESTART was set by the caller of this function and
1431 * it is no longer set that means that it was cleared by another
1432 * thread and hence that a queue rerun is needed.
9ba52e58 1433 *
eb619fdb
JA
1434 * If 'no_tag' is set, that means that we failed getting
1435 * a driver tag with an I/O scheduler attached. If our dispatch
1436 * waitqueue is no longer active, ensure that we run the queue
1437 * AFTER adding our entries back to the list.
bd166ef1 1438 *
710c785f
BVA
1439 * If no I/O scheduler has been configured it is possible that
1440 * the hardware queue got stopped and restarted before requests
1441 * were pushed back onto the dispatch list. Rerun the queue to
1442 * avoid starvation. Notes:
1443 * - blk_mq_run_hw_queue() checks whether or not a queue has
1444 * been stopped before rerunning a queue.
1445 * - Some but not all block drivers stop a queue before
fc17b653 1446 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
710c785f 1447 * and dm-rq.
86ff7c2a
ML
1448 *
1449 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1450 * bit is set, run queue after a delay to avoid IO stalls
ab3cee37
DA
1451 * that could otherwise occur if the queue is idle. We'll do
1452 * similar if we couldn't get budget and SCHED_RESTART is set.
bd166ef1 1453 */
86ff7c2a
ML
1454 needs_restart = blk_mq_sched_needs_restart(hctx);
1455 if (!needs_restart ||
eb619fdb 1456 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
bd166ef1 1457 blk_mq_run_hw_queue(hctx, true);
ab3cee37
DA
1458 else if (needs_restart && (ret == BLK_STS_RESOURCE ||
1459 no_budget_avail))
86ff7c2a 1460 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1f57f8d4 1461
6e768717 1462 blk_mq_update_dispatch_busy(hctx, true);
1f57f8d4 1463 return false;
6e768717
ML
1464 } else
1465 blk_mq_update_dispatch_busy(hctx, false);
f04c3df3 1466
93efe981 1467 return (queued + errors) != 0;
f04c3df3
JA
1468}
1469
105663f7
AA
1470/**
1471 * __blk_mq_run_hw_queue - Run a hardware queue.
1472 * @hctx: Pointer to the hardware queue to run.
1473 *
1474 * Send pending requests to the hardware.
1475 */
6a83e74d
BVA
1476static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1477{
1478 int srcu_idx;
1479
b7a71e66
JA
1480 /*
1481 * We can't run the queue inline with ints disabled. Ensure that
1482 * we catch bad users of this early.
1483 */
1484 WARN_ON_ONCE(in_interrupt());
1485
04ced159 1486 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
bf4907c0 1487
04ced159
JA
1488 hctx_lock(hctx, &srcu_idx);
1489 blk_mq_sched_dispatch_requests(hctx);
1490 hctx_unlock(hctx, srcu_idx);
6a83e74d
BVA
1491}
1492
f82ddf19
ML
1493static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1494{
1495 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1496
1497 if (cpu >= nr_cpu_ids)
1498 cpu = cpumask_first(hctx->cpumask);
1499 return cpu;
1500}
1501
506e931f
JA
1502/*
1503 * It'd be great if the workqueue API had a way to pass
1504 * in a mask and had some smarts for more clever placement.
1505 * For now we just round-robin here, switching for every
1506 * BLK_MQ_CPU_WORK_BATCH queued items.
1507 */
1508static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1509{
7bed4595 1510 bool tried = false;
476f8c98 1511 int next_cpu = hctx->next_cpu;
7bed4595 1512
b657d7e6
CH
1513 if (hctx->queue->nr_hw_queues == 1)
1514 return WORK_CPU_UNBOUND;
506e931f
JA
1515
1516 if (--hctx->next_cpu_batch <= 0) {
7bed4595 1517select_cpu:
476f8c98 1518 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
20e4d813 1519 cpu_online_mask);
506e931f 1520 if (next_cpu >= nr_cpu_ids)
f82ddf19 1521 next_cpu = blk_mq_first_mapped_cpu(hctx);
506e931f
JA
1522 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1523 }
1524
7bed4595
ML
1525 /*
1526 * Do unbound schedule if we can't find a online CPU for this hctx,
1527 * and it should only happen in the path of handling CPU DEAD.
1528 */
476f8c98 1529 if (!cpu_online(next_cpu)) {
7bed4595
ML
1530 if (!tried) {
1531 tried = true;
1532 goto select_cpu;
1533 }
1534
1535 /*
1536 * Make sure to re-select CPU next time once after CPUs
1537 * in hctx->cpumask become online again.
1538 */
476f8c98 1539 hctx->next_cpu = next_cpu;
7bed4595
ML
1540 hctx->next_cpu_batch = 1;
1541 return WORK_CPU_UNBOUND;
1542 }
476f8c98
ML
1543
1544 hctx->next_cpu = next_cpu;
1545 return next_cpu;
506e931f
JA
1546}
1547
105663f7
AA
1548/**
1549 * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
1550 * @hctx: Pointer to the hardware queue to run.
1551 * @async: If we want to run the queue asynchronously.
fa94ba8a 1552 * @msecs: Milliseconds of delay to wait before running the queue.
105663f7
AA
1553 *
1554 * If !@async, try to run the queue now. Else, run the queue asynchronously and
1555 * with a delay of @msecs.
1556 */
7587a5ae
BVA
1557static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1558 unsigned long msecs)
320ae51f 1559{
5435c023 1560 if (unlikely(blk_mq_hctx_stopped(hctx)))
320ae51f
JA
1561 return;
1562
1b792f2f 1563 if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
2a90d4aa
PB
1564 int cpu = get_cpu();
1565 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
398205b8 1566 __blk_mq_run_hw_queue(hctx);
2a90d4aa 1567 put_cpu();
398205b8
PB
1568 return;
1569 }
e4043dcf 1570
2a90d4aa 1571 put_cpu();
e4043dcf 1572 }
398205b8 1573
ae943d20
BVA
1574 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1575 msecs_to_jiffies(msecs));
7587a5ae
BVA
1576}
1577
105663f7
AA
1578/**
1579 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
1580 * @hctx: Pointer to the hardware queue to run.
fa94ba8a 1581 * @msecs: Milliseconds of delay to wait before running the queue.
105663f7
AA
1582 *
1583 * Run a hardware queue asynchronously with a delay of @msecs.
1584 */
7587a5ae
BVA
1585void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1586{
1587 __blk_mq_delay_run_hw_queue(hctx, true, msecs);
1588}
1589EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1590
105663f7
AA
1591/**
1592 * blk_mq_run_hw_queue - Start to run a hardware queue.
1593 * @hctx: Pointer to the hardware queue to run.
1594 * @async: If we want to run the queue asynchronously.
1595 *
1596 * Check if the request queue is not in a quiesced state and if there are
1597 * pending requests to be sent. If this is true, run the queue to send requests
1598 * to hardware.
1599 */
626fb735 1600void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
7587a5ae 1601{
24f5a90f
ML
1602 int srcu_idx;
1603 bool need_run;
1604
1605 /*
1606 * When queue is quiesced, we may be switching io scheduler, or
1607 * updating nr_hw_queues, or other things, and we can't run queue
1608 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1609 *
1610 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1611 * quiesced.
1612 */
04ced159
JA
1613 hctx_lock(hctx, &srcu_idx);
1614 need_run = !blk_queue_quiesced(hctx->queue) &&
1615 blk_mq_hctx_has_pending(hctx);
1616 hctx_unlock(hctx, srcu_idx);
24f5a90f 1617
626fb735 1618 if (need_run)
79f720a7 1619 __blk_mq_delay_run_hw_queue(hctx, async, 0);
320ae51f 1620}
5b727272 1621EXPORT_SYMBOL(blk_mq_run_hw_queue);
320ae51f 1622
b6e68ee8
JK
1623/*
1624 * Is the request queue handled by an IO scheduler that does not respect
1625 * hardware queues when dispatching?
1626 */
1627static bool blk_mq_has_sqsched(struct request_queue *q)
1628{
1629 struct elevator_queue *e = q->elevator;
1630
1631 if (e && e->type->ops.dispatch_request &&
1632 !(e->type->elevator_features & ELEVATOR_F_MQ_AWARE))
1633 return true;
1634 return false;
1635}
1636
1637/*
1638 * Return prefered queue to dispatch from (if any) for non-mq aware IO
1639 * scheduler.
1640 */
1641static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
1642{
1643 struct blk_mq_hw_ctx *hctx;
1644
1645 /*
1646 * If the IO scheduler does not respect hardware queues when
1647 * dispatching, we just don't bother with multiple HW queues and
1648 * dispatch from hctx for the current CPU since running multiple queues
1649 * just causes lock contention inside the scheduler and pointless cache
1650 * bouncing.
1651 */
1652 hctx = blk_mq_map_queue_type(q, HCTX_TYPE_DEFAULT,
1653 raw_smp_processor_id());
1654 if (!blk_mq_hctx_stopped(hctx))
1655 return hctx;
1656 return NULL;
1657}
1658
105663f7 1659/**
24f7bb88 1660 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
105663f7
AA
1661 * @q: Pointer to the request queue to run.
1662 * @async: If we want to run the queue asynchronously.
1663 */
b94ec296 1664void blk_mq_run_hw_queues(struct request_queue *q, bool async)
320ae51f 1665{
b6e68ee8 1666 struct blk_mq_hw_ctx *hctx, *sq_hctx;
320ae51f
JA
1667 int i;
1668
b6e68ee8
JK
1669 sq_hctx = NULL;
1670 if (blk_mq_has_sqsched(q))
1671 sq_hctx = blk_mq_get_sq_hctx(q);
320ae51f 1672 queue_for_each_hw_ctx(q, hctx, i) {
79f720a7 1673 if (blk_mq_hctx_stopped(hctx))
320ae51f 1674 continue;
b6e68ee8
JK
1675 /*
1676 * Dispatch from this hctx either if there's no hctx preferred
1677 * by IO scheduler or if it has requests that bypass the
1678 * scheduler.
1679 */
1680 if (!sq_hctx || sq_hctx == hctx ||
1681 !list_empty_careful(&hctx->dispatch))
1682 blk_mq_run_hw_queue(hctx, async);
320ae51f
JA
1683 }
1684}
b94ec296 1685EXPORT_SYMBOL(blk_mq_run_hw_queues);
320ae51f 1686
b9151e7b
DA
1687/**
1688 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
1689 * @q: Pointer to the request queue to run.
fa94ba8a 1690 * @msecs: Milliseconds of delay to wait before running the queues.
b9151e7b
DA
1691 */
1692void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
1693{
b6e68ee8 1694 struct blk_mq_hw_ctx *hctx, *sq_hctx;
b9151e7b
DA
1695 int i;
1696
b6e68ee8
JK
1697 sq_hctx = NULL;
1698 if (blk_mq_has_sqsched(q))
1699 sq_hctx = blk_mq_get_sq_hctx(q);
b9151e7b
DA
1700 queue_for_each_hw_ctx(q, hctx, i) {
1701 if (blk_mq_hctx_stopped(hctx))
1702 continue;
b6e68ee8
JK
1703 /*
1704 * Dispatch from this hctx either if there's no hctx preferred
1705 * by IO scheduler or if it has requests that bypass the
1706 * scheduler.
1707 */
1708 if (!sq_hctx || sq_hctx == hctx ||
1709 !list_empty_careful(&hctx->dispatch))
1710 blk_mq_delay_run_hw_queue(hctx, msecs);
b9151e7b
DA
1711 }
1712}
1713EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
1714
fd001443
BVA
1715/**
1716 * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1717 * @q: request queue.
1718 *
1719 * The caller is responsible for serializing this function against
1720 * blk_mq_{start,stop}_hw_queue().
1721 */
1722bool blk_mq_queue_stopped(struct request_queue *q)
1723{
1724 struct blk_mq_hw_ctx *hctx;
1725 int i;
1726
1727 queue_for_each_hw_ctx(q, hctx, i)
1728 if (blk_mq_hctx_stopped(hctx))
1729 return true;
1730
1731 return false;
1732}
1733EXPORT_SYMBOL(blk_mq_queue_stopped);
1734
39a70c76
ML
1735/*
1736 * This function is often used for pausing .queue_rq() by driver when
1737 * there isn't enough resource or some conditions aren't satisfied, and
4d606219 1738 * BLK_STS_RESOURCE is usually returned.
39a70c76
ML
1739 *
1740 * We do not guarantee that dispatch can be drained or blocked
1741 * after blk_mq_stop_hw_queue() returns. Please use
1742 * blk_mq_quiesce_queue() for that requirement.
1743 */
2719aa21
JA
1744void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1745{
641a9ed6 1746 cancel_delayed_work(&hctx->run_work);
280d45f6 1747
641a9ed6 1748 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2719aa21 1749}
641a9ed6 1750EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2719aa21 1751
39a70c76
ML
1752/*
1753 * This function is often used for pausing .queue_rq() by driver when
1754 * there isn't enough resource or some conditions aren't satisfied, and
4d606219 1755 * BLK_STS_RESOURCE is usually returned.
39a70c76
ML
1756 *
1757 * We do not guarantee that dispatch can be drained or blocked
1758 * after blk_mq_stop_hw_queues() returns. Please use
1759 * blk_mq_quiesce_queue() for that requirement.
1760 */
2719aa21
JA
1761void blk_mq_stop_hw_queues(struct request_queue *q)
1762{
641a9ed6
ML
1763 struct blk_mq_hw_ctx *hctx;
1764 int i;
1765
1766 queue_for_each_hw_ctx(q, hctx, i)
1767 blk_mq_stop_hw_queue(hctx);
280d45f6
CH
1768}
1769EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1770
320ae51f
JA
1771void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1772{
1773 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
e4043dcf 1774
0ffbce80 1775 blk_mq_run_hw_queue(hctx, false);
320ae51f
JA
1776}
1777EXPORT_SYMBOL(blk_mq_start_hw_queue);
1778
2f268556
CH
1779void blk_mq_start_hw_queues(struct request_queue *q)
1780{
1781 struct blk_mq_hw_ctx *hctx;
1782 int i;
1783
1784 queue_for_each_hw_ctx(q, hctx, i)
1785 blk_mq_start_hw_queue(hctx);
1786}
1787EXPORT_SYMBOL(blk_mq_start_hw_queues);
1788
ae911c5e
JA
1789void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1790{
1791 if (!blk_mq_hctx_stopped(hctx))
1792 return;
1793
1794 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1795 blk_mq_run_hw_queue(hctx, async);
1796}
1797EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1798
1b4a3258 1799void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
320ae51f
JA
1800{
1801 struct blk_mq_hw_ctx *hctx;
1802 int i;
1803
ae911c5e
JA
1804 queue_for_each_hw_ctx(q, hctx, i)
1805 blk_mq_start_stopped_hw_queue(hctx, async);
320ae51f
JA
1806}
1807EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1808
70f4db63 1809static void blk_mq_run_work_fn(struct work_struct *work)
320ae51f
JA
1810{
1811 struct blk_mq_hw_ctx *hctx;
1812
9f993737 1813 hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
320ae51f 1814
21c6e939 1815 /*
15fe8a90 1816 * If we are stopped, don't run the queue.
21c6e939 1817 */
0841031a 1818 if (blk_mq_hctx_stopped(hctx))
0196d6b4 1819 return;
7587a5ae
BVA
1820
1821 __blk_mq_run_hw_queue(hctx);
1822}
1823
cfd0c552 1824static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
cfd0c552
ML
1825 struct request *rq,
1826 bool at_head)
320ae51f 1827{
e57690fe 1828 struct blk_mq_ctx *ctx = rq->mq_ctx;
c16d6b5a 1829 enum hctx_type type = hctx->type;
e57690fe 1830
7b607814
BVA
1831 lockdep_assert_held(&ctx->lock);
1832
a54895fa 1833 trace_block_rq_insert(rq);
01b983c9 1834
72a0a36e 1835 if (at_head)
c16d6b5a 1836 list_add(&rq->queuelist, &ctx->rq_lists[type]);
72a0a36e 1837 else
c16d6b5a 1838 list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
cfd0c552 1839}
4bb659b1 1840
2c3ad667
JA
1841void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1842 bool at_head)
cfd0c552
ML
1843{
1844 struct blk_mq_ctx *ctx = rq->mq_ctx;
1845
7b607814
BVA
1846 lockdep_assert_held(&ctx->lock);
1847
e57690fe 1848 __blk_mq_insert_req_list(hctx, rq, at_head);
320ae51f 1849 blk_mq_hctx_mark_pending(hctx, ctx);
320ae51f
JA
1850}
1851
105663f7
AA
1852/**
1853 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
1854 * @rq: Pointer to request to be inserted.
26bfeb26 1855 * @at_head: true if the request should be inserted at the head of the list.
105663f7
AA
1856 * @run_queue: If we should run the hardware queue after inserting the request.
1857 *
157f377b
JA
1858 * Should only be used carefully, when the caller knows we want to
1859 * bypass a potential IO scheduler on the target device.
1860 */
01e99aec
ML
1861void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
1862 bool run_queue)
157f377b 1863{
ea4f995e 1864 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
157f377b
JA
1865
1866 spin_lock(&hctx->lock);
01e99aec
ML
1867 if (at_head)
1868 list_add(&rq->queuelist, &hctx->dispatch);
1869 else
1870 list_add_tail(&rq->queuelist, &hctx->dispatch);
157f377b
JA
1871 spin_unlock(&hctx->lock);
1872
b0850297
ML
1873 if (run_queue)
1874 blk_mq_run_hw_queue(hctx, false);
157f377b
JA
1875}
1876
bd166ef1
JA
1877void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1878 struct list_head *list)
320ae51f
JA
1879
1880{
3f0cedc7 1881 struct request *rq;
c16d6b5a 1882 enum hctx_type type = hctx->type;
3f0cedc7 1883
320ae51f
JA
1884 /*
1885 * preemption doesn't flush plug list, so it's possible ctx->cpu is
1886 * offline now
1887 */
3f0cedc7 1888 list_for_each_entry(rq, list, queuelist) {
e57690fe 1889 BUG_ON(rq->mq_ctx != ctx);
a54895fa 1890 trace_block_rq_insert(rq);
320ae51f 1891 }
3f0cedc7
ML
1892
1893 spin_lock(&ctx->lock);
c16d6b5a 1894 list_splice_tail_init(list, &ctx->rq_lists[type]);
cfd0c552 1895 blk_mq_hctx_mark_pending(hctx, ctx);
320ae51f 1896 spin_unlock(&ctx->lock);
320ae51f
JA
1897}
1898
4f0f586b
ST
1899static int plug_rq_cmp(void *priv, const struct list_head *a,
1900 const struct list_head *b)
320ae51f
JA
1901{
1902 struct request *rqa = container_of(a, struct request, queuelist);
1903 struct request *rqb = container_of(b, struct request, queuelist);
1904
7d30a621
PB
1905 if (rqa->mq_ctx != rqb->mq_ctx)
1906 return rqa->mq_ctx > rqb->mq_ctx;
1907 if (rqa->mq_hctx != rqb->mq_hctx)
1908 return rqa->mq_hctx > rqb->mq_hctx;
3110fc79
JA
1909
1910 return blk_rq_pos(rqa) > blk_rq_pos(rqb);
320ae51f
JA
1911}
1912
1913void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1914{
320ae51f 1915 LIST_HEAD(list);
320ae51f 1916
95ed0c5b
PB
1917 if (list_empty(&plug->mq_list))
1918 return;
320ae51f
JA
1919 list_splice_init(&plug->mq_list, &list);
1920
ce5b009c
JA
1921 if (plug->rq_count > 2 && plug->multiple_queues)
1922 list_sort(NULL, &list, plug_rq_cmp);
320ae51f 1923
bcc816df
DZ
1924 plug->rq_count = 0;
1925
95ed0c5b
PB
1926 do {
1927 struct list_head rq_list;
1928 struct request *rq, *head_rq = list_entry_rq(list.next);
1929 struct list_head *pos = &head_rq->queuelist; /* skip first */
1930 struct blk_mq_hw_ctx *this_hctx = head_rq->mq_hctx;
1931 struct blk_mq_ctx *this_ctx = head_rq->mq_ctx;
1932 unsigned int depth = 1;
1933
1934 list_for_each_continue(pos, &list) {
1935 rq = list_entry_rq(pos);
1936 BUG_ON(!rq->q);
1937 if (rq->mq_hctx != this_hctx || rq->mq_ctx != this_ctx)
1938 break;
1939 depth++;
320ae51f
JA
1940 }
1941
95ed0c5b
PB
1942 list_cut_before(&rq_list, &list, pos);
1943 trace_block_unplug(head_rq->q, depth, !from_schedule);
67cae4c9 1944 blk_mq_sched_insert_requests(this_hctx, this_ctx, &rq_list,
bd166ef1 1945 from_schedule);
95ed0c5b 1946 } while(!list_empty(&list));
320ae51f
JA
1947}
1948
14ccb66b
CH
1949static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
1950 unsigned int nr_segs)
320ae51f 1951{
93f221ae
EB
1952 int err;
1953
f924cdde
CH
1954 if (bio->bi_opf & REQ_RAHEAD)
1955 rq->cmd_flags |= REQ_FAILFAST_MASK;
1956
1957 rq->__sector = bio->bi_iter.bi_sector;
1958 rq->write_hint = bio->bi_write_hint;
14ccb66b 1959 blk_rq_bio_prep(rq, bio, nr_segs);
93f221ae
EB
1960
1961 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
1962 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
1963 WARN_ON_ONCE(err);
4b570521 1964
b5af37ab 1965 blk_account_io_start(rq);
320ae51f
JA
1966}
1967
0f95549c
MS
1968static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
1969 struct request *rq,
be94f058 1970 blk_qc_t *cookie, bool last)
f984df1f 1971{
f984df1f 1972 struct request_queue *q = rq->q;
f984df1f
SL
1973 struct blk_mq_queue_data bd = {
1974 .rq = rq,
be94f058 1975 .last = last,
f984df1f 1976 };
bd166ef1 1977 blk_qc_t new_cookie;
f06345ad 1978 blk_status_t ret;
0f95549c
MS
1979
1980 new_cookie = request_to_qc_t(hctx, rq);
1981
1982 /*
1983 * For OK queue, we are done. For error, caller may kill it.
1984 * Any other error (busy), just add it to our list as we
1985 * previously would have done.
1986 */
1987 ret = q->mq_ops->queue_rq(hctx, &bd);
1988 switch (ret) {
1989 case BLK_STS_OK:
6ce3dd6e 1990 blk_mq_update_dispatch_busy(hctx, false);
0f95549c
MS
1991 *cookie = new_cookie;
1992 break;
1993 case BLK_STS_RESOURCE:
86ff7c2a 1994 case BLK_STS_DEV_RESOURCE:
6ce3dd6e 1995 blk_mq_update_dispatch_busy(hctx, true);
0f95549c
MS
1996 __blk_mq_requeue_request(rq);
1997 break;
1998 default:
6ce3dd6e 1999 blk_mq_update_dispatch_busy(hctx, false);
0f95549c
MS
2000 *cookie = BLK_QC_T_NONE;
2001 break;
2002 }
2003
2004 return ret;
2005}
2006
fd9c40f6 2007static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
0f95549c 2008 struct request *rq,
396eaf21 2009 blk_qc_t *cookie,
fd9c40f6 2010 bool bypass_insert, bool last)
0f95549c
MS
2011{
2012 struct request_queue *q = rq->q;
d964f04a 2013 bool run_queue = true;
2a5a24aa 2014 int budget_token;
d964f04a 2015
23d4ee19 2016 /*
fd9c40f6 2017 * RCU or SRCU read lock is needed before checking quiesced flag.
23d4ee19 2018 *
fd9c40f6
BVA
2019 * When queue is stopped or quiesced, ignore 'bypass_insert' from
2020 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
2021 * and avoid driver to try to dispatch again.
23d4ee19 2022 */
fd9c40f6 2023 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
d964f04a 2024 run_queue = false;
fd9c40f6
BVA
2025 bypass_insert = false;
2026 goto insert;
d964f04a 2027 }
f984df1f 2028
fd9c40f6
BVA
2029 if (q->elevator && !bypass_insert)
2030 goto insert;
2253efc8 2031
2a5a24aa
ML
2032 budget_token = blk_mq_get_dispatch_budget(q);
2033 if (budget_token < 0)
fd9c40f6 2034 goto insert;
bd166ef1 2035
2a5a24aa
ML
2036 blk_mq_set_rq_budget_token(rq, budget_token);
2037
8ab6bb9e 2038 if (!blk_mq_get_driver_tag(rq)) {
2a5a24aa 2039 blk_mq_put_dispatch_budget(q, budget_token);
fd9c40f6 2040 goto insert;
88022d72 2041 }
de148297 2042
fd9c40f6
BVA
2043 return __blk_mq_issue_directly(hctx, rq, cookie, last);
2044insert:
2045 if (bypass_insert)
2046 return BLK_STS_RESOURCE;
2047
db03f88f
ML
2048 blk_mq_sched_insert_request(rq, false, run_queue, false);
2049
fd9c40f6
BVA
2050 return BLK_STS_OK;
2051}
2052
105663f7
AA
2053/**
2054 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2055 * @hctx: Pointer of the associated hardware queue.
2056 * @rq: Pointer to request to be sent.
2057 * @cookie: Request queue cookie.
2058 *
2059 * If the device has enough resources to accept a new request now, send the
2060 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2061 * we can try send it another time in the future. Requests inserted at this
2062 * queue have higher priority.
2063 */
fd9c40f6
BVA
2064static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2065 struct request *rq, blk_qc_t *cookie)
2066{
2067 blk_status_t ret;
2068 int srcu_idx;
2069
2070 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
2071
2072 hctx_lock(hctx, &srcu_idx);
2073
2074 ret = __blk_mq_try_issue_directly(hctx, rq, cookie, false, true);
2075 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
01e99aec 2076 blk_mq_request_bypass_insert(rq, false, true);
fd9c40f6
BVA
2077 else if (ret != BLK_STS_OK)
2078 blk_mq_end_request(rq, ret);
2079
2080 hctx_unlock(hctx, srcu_idx);
2081}
2082
2083blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2084{
2085 blk_status_t ret;
2086 int srcu_idx;
2087 blk_qc_t unused_cookie;
2088 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2089
2090 hctx_lock(hctx, &srcu_idx);
2091 ret = __blk_mq_try_issue_directly(hctx, rq, &unused_cookie, true, last);
04ced159 2092 hctx_unlock(hctx, srcu_idx);
7f556a44
JW
2093
2094 return ret;
5eb6126e
CH
2095}
2096
6ce3dd6e
ML
2097void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2098 struct list_head *list)
2099{
536167d4 2100 int queued = 0;
632bfb63 2101 int errors = 0;
536167d4 2102
6ce3dd6e 2103 while (!list_empty(list)) {
fd9c40f6 2104 blk_status_t ret;
6ce3dd6e
ML
2105 struct request *rq = list_first_entry(list, struct request,
2106 queuelist);
2107
2108 list_del_init(&rq->queuelist);
fd9c40f6
BVA
2109 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2110 if (ret != BLK_STS_OK) {
2111 if (ret == BLK_STS_RESOURCE ||
2112 ret == BLK_STS_DEV_RESOURCE) {
01e99aec 2113 blk_mq_request_bypass_insert(rq, false,
c616cbee 2114 list_empty(list));
fd9c40f6
BVA
2115 break;
2116 }
2117 blk_mq_end_request(rq, ret);
632bfb63 2118 errors++;
536167d4
KB
2119 } else
2120 queued++;
6ce3dd6e 2121 }
d666ba98
JA
2122
2123 /*
2124 * If we didn't flush the entire list, we could have told
2125 * the driver there was more coming, but that turned out to
2126 * be a lie.
2127 */
632bfb63 2128 if ((!list_empty(list) || errors) &&
2129 hctx->queue->mq_ops->commit_rqs && queued)
d666ba98 2130 hctx->queue->mq_ops->commit_rqs(hctx);
6ce3dd6e
ML
2131}
2132
ce5b009c
JA
2133static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2134{
2135 list_add_tail(&rq->queuelist, &plug->mq_list);
2136 plug->rq_count++;
2137 if (!plug->multiple_queues && !list_is_singular(&plug->mq_list)) {
2138 struct request *tmp;
2139
2140 tmp = list_first_entry(&plug->mq_list, struct request,
2141 queuelist);
2142 if (tmp->q != rq->q)
2143 plug->multiple_queues = true;
2144 }
2145}
2146
7f2a6a69
SL
2147/*
2148 * Allow 4x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
2149 * queues. This is important for md arrays to benefit from merging
2150 * requests.
2151 */
2152static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
2153{
2154 if (plug->multiple_queues)
2155 return BLK_MAX_REQUEST_COUNT * 4;
2156 return BLK_MAX_REQUEST_COUNT;
2157}
2158
105663f7 2159/**
c62b37d9 2160 * blk_mq_submit_bio - Create and send a request to block device.
105663f7
AA
2161 * @bio: Bio pointer.
2162 *
2163 * Builds up a request structure from @q and @bio and send to the device. The
2164 * request may not be queued directly to hardware if:
2165 * * This request can be merged with another one
2166 * * We want to place request at plug queue for possible future merging
2167 * * There is an IO scheduler active at this queue
2168 *
2169 * It will not queue the request if there is an error with the bio, or at the
2170 * request creation.
2171 *
2172 * Returns: Request queue cookie.
2173 */
c62b37d9 2174blk_qc_t blk_mq_submit_bio(struct bio *bio)
07068d5b 2175{
309dca30 2176 struct request_queue *q = bio->bi_bdev->bd_disk->queue;
ef295ecf 2177 const int is_sync = op_is_sync(bio->bi_opf);
f73f44eb 2178 const int is_flush_fua = op_is_flush(bio->bi_opf);
e6e7abff
CH
2179 struct blk_mq_alloc_data data = {
2180 .q = q,
2181 };
07068d5b 2182 struct request *rq;
f984df1f 2183 struct blk_plug *plug;
5b3f341f 2184 struct request *same_queue_rq = NULL;
14ccb66b 2185 unsigned int nr_segs;
7b371636 2186 blk_qc_t cookie;
a892c8d5 2187 blk_status_t ret;
cc29e1bf 2188 bool hipri;
07068d5b
JA
2189
2190 blk_queue_bounce(q, &bio);
f695ca38 2191 __blk_queue_split(&bio, &nr_segs);
f36ea50c 2192
e23947bd 2193 if (!bio_integrity_prep(bio))
ac7c5675 2194 goto queue_exit;
07068d5b 2195
87c279e6 2196 if (!is_flush_fua && !blk_queue_nomerges(q) &&
14ccb66b 2197 blk_attempt_plug_merge(q, bio, nr_segs, &same_queue_rq))
ac7c5675 2198 goto queue_exit;
f984df1f 2199
14ccb66b 2200 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
ac7c5675 2201 goto queue_exit;
bd166ef1 2202
d5337560 2203 rq_qos_throttle(q, bio);
87760e5e 2204
cc29e1bf
JX
2205 hipri = bio->bi_opf & REQ_HIPRI;
2206
7809167d 2207 data.cmd_flags = bio->bi_opf;
e6e7abff 2208 rq = __blk_mq_alloc_request(&data);
87760e5e 2209 if (unlikely(!rq)) {
c1c80384 2210 rq_qos_cleanup(q, bio);
7b6620d7 2211 if (bio->bi_opf & REQ_NOWAIT)
03a07c92 2212 bio_wouldblock_error(bio);
ac7c5675 2213 goto queue_exit;
87760e5e
JA
2214 }
2215
e8a676d6 2216 trace_block_getrq(bio);
d6f1dda2 2217
c1c80384 2218 rq_qos_track(q, rq, bio);
07068d5b 2219
fd2d3326 2220 cookie = request_to_qc_t(data.hctx, rq);
07068d5b 2221
970d168d
BVA
2222 blk_mq_bio_to_request(rq, bio, nr_segs);
2223
a892c8d5
ST
2224 ret = blk_crypto_init_request(rq);
2225 if (ret != BLK_STS_OK) {
2226 bio->bi_status = ret;
2227 bio_endio(bio);
2228 blk_mq_free_request(rq);
2229 return BLK_QC_T_NONE;
2230 }
2231
b49773e7 2232 plug = blk_mq_plug(q, bio);
07068d5b 2233 if (unlikely(is_flush_fua)) {
105663f7 2234 /* Bypass scheduler for flush requests */
923218f6
ML
2235 blk_insert_flush(rq);
2236 blk_mq_run_hw_queue(data.hctx, true);
03f26d8f
ML
2237 } else if (plug && (q->nr_hw_queues == 1 ||
2238 blk_mq_is_sbitmap_shared(rq->mq_hctx->flags) ||
2239 q->mq_ops->commit_rqs || !blk_queue_nonrot(q))) {
b2c5d16b
JA
2240 /*
2241 * Use plugging if we have a ->commit_rqs() hook as well, as
2242 * we know the driver uses bd->last in a smart fashion.
3154df26
ML
2243 *
2244 * Use normal plugging if this disk is slow HDD, as sequential
2245 * IO may benefit a lot from plug merging.
b2c5d16b 2246 */
5f0ed774 2247 unsigned int request_count = plug->rq_count;
600271d9
SL
2248 struct request *last = NULL;
2249
676d0607 2250 if (!request_count)
e6c4438b 2251 trace_block_plug(q);
600271d9
SL
2252 else
2253 last = list_entry_rq(plug->mq_list.prev);
b094f89c 2254
7f2a6a69 2255 if (request_count >= blk_plug_max_rq_count(plug) || (last &&
600271d9 2256 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
e6c4438b
JM
2257 blk_flush_plug_list(plug, false);
2258 trace_block_plug(q);
320ae51f 2259 }
b094f89c 2260
ce5b009c 2261 blk_add_rq_to_plug(plug, rq);
a12de1d4 2262 } else if (q->elevator) {
105663f7 2263 /* Insert the request at the IO scheduler queue */
a12de1d4 2264 blk_mq_sched_insert_request(rq, false, true, true);
2299722c 2265 } else if (plug && !blk_queue_nomerges(q)) {
07068d5b 2266 /*
6a83e74d 2267 * We do limited plugging. If the bio can be merged, do that.
f984df1f
SL
2268 * Otherwise the existing request in the plug list will be
2269 * issued. So the plug list will have one request at most
2299722c
CH
2270 * The plug list might get flushed before this. If that happens,
2271 * the plug list is empty, and same_queue_rq is invalid.
07068d5b 2272 */
2299722c
CH
2273 if (list_empty(&plug->mq_list))
2274 same_queue_rq = NULL;
4711b573 2275 if (same_queue_rq) {
2299722c 2276 list_del_init(&same_queue_rq->queuelist);
4711b573
JA
2277 plug->rq_count--;
2278 }
ce5b009c 2279 blk_add_rq_to_plug(plug, rq);
ff3b74b8 2280 trace_block_plug(q);
2299722c 2281
dad7a3be 2282 if (same_queue_rq) {
ea4f995e 2283 data.hctx = same_queue_rq->mq_hctx;
ff3b74b8 2284 trace_block_unplug(q, 1, true);
2299722c 2285 blk_mq_try_issue_directly(data.hctx, same_queue_rq,
fd9c40f6 2286 &cookie);
dad7a3be 2287 }
a12de1d4
ML
2288 } else if ((q->nr_hw_queues > 1 && is_sync) ||
2289 !data.hctx->dispatch_busy) {
105663f7
AA
2290 /*
2291 * There is no scheduler and we can try to send directly
2292 * to the hardware.
2293 */
fd9c40f6 2294 blk_mq_try_issue_directly(data.hctx, rq, &cookie);
ab42f35d 2295 } else {
105663f7 2296 /* Default case. */
8fa9f556 2297 blk_mq_sched_insert_request(rq, false, true, true);
ab42f35d 2298 }
320ae51f 2299
cc29e1bf
JX
2300 if (!hipri)
2301 return BLK_QC_T_NONE;
7b371636 2302 return cookie;
ac7c5675
CH
2303queue_exit:
2304 blk_queue_exit(q);
2305 return BLK_QC_T_NONE;
320ae51f
JA
2306}
2307
bd63141d
ML
2308static size_t order_to_size(unsigned int order)
2309{
2310 return (size_t)PAGE_SIZE << order;
2311}
2312
2313/* called before freeing request pool in @tags */
2314static void blk_mq_clear_rq_mapping(struct blk_mq_tag_set *set,
2315 struct blk_mq_tags *tags, unsigned int hctx_idx)
2316{
2317 struct blk_mq_tags *drv_tags = set->tags[hctx_idx];
2318 struct page *page;
2319 unsigned long flags;
2320
2321 list_for_each_entry(page, &tags->page_list, lru) {
2322 unsigned long start = (unsigned long)page_address(page);
2323 unsigned long end = start + order_to_size(page->private);
2324 int i;
2325
2326 for (i = 0; i < set->queue_depth; i++) {
2327 struct request *rq = drv_tags->rqs[i];
2328 unsigned long rq_addr = (unsigned long)rq;
2329
2330 if (rq_addr >= start && rq_addr < end) {
2331 WARN_ON_ONCE(refcount_read(&rq->ref) != 0);
2332 cmpxchg(&drv_tags->rqs[i], rq, NULL);
2333 }
2334 }
2335 }
2336
2337 /*
2338 * Wait until all pending iteration is done.
2339 *
2340 * Request reference is cleared and it is guaranteed to be observed
2341 * after the ->lock is released.
2342 */
2343 spin_lock_irqsave(&drv_tags->lock, flags);
2344 spin_unlock_irqrestore(&drv_tags->lock, flags);
2345}
2346
cc71a6f4
JA
2347void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2348 unsigned int hctx_idx)
95363efd 2349{
e9b267d9 2350 struct page *page;
320ae51f 2351
65de57bb 2352 if (tags->static_rqs && set->ops->exit_request) {
e9b267d9 2353 int i;
320ae51f 2354
24d2f903 2355 for (i = 0; i < tags->nr_tags; i++) {
2af8cbe3
JA
2356 struct request *rq = tags->static_rqs[i];
2357
2358 if (!rq)
e9b267d9 2359 continue;
d6296d39 2360 set->ops->exit_request(set, rq, hctx_idx);
2af8cbe3 2361 tags->static_rqs[i] = NULL;
e9b267d9 2362 }
320ae51f 2363 }
320ae51f 2364
bd63141d
ML
2365 blk_mq_clear_rq_mapping(set, tags, hctx_idx);
2366
24d2f903
CH
2367 while (!list_empty(&tags->page_list)) {
2368 page = list_first_entry(&tags->page_list, struct page, lru);
6753471c 2369 list_del_init(&page->lru);
f75782e4
CM
2370 /*
2371 * Remove kmemleak object previously allocated in
273938bf 2372 * blk_mq_alloc_rqs().
f75782e4
CM
2373 */
2374 kmemleak_free(page_address(page));
320ae51f
JA
2375 __free_pages(page, page->private);
2376 }
cc71a6f4 2377}
320ae51f 2378
1c0706a7 2379void blk_mq_free_rq_map(struct blk_mq_tags *tags, unsigned int flags)
cc71a6f4 2380{
24d2f903 2381 kfree(tags->rqs);
cc71a6f4 2382 tags->rqs = NULL;
2af8cbe3
JA
2383 kfree(tags->static_rqs);
2384 tags->static_rqs = NULL;
320ae51f 2385
1c0706a7 2386 blk_mq_free_tags(tags, flags);
320ae51f
JA
2387}
2388
cc71a6f4
JA
2389struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2390 unsigned int hctx_idx,
2391 unsigned int nr_tags,
1c0706a7
JG
2392 unsigned int reserved_tags,
2393 unsigned int flags)
320ae51f 2394{
24d2f903 2395 struct blk_mq_tags *tags;
59f082e4 2396 int node;
320ae51f 2397
7d76f856 2398 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
59f082e4
SL
2399 if (node == NUMA_NO_NODE)
2400 node = set->numa_node;
2401
1c0706a7 2402 tags = blk_mq_init_tags(nr_tags, reserved_tags, node, flags);
24d2f903
CH
2403 if (!tags)
2404 return NULL;
320ae51f 2405
590b5b7d 2406 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
36e1f3d1 2407 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
59f082e4 2408 node);
24d2f903 2409 if (!tags->rqs) {
1c0706a7 2410 blk_mq_free_tags(tags, flags);
24d2f903
CH
2411 return NULL;
2412 }
320ae51f 2413
590b5b7d
KC
2414 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2415 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2416 node);
2af8cbe3
JA
2417 if (!tags->static_rqs) {
2418 kfree(tags->rqs);
1c0706a7 2419 blk_mq_free_tags(tags, flags);
2af8cbe3
JA
2420 return NULL;
2421 }
2422
cc71a6f4
JA
2423 return tags;
2424}
2425
1d9bd516
TH
2426static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2427 unsigned int hctx_idx, int node)
2428{
2429 int ret;
2430
2431 if (set->ops->init_request) {
2432 ret = set->ops->init_request(set, rq, hctx_idx, node);
2433 if (ret)
2434 return ret;
2435 }
2436
12f5b931 2437 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1d9bd516
TH
2438 return 0;
2439}
2440
cc71a6f4
JA
2441int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2442 unsigned int hctx_idx, unsigned int depth)
2443{
2444 unsigned int i, j, entries_per_page, max_order = 4;
2445 size_t rq_size, left;
59f082e4
SL
2446 int node;
2447
7d76f856 2448 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
59f082e4
SL
2449 if (node == NUMA_NO_NODE)
2450 node = set->numa_node;
cc71a6f4
JA
2451
2452 INIT_LIST_HEAD(&tags->page_list);
2453
320ae51f
JA
2454 /*
2455 * rq_size is the size of the request plus driver payload, rounded
2456 * to the cacheline size
2457 */
24d2f903 2458 rq_size = round_up(sizeof(struct request) + set->cmd_size,
320ae51f 2459 cache_line_size());
cc71a6f4 2460 left = rq_size * depth;
320ae51f 2461
cc71a6f4 2462 for (i = 0; i < depth; ) {
320ae51f
JA
2463 int this_order = max_order;
2464 struct page *page;
2465 int to_do;
2466 void *p;
2467
b3a834b1 2468 while (this_order && left < order_to_size(this_order - 1))
320ae51f
JA
2469 this_order--;
2470
2471 do {
59f082e4 2472 page = alloc_pages_node(node,
36e1f3d1 2473 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
a5164405 2474 this_order);
320ae51f
JA
2475 if (page)
2476 break;
2477 if (!this_order--)
2478 break;
2479 if (order_to_size(this_order) < rq_size)
2480 break;
2481 } while (1);
2482
2483 if (!page)
24d2f903 2484 goto fail;
320ae51f
JA
2485
2486 page->private = this_order;
24d2f903 2487 list_add_tail(&page->lru, &tags->page_list);
320ae51f
JA
2488
2489 p = page_address(page);
f75782e4
CM
2490 /*
2491 * Allow kmemleak to scan these pages as they contain pointers
2492 * to additional allocations like via ops->init_request().
2493 */
36e1f3d1 2494 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
320ae51f 2495 entries_per_page = order_to_size(this_order) / rq_size;
cc71a6f4 2496 to_do = min(entries_per_page, depth - i);
320ae51f
JA
2497 left -= to_do * rq_size;
2498 for (j = 0; j < to_do; j++) {
2af8cbe3
JA
2499 struct request *rq = p;
2500
2501 tags->static_rqs[i] = rq;
1d9bd516
TH
2502 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2503 tags->static_rqs[i] = NULL;
2504 goto fail;
e9b267d9
CH
2505 }
2506
320ae51f
JA
2507 p += rq_size;
2508 i++;
2509 }
2510 }
cc71a6f4 2511 return 0;
320ae51f 2512
24d2f903 2513fail:
cc71a6f4
JA
2514 blk_mq_free_rqs(set, tags, hctx_idx);
2515 return -ENOMEM;
320ae51f
JA
2516}
2517
bf0beec0
ML
2518struct rq_iter_data {
2519 struct blk_mq_hw_ctx *hctx;
2520 bool has_rq;
2521};
2522
2523static bool blk_mq_has_request(struct request *rq, void *data, bool reserved)
2524{
2525 struct rq_iter_data *iter_data = data;
2526
2527 if (rq->mq_hctx != iter_data->hctx)
2528 return true;
2529 iter_data->has_rq = true;
2530 return false;
2531}
2532
2533static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
2534{
2535 struct blk_mq_tags *tags = hctx->sched_tags ?
2536 hctx->sched_tags : hctx->tags;
2537 struct rq_iter_data data = {
2538 .hctx = hctx,
2539 };
2540
2541 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
2542 return data.has_rq;
2543}
2544
2545static inline bool blk_mq_last_cpu_in_hctx(unsigned int cpu,
2546 struct blk_mq_hw_ctx *hctx)
2547{
2548 if (cpumask_next_and(-1, hctx->cpumask, cpu_online_mask) != cpu)
2549 return false;
2550 if (cpumask_next_and(cpu, hctx->cpumask, cpu_online_mask) < nr_cpu_ids)
2551 return false;
2552 return true;
2553}
2554
2555static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
2556{
2557 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2558 struct blk_mq_hw_ctx, cpuhp_online);
2559
2560 if (!cpumask_test_cpu(cpu, hctx->cpumask) ||
2561 !blk_mq_last_cpu_in_hctx(cpu, hctx))
2562 return 0;
2563
2564 /*
2565 * Prevent new request from being allocated on the current hctx.
2566 *
2567 * The smp_mb__after_atomic() Pairs with the implied barrier in
2568 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
2569 * seen once we return from the tag allocator.
2570 */
2571 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2572 smp_mb__after_atomic();
2573
2574 /*
2575 * Try to grab a reference to the queue and wait for any outstanding
2576 * requests. If we could not grab a reference the queue has been
2577 * frozen and there are no requests.
2578 */
2579 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
2580 while (blk_mq_hctx_has_requests(hctx))
2581 msleep(5);
2582 percpu_ref_put(&hctx->queue->q_usage_counter);
2583 }
2584
2585 return 0;
2586}
2587
2588static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
2589{
2590 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2591 struct blk_mq_hw_ctx, cpuhp_online);
2592
2593 if (cpumask_test_cpu(cpu, hctx->cpumask))
2594 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2595 return 0;
2596}
2597
e57690fe
JA
2598/*
2599 * 'cpu' is going away. splice any existing rq_list entries from this
2600 * software queue to the hw queue dispatch list, and ensure that it
2601 * gets run.
2602 */
9467f859 2603static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
484b4061 2604{
9467f859 2605 struct blk_mq_hw_ctx *hctx;
484b4061
JA
2606 struct blk_mq_ctx *ctx;
2607 LIST_HEAD(tmp);
c16d6b5a 2608 enum hctx_type type;
484b4061 2609
9467f859 2610 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
bf0beec0
ML
2611 if (!cpumask_test_cpu(cpu, hctx->cpumask))
2612 return 0;
2613
e57690fe 2614 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
c16d6b5a 2615 type = hctx->type;
484b4061
JA
2616
2617 spin_lock(&ctx->lock);
c16d6b5a
ML
2618 if (!list_empty(&ctx->rq_lists[type])) {
2619 list_splice_init(&ctx->rq_lists[type], &tmp);
484b4061
JA
2620 blk_mq_hctx_clear_pending(hctx, ctx);
2621 }
2622 spin_unlock(&ctx->lock);
2623
2624 if (list_empty(&tmp))
9467f859 2625 return 0;
484b4061 2626
e57690fe
JA
2627 spin_lock(&hctx->lock);
2628 list_splice_tail_init(&tmp, &hctx->dispatch);
2629 spin_unlock(&hctx->lock);
484b4061
JA
2630
2631 blk_mq_run_hw_queue(hctx, true);
9467f859 2632 return 0;
484b4061
JA
2633}
2634
9467f859 2635static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
484b4061 2636{
bf0beec0
ML
2637 if (!(hctx->flags & BLK_MQ_F_STACKING))
2638 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2639 &hctx->cpuhp_online);
9467f859
TG
2640 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2641 &hctx->cpuhp_dead);
484b4061
JA
2642}
2643
364b6181
ML
2644/*
2645 * Before freeing hw queue, clearing the flush request reference in
2646 * tags->rqs[] for avoiding potential UAF.
2647 */
2648static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
2649 unsigned int queue_depth, struct request *flush_rq)
2650{
2651 int i;
2652 unsigned long flags;
2653
2654 /* The hw queue may not be mapped yet */
2655 if (!tags)
2656 return;
2657
2658 WARN_ON_ONCE(refcount_read(&flush_rq->ref) != 0);
2659
2660 for (i = 0; i < queue_depth; i++)
2661 cmpxchg(&tags->rqs[i], flush_rq, NULL);
2662
2663 /*
2664 * Wait until all pending iteration is done.
2665 *
2666 * Request reference is cleared and it is guaranteed to be observed
2667 * after the ->lock is released.
2668 */
2669 spin_lock_irqsave(&tags->lock, flags);
2670 spin_unlock_irqrestore(&tags->lock, flags);
2671}
2672
c3b4afca 2673/* hctx->ctxs will be freed in queue's release handler */
08e98fc6
ML
2674static void blk_mq_exit_hctx(struct request_queue *q,
2675 struct blk_mq_tag_set *set,
2676 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
2677{
364b6181
ML
2678 struct request *flush_rq = hctx->fq->flush_rq;
2679
8ab0b7dc
ML
2680 if (blk_mq_hw_queue_mapped(hctx))
2681 blk_mq_tag_idle(hctx);
08e98fc6 2682
364b6181
ML
2683 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
2684 set->queue_depth, flush_rq);
f70ced09 2685 if (set->ops->exit_request)
364b6181 2686 set->ops->exit_request(set, flush_rq, hctx_idx);
f70ced09 2687
08e98fc6
ML
2688 if (set->ops->exit_hctx)
2689 set->ops->exit_hctx(hctx, hctx_idx);
2690
9467f859 2691 blk_mq_remove_cpuhp(hctx);
2f8f1336
ML
2692
2693 spin_lock(&q->unused_hctx_lock);
2694 list_add(&hctx->hctx_list, &q->unused_hctx_list);
2695 spin_unlock(&q->unused_hctx_lock);
08e98fc6
ML
2696}
2697
624dbe47
ML
2698static void blk_mq_exit_hw_queues(struct request_queue *q,
2699 struct blk_mq_tag_set *set, int nr_queue)
2700{
2701 struct blk_mq_hw_ctx *hctx;
2702 unsigned int i;
2703
2704 queue_for_each_hw_ctx(q, hctx, i) {
2705 if (i == nr_queue)
2706 break;
477e19de 2707 blk_mq_debugfs_unregister_hctx(hctx);
08e98fc6 2708 blk_mq_exit_hctx(q, set, hctx, i);
624dbe47 2709 }
624dbe47
ML
2710}
2711
7c6c5b7c
ML
2712static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
2713{
2714 int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
2715
2716 BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
2717 __alignof__(struct blk_mq_hw_ctx)) !=
2718 sizeof(struct blk_mq_hw_ctx));
2719
2720 if (tag_set->flags & BLK_MQ_F_BLOCKING)
2721 hw_ctx_size += sizeof(struct srcu_struct);
2722
2723 return hw_ctx_size;
2724}
2725
08e98fc6
ML
2726static int blk_mq_init_hctx(struct request_queue *q,
2727 struct blk_mq_tag_set *set,
2728 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
320ae51f 2729{
7c6c5b7c
ML
2730 hctx->queue_num = hctx_idx;
2731
bf0beec0
ML
2732 if (!(hctx->flags & BLK_MQ_F_STACKING))
2733 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2734 &hctx->cpuhp_online);
7c6c5b7c
ML
2735 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
2736
2737 hctx->tags = set->tags[hctx_idx];
2738
2739 if (set->ops->init_hctx &&
2740 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
2741 goto unregister_cpu_notifier;
08e98fc6 2742
7c6c5b7c
ML
2743 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
2744 hctx->numa_node))
2745 goto exit_hctx;
2746 return 0;
2747
2748 exit_hctx:
2749 if (set->ops->exit_hctx)
2750 set->ops->exit_hctx(hctx, hctx_idx);
2751 unregister_cpu_notifier:
2752 blk_mq_remove_cpuhp(hctx);
2753 return -1;
2754}
2755
2756static struct blk_mq_hw_ctx *
2757blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
2758 int node)
2759{
2760 struct blk_mq_hw_ctx *hctx;
2761 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
2762
2763 hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
2764 if (!hctx)
2765 goto fail_alloc_hctx;
2766
2767 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
2768 goto free_hctx;
2769
2770 atomic_set(&hctx->nr_active, 0);
08e98fc6 2771 if (node == NUMA_NO_NODE)
7c6c5b7c
ML
2772 node = set->numa_node;
2773 hctx->numa_node = node;
08e98fc6 2774
9f993737 2775 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
08e98fc6
ML
2776 spin_lock_init(&hctx->lock);
2777 INIT_LIST_HEAD(&hctx->dispatch);
2778 hctx->queue = q;
51db1c37 2779 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
08e98fc6 2780
2f8f1336
ML
2781 INIT_LIST_HEAD(&hctx->hctx_list);
2782
320ae51f 2783 /*
08e98fc6
ML
2784 * Allocate space for all possible cpus to avoid allocation at
2785 * runtime
320ae51f 2786 */
d904bfa7 2787 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
7c6c5b7c 2788 gfp, node);
08e98fc6 2789 if (!hctx->ctxs)
7c6c5b7c 2790 goto free_cpumask;
320ae51f 2791
5b202853 2792 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
c548e62b 2793 gfp, node, false, false))
08e98fc6 2794 goto free_ctxs;
08e98fc6 2795 hctx->nr_ctx = 0;
320ae51f 2796
5815839b 2797 spin_lock_init(&hctx->dispatch_wait_lock);
eb619fdb
JA
2798 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
2799 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
2800
754a1572 2801 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
f70ced09 2802 if (!hctx->fq)
7c6c5b7c 2803 goto free_bitmap;
320ae51f 2804
6a83e74d 2805 if (hctx->flags & BLK_MQ_F_BLOCKING)
05707b64 2806 init_srcu_struct(hctx->srcu);
7c6c5b7c 2807 blk_mq_hctx_kobj_init(hctx);
6a83e74d 2808
7c6c5b7c 2809 return hctx;
320ae51f 2810
08e98fc6 2811 free_bitmap:
88459642 2812 sbitmap_free(&hctx->ctx_map);
08e98fc6
ML
2813 free_ctxs:
2814 kfree(hctx->ctxs);
7c6c5b7c
ML
2815 free_cpumask:
2816 free_cpumask_var(hctx->cpumask);
2817 free_hctx:
2818 kfree(hctx);
2819 fail_alloc_hctx:
2820 return NULL;
08e98fc6 2821}
320ae51f 2822
320ae51f
JA
2823static void blk_mq_init_cpu_queues(struct request_queue *q,
2824 unsigned int nr_hw_queues)
2825{
b3c661b1
JA
2826 struct blk_mq_tag_set *set = q->tag_set;
2827 unsigned int i, j;
320ae51f
JA
2828
2829 for_each_possible_cpu(i) {
2830 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
2831 struct blk_mq_hw_ctx *hctx;
c16d6b5a 2832 int k;
320ae51f 2833
320ae51f
JA
2834 __ctx->cpu = i;
2835 spin_lock_init(&__ctx->lock);
c16d6b5a
ML
2836 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
2837 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
2838
320ae51f
JA
2839 __ctx->queue = q;
2840
320ae51f
JA
2841 /*
2842 * Set local node, IFF we have more than one hw queue. If
2843 * not, we remain on the home node of the device
2844 */
b3c661b1
JA
2845 for (j = 0; j < set->nr_maps; j++) {
2846 hctx = blk_mq_map_queue_type(q, j, i);
2847 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
576e85c5 2848 hctx->numa_node = cpu_to_node(i);
b3c661b1 2849 }
320ae51f
JA
2850 }
2851}
2852
03b63b02
WZ
2853static bool __blk_mq_alloc_map_and_request(struct blk_mq_tag_set *set,
2854 int hctx_idx)
cc71a6f4 2855{
1c0706a7 2856 unsigned int flags = set->flags;
cc71a6f4
JA
2857 int ret = 0;
2858
2859 set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
1c0706a7 2860 set->queue_depth, set->reserved_tags, flags);
cc71a6f4
JA
2861 if (!set->tags[hctx_idx])
2862 return false;
2863
2864 ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
2865 set->queue_depth);
2866 if (!ret)
2867 return true;
2868
1c0706a7 2869 blk_mq_free_rq_map(set->tags[hctx_idx], flags);
cc71a6f4
JA
2870 set->tags[hctx_idx] = NULL;
2871 return false;
2872}
2873
2874static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2875 unsigned int hctx_idx)
2876{
1c0706a7
JG
2877 unsigned int flags = set->flags;
2878
4e6db0f2 2879 if (set->tags && set->tags[hctx_idx]) {
bd166ef1 2880 blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
1c0706a7 2881 blk_mq_free_rq_map(set->tags[hctx_idx], flags);
bd166ef1
JA
2882 set->tags[hctx_idx] = NULL;
2883 }
cc71a6f4
JA
2884}
2885
4b855ad3 2886static void blk_mq_map_swqueue(struct request_queue *q)
320ae51f 2887{
b3c661b1 2888 unsigned int i, j, hctx_idx;
320ae51f
JA
2889 struct blk_mq_hw_ctx *hctx;
2890 struct blk_mq_ctx *ctx;
2a34c087 2891 struct blk_mq_tag_set *set = q->tag_set;
320ae51f
JA
2892
2893 queue_for_each_hw_ctx(q, hctx, i) {
e4043dcf 2894 cpumask_clear(hctx->cpumask);
320ae51f 2895 hctx->nr_ctx = 0;
d416c92c 2896 hctx->dispatch_from = NULL;
320ae51f
JA
2897 }
2898
2899 /*
4b855ad3 2900 * Map software to hardware queues.
4412efec
ML
2901 *
2902 * If the cpu isn't present, the cpu is mapped to first hctx.
320ae51f 2903 */
20e4d813 2904 for_each_possible_cpu(i) {
4412efec 2905
897bb0c7 2906 ctx = per_cpu_ptr(q->queue_ctx, i);
b3c661b1 2907 for (j = 0; j < set->nr_maps; j++) {
bb94aea1
JW
2908 if (!set->map[j].nr_queues) {
2909 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2910 HCTX_TYPE_DEFAULT, i);
e5edd5f2 2911 continue;
bb94aea1 2912 }
fd689871
ML
2913 hctx_idx = set->map[j].mq_map[i];
2914 /* unmapped hw queue can be remapped after CPU topo changed */
2915 if (!set->tags[hctx_idx] &&
03b63b02 2916 !__blk_mq_alloc_map_and_request(set, hctx_idx)) {
fd689871
ML
2917 /*
2918 * If tags initialization fail for some hctx,
2919 * that hctx won't be brought online. In this
2920 * case, remap the current ctx to hctx[0] which
2921 * is guaranteed to always have tags allocated
2922 */
2923 set->map[j].mq_map[i] = 0;
2924 }
e5edd5f2 2925
b3c661b1 2926 hctx = blk_mq_map_queue_type(q, j, i);
8ccdf4a3 2927 ctx->hctxs[j] = hctx;
b3c661b1
JA
2928 /*
2929 * If the CPU is already set in the mask, then we've
2930 * mapped this one already. This can happen if
2931 * devices share queues across queue maps.
2932 */
2933 if (cpumask_test_cpu(i, hctx->cpumask))
2934 continue;
2935
2936 cpumask_set_cpu(i, hctx->cpumask);
2937 hctx->type = j;
2938 ctx->index_hw[hctx->type] = hctx->nr_ctx;
2939 hctx->ctxs[hctx->nr_ctx++] = ctx;
2940
2941 /*
2942 * If the nr_ctx type overflows, we have exceeded the
2943 * amount of sw queues we can support.
2944 */
2945 BUG_ON(!hctx->nr_ctx);
2946 }
bb94aea1
JW
2947
2948 for (; j < HCTX_MAX_TYPES; j++)
2949 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2950 HCTX_TYPE_DEFAULT, i);
320ae51f 2951 }
506e931f
JA
2952
2953 queue_for_each_hw_ctx(q, hctx, i) {
4412efec
ML
2954 /*
2955 * If no software queues are mapped to this hardware queue,
2956 * disable it and free the request entries.
2957 */
2958 if (!hctx->nr_ctx) {
2959 /* Never unmap queue 0. We need it as a
2960 * fallback in case of a new remap fails
2961 * allocation
2962 */
2963 if (i && set->tags[i])
2964 blk_mq_free_map_and_requests(set, i);
2965
2966 hctx->tags = NULL;
2967 continue;
2968 }
484b4061 2969
2a34c087
ML
2970 hctx->tags = set->tags[i];
2971 WARN_ON(!hctx->tags);
2972
889fa31f
CY
2973 /*
2974 * Set the map size to the number of mapped software queues.
2975 * This is more accurate and more efficient than looping
2976 * over all possibly mapped software queues.
2977 */
88459642 2978 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
889fa31f 2979
484b4061
JA
2980 /*
2981 * Initialize batch roundrobin counts
2982 */
f82ddf19 2983 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
506e931f
JA
2984 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2985 }
320ae51f
JA
2986}
2987
8e8320c9
JA
2988/*
2989 * Caller needs to ensure that we're either frozen/quiesced, or that
2990 * the queue isn't live yet.
2991 */
2404e607 2992static void queue_set_hctx_shared(struct request_queue *q, bool shared)
0d2602ca
JA
2993{
2994 struct blk_mq_hw_ctx *hctx;
0d2602ca
JA
2995 int i;
2996
2404e607 2997 queue_for_each_hw_ctx(q, hctx, i) {
454bb677 2998 if (shared) {
51db1c37 2999 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
454bb677
YK
3000 } else {
3001 blk_mq_tag_idle(hctx);
51db1c37 3002 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
454bb677 3003 }
2404e607
JM
3004 }
3005}
3006
655ac300
HR
3007static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
3008 bool shared)
2404e607
JM
3009{
3010 struct request_queue *q;
0d2602ca 3011
705cda97
BVA
3012 lockdep_assert_held(&set->tag_list_lock);
3013
0d2602ca
JA
3014 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3015 blk_mq_freeze_queue(q);
2404e607 3016 queue_set_hctx_shared(q, shared);
0d2602ca
JA
3017 blk_mq_unfreeze_queue(q);
3018 }
3019}
3020
3021static void blk_mq_del_queue_tag_set(struct request_queue *q)
3022{
3023 struct blk_mq_tag_set *set = q->tag_set;
3024
0d2602ca 3025 mutex_lock(&set->tag_list_lock);
08c875cb 3026 list_del(&q->tag_set_list);
2404e607
JM
3027 if (list_is_singular(&set->tag_list)) {
3028 /* just transitioned to unshared */
51db1c37 3029 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
2404e607 3030 /* update existing queue */
655ac300 3031 blk_mq_update_tag_set_shared(set, false);
2404e607 3032 }
0d2602ca 3033 mutex_unlock(&set->tag_list_lock);
a347c7ad 3034 INIT_LIST_HEAD(&q->tag_set_list);
0d2602ca
JA
3035}
3036
3037static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
3038 struct request_queue *q)
3039{
0d2602ca 3040 mutex_lock(&set->tag_list_lock);
2404e607 3041
ff821d27
JA
3042 /*
3043 * Check to see if we're transitioning to shared (from 1 to 2 queues).
3044 */
3045 if (!list_empty(&set->tag_list) &&
51db1c37
ML
3046 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
3047 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
2404e607 3048 /* update existing queue */
655ac300 3049 blk_mq_update_tag_set_shared(set, true);
2404e607 3050 }
51db1c37 3051 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
2404e607 3052 queue_set_hctx_shared(q, true);
08c875cb 3053 list_add_tail(&q->tag_set_list, &set->tag_list);
2404e607 3054
0d2602ca
JA
3055 mutex_unlock(&set->tag_list_lock);
3056}
3057
1db4909e
ML
3058/* All allocations will be freed in release handler of q->mq_kobj */
3059static int blk_mq_alloc_ctxs(struct request_queue *q)
3060{
3061 struct blk_mq_ctxs *ctxs;
3062 int cpu;
3063
3064 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
3065 if (!ctxs)
3066 return -ENOMEM;
3067
3068 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
3069 if (!ctxs->queue_ctx)
3070 goto fail;
3071
3072 for_each_possible_cpu(cpu) {
3073 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
3074 ctx->ctxs = ctxs;
3075 }
3076
3077 q->mq_kobj = &ctxs->kobj;
3078 q->queue_ctx = ctxs->queue_ctx;
3079
3080 return 0;
3081 fail:
3082 kfree(ctxs);
3083 return -ENOMEM;
3084}
3085
e09aae7e
ML
3086/*
3087 * It is the actual release handler for mq, but we do it from
3088 * request queue's release handler for avoiding use-after-free
3089 * and headache because q->mq_kobj shouldn't have been introduced,
3090 * but we can't group ctx/kctx kobj without it.
3091 */
3092void blk_mq_release(struct request_queue *q)
3093{
2f8f1336
ML
3094 struct blk_mq_hw_ctx *hctx, *next;
3095 int i;
e09aae7e 3096
2f8f1336
ML
3097 queue_for_each_hw_ctx(q, hctx, i)
3098 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
3099
3100 /* all hctx are in .unused_hctx_list now */
3101 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
3102 list_del_init(&hctx->hctx_list);
6c8b232e 3103 kobject_put(&hctx->kobj);
c3b4afca 3104 }
e09aae7e
ML
3105
3106 kfree(q->queue_hw_ctx);
3107
7ea5fe31
ML
3108 /*
3109 * release .mq_kobj and sw queue's kobject now because
3110 * both share lifetime with request queue.
3111 */
3112 blk_mq_sysfs_deinit(q);
e09aae7e
ML
3113}
3114
5ec780a6 3115static struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
2f227bb9 3116 void *queuedata)
b62c21b7 3117{
26a9750a
CH
3118 struct request_queue *q;
3119 int ret;
b62c21b7 3120
26a9750a
CH
3121 q = blk_alloc_queue(set->numa_node);
3122 if (!q)
b62c21b7 3123 return ERR_PTR(-ENOMEM);
26a9750a
CH
3124 q->queuedata = queuedata;
3125 ret = blk_mq_init_allocated_queue(set, q);
3126 if (ret) {
3127 blk_cleanup_queue(q);
3128 return ERR_PTR(ret);
3129 }
b62c21b7
MS
3130 return q;
3131}
2f227bb9
CH
3132
3133struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
3134{
3135 return blk_mq_init_queue_data(set, NULL);
3136}
b62c21b7
MS
3137EXPORT_SYMBOL(blk_mq_init_queue);
3138
4dcc4874
CH
3139struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set, void *queuedata,
3140 struct lock_class_key *lkclass)
9316a9ed
JA
3141{
3142 struct request_queue *q;
b461dfc4 3143 struct gendisk *disk;
9316a9ed 3144
b461dfc4
CH
3145 q = blk_mq_init_queue_data(set, queuedata);
3146 if (IS_ERR(q))
3147 return ERR_CAST(q);
9316a9ed 3148
4a1fa41d 3149 disk = __alloc_disk_node(q, set->numa_node, lkclass);
b461dfc4
CH
3150 if (!disk) {
3151 blk_cleanup_queue(q);
3152 return ERR_PTR(-ENOMEM);
9316a9ed 3153 }
b461dfc4 3154 return disk;
9316a9ed 3155}
b461dfc4 3156EXPORT_SYMBOL(__blk_mq_alloc_disk);
9316a9ed 3157
34d11ffa
JW
3158static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
3159 struct blk_mq_tag_set *set, struct request_queue *q,
3160 int hctx_idx, int node)
3161{
2f8f1336 3162 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
34d11ffa 3163
2f8f1336
ML
3164 /* reuse dead hctx first */
3165 spin_lock(&q->unused_hctx_lock);
3166 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
3167 if (tmp->numa_node == node) {
3168 hctx = tmp;
3169 break;
3170 }
3171 }
3172 if (hctx)
3173 list_del_init(&hctx->hctx_list);
3174 spin_unlock(&q->unused_hctx_lock);
3175
3176 if (!hctx)
3177 hctx = blk_mq_alloc_hctx(q, set, node);
34d11ffa 3178 if (!hctx)
7c6c5b7c 3179 goto fail;
34d11ffa 3180
7c6c5b7c
ML
3181 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
3182 goto free_hctx;
34d11ffa
JW
3183
3184 return hctx;
7c6c5b7c
ML
3185
3186 free_hctx:
3187 kobject_put(&hctx->kobj);
3188 fail:
3189 return NULL;
34d11ffa
JW
3190}
3191
868f2f0b
KB
3192static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
3193 struct request_queue *q)
320ae51f 3194{
e01ad46d 3195 int i, j, end;
868f2f0b 3196 struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
f14bbe77 3197
ac0d6b92
BVA
3198 if (q->nr_hw_queues < set->nr_hw_queues) {
3199 struct blk_mq_hw_ctx **new_hctxs;
3200
3201 new_hctxs = kcalloc_node(set->nr_hw_queues,
3202 sizeof(*new_hctxs), GFP_KERNEL,
3203 set->numa_node);
3204 if (!new_hctxs)
3205 return;
3206 if (hctxs)
3207 memcpy(new_hctxs, hctxs, q->nr_hw_queues *
3208 sizeof(*hctxs));
3209 q->queue_hw_ctx = new_hctxs;
ac0d6b92
BVA
3210 kfree(hctxs);
3211 hctxs = new_hctxs;
3212 }
3213
fb350e0a
ML
3214 /* protect against switching io scheduler */
3215 mutex_lock(&q->sysfs_lock);
24d2f903 3216 for (i = 0; i < set->nr_hw_queues; i++) {
868f2f0b 3217 int node;
34d11ffa 3218 struct blk_mq_hw_ctx *hctx;
868f2f0b 3219
7d76f856 3220 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
34d11ffa
JW
3221 /*
3222 * If the hw queue has been mapped to another numa node,
3223 * we need to realloc the hctx. If allocation fails, fallback
3224 * to use the previous one.
3225 */
3226 if (hctxs[i] && (hctxs[i]->numa_node == node))
3227 continue;
868f2f0b 3228
34d11ffa
JW
3229 hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
3230 if (hctx) {
2f8f1336 3231 if (hctxs[i])
34d11ffa 3232 blk_mq_exit_hctx(q, set, hctxs[i], i);
34d11ffa
JW
3233 hctxs[i] = hctx;
3234 } else {
3235 if (hctxs[i])
3236 pr_warn("Allocate new hctx on node %d fails,\
3237 fallback to previous one on node %d\n",
3238 node, hctxs[i]->numa_node);
3239 else
3240 break;
868f2f0b 3241 }
320ae51f 3242 }
e01ad46d
JW
3243 /*
3244 * Increasing nr_hw_queues fails. Free the newly allocated
3245 * hctxs and keep the previous q->nr_hw_queues.
3246 */
3247 if (i != set->nr_hw_queues) {
3248 j = q->nr_hw_queues;
3249 end = i;
3250 } else {
3251 j = i;
3252 end = q->nr_hw_queues;
3253 q->nr_hw_queues = set->nr_hw_queues;
3254 }
34d11ffa 3255
e01ad46d 3256 for (; j < end; j++) {
868f2f0b
KB
3257 struct blk_mq_hw_ctx *hctx = hctxs[j];
3258
3259 if (hctx) {
cc71a6f4
JA
3260 if (hctx->tags)
3261 blk_mq_free_map_and_requests(set, j);
868f2f0b 3262 blk_mq_exit_hctx(q, set, hctx, j);
868f2f0b 3263 hctxs[j] = NULL;
868f2f0b
KB
3264 }
3265 }
fb350e0a 3266 mutex_unlock(&q->sysfs_lock);
868f2f0b
KB
3267}
3268
26a9750a
CH
3269int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
3270 struct request_queue *q)
868f2f0b 3271{
66841672
ML
3272 /* mark the queue as mq asap */
3273 q->mq_ops = set->ops;
3274
34dbad5d 3275 q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
720b8ccc
SB
3276 blk_mq_poll_stats_bkt,
3277 BLK_MQ_POLL_STATS_BKTS, q);
34dbad5d
OS
3278 if (!q->poll_cb)
3279 goto err_exit;
3280
1db4909e 3281 if (blk_mq_alloc_ctxs(q))
41de54c6 3282 goto err_poll;
868f2f0b 3283
737f98cf
ML
3284 /* init q->mq_kobj and sw queues' kobjects */
3285 blk_mq_sysfs_init(q);
3286
2f8f1336
ML
3287 INIT_LIST_HEAD(&q->unused_hctx_list);
3288 spin_lock_init(&q->unused_hctx_lock);
3289
868f2f0b
KB
3290 blk_mq_realloc_hw_ctxs(set, q);
3291 if (!q->nr_hw_queues)
3292 goto err_hctxs;
320ae51f 3293
287922eb 3294 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
e56f698b 3295 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
320ae51f 3296
a8908939 3297 q->tag_set = set;
320ae51f 3298
94eddfbe 3299 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
cd19181b
ML
3300 if (set->nr_maps > HCTX_TYPE_POLL &&
3301 set->map[HCTX_TYPE_POLL].nr_queues)
6544d229 3302 blk_queue_flag_set(QUEUE_FLAG_POLL, q);
320ae51f 3303
2849450a 3304 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
6fca6a61
CH
3305 INIT_LIST_HEAD(&q->requeue_list);
3306 spin_lock_init(&q->requeue_lock);
3307
eba71768
JA
3308 q->nr_requests = set->queue_depth;
3309
64f1c21e
JA
3310 /*
3311 * Default to classic polling
3312 */
29ece8b4 3313 q->poll_nsec = BLK_MQ_POLL_CLASSIC;
64f1c21e 3314
24d2f903 3315 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
0d2602ca 3316 blk_mq_add_queue_tag_set(set, q);
4b855ad3 3317 blk_mq_map_swqueue(q);
26a9750a 3318 return 0;
18741986 3319
320ae51f 3320err_hctxs:
868f2f0b 3321 kfree(q->queue_hw_ctx);
73d9c8d4 3322 q->nr_hw_queues = 0;
1db4909e 3323 blk_mq_sysfs_deinit(q);
41de54c6
JS
3324err_poll:
3325 blk_stat_free_callback(q->poll_cb);
3326 q->poll_cb = NULL;
c7de5726
ML
3327err_exit:
3328 q->mq_ops = NULL;
26a9750a 3329 return -ENOMEM;
320ae51f 3330}
b62c21b7 3331EXPORT_SYMBOL(blk_mq_init_allocated_queue);
320ae51f 3332
c7e2d94b
ML
3333/* tags can _not_ be used after returning from blk_mq_exit_queue */
3334void blk_mq_exit_queue(struct request_queue *q)
320ae51f 3335{
630ef623 3336 struct blk_mq_tag_set *set = q->tag_set;
320ae51f 3337
630ef623 3338 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
624dbe47 3339 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
630ef623
BVA
3340 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
3341 blk_mq_del_queue_tag_set(q);
320ae51f 3342}
320ae51f 3343
a5164405
JA
3344static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
3345{
3346 int i;
3347
8229cca8 3348 for (i = 0; i < set->nr_hw_queues; i++) {
03b63b02 3349 if (!__blk_mq_alloc_map_and_request(set, i))
a5164405 3350 goto out_unwind;
8229cca8
XT
3351 cond_resched();
3352 }
a5164405
JA
3353
3354 return 0;
3355
3356out_unwind:
3357 while (--i >= 0)
2e194422 3358 blk_mq_free_map_and_requests(set, i);
a5164405 3359
a5164405
JA
3360 return -ENOMEM;
3361}
3362
3363/*
3364 * Allocate the request maps associated with this tag_set. Note that this
3365 * may reduce the depth asked for, if memory is tight. set->queue_depth
3366 * will be updated to reflect the allocated depth.
3367 */
79fab528 3368static int blk_mq_alloc_map_and_requests(struct blk_mq_tag_set *set)
a5164405
JA
3369{
3370 unsigned int depth;
3371 int err;
3372
3373 depth = set->queue_depth;
3374 do {
3375 err = __blk_mq_alloc_rq_maps(set);
3376 if (!err)
3377 break;
3378
3379 set->queue_depth >>= 1;
3380 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
3381 err = -ENOMEM;
3382 break;
3383 }
3384 } while (set->queue_depth);
3385
3386 if (!set->queue_depth || err) {
3387 pr_err("blk-mq: failed to allocate request map\n");
3388 return -ENOMEM;
3389 }
3390
3391 if (depth != set->queue_depth)
3392 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
3393 depth, set->queue_depth);
3394
3395 return 0;
3396}
3397
ebe8bddb
OS
3398static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
3399{
6e66b493
BVA
3400 /*
3401 * blk_mq_map_queues() and multiple .map_queues() implementations
3402 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
3403 * number of hardware queues.
3404 */
3405 if (set->nr_maps == 1)
3406 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
3407
59388702 3408 if (set->ops->map_queues && !is_kdump_kernel()) {
b3c661b1
JA
3409 int i;
3410
7d4901a9
ML
3411 /*
3412 * transport .map_queues is usually done in the following
3413 * way:
3414 *
3415 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
3416 * mask = get_cpu_mask(queue)
3417 * for_each_cpu(cpu, mask)
b3c661b1 3418 * set->map[x].mq_map[cpu] = queue;
7d4901a9
ML
3419 * }
3420 *
3421 * When we need to remap, the table has to be cleared for
3422 * killing stale mapping since one CPU may not be mapped
3423 * to any hw queue.
3424 */
b3c661b1
JA
3425 for (i = 0; i < set->nr_maps; i++)
3426 blk_mq_clear_mq_map(&set->map[i]);
7d4901a9 3427
ebe8bddb 3428 return set->ops->map_queues(set);
b3c661b1
JA
3429 } else {
3430 BUG_ON(set->nr_maps > 1);
7d76f856 3431 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
b3c661b1 3432 }
ebe8bddb
OS
3433}
3434
f7e76dbc
BVA
3435static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
3436 int cur_nr_hw_queues, int new_nr_hw_queues)
3437{
3438 struct blk_mq_tags **new_tags;
3439
3440 if (cur_nr_hw_queues >= new_nr_hw_queues)
3441 return 0;
3442
3443 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
3444 GFP_KERNEL, set->numa_node);
3445 if (!new_tags)
3446 return -ENOMEM;
3447
3448 if (set->tags)
3449 memcpy(new_tags, set->tags, cur_nr_hw_queues *
3450 sizeof(*set->tags));
3451 kfree(set->tags);
3452 set->tags = new_tags;
3453 set->nr_hw_queues = new_nr_hw_queues;
3454
3455 return 0;
3456}
3457
91cdf265
MI
3458static int blk_mq_alloc_tag_set_tags(struct blk_mq_tag_set *set,
3459 int new_nr_hw_queues)
3460{
3461 return blk_mq_realloc_tag_set_tags(set, 0, new_nr_hw_queues);
3462}
3463
a4391c64
JA
3464/*
3465 * Alloc a tag set to be associated with one or more request queues.
3466 * May fail with EINVAL for various error conditions. May adjust the
c018c84f 3467 * requested depth down, if it's too large. In that case, the set
a4391c64
JA
3468 * value will be stored in set->queue_depth.
3469 */
24d2f903
CH
3470int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
3471{
b3c661b1 3472 int i, ret;
da695ba2 3473
205fb5f5
BVA
3474 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
3475
24d2f903
CH
3476 if (!set->nr_hw_queues)
3477 return -EINVAL;
a4391c64 3478 if (!set->queue_depth)
24d2f903
CH
3479 return -EINVAL;
3480 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
3481 return -EINVAL;
3482
7d7e0f90 3483 if (!set->ops->queue_rq)
24d2f903
CH
3484 return -EINVAL;
3485
de148297
ML
3486 if (!set->ops->get_budget ^ !set->ops->put_budget)
3487 return -EINVAL;
3488
a4391c64
JA
3489 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
3490 pr_info("blk-mq: reduced tag depth to %u\n",
3491 BLK_MQ_MAX_DEPTH);
3492 set->queue_depth = BLK_MQ_MAX_DEPTH;
3493 }
24d2f903 3494
b3c661b1
JA
3495 if (!set->nr_maps)
3496 set->nr_maps = 1;
3497 else if (set->nr_maps > HCTX_MAX_TYPES)
3498 return -EINVAL;
3499
6637fadf
SL
3500 /*
3501 * If a crashdump is active, then we are potentially in a very
3502 * memory constrained environment. Limit us to 1 queue and
3503 * 64 tags to prevent using too much memory.
3504 */
3505 if (is_kdump_kernel()) {
3506 set->nr_hw_queues = 1;
59388702 3507 set->nr_maps = 1;
6637fadf
SL
3508 set->queue_depth = min(64U, set->queue_depth);
3509 }
868f2f0b 3510 /*
392546ae
JA
3511 * There is no use for more h/w queues than cpus if we just have
3512 * a single map
868f2f0b 3513 */
392546ae 3514 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
868f2f0b 3515 set->nr_hw_queues = nr_cpu_ids;
6637fadf 3516
91cdf265 3517 if (blk_mq_alloc_tag_set_tags(set, set->nr_hw_queues) < 0)
a5164405 3518 return -ENOMEM;
24d2f903 3519
da695ba2 3520 ret = -ENOMEM;
b3c661b1
JA
3521 for (i = 0; i < set->nr_maps; i++) {
3522 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
07b35eb5 3523 sizeof(set->map[i].mq_map[0]),
b3c661b1
JA
3524 GFP_KERNEL, set->numa_node);
3525 if (!set->map[i].mq_map)
3526 goto out_free_mq_map;
59388702 3527 set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
b3c661b1 3528 }
bdd17e75 3529
ebe8bddb 3530 ret = blk_mq_update_queue_map(set);
da695ba2
CH
3531 if (ret)
3532 goto out_free_mq_map;
3533
79fab528 3534 ret = blk_mq_alloc_map_and_requests(set);
da695ba2 3535 if (ret)
bdd17e75 3536 goto out_free_mq_map;
24d2f903 3537
32bc15af 3538 if (blk_mq_is_sbitmap_shared(set->flags)) {
f1b49fdc
JG
3539 atomic_set(&set->active_queues_shared_sbitmap, 0);
3540
56b68085 3541 if (blk_mq_init_shared_sbitmap(set)) {
32bc15af
JG
3542 ret = -ENOMEM;
3543 goto out_free_mq_rq_maps;
3544 }
3545 }
3546
0d2602ca
JA
3547 mutex_init(&set->tag_list_lock);
3548 INIT_LIST_HEAD(&set->tag_list);
3549
24d2f903 3550 return 0;
bdd17e75 3551
32bc15af
JG
3552out_free_mq_rq_maps:
3553 for (i = 0; i < set->nr_hw_queues; i++)
3554 blk_mq_free_map_and_requests(set, i);
bdd17e75 3555out_free_mq_map:
b3c661b1
JA
3556 for (i = 0; i < set->nr_maps; i++) {
3557 kfree(set->map[i].mq_map);
3558 set->map[i].mq_map = NULL;
3559 }
5676e7b6
RE
3560 kfree(set->tags);
3561 set->tags = NULL;
da695ba2 3562 return ret;
24d2f903
CH
3563}
3564EXPORT_SYMBOL(blk_mq_alloc_tag_set);
3565
cdb14e0f
CH
3566/* allocate and initialize a tagset for a simple single-queue device */
3567int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
3568 const struct blk_mq_ops *ops, unsigned int queue_depth,
3569 unsigned int set_flags)
3570{
3571 memset(set, 0, sizeof(*set));
3572 set->ops = ops;
3573 set->nr_hw_queues = 1;
3574 set->nr_maps = 1;
3575 set->queue_depth = queue_depth;
3576 set->numa_node = NUMA_NO_NODE;
3577 set->flags = set_flags;
3578 return blk_mq_alloc_tag_set(set);
3579}
3580EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
3581
24d2f903
CH
3582void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
3583{
b3c661b1 3584 int i, j;
24d2f903 3585
f7e76dbc 3586 for (i = 0; i < set->nr_hw_queues; i++)
cc71a6f4 3587 blk_mq_free_map_and_requests(set, i);
484b4061 3588
32bc15af
JG
3589 if (blk_mq_is_sbitmap_shared(set->flags))
3590 blk_mq_exit_shared_sbitmap(set);
3591
b3c661b1
JA
3592 for (j = 0; j < set->nr_maps; j++) {
3593 kfree(set->map[j].mq_map);
3594 set->map[j].mq_map = NULL;
3595 }
bdd17e75 3596
981bd189 3597 kfree(set->tags);
5676e7b6 3598 set->tags = NULL;
24d2f903
CH
3599}
3600EXPORT_SYMBOL(blk_mq_free_tag_set);
3601
e3a2b3f9
JA
3602int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
3603{
3604 struct blk_mq_tag_set *set = q->tag_set;
3605 struct blk_mq_hw_ctx *hctx;
3606 int i, ret;
3607
bd166ef1 3608 if (!set)
e3a2b3f9
JA
3609 return -EINVAL;
3610
e5fa8140
AZ
3611 if (q->nr_requests == nr)
3612 return 0;
3613
70f36b60 3614 blk_mq_freeze_queue(q);
24f5a90f 3615 blk_mq_quiesce_queue(q);
70f36b60 3616
e3a2b3f9
JA
3617 ret = 0;
3618 queue_for_each_hw_ctx(q, hctx, i) {
e9137d4b
KB
3619 if (!hctx->tags)
3620 continue;
bd166ef1
JA
3621 /*
3622 * If we're using an MQ scheduler, just update the scheduler
3623 * queue depth. This is similar to what the old code would do.
3624 */
70f36b60 3625 if (!hctx->sched_tags) {
c2e82a23 3626 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
70f36b60 3627 false);
32bc15af
JG
3628 if (!ret && blk_mq_is_sbitmap_shared(set->flags))
3629 blk_mq_tag_resize_shared_sbitmap(set, nr);
70f36b60
JA
3630 } else {
3631 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
3632 nr, true);
d97e594c
JG
3633 if (blk_mq_is_sbitmap_shared(set->flags)) {
3634 hctx->sched_tags->bitmap_tags =
3635 &q->sched_bitmap_tags;
3636 hctx->sched_tags->breserved_tags =
3637 &q->sched_breserved_tags;
3638 }
70f36b60 3639 }
e3a2b3f9
JA
3640 if (ret)
3641 break;
77f1e0a5
JA
3642 if (q->elevator && q->elevator->type->ops.depth_updated)
3643 q->elevator->type->ops.depth_updated(hctx);
e3a2b3f9 3644 }
d97e594c 3645 if (!ret) {
e3a2b3f9 3646 q->nr_requests = nr;
d97e594c
JG
3647 if (q->elevator && blk_mq_is_sbitmap_shared(set->flags))
3648 sbitmap_queue_resize(&q->sched_bitmap_tags,
3649 nr - set->reserved_tags);
3650 }
e3a2b3f9 3651
24f5a90f 3652 blk_mq_unquiesce_queue(q);
70f36b60 3653 blk_mq_unfreeze_queue(q);
70f36b60 3654
e3a2b3f9
JA
3655 return ret;
3656}
3657
d48ece20
JW
3658/*
3659 * request_queue and elevator_type pair.
3660 * It is just used by __blk_mq_update_nr_hw_queues to cache
3661 * the elevator_type associated with a request_queue.
3662 */
3663struct blk_mq_qe_pair {
3664 struct list_head node;
3665 struct request_queue *q;
3666 struct elevator_type *type;
3667};
3668
3669/*
3670 * Cache the elevator_type in qe pair list and switch the
3671 * io scheduler to 'none'
3672 */
3673static bool blk_mq_elv_switch_none(struct list_head *head,
3674 struct request_queue *q)
3675{
3676 struct blk_mq_qe_pair *qe;
3677
3678 if (!q->elevator)
3679 return true;
3680
3681 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
3682 if (!qe)
3683 return false;
3684
3685 INIT_LIST_HEAD(&qe->node);
3686 qe->q = q;
3687 qe->type = q->elevator->type;
3688 list_add(&qe->node, head);
3689
3690 mutex_lock(&q->sysfs_lock);
3691 /*
3692 * After elevator_switch_mq, the previous elevator_queue will be
3693 * released by elevator_release. The reference of the io scheduler
3694 * module get by elevator_get will also be put. So we need to get
3695 * a reference of the io scheduler module here to prevent it to be
3696 * removed.
3697 */
3698 __module_get(qe->type->elevator_owner);
3699 elevator_switch_mq(q, NULL);
3700 mutex_unlock(&q->sysfs_lock);
3701
3702 return true;
3703}
3704
3705static void blk_mq_elv_switch_back(struct list_head *head,
3706 struct request_queue *q)
3707{
3708 struct blk_mq_qe_pair *qe;
3709 struct elevator_type *t = NULL;
3710
3711 list_for_each_entry(qe, head, node)
3712 if (qe->q == q) {
3713 t = qe->type;
3714 break;
3715 }
3716
3717 if (!t)
3718 return;
3719
3720 list_del(&qe->node);
3721 kfree(qe);
3722
3723 mutex_lock(&q->sysfs_lock);
3724 elevator_switch_mq(q, t);
3725 mutex_unlock(&q->sysfs_lock);
3726}
3727
e4dc2b32
KB
3728static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
3729 int nr_hw_queues)
868f2f0b
KB
3730{
3731 struct request_queue *q;
d48ece20 3732 LIST_HEAD(head);
e01ad46d 3733 int prev_nr_hw_queues;
868f2f0b 3734
705cda97
BVA
3735 lockdep_assert_held(&set->tag_list_lock);
3736
392546ae 3737 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
868f2f0b 3738 nr_hw_queues = nr_cpu_ids;
fe35ec58
WZ
3739 if (nr_hw_queues < 1)
3740 return;
3741 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
868f2f0b
KB
3742 return;
3743
3744 list_for_each_entry(q, &set->tag_list, tag_set_list)
3745 blk_mq_freeze_queue(q);
d48ece20
JW
3746 /*
3747 * Switch IO scheduler to 'none', cleaning up the data associated
3748 * with the previous scheduler. We will switch back once we are done
3749 * updating the new sw to hw queue mappings.
3750 */
3751 list_for_each_entry(q, &set->tag_list, tag_set_list)
3752 if (!blk_mq_elv_switch_none(&head, q))
3753 goto switch_back;
868f2f0b 3754
477e19de
JW
3755 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3756 blk_mq_debugfs_unregister_hctxs(q);
3757 blk_mq_sysfs_unregister(q);
3758 }
3759
a2584e43 3760 prev_nr_hw_queues = set->nr_hw_queues;
f7e76dbc
BVA
3761 if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
3762 0)
3763 goto reregister;
3764
868f2f0b 3765 set->nr_hw_queues = nr_hw_queues;
e01ad46d 3766fallback:
aa880ad6 3767 blk_mq_update_queue_map(set);
868f2f0b
KB
3768 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3769 blk_mq_realloc_hw_ctxs(set, q);
e01ad46d
JW
3770 if (q->nr_hw_queues != set->nr_hw_queues) {
3771 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
3772 nr_hw_queues, prev_nr_hw_queues);
3773 set->nr_hw_queues = prev_nr_hw_queues;
7d76f856 3774 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
e01ad46d
JW
3775 goto fallback;
3776 }
477e19de
JW
3777 blk_mq_map_swqueue(q);
3778 }
3779
f7e76dbc 3780reregister:
477e19de
JW
3781 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3782 blk_mq_sysfs_register(q);
3783 blk_mq_debugfs_register_hctxs(q);
868f2f0b
KB
3784 }
3785
d48ece20
JW
3786switch_back:
3787 list_for_each_entry(q, &set->tag_list, tag_set_list)
3788 blk_mq_elv_switch_back(&head, q);
3789
868f2f0b
KB
3790 list_for_each_entry(q, &set->tag_list, tag_set_list)
3791 blk_mq_unfreeze_queue(q);
3792}
e4dc2b32
KB
3793
3794void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
3795{
3796 mutex_lock(&set->tag_list_lock);
3797 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
3798 mutex_unlock(&set->tag_list_lock);
3799}
868f2f0b
KB
3800EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
3801
34dbad5d
OS
3802/* Enable polling stats and return whether they were already enabled. */
3803static bool blk_poll_stats_enable(struct request_queue *q)
3804{
3805 if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
7dfdbc73 3806 blk_queue_flag_test_and_set(QUEUE_FLAG_POLL_STATS, q))
34dbad5d
OS
3807 return true;
3808 blk_stat_add_callback(q, q->poll_cb);
3809 return false;
3810}
3811
3812static void blk_mq_poll_stats_start(struct request_queue *q)
3813{
3814 /*
3815 * We don't arm the callback if polling stats are not enabled or the
3816 * callback is already active.
3817 */
3818 if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3819 blk_stat_is_active(q->poll_cb))
3820 return;
3821
3822 blk_stat_activate_msecs(q->poll_cb, 100);
3823}
3824
3825static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
3826{
3827 struct request_queue *q = cb->data;
720b8ccc 3828 int bucket;
34dbad5d 3829
720b8ccc
SB
3830 for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
3831 if (cb->stat[bucket].nr_samples)
3832 q->poll_stat[bucket] = cb->stat[bucket];
3833 }
34dbad5d
OS
3834}
3835
64f1c21e 3836static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
64f1c21e
JA
3837 struct request *rq)
3838{
64f1c21e 3839 unsigned long ret = 0;
720b8ccc 3840 int bucket;
64f1c21e
JA
3841
3842 /*
3843 * If stats collection isn't on, don't sleep but turn it on for
3844 * future users
3845 */
34dbad5d 3846 if (!blk_poll_stats_enable(q))
64f1c21e
JA
3847 return 0;
3848
64f1c21e
JA
3849 /*
3850 * As an optimistic guess, use half of the mean service time
3851 * for this type of request. We can (and should) make this smarter.
3852 * For instance, if the completion latencies are tight, we can
3853 * get closer than just half the mean. This is especially
3854 * important on devices where the completion latencies are longer
720b8ccc
SB
3855 * than ~10 usec. We do use the stats for the relevant IO size
3856 * if available which does lead to better estimates.
64f1c21e 3857 */
720b8ccc
SB
3858 bucket = blk_mq_poll_stats_bkt(rq);
3859 if (bucket < 0)
3860 return ret;
3861
3862 if (q->poll_stat[bucket].nr_samples)
3863 ret = (q->poll_stat[bucket].mean + 1) / 2;
64f1c21e
JA
3864
3865 return ret;
3866}
3867
06426adf
JA
3868static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
3869 struct request *rq)
3870{
3871 struct hrtimer_sleeper hs;
3872 enum hrtimer_mode mode;
64f1c21e 3873 unsigned int nsecs;
06426adf
JA
3874 ktime_t kt;
3875
76a86f9d 3876 if (rq->rq_flags & RQF_MQ_POLL_SLEPT)
64f1c21e
JA
3877 return false;
3878
3879 /*
1052b8ac 3880 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
64f1c21e 3881 *
64f1c21e
JA
3882 * 0: use half of prev avg
3883 * >0: use this specific value
3884 */
1052b8ac 3885 if (q->poll_nsec > 0)
64f1c21e
JA
3886 nsecs = q->poll_nsec;
3887 else
cae740a0 3888 nsecs = blk_mq_poll_nsecs(q, rq);
64f1c21e
JA
3889
3890 if (!nsecs)
06426adf
JA
3891 return false;
3892
76a86f9d 3893 rq->rq_flags |= RQF_MQ_POLL_SLEPT;
06426adf
JA
3894
3895 /*
3896 * This will be replaced with the stats tracking code, using
3897 * 'avg_completion_time / 2' as the pre-sleep target.
3898 */
8b0e1953 3899 kt = nsecs;
06426adf
JA
3900
3901 mode = HRTIMER_MODE_REL;
dbc1625f 3902 hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
06426adf
JA
3903 hrtimer_set_expires(&hs.timer, kt);
3904
06426adf 3905 do {
5a61c363 3906 if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
06426adf
JA
3907 break;
3908 set_current_state(TASK_UNINTERRUPTIBLE);
9dd8813e 3909 hrtimer_sleeper_start_expires(&hs, mode);
06426adf
JA
3910 if (hs.task)
3911 io_schedule();
3912 hrtimer_cancel(&hs.timer);
3913 mode = HRTIMER_MODE_ABS;
3914 } while (hs.task && !signal_pending(current));
3915
3916 __set_current_state(TASK_RUNNING);
3917 destroy_hrtimer_on_stack(&hs.timer);
3918 return true;
3919}
3920
1052b8ac
JA
3921static bool blk_mq_poll_hybrid(struct request_queue *q,
3922 struct blk_mq_hw_ctx *hctx, blk_qc_t cookie)
bbd7bb70 3923{
1052b8ac
JA
3924 struct request *rq;
3925
29ece8b4 3926 if (q->poll_nsec == BLK_MQ_POLL_CLASSIC)
1052b8ac
JA
3927 return false;
3928
3929 if (!blk_qc_t_is_internal(cookie))
3930 rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
3931 else {
3932 rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
3933 /*
3934 * With scheduling, if the request has completed, we'll
3935 * get a NULL return here, as we clear the sched tag when
3936 * that happens. The request still remains valid, like always,
3937 * so we should be safe with just the NULL check.
3938 */
3939 if (!rq)
3940 return false;
3941 }
3942
cae740a0 3943 return blk_mq_poll_hybrid_sleep(q, rq);
1052b8ac
JA
3944}
3945
529262d5
CH
3946/**
3947 * blk_poll - poll for IO completions
3948 * @q: the queue
3949 * @cookie: cookie passed back at IO submission time
3950 * @spin: whether to spin for completions
3951 *
3952 * Description:
3953 * Poll for completions on the passed in queue. Returns number of
3954 * completed entries found. If @spin is true, then blk_poll will continue
3955 * looping until at least one completion is found, unless the task is
3956 * otherwise marked running (or we need to reschedule).
3957 */
3958int blk_poll(struct request_queue *q, blk_qc_t cookie, bool spin)
1052b8ac
JA
3959{
3960 struct blk_mq_hw_ctx *hctx;
2f064a59 3961 unsigned int state;
bbd7bb70 3962
529262d5
CH
3963 if (!blk_qc_t_valid(cookie) ||
3964 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
1052b8ac
JA
3965 return 0;
3966
529262d5
CH
3967 if (current->plug)
3968 blk_flush_plug_list(current->plug, false);
3969
1052b8ac
JA
3970 hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
3971
06426adf
JA
3972 /*
3973 * If we sleep, have the caller restart the poll loop to reset
3974 * the state. Like for the other success return cases, the
3975 * caller is responsible for checking if the IO completed. If
3976 * the IO isn't complete, we'll get called again and will go
f6f371f7
PB
3977 * straight to the busy poll loop. If specified not to spin,
3978 * we also should not sleep.
06426adf 3979 */
f6f371f7 3980 if (spin && blk_mq_poll_hybrid(q, hctx, cookie))
85f4d4b6 3981 return 1;
06426adf 3982
bbd7bb70
JA
3983 hctx->poll_considered++;
3984
d6c23bb3 3985 state = get_current_state();
aa61bec3 3986 do {
bbd7bb70
JA
3987 int ret;
3988
3989 hctx->poll_invoked++;
3990
9743139c 3991 ret = q->mq_ops->poll(hctx);
bbd7bb70
JA
3992 if (ret > 0) {
3993 hctx->poll_success++;
849a3700 3994 __set_current_state(TASK_RUNNING);
85f4d4b6 3995 return ret;
bbd7bb70
JA
3996 }
3997
3998 if (signal_pending_state(state, current))
849a3700 3999 __set_current_state(TASK_RUNNING);
bbd7bb70 4000
b03fbd4f 4001 if (task_is_running(current))
85f4d4b6 4002 return 1;
0a1b8b87 4003 if (ret < 0 || !spin)
bbd7bb70
JA
4004 break;
4005 cpu_relax();
aa61bec3 4006 } while (!need_resched());
bbd7bb70 4007
67b4110f 4008 __set_current_state(TASK_RUNNING);
85f4d4b6 4009 return 0;
bbd7bb70 4010}
529262d5 4011EXPORT_SYMBOL_GPL(blk_poll);
bbd7bb70 4012
9cf2bab6
JA
4013unsigned int blk_mq_rq_cpu(struct request *rq)
4014{
4015 return rq->mq_ctx->cpu;
4016}
4017EXPORT_SYMBOL(blk_mq_rq_cpu);
4018
320ae51f
JA
4019static int __init blk_mq_init(void)
4020{
c3077b5d
CH
4021 int i;
4022
4023 for_each_possible_cpu(i)
f9ab4918 4024 init_llist_head(&per_cpu(blk_cpu_done, i));
c3077b5d
CH
4025 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
4026
4027 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
4028 "block/softirq:dead", NULL,
4029 blk_softirq_cpu_dead);
9467f859
TG
4030 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
4031 blk_mq_hctx_notify_dead);
bf0beec0
ML
4032 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
4033 blk_mq_hctx_notify_online,
4034 blk_mq_hctx_notify_offline);
320ae51f
JA
4035 return 0;
4036}
4037subsys_initcall(blk_mq_init);