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