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