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