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