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