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