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