]> git.ipfire.org Git - thirdparty/linux.git/blob - block/blk-mq.c
74ebab41f7d2a8c03673b90e8577f7f07b453b56
[thirdparty/linux.git] / block / blk-mq.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Block multiqueue core code
4 *
5 * Copyright (C) 2013-2014 Jens Axboe
6 * Copyright (C) 2013-2014 Christoph Hellwig
7 */
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>
13 #include <linux/kmemleak.h>
14 #include <linux/mm.h>
15 #include <linux/init.h>
16 #include <linux/slab.h>
17 #include <linux/workqueue.h>
18 #include <linux/smp.h>
19 #include <linux/llist.h>
20 #include <linux/list_sort.h>
21 #include <linux/cpu.h>
22 #include <linux/cache.h>
23 #include <linux/sched/sysctl.h>
24 #include <linux/sched/topology.h>
25 #include <linux/sched/signal.h>
26 #include <linux/delay.h>
27 #include <linux/crash_dump.h>
28 #include <linux/prefetch.h>
29 #include <linux/blk-crypto.h>
30
31 #include <trace/events/block.h>
32
33 #include <linux/blk-mq.h>
34 #include <linux/t10-pi.h>
35 #include "blk.h"
36 #include "blk-mq.h"
37 #include "blk-mq-debugfs.h"
38 #include "blk-mq-tag.h"
39 #include "blk-pm.h"
40 #include "blk-stat.h"
41 #include "blk-mq-sched.h"
42 #include "blk-rq-qos.h"
43
44 static void blk_mq_poll_stats_start(struct request_queue *q);
45 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
46
47 static int blk_mq_poll_stats_bkt(const struct request *rq)
48 {
49 int ddir, sectors, bucket;
50
51 ddir = rq_data_dir(rq);
52 sectors = blk_rq_stats_sectors(rq);
53
54 bucket = ddir + 2 * ilog2(sectors);
55
56 if (bucket < 0)
57 return -1;
58 else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
59 return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
60
61 return bucket;
62 }
63
64 /*
65 * Check if any of the ctx, dispatch list or elevator
66 * have pending work in this hardware queue.
67 */
68 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
69 {
70 return !list_empty_careful(&hctx->dispatch) ||
71 sbitmap_any_bit_set(&hctx->ctx_map) ||
72 blk_mq_sched_has_work(hctx);
73 }
74
75 /*
76 * Mark this ctx as having pending work in this hardware queue
77 */
78 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
79 struct blk_mq_ctx *ctx)
80 {
81 const int bit = ctx->index_hw[hctx->type];
82
83 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
84 sbitmap_set_bit(&hctx->ctx_map, bit);
85 }
86
87 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
88 struct blk_mq_ctx *ctx)
89 {
90 const int bit = ctx->index_hw[hctx->type];
91
92 sbitmap_clear_bit(&hctx->ctx_map, bit);
93 }
94
95 struct mq_inflight {
96 struct hd_struct *part;
97 unsigned int inflight[2];
98 };
99
100 static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
101 struct request *rq, void *priv,
102 bool reserved)
103 {
104 struct mq_inflight *mi = priv;
105
106 if (rq->part == mi->part)
107 mi->inflight[rq_data_dir(rq)]++;
108
109 return true;
110 }
111
112 unsigned int blk_mq_in_flight(struct request_queue *q, struct hd_struct *part)
113 {
114 struct mq_inflight mi = { .part = part };
115
116 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
117
118 return mi.inflight[0] + mi.inflight[1];
119 }
120
121 void blk_mq_in_flight_rw(struct request_queue *q, struct hd_struct *part,
122 unsigned int inflight[2])
123 {
124 struct mq_inflight mi = { .part = part };
125
126 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
127 inflight[0] = mi.inflight[0];
128 inflight[1] = mi.inflight[1];
129 }
130
131 void blk_freeze_queue_start(struct request_queue *q)
132 {
133 mutex_lock(&q->mq_freeze_lock);
134 if (++q->mq_freeze_depth == 1) {
135 percpu_ref_kill(&q->q_usage_counter);
136 mutex_unlock(&q->mq_freeze_lock);
137 if (queue_is_mq(q))
138 blk_mq_run_hw_queues(q, false);
139 } else {
140 mutex_unlock(&q->mq_freeze_lock);
141 }
142 }
143 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
144
145 void blk_mq_freeze_queue_wait(struct request_queue *q)
146 {
147 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
148 }
149 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
150
151 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
152 unsigned long timeout)
153 {
154 return wait_event_timeout(q->mq_freeze_wq,
155 percpu_ref_is_zero(&q->q_usage_counter),
156 timeout);
157 }
158 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
159
160 /*
161 * Guarantee no request is in use, so we can change any data structure of
162 * the queue afterward.
163 */
164 void blk_freeze_queue(struct request_queue *q)
165 {
166 /*
167 * In the !blk_mq case we are only calling this to kill the
168 * q_usage_counter, otherwise this increases the freeze depth
169 * and waits for it to return to zero. For this reason there is
170 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
171 * exported to drivers as the only user for unfreeze is blk_mq.
172 */
173 blk_freeze_queue_start(q);
174 blk_mq_freeze_queue_wait(q);
175 }
176
177 void blk_mq_freeze_queue(struct request_queue *q)
178 {
179 /*
180 * ...just an alias to keep freeze and unfreeze actions balanced
181 * in the blk_mq_* namespace
182 */
183 blk_freeze_queue(q);
184 }
185 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
186
187 void blk_mq_unfreeze_queue(struct request_queue *q)
188 {
189 mutex_lock(&q->mq_freeze_lock);
190 q->mq_freeze_depth--;
191 WARN_ON_ONCE(q->mq_freeze_depth < 0);
192 if (!q->mq_freeze_depth) {
193 percpu_ref_resurrect(&q->q_usage_counter);
194 wake_up_all(&q->mq_freeze_wq);
195 }
196 mutex_unlock(&q->mq_freeze_lock);
197 }
198 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
199
200 /*
201 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
202 * mpt3sas driver such that this function can be removed.
203 */
204 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
205 {
206 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
207 }
208 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
209
210 /**
211 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
212 * @q: request queue.
213 *
214 * Note: this function does not prevent that the struct request end_io()
215 * callback function is invoked. Once this function is returned, we make
216 * sure no dispatch can happen until the queue is unquiesced via
217 * blk_mq_unquiesce_queue().
218 */
219 void blk_mq_quiesce_queue(struct request_queue *q)
220 {
221 struct blk_mq_hw_ctx *hctx;
222 unsigned int i;
223 bool rcu = false;
224
225 blk_mq_quiesce_queue_nowait(q);
226
227 queue_for_each_hw_ctx(q, hctx, i) {
228 if (hctx->flags & BLK_MQ_F_BLOCKING)
229 synchronize_srcu(hctx->srcu);
230 else
231 rcu = true;
232 }
233 if (rcu)
234 synchronize_rcu();
235 }
236 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
237
238 /*
239 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
240 * @q: request queue.
241 *
242 * This function recovers queue into the state before quiescing
243 * which is done by blk_mq_quiesce_queue.
244 */
245 void blk_mq_unquiesce_queue(struct request_queue *q)
246 {
247 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
248
249 /* dispatch requests which are inserted during quiescing */
250 blk_mq_run_hw_queues(q, true);
251 }
252 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
253
254 void blk_mq_wake_waiters(struct request_queue *q)
255 {
256 struct blk_mq_hw_ctx *hctx;
257 unsigned int i;
258
259 queue_for_each_hw_ctx(q, hctx, i)
260 if (blk_mq_hw_queue_mapped(hctx))
261 blk_mq_tag_wakeup_all(hctx->tags, true);
262 }
263
264 /*
265 * Only need start/end time stamping if we have iostat or
266 * blk stats enabled, or using an IO scheduler.
267 */
268 static inline bool blk_mq_need_time_stamp(struct request *rq)
269 {
270 return (rq->rq_flags & (RQF_IO_STAT | RQF_STATS)) || rq->q->elevator;
271 }
272
273 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
274 unsigned int tag, unsigned int op, u64 alloc_time_ns)
275 {
276 struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
277 struct request *rq = tags->static_rqs[tag];
278 req_flags_t rq_flags = 0;
279
280 if (data->flags & BLK_MQ_REQ_INTERNAL) {
281 rq->tag = -1;
282 rq->internal_tag = tag;
283 } else {
284 if (data->hctx->flags & BLK_MQ_F_TAG_SHARED) {
285 rq_flags = RQF_MQ_INFLIGHT;
286 atomic_inc(&data->hctx->nr_active);
287 }
288 rq->tag = tag;
289 rq->internal_tag = -1;
290 data->hctx->tags->rqs[rq->tag] = rq;
291 }
292
293 /* csd/requeue_work/fifo_time is initialized before use */
294 rq->q = data->q;
295 rq->mq_ctx = data->ctx;
296 rq->mq_hctx = data->hctx;
297 rq->rq_flags = rq_flags;
298 rq->cmd_flags = op;
299 if (data->flags & BLK_MQ_REQ_PREEMPT)
300 rq->rq_flags |= RQF_PREEMPT;
301 if (blk_queue_io_stat(data->q))
302 rq->rq_flags |= RQF_IO_STAT;
303 INIT_LIST_HEAD(&rq->queuelist);
304 INIT_HLIST_NODE(&rq->hash);
305 RB_CLEAR_NODE(&rq->rb_node);
306 rq->rq_disk = NULL;
307 rq->part = NULL;
308 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
309 rq->alloc_time_ns = alloc_time_ns;
310 #endif
311 if (blk_mq_need_time_stamp(rq))
312 rq->start_time_ns = ktime_get_ns();
313 else
314 rq->start_time_ns = 0;
315 rq->io_start_time_ns = 0;
316 rq->stats_sectors = 0;
317 rq->nr_phys_segments = 0;
318 #if defined(CONFIG_BLK_DEV_INTEGRITY)
319 rq->nr_integrity_segments = 0;
320 #endif
321 blk_crypto_rq_set_defaults(rq);
322 /* tag was already set */
323 WRITE_ONCE(rq->deadline, 0);
324
325 rq->timeout = 0;
326
327 rq->end_io = NULL;
328 rq->end_io_data = NULL;
329
330 data->ctx->rq_dispatched[op_is_sync(op)]++;
331 refcount_set(&rq->ref, 1);
332 return rq;
333 }
334
335 static struct request *__blk_mq_alloc_request(struct blk_mq_alloc_data *data)
336 {
337 struct request_queue *q = data->q;
338 struct elevator_queue *e = q->elevator;
339 struct request *rq;
340 unsigned int tag;
341 bool clear_ctx_on_error = false;
342 u64 alloc_time_ns = 0;
343
344 /* alloc_time includes depth and tag waits */
345 if (blk_queue_rq_alloc_time(q))
346 alloc_time_ns = ktime_get_ns();
347
348 if (likely(!data->ctx)) {
349 data->ctx = blk_mq_get_ctx(q);
350 clear_ctx_on_error = true;
351 }
352 if (likely(!data->hctx))
353 data->hctx = blk_mq_map_queue(q, data->cmd_flags,
354 data->ctx);
355 if (data->cmd_flags & REQ_NOWAIT)
356 data->flags |= BLK_MQ_REQ_NOWAIT;
357
358 if (e) {
359 data->flags |= BLK_MQ_REQ_INTERNAL;
360
361 /*
362 * Flush requests are special and go directly to the
363 * dispatch list. Don't include reserved tags in the
364 * limiting, as it isn't useful.
365 */
366 if (!op_is_flush(data->cmd_flags) &&
367 e->type->ops.limit_depth &&
368 !(data->flags & BLK_MQ_REQ_RESERVED))
369 e->type->ops.limit_depth(data->cmd_flags, data);
370 } else {
371 blk_mq_tag_busy(data->hctx);
372 }
373
374 tag = blk_mq_get_tag(data);
375 if (tag == BLK_MQ_TAG_FAIL) {
376 if (clear_ctx_on_error)
377 data->ctx = NULL;
378 return NULL;
379 }
380
381 rq = blk_mq_rq_ctx_init(data, tag, data->cmd_flags, alloc_time_ns);
382 if (!op_is_flush(data->cmd_flags)) {
383 rq->elv.icq = NULL;
384 if (e && e->type->ops.prepare_request) {
385 if (e->type->icq_cache)
386 blk_mq_sched_assign_ioc(rq);
387
388 e->type->ops.prepare_request(rq);
389 rq->rq_flags |= RQF_ELVPRIV;
390 }
391 }
392 data->hctx->queued++;
393 return rq;
394 }
395
396 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
397 blk_mq_req_flags_t flags)
398 {
399 struct blk_mq_alloc_data data = {
400 .q = q,
401 .flags = flags,
402 .cmd_flags = op,
403 };
404 struct request *rq;
405 int ret;
406
407 ret = blk_queue_enter(q, flags);
408 if (ret)
409 return ERR_PTR(ret);
410
411 rq = __blk_mq_alloc_request(&data);
412 if (!rq)
413 goto out_queue_exit;
414 rq->__data_len = 0;
415 rq->__sector = (sector_t) -1;
416 rq->bio = rq->biotail = NULL;
417 return rq;
418 out_queue_exit:
419 blk_queue_exit(q);
420 return ERR_PTR(-EWOULDBLOCK);
421 }
422 EXPORT_SYMBOL(blk_mq_alloc_request);
423
424 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
425 unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
426 {
427 struct blk_mq_alloc_data data = {
428 .q = q,
429 .flags = flags,
430 .cmd_flags = op,
431 };
432 struct request *rq;
433 unsigned int cpu;
434 int ret;
435
436 /*
437 * If the tag allocator sleeps we could get an allocation for a
438 * different hardware context. No need to complicate the low level
439 * allocator for this for the rare use case of a command tied to
440 * a specific queue.
441 */
442 if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)))
443 return ERR_PTR(-EINVAL);
444
445 if (hctx_idx >= q->nr_hw_queues)
446 return ERR_PTR(-EIO);
447
448 ret = blk_queue_enter(q, flags);
449 if (ret)
450 return ERR_PTR(ret);
451
452 /*
453 * Check if the hardware context is actually mapped to anything.
454 * If not tell the caller that it should skip this queue.
455 */
456 ret = -EXDEV;
457 data.hctx = q->queue_hw_ctx[hctx_idx];
458 if (!blk_mq_hw_queue_mapped(data.hctx))
459 goto out_queue_exit;
460 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
461 data.ctx = __blk_mq_get_ctx(q, cpu);
462
463 ret = -EWOULDBLOCK;
464 rq = __blk_mq_alloc_request(&data);
465 if (!rq)
466 goto out_queue_exit;
467 return rq;
468 out_queue_exit:
469 blk_queue_exit(q);
470 return ERR_PTR(ret);
471 }
472 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
473
474 static void __blk_mq_free_request(struct request *rq)
475 {
476 struct request_queue *q = rq->q;
477 struct blk_mq_ctx *ctx = rq->mq_ctx;
478 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
479 const int sched_tag = rq->internal_tag;
480
481 blk_crypto_free_request(rq);
482 blk_pm_mark_last_busy(rq);
483 rq->mq_hctx = NULL;
484 if (rq->tag != -1)
485 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
486 if (sched_tag != -1)
487 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
488 blk_mq_sched_restart(hctx);
489 blk_queue_exit(q);
490 }
491
492 void blk_mq_free_request(struct request *rq)
493 {
494 struct request_queue *q = rq->q;
495 struct elevator_queue *e = q->elevator;
496 struct blk_mq_ctx *ctx = rq->mq_ctx;
497 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
498
499 if (rq->rq_flags & RQF_ELVPRIV) {
500 if (e && e->type->ops.finish_request)
501 e->type->ops.finish_request(rq);
502 if (rq->elv.icq) {
503 put_io_context(rq->elv.icq->ioc);
504 rq->elv.icq = NULL;
505 }
506 }
507
508 ctx->rq_completed[rq_is_sync(rq)]++;
509 if (rq->rq_flags & RQF_MQ_INFLIGHT)
510 atomic_dec(&hctx->nr_active);
511
512 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
513 laptop_io_completion(q->backing_dev_info);
514
515 rq_qos_done(q, rq);
516
517 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
518 if (refcount_dec_and_test(&rq->ref))
519 __blk_mq_free_request(rq);
520 }
521 EXPORT_SYMBOL_GPL(blk_mq_free_request);
522
523 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
524 {
525 u64 now = 0;
526
527 if (blk_mq_need_time_stamp(rq))
528 now = ktime_get_ns();
529
530 if (rq->rq_flags & RQF_STATS) {
531 blk_mq_poll_stats_start(rq->q);
532 blk_stat_add(rq, now);
533 }
534
535 if (rq->internal_tag != -1)
536 blk_mq_sched_completed_request(rq, now);
537
538 blk_account_io_done(rq, now);
539
540 if (rq->end_io) {
541 rq_qos_done(rq->q, rq);
542 rq->end_io(rq, error);
543 } else {
544 blk_mq_free_request(rq);
545 }
546 }
547 EXPORT_SYMBOL(__blk_mq_end_request);
548
549 void blk_mq_end_request(struct request *rq, blk_status_t error)
550 {
551 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
552 BUG();
553 __blk_mq_end_request(rq, error);
554 }
555 EXPORT_SYMBOL(blk_mq_end_request);
556
557 static void __blk_mq_complete_request_remote(void *data)
558 {
559 struct request *rq = data;
560 struct request_queue *q = rq->q;
561
562 q->mq_ops->complete(rq);
563 }
564
565 /**
566 * blk_mq_force_complete_rq() - Force complete the request, bypassing any error
567 * injection that could drop the completion.
568 * @rq: Request to be force completed
569 *
570 * Drivers should use blk_mq_complete_request() to complete requests in their
571 * normal IO path. For timeout error recovery, drivers may call this forced
572 * completion routine after they've reclaimed timed out requests to bypass
573 * potentially subsequent fake timeouts.
574 */
575 void blk_mq_force_complete_rq(struct request *rq)
576 {
577 struct blk_mq_ctx *ctx = rq->mq_ctx;
578 struct request_queue *q = rq->q;
579 bool shared = false;
580 int cpu;
581
582 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
583 /*
584 * Most of single queue controllers, there is only one irq vector
585 * for handling IO completion, and the only irq's affinity is set
586 * as all possible CPUs. On most of ARCHs, this affinity means the
587 * irq is handled on one specific CPU.
588 *
589 * So complete IO reqeust in softirq context in case of single queue
590 * for not degrading IO performance by irqsoff latency.
591 */
592 if (q->nr_hw_queues == 1) {
593 __blk_complete_request(rq);
594 return;
595 }
596
597 /*
598 * For a polled request, always complete locallly, it's pointless
599 * to redirect the completion.
600 */
601 if ((rq->cmd_flags & REQ_HIPRI) ||
602 !test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags)) {
603 q->mq_ops->complete(rq);
604 return;
605 }
606
607 cpu = get_cpu();
608 if (!test_bit(QUEUE_FLAG_SAME_FORCE, &q->queue_flags))
609 shared = cpus_share_cache(cpu, ctx->cpu);
610
611 if (cpu != ctx->cpu && !shared && cpu_online(ctx->cpu)) {
612 rq->csd.func = __blk_mq_complete_request_remote;
613 rq->csd.info = rq;
614 rq->csd.flags = 0;
615 smp_call_function_single_async(ctx->cpu, &rq->csd);
616 } else {
617 q->mq_ops->complete(rq);
618 }
619 put_cpu();
620 }
621 EXPORT_SYMBOL_GPL(blk_mq_force_complete_rq);
622
623 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
624 __releases(hctx->srcu)
625 {
626 if (!(hctx->flags & BLK_MQ_F_BLOCKING))
627 rcu_read_unlock();
628 else
629 srcu_read_unlock(hctx->srcu, srcu_idx);
630 }
631
632 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
633 __acquires(hctx->srcu)
634 {
635 if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
636 /* shut up gcc false positive */
637 *srcu_idx = 0;
638 rcu_read_lock();
639 } else
640 *srcu_idx = srcu_read_lock(hctx->srcu);
641 }
642
643 /**
644 * blk_mq_complete_request - end I/O on a request
645 * @rq: the request being processed
646 *
647 * Description:
648 * Ends all I/O on a request. It does not handle partial completions.
649 * The actual completion happens out-of-order, through a IPI handler.
650 **/
651 bool blk_mq_complete_request(struct request *rq)
652 {
653 if (unlikely(blk_should_fake_timeout(rq->q)))
654 return false;
655 blk_mq_force_complete_rq(rq);
656 return true;
657 }
658 EXPORT_SYMBOL(blk_mq_complete_request);
659
660 /**
661 * blk_mq_start_request - Start processing a request
662 * @rq: Pointer to request to be started
663 *
664 * Function used by device drivers to notify the block layer that a request
665 * is going to be processed now, so blk layer can do proper initializations
666 * such as starting the timeout timer.
667 */
668 void blk_mq_start_request(struct request *rq)
669 {
670 struct request_queue *q = rq->q;
671
672 trace_block_rq_issue(q, rq);
673
674 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
675 rq->io_start_time_ns = ktime_get_ns();
676 rq->stats_sectors = blk_rq_sectors(rq);
677 rq->rq_flags |= RQF_STATS;
678 rq_qos_issue(q, rq);
679 }
680
681 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
682
683 blk_add_timer(rq);
684 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
685
686 #ifdef CONFIG_BLK_DEV_INTEGRITY
687 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
688 q->integrity.profile->prepare_fn(rq);
689 #endif
690 }
691 EXPORT_SYMBOL(blk_mq_start_request);
692
693 static void __blk_mq_requeue_request(struct request *rq)
694 {
695 struct request_queue *q = rq->q;
696
697 blk_mq_put_driver_tag(rq);
698
699 trace_block_rq_requeue(q, rq);
700 rq_qos_requeue(q, rq);
701
702 if (blk_mq_request_started(rq)) {
703 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
704 rq->rq_flags &= ~RQF_TIMED_OUT;
705 }
706 }
707
708 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
709 {
710 __blk_mq_requeue_request(rq);
711
712 /* this request will be re-inserted to io scheduler queue */
713 blk_mq_sched_requeue_request(rq);
714
715 BUG_ON(!list_empty(&rq->queuelist));
716 blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
717 }
718 EXPORT_SYMBOL(blk_mq_requeue_request);
719
720 static void blk_mq_requeue_work(struct work_struct *work)
721 {
722 struct request_queue *q =
723 container_of(work, struct request_queue, requeue_work.work);
724 LIST_HEAD(rq_list);
725 struct request *rq, *next;
726
727 spin_lock_irq(&q->requeue_lock);
728 list_splice_init(&q->requeue_list, &rq_list);
729 spin_unlock_irq(&q->requeue_lock);
730
731 list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
732 if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
733 continue;
734
735 rq->rq_flags &= ~RQF_SOFTBARRIER;
736 list_del_init(&rq->queuelist);
737 /*
738 * If RQF_DONTPREP, rq has contained some driver specific
739 * data, so insert it to hctx dispatch list to avoid any
740 * merge.
741 */
742 if (rq->rq_flags & RQF_DONTPREP)
743 blk_mq_request_bypass_insert(rq, false, false);
744 else
745 blk_mq_sched_insert_request(rq, true, false, false);
746 }
747
748 while (!list_empty(&rq_list)) {
749 rq = list_entry(rq_list.next, struct request, queuelist);
750 list_del_init(&rq->queuelist);
751 blk_mq_sched_insert_request(rq, false, false, false);
752 }
753
754 blk_mq_run_hw_queues(q, false);
755 }
756
757 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
758 bool kick_requeue_list)
759 {
760 struct request_queue *q = rq->q;
761 unsigned long flags;
762
763 /*
764 * We abuse this flag that is otherwise used by the I/O scheduler to
765 * request head insertion from the workqueue.
766 */
767 BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
768
769 spin_lock_irqsave(&q->requeue_lock, flags);
770 if (at_head) {
771 rq->rq_flags |= RQF_SOFTBARRIER;
772 list_add(&rq->queuelist, &q->requeue_list);
773 } else {
774 list_add_tail(&rq->queuelist, &q->requeue_list);
775 }
776 spin_unlock_irqrestore(&q->requeue_lock, flags);
777
778 if (kick_requeue_list)
779 blk_mq_kick_requeue_list(q);
780 }
781
782 void blk_mq_kick_requeue_list(struct request_queue *q)
783 {
784 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
785 }
786 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
787
788 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
789 unsigned long msecs)
790 {
791 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
792 msecs_to_jiffies(msecs));
793 }
794 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
795
796 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
797 {
798 if (tag < tags->nr_tags) {
799 prefetch(tags->rqs[tag]);
800 return tags->rqs[tag];
801 }
802
803 return NULL;
804 }
805 EXPORT_SYMBOL(blk_mq_tag_to_rq);
806
807 static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
808 void *priv, bool reserved)
809 {
810 /*
811 * If we find a request that is inflight and the queue matches,
812 * we know the queue is busy. Return false to stop the iteration.
813 */
814 if (rq->state == MQ_RQ_IN_FLIGHT && rq->q == hctx->queue) {
815 bool *busy = priv;
816
817 *busy = true;
818 return false;
819 }
820
821 return true;
822 }
823
824 bool blk_mq_queue_inflight(struct request_queue *q)
825 {
826 bool busy = false;
827
828 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
829 return busy;
830 }
831 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
832
833 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
834 {
835 req->rq_flags |= RQF_TIMED_OUT;
836 if (req->q->mq_ops->timeout) {
837 enum blk_eh_timer_return ret;
838
839 ret = req->q->mq_ops->timeout(req, reserved);
840 if (ret == BLK_EH_DONE)
841 return;
842 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
843 }
844
845 blk_add_timer(req);
846 }
847
848 static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
849 {
850 unsigned long deadline;
851
852 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
853 return false;
854 if (rq->rq_flags & RQF_TIMED_OUT)
855 return false;
856
857 deadline = READ_ONCE(rq->deadline);
858 if (time_after_eq(jiffies, deadline))
859 return true;
860
861 if (*next == 0)
862 *next = deadline;
863 else if (time_after(*next, deadline))
864 *next = deadline;
865 return false;
866 }
867
868 static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
869 struct request *rq, void *priv, bool reserved)
870 {
871 unsigned long *next = priv;
872
873 /*
874 * Just do a quick check if it is expired before locking the request in
875 * so we're not unnecessarilly synchronizing across CPUs.
876 */
877 if (!blk_mq_req_expired(rq, next))
878 return true;
879
880 /*
881 * We have reason to believe the request may be expired. Take a
882 * reference on the request to lock this request lifetime into its
883 * currently allocated context to prevent it from being reallocated in
884 * the event the completion by-passes this timeout handler.
885 *
886 * If the reference was already released, then the driver beat the
887 * timeout handler to posting a natural completion.
888 */
889 if (!refcount_inc_not_zero(&rq->ref))
890 return true;
891
892 /*
893 * The request is now locked and cannot be reallocated underneath the
894 * timeout handler's processing. Re-verify this exact request is truly
895 * expired; if it is not expired, then the request was completed and
896 * reallocated as a new request.
897 */
898 if (blk_mq_req_expired(rq, next))
899 blk_mq_rq_timed_out(rq, reserved);
900
901 if (is_flush_rq(rq, hctx))
902 rq->end_io(rq, 0);
903 else if (refcount_dec_and_test(&rq->ref))
904 __blk_mq_free_request(rq);
905
906 return true;
907 }
908
909 static void blk_mq_timeout_work(struct work_struct *work)
910 {
911 struct request_queue *q =
912 container_of(work, struct request_queue, timeout_work);
913 unsigned long next = 0;
914 struct blk_mq_hw_ctx *hctx;
915 int i;
916
917 /* A deadlock might occur if a request is stuck requiring a
918 * timeout at the same time a queue freeze is waiting
919 * completion, since the timeout code would not be able to
920 * acquire the queue reference here.
921 *
922 * That's why we don't use blk_queue_enter here; instead, we use
923 * percpu_ref_tryget directly, because we need to be able to
924 * obtain a reference even in the short window between the queue
925 * starting to freeze, by dropping the first reference in
926 * blk_freeze_queue_start, and the moment the last request is
927 * consumed, marked by the instant q_usage_counter reaches
928 * zero.
929 */
930 if (!percpu_ref_tryget(&q->q_usage_counter))
931 return;
932
933 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
934
935 if (next != 0) {
936 mod_timer(&q->timeout, next);
937 } else {
938 /*
939 * Request timeouts are handled as a forward rolling timer. If
940 * we end up here it means that no requests are pending and
941 * also that no request has been pending for a while. Mark
942 * each hctx as idle.
943 */
944 queue_for_each_hw_ctx(q, hctx, i) {
945 /* the hctx may be unmapped, so check it here */
946 if (blk_mq_hw_queue_mapped(hctx))
947 blk_mq_tag_idle(hctx);
948 }
949 }
950 blk_queue_exit(q);
951 }
952
953 struct flush_busy_ctx_data {
954 struct blk_mq_hw_ctx *hctx;
955 struct list_head *list;
956 };
957
958 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
959 {
960 struct flush_busy_ctx_data *flush_data = data;
961 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
962 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
963 enum hctx_type type = hctx->type;
964
965 spin_lock(&ctx->lock);
966 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
967 sbitmap_clear_bit(sb, bitnr);
968 spin_unlock(&ctx->lock);
969 return true;
970 }
971
972 /*
973 * Process software queues that have been marked busy, splicing them
974 * to the for-dispatch
975 */
976 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
977 {
978 struct flush_busy_ctx_data data = {
979 .hctx = hctx,
980 .list = list,
981 };
982
983 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
984 }
985 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
986
987 struct dispatch_rq_data {
988 struct blk_mq_hw_ctx *hctx;
989 struct request *rq;
990 };
991
992 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
993 void *data)
994 {
995 struct dispatch_rq_data *dispatch_data = data;
996 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
997 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
998 enum hctx_type type = hctx->type;
999
1000 spin_lock(&ctx->lock);
1001 if (!list_empty(&ctx->rq_lists[type])) {
1002 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1003 list_del_init(&dispatch_data->rq->queuelist);
1004 if (list_empty(&ctx->rq_lists[type]))
1005 sbitmap_clear_bit(sb, bitnr);
1006 }
1007 spin_unlock(&ctx->lock);
1008
1009 return !dispatch_data->rq;
1010 }
1011
1012 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1013 struct blk_mq_ctx *start)
1014 {
1015 unsigned off = start ? start->index_hw[hctx->type] : 0;
1016 struct dispatch_rq_data data = {
1017 .hctx = hctx,
1018 .rq = NULL,
1019 };
1020
1021 __sbitmap_for_each_set(&hctx->ctx_map, off,
1022 dispatch_rq_from_ctx, &data);
1023
1024 return data.rq;
1025 }
1026
1027 static inline unsigned int queued_to_index(unsigned int queued)
1028 {
1029 if (!queued)
1030 return 0;
1031
1032 return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
1033 }
1034
1035 bool blk_mq_get_driver_tag(struct request *rq)
1036 {
1037 struct blk_mq_alloc_data data = {
1038 .q = rq->q,
1039 .hctx = rq->mq_hctx,
1040 .flags = BLK_MQ_REQ_NOWAIT,
1041 .cmd_flags = rq->cmd_flags,
1042 };
1043 bool shared;
1044
1045 if (rq->tag != -1)
1046 return true;
1047
1048 if (blk_mq_tag_is_reserved(data.hctx->sched_tags, rq->internal_tag))
1049 data.flags |= BLK_MQ_REQ_RESERVED;
1050
1051 shared = blk_mq_tag_busy(data.hctx);
1052 rq->tag = blk_mq_get_tag(&data);
1053 if (rq->tag >= 0) {
1054 if (shared) {
1055 rq->rq_flags |= RQF_MQ_INFLIGHT;
1056 atomic_inc(&data.hctx->nr_active);
1057 }
1058 data.hctx->tags->rqs[rq->tag] = rq;
1059 }
1060
1061 return rq->tag != -1;
1062 }
1063
1064 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1065 int flags, void *key)
1066 {
1067 struct blk_mq_hw_ctx *hctx;
1068
1069 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1070
1071 spin_lock(&hctx->dispatch_wait_lock);
1072 if (!list_empty(&wait->entry)) {
1073 struct sbitmap_queue *sbq;
1074
1075 list_del_init(&wait->entry);
1076 sbq = &hctx->tags->bitmap_tags;
1077 atomic_dec(&sbq->ws_active);
1078 }
1079 spin_unlock(&hctx->dispatch_wait_lock);
1080
1081 blk_mq_run_hw_queue(hctx, true);
1082 return 1;
1083 }
1084
1085 /*
1086 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1087 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1088 * restart. For both cases, take care to check the condition again after
1089 * marking us as waiting.
1090 */
1091 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1092 struct request *rq)
1093 {
1094 struct sbitmap_queue *sbq = &hctx->tags->bitmap_tags;
1095 struct wait_queue_head *wq;
1096 wait_queue_entry_t *wait;
1097 bool ret;
1098
1099 if (!(hctx->flags & BLK_MQ_F_TAG_SHARED)) {
1100 blk_mq_sched_mark_restart_hctx(hctx);
1101
1102 /*
1103 * It's possible that a tag was freed in the window between the
1104 * allocation failure and adding the hardware queue to the wait
1105 * queue.
1106 *
1107 * Don't clear RESTART here, someone else could have set it.
1108 * At most this will cost an extra queue run.
1109 */
1110 return blk_mq_get_driver_tag(rq);
1111 }
1112
1113 wait = &hctx->dispatch_wait;
1114 if (!list_empty_careful(&wait->entry))
1115 return false;
1116
1117 wq = &bt_wait_ptr(sbq, hctx)->wait;
1118
1119 spin_lock_irq(&wq->lock);
1120 spin_lock(&hctx->dispatch_wait_lock);
1121 if (!list_empty(&wait->entry)) {
1122 spin_unlock(&hctx->dispatch_wait_lock);
1123 spin_unlock_irq(&wq->lock);
1124 return false;
1125 }
1126
1127 atomic_inc(&sbq->ws_active);
1128 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1129 __add_wait_queue(wq, wait);
1130
1131 /*
1132 * It's possible that a tag was freed in the window between the
1133 * allocation failure and adding the hardware queue to the wait
1134 * queue.
1135 */
1136 ret = blk_mq_get_driver_tag(rq);
1137 if (!ret) {
1138 spin_unlock(&hctx->dispatch_wait_lock);
1139 spin_unlock_irq(&wq->lock);
1140 return false;
1141 }
1142
1143 /*
1144 * We got a tag, remove ourselves from the wait queue to ensure
1145 * someone else gets the wakeup.
1146 */
1147 list_del_init(&wait->entry);
1148 atomic_dec(&sbq->ws_active);
1149 spin_unlock(&hctx->dispatch_wait_lock);
1150 spin_unlock_irq(&wq->lock);
1151
1152 return true;
1153 }
1154
1155 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1156 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1157 /*
1158 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1159 * - EWMA is one simple way to compute running average value
1160 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1161 * - take 4 as factor for avoiding to get too small(0) result, and this
1162 * factor doesn't matter because EWMA decreases exponentially
1163 */
1164 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1165 {
1166 unsigned int ewma;
1167
1168 if (hctx->queue->elevator)
1169 return;
1170
1171 ewma = hctx->dispatch_busy;
1172
1173 if (!ewma && !busy)
1174 return;
1175
1176 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1177 if (busy)
1178 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1179 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1180
1181 hctx->dispatch_busy = ewma;
1182 }
1183
1184 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1185
1186 static void blk_mq_handle_dev_resource(struct request *rq,
1187 struct list_head *list)
1188 {
1189 struct request *next =
1190 list_first_entry_or_null(list, struct request, queuelist);
1191
1192 /*
1193 * If an I/O scheduler has been configured and we got a driver tag for
1194 * the next request already, free it.
1195 */
1196 if (next)
1197 blk_mq_put_driver_tag(next);
1198
1199 list_add(&rq->queuelist, list);
1200 __blk_mq_requeue_request(rq);
1201 }
1202
1203 static void blk_mq_handle_zone_resource(struct request *rq,
1204 struct list_head *zone_list)
1205 {
1206 /*
1207 * If we end up here it is because we cannot dispatch a request to a
1208 * specific zone due to LLD level zone-write locking or other zone
1209 * related resource not being available. In this case, set the request
1210 * aside in zone_list for retrying it later.
1211 */
1212 list_add(&rq->queuelist, zone_list);
1213 __blk_mq_requeue_request(rq);
1214 }
1215
1216 /*
1217 * Returns true if we did some work AND can potentially do more.
1218 */
1219 bool blk_mq_dispatch_rq_list(struct request_queue *q, struct list_head *list,
1220 bool got_budget)
1221 {
1222 struct blk_mq_hw_ctx *hctx;
1223 struct request *rq, *nxt;
1224 bool no_tag = false;
1225 int errors, queued;
1226 blk_status_t ret = BLK_STS_OK;
1227 bool no_budget_avail = false;
1228 LIST_HEAD(zone_list);
1229
1230 if (list_empty(list))
1231 return false;
1232
1233 WARN_ON(!list_is_singular(list) && got_budget);
1234
1235 /*
1236 * Now process all the entries, sending them to the driver.
1237 */
1238 errors = queued = 0;
1239 do {
1240 struct blk_mq_queue_data bd;
1241
1242 rq = list_first_entry(list, struct request, queuelist);
1243
1244 hctx = rq->mq_hctx;
1245 if (!got_budget && !blk_mq_get_dispatch_budget(hctx)) {
1246 blk_mq_put_driver_tag(rq);
1247 no_budget_avail = true;
1248 break;
1249 }
1250
1251 if (!blk_mq_get_driver_tag(rq)) {
1252 /*
1253 * The initial allocation attempt failed, so we need to
1254 * rerun the hardware queue when a tag is freed. The
1255 * waitqueue takes care of that. If the queue is run
1256 * before we add this entry back on the dispatch list,
1257 * we'll re-run it below.
1258 */
1259 if (!blk_mq_mark_tag_wait(hctx, rq)) {
1260 blk_mq_put_dispatch_budget(hctx);
1261 /*
1262 * For non-shared tags, the RESTART check
1263 * will suffice.
1264 */
1265 if (hctx->flags & BLK_MQ_F_TAG_SHARED)
1266 no_tag = true;
1267 break;
1268 }
1269 }
1270
1271 list_del_init(&rq->queuelist);
1272
1273 bd.rq = rq;
1274
1275 /*
1276 * Flag last if we have no more requests, or if we have more
1277 * but can't assign a driver tag to it.
1278 */
1279 if (list_empty(list))
1280 bd.last = true;
1281 else {
1282 nxt = list_first_entry(list, struct request, queuelist);
1283 bd.last = !blk_mq_get_driver_tag(nxt);
1284 }
1285
1286 ret = q->mq_ops->queue_rq(hctx, &bd);
1287 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE) {
1288 blk_mq_handle_dev_resource(rq, list);
1289 break;
1290 } else if (ret == BLK_STS_ZONE_RESOURCE) {
1291 /*
1292 * Move the request to zone_list and keep going through
1293 * the dispatch list to find more requests the drive can
1294 * accept.
1295 */
1296 blk_mq_handle_zone_resource(rq, &zone_list);
1297 if (list_empty(list))
1298 break;
1299 continue;
1300 }
1301
1302 if (unlikely(ret != BLK_STS_OK)) {
1303 errors++;
1304 blk_mq_end_request(rq, BLK_STS_IOERR);
1305 continue;
1306 }
1307
1308 queued++;
1309 } while (!list_empty(list));
1310
1311 if (!list_empty(&zone_list))
1312 list_splice_tail_init(&zone_list, list);
1313
1314 hctx->dispatched[queued_to_index(queued)]++;
1315
1316 /*
1317 * Any items that need requeuing? Stuff them into hctx->dispatch,
1318 * that is where we will continue on next queue run.
1319 */
1320 if (!list_empty(list)) {
1321 bool needs_restart;
1322
1323 /*
1324 * If we didn't flush the entire list, we could have told
1325 * the driver there was more coming, but that turned out to
1326 * be a lie.
1327 */
1328 if (q->mq_ops->commit_rqs && queued)
1329 q->mq_ops->commit_rqs(hctx);
1330
1331 spin_lock(&hctx->lock);
1332 list_splice_tail_init(list, &hctx->dispatch);
1333 spin_unlock(&hctx->lock);
1334
1335 /*
1336 * If SCHED_RESTART was set by the caller of this function and
1337 * it is no longer set that means that it was cleared by another
1338 * thread and hence that a queue rerun is needed.
1339 *
1340 * If 'no_tag' is set, that means that we failed getting
1341 * a driver tag with an I/O scheduler attached. If our dispatch
1342 * waitqueue is no longer active, ensure that we run the queue
1343 * AFTER adding our entries back to the list.
1344 *
1345 * If no I/O scheduler has been configured it is possible that
1346 * the hardware queue got stopped and restarted before requests
1347 * were pushed back onto the dispatch list. Rerun the queue to
1348 * avoid starvation. Notes:
1349 * - blk_mq_run_hw_queue() checks whether or not a queue has
1350 * been stopped before rerunning a queue.
1351 * - Some but not all block drivers stop a queue before
1352 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1353 * and dm-rq.
1354 *
1355 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1356 * bit is set, run queue after a delay to avoid IO stalls
1357 * that could otherwise occur if the queue is idle. We'll do
1358 * similar if we couldn't get budget and SCHED_RESTART is set.
1359 */
1360 needs_restart = blk_mq_sched_needs_restart(hctx);
1361 if (!needs_restart ||
1362 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1363 blk_mq_run_hw_queue(hctx, true);
1364 else if (needs_restart && (ret == BLK_STS_RESOURCE ||
1365 no_budget_avail))
1366 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1367
1368 blk_mq_update_dispatch_busy(hctx, true);
1369 return false;
1370 } else
1371 blk_mq_update_dispatch_busy(hctx, false);
1372
1373 /*
1374 * If the host/device is unable to accept more work, inform the
1375 * caller of that.
1376 */
1377 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
1378 return false;
1379
1380 return (queued + errors) != 0;
1381 }
1382
1383 /**
1384 * __blk_mq_run_hw_queue - Run a hardware queue.
1385 * @hctx: Pointer to the hardware queue to run.
1386 *
1387 * Send pending requests to the hardware.
1388 */
1389 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1390 {
1391 int srcu_idx;
1392
1393 /*
1394 * We should be running this queue from one of the CPUs that
1395 * are mapped to it.
1396 *
1397 * There are at least two related races now between setting
1398 * hctx->next_cpu from blk_mq_hctx_next_cpu() and running
1399 * __blk_mq_run_hw_queue():
1400 *
1401 * - hctx->next_cpu is found offline in blk_mq_hctx_next_cpu(),
1402 * but later it becomes online, then this warning is harmless
1403 * at all
1404 *
1405 * - hctx->next_cpu is found online in blk_mq_hctx_next_cpu(),
1406 * but later it becomes offline, then the warning can't be
1407 * triggered, and we depend on blk-mq timeout handler to
1408 * handle dispatched requests to this hctx
1409 */
1410 if (!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask) &&
1411 cpu_online(hctx->next_cpu)) {
1412 printk(KERN_WARNING "run queue from wrong CPU %d, hctx %s\n",
1413 raw_smp_processor_id(),
1414 cpumask_empty(hctx->cpumask) ? "inactive": "active");
1415 dump_stack();
1416 }
1417
1418 /*
1419 * We can't run the queue inline with ints disabled. Ensure that
1420 * we catch bad users of this early.
1421 */
1422 WARN_ON_ONCE(in_interrupt());
1423
1424 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1425
1426 hctx_lock(hctx, &srcu_idx);
1427 blk_mq_sched_dispatch_requests(hctx);
1428 hctx_unlock(hctx, srcu_idx);
1429 }
1430
1431 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1432 {
1433 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1434
1435 if (cpu >= nr_cpu_ids)
1436 cpu = cpumask_first(hctx->cpumask);
1437 return cpu;
1438 }
1439
1440 /*
1441 * It'd be great if the workqueue API had a way to pass
1442 * in a mask and had some smarts for more clever placement.
1443 * For now we just round-robin here, switching for every
1444 * BLK_MQ_CPU_WORK_BATCH queued items.
1445 */
1446 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1447 {
1448 bool tried = false;
1449 int next_cpu = hctx->next_cpu;
1450
1451 if (hctx->queue->nr_hw_queues == 1)
1452 return WORK_CPU_UNBOUND;
1453
1454 if (--hctx->next_cpu_batch <= 0) {
1455 select_cpu:
1456 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
1457 cpu_online_mask);
1458 if (next_cpu >= nr_cpu_ids)
1459 next_cpu = blk_mq_first_mapped_cpu(hctx);
1460 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1461 }
1462
1463 /*
1464 * Do unbound schedule if we can't find a online CPU for this hctx,
1465 * and it should only happen in the path of handling CPU DEAD.
1466 */
1467 if (!cpu_online(next_cpu)) {
1468 if (!tried) {
1469 tried = true;
1470 goto select_cpu;
1471 }
1472
1473 /*
1474 * Make sure to re-select CPU next time once after CPUs
1475 * in hctx->cpumask become online again.
1476 */
1477 hctx->next_cpu = next_cpu;
1478 hctx->next_cpu_batch = 1;
1479 return WORK_CPU_UNBOUND;
1480 }
1481
1482 hctx->next_cpu = next_cpu;
1483 return next_cpu;
1484 }
1485
1486 /**
1487 * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
1488 * @hctx: Pointer to the hardware queue to run.
1489 * @async: If we want to run the queue asynchronously.
1490 * @msecs: Microseconds of delay to wait before running the queue.
1491 *
1492 * If !@async, try to run the queue now. Else, run the queue asynchronously and
1493 * with a delay of @msecs.
1494 */
1495 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1496 unsigned long msecs)
1497 {
1498 if (unlikely(blk_mq_hctx_stopped(hctx)))
1499 return;
1500
1501 if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1502 int cpu = get_cpu();
1503 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1504 __blk_mq_run_hw_queue(hctx);
1505 put_cpu();
1506 return;
1507 }
1508
1509 put_cpu();
1510 }
1511
1512 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1513 msecs_to_jiffies(msecs));
1514 }
1515
1516 /**
1517 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
1518 * @hctx: Pointer to the hardware queue to run.
1519 * @msecs: Microseconds of delay to wait before running the queue.
1520 *
1521 * Run a hardware queue asynchronously with a delay of @msecs.
1522 */
1523 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1524 {
1525 __blk_mq_delay_run_hw_queue(hctx, true, msecs);
1526 }
1527 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1528
1529 /**
1530 * blk_mq_run_hw_queue - Start to run a hardware queue.
1531 * @hctx: Pointer to the hardware queue to run.
1532 * @async: If we want to run the queue asynchronously.
1533 *
1534 * Check if the request queue is not in a quiesced state and if there are
1535 * pending requests to be sent. If this is true, run the queue to send requests
1536 * to hardware.
1537 */
1538 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1539 {
1540 int srcu_idx;
1541 bool need_run;
1542
1543 /*
1544 * When queue is quiesced, we may be switching io scheduler, or
1545 * updating nr_hw_queues, or other things, and we can't run queue
1546 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1547 *
1548 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1549 * quiesced.
1550 */
1551 hctx_lock(hctx, &srcu_idx);
1552 need_run = !blk_queue_quiesced(hctx->queue) &&
1553 blk_mq_hctx_has_pending(hctx);
1554 hctx_unlock(hctx, srcu_idx);
1555
1556 if (need_run)
1557 __blk_mq_delay_run_hw_queue(hctx, async, 0);
1558 }
1559 EXPORT_SYMBOL(blk_mq_run_hw_queue);
1560
1561 /**
1562 * blk_mq_run_hw_queue - Run all hardware queues in a request queue.
1563 * @q: Pointer to the request queue to run.
1564 * @async: If we want to run the queue asynchronously.
1565 */
1566 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1567 {
1568 struct blk_mq_hw_ctx *hctx;
1569 int i;
1570
1571 queue_for_each_hw_ctx(q, hctx, i) {
1572 if (blk_mq_hctx_stopped(hctx))
1573 continue;
1574
1575 blk_mq_run_hw_queue(hctx, async);
1576 }
1577 }
1578 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1579
1580 /**
1581 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
1582 * @q: Pointer to the request queue to run.
1583 * @msecs: Microseconds of delay to wait before running the queues.
1584 */
1585 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
1586 {
1587 struct blk_mq_hw_ctx *hctx;
1588 int i;
1589
1590 queue_for_each_hw_ctx(q, hctx, i) {
1591 if (blk_mq_hctx_stopped(hctx))
1592 continue;
1593
1594 blk_mq_delay_run_hw_queue(hctx, msecs);
1595 }
1596 }
1597 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
1598
1599 /**
1600 * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1601 * @q: request queue.
1602 *
1603 * The caller is responsible for serializing this function against
1604 * blk_mq_{start,stop}_hw_queue().
1605 */
1606 bool blk_mq_queue_stopped(struct request_queue *q)
1607 {
1608 struct blk_mq_hw_ctx *hctx;
1609 int i;
1610
1611 queue_for_each_hw_ctx(q, hctx, i)
1612 if (blk_mq_hctx_stopped(hctx))
1613 return true;
1614
1615 return false;
1616 }
1617 EXPORT_SYMBOL(blk_mq_queue_stopped);
1618
1619 /*
1620 * This function is often used for pausing .queue_rq() by driver when
1621 * there isn't enough resource or some conditions aren't satisfied, and
1622 * BLK_STS_RESOURCE is usually returned.
1623 *
1624 * We do not guarantee that dispatch can be drained or blocked
1625 * after blk_mq_stop_hw_queue() returns. Please use
1626 * blk_mq_quiesce_queue() for that requirement.
1627 */
1628 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1629 {
1630 cancel_delayed_work(&hctx->run_work);
1631
1632 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
1633 }
1634 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
1635
1636 /*
1637 * This function is often used for pausing .queue_rq() by driver when
1638 * there isn't enough resource or some conditions aren't satisfied, and
1639 * BLK_STS_RESOURCE is usually returned.
1640 *
1641 * We do not guarantee that dispatch can be drained or blocked
1642 * after blk_mq_stop_hw_queues() returns. Please use
1643 * blk_mq_quiesce_queue() for that requirement.
1644 */
1645 void blk_mq_stop_hw_queues(struct request_queue *q)
1646 {
1647 struct blk_mq_hw_ctx *hctx;
1648 int i;
1649
1650 queue_for_each_hw_ctx(q, hctx, i)
1651 blk_mq_stop_hw_queue(hctx);
1652 }
1653 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1654
1655 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1656 {
1657 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1658
1659 blk_mq_run_hw_queue(hctx, false);
1660 }
1661 EXPORT_SYMBOL(blk_mq_start_hw_queue);
1662
1663 void blk_mq_start_hw_queues(struct request_queue *q)
1664 {
1665 struct blk_mq_hw_ctx *hctx;
1666 int i;
1667
1668 queue_for_each_hw_ctx(q, hctx, i)
1669 blk_mq_start_hw_queue(hctx);
1670 }
1671 EXPORT_SYMBOL(blk_mq_start_hw_queues);
1672
1673 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1674 {
1675 if (!blk_mq_hctx_stopped(hctx))
1676 return;
1677
1678 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1679 blk_mq_run_hw_queue(hctx, async);
1680 }
1681 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1682
1683 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
1684 {
1685 struct blk_mq_hw_ctx *hctx;
1686 int i;
1687
1688 queue_for_each_hw_ctx(q, hctx, i)
1689 blk_mq_start_stopped_hw_queue(hctx, async);
1690 }
1691 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1692
1693 static void blk_mq_run_work_fn(struct work_struct *work)
1694 {
1695 struct blk_mq_hw_ctx *hctx;
1696
1697 hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
1698
1699 /*
1700 * If we are stopped, don't run the queue.
1701 */
1702 if (test_bit(BLK_MQ_S_STOPPED, &hctx->state))
1703 return;
1704
1705 __blk_mq_run_hw_queue(hctx);
1706 }
1707
1708 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
1709 struct request *rq,
1710 bool at_head)
1711 {
1712 struct blk_mq_ctx *ctx = rq->mq_ctx;
1713 enum hctx_type type = hctx->type;
1714
1715 lockdep_assert_held(&ctx->lock);
1716
1717 trace_block_rq_insert(hctx->queue, rq);
1718
1719 if (at_head)
1720 list_add(&rq->queuelist, &ctx->rq_lists[type]);
1721 else
1722 list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
1723 }
1724
1725 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1726 bool at_head)
1727 {
1728 struct blk_mq_ctx *ctx = rq->mq_ctx;
1729
1730 lockdep_assert_held(&ctx->lock);
1731
1732 __blk_mq_insert_req_list(hctx, rq, at_head);
1733 blk_mq_hctx_mark_pending(hctx, ctx);
1734 }
1735
1736 /**
1737 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
1738 * @rq: Pointer to request to be inserted.
1739 * @run_queue: If we should run the hardware queue after inserting the request.
1740 *
1741 * Should only be used carefully, when the caller knows we want to
1742 * bypass a potential IO scheduler on the target device.
1743 */
1744 void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
1745 bool run_queue)
1746 {
1747 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1748
1749 spin_lock(&hctx->lock);
1750 if (at_head)
1751 list_add(&rq->queuelist, &hctx->dispatch);
1752 else
1753 list_add_tail(&rq->queuelist, &hctx->dispatch);
1754 spin_unlock(&hctx->lock);
1755
1756 if (run_queue)
1757 blk_mq_run_hw_queue(hctx, false);
1758 }
1759
1760 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1761 struct list_head *list)
1762
1763 {
1764 struct request *rq;
1765 enum hctx_type type = hctx->type;
1766
1767 /*
1768 * preemption doesn't flush plug list, so it's possible ctx->cpu is
1769 * offline now
1770 */
1771 list_for_each_entry(rq, list, queuelist) {
1772 BUG_ON(rq->mq_ctx != ctx);
1773 trace_block_rq_insert(hctx->queue, rq);
1774 }
1775
1776 spin_lock(&ctx->lock);
1777 list_splice_tail_init(list, &ctx->rq_lists[type]);
1778 blk_mq_hctx_mark_pending(hctx, ctx);
1779 spin_unlock(&ctx->lock);
1780 }
1781
1782 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
1783 {
1784 struct request *rqa = container_of(a, struct request, queuelist);
1785 struct request *rqb = container_of(b, struct request, queuelist);
1786
1787 if (rqa->mq_ctx != rqb->mq_ctx)
1788 return rqa->mq_ctx > rqb->mq_ctx;
1789 if (rqa->mq_hctx != rqb->mq_hctx)
1790 return rqa->mq_hctx > rqb->mq_hctx;
1791
1792 return blk_rq_pos(rqa) > blk_rq_pos(rqb);
1793 }
1794
1795 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1796 {
1797 LIST_HEAD(list);
1798
1799 if (list_empty(&plug->mq_list))
1800 return;
1801 list_splice_init(&plug->mq_list, &list);
1802
1803 if (plug->rq_count > 2 && plug->multiple_queues)
1804 list_sort(NULL, &list, plug_rq_cmp);
1805
1806 plug->rq_count = 0;
1807
1808 do {
1809 struct list_head rq_list;
1810 struct request *rq, *head_rq = list_entry_rq(list.next);
1811 struct list_head *pos = &head_rq->queuelist; /* skip first */
1812 struct blk_mq_hw_ctx *this_hctx = head_rq->mq_hctx;
1813 struct blk_mq_ctx *this_ctx = head_rq->mq_ctx;
1814 unsigned int depth = 1;
1815
1816 list_for_each_continue(pos, &list) {
1817 rq = list_entry_rq(pos);
1818 BUG_ON(!rq->q);
1819 if (rq->mq_hctx != this_hctx || rq->mq_ctx != this_ctx)
1820 break;
1821 depth++;
1822 }
1823
1824 list_cut_before(&rq_list, &list, pos);
1825 trace_block_unplug(head_rq->q, depth, !from_schedule);
1826 blk_mq_sched_insert_requests(this_hctx, this_ctx, &rq_list,
1827 from_schedule);
1828 } while(!list_empty(&list));
1829 }
1830
1831 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
1832 unsigned int nr_segs)
1833 {
1834 if (bio->bi_opf & REQ_RAHEAD)
1835 rq->cmd_flags |= REQ_FAILFAST_MASK;
1836
1837 rq->__sector = bio->bi_iter.bi_sector;
1838 rq->write_hint = bio->bi_write_hint;
1839 blk_rq_bio_prep(rq, bio, nr_segs);
1840 blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
1841
1842 blk_account_io_start(rq);
1843 }
1844
1845 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
1846 struct request *rq,
1847 blk_qc_t *cookie, bool last)
1848 {
1849 struct request_queue *q = rq->q;
1850 struct blk_mq_queue_data bd = {
1851 .rq = rq,
1852 .last = last,
1853 };
1854 blk_qc_t new_cookie;
1855 blk_status_t ret;
1856
1857 new_cookie = request_to_qc_t(hctx, rq);
1858
1859 /*
1860 * For OK queue, we are done. For error, caller may kill it.
1861 * Any other error (busy), just add it to our list as we
1862 * previously would have done.
1863 */
1864 ret = q->mq_ops->queue_rq(hctx, &bd);
1865 switch (ret) {
1866 case BLK_STS_OK:
1867 blk_mq_update_dispatch_busy(hctx, false);
1868 *cookie = new_cookie;
1869 break;
1870 case BLK_STS_RESOURCE:
1871 case BLK_STS_DEV_RESOURCE:
1872 blk_mq_update_dispatch_busy(hctx, true);
1873 __blk_mq_requeue_request(rq);
1874 break;
1875 default:
1876 blk_mq_update_dispatch_busy(hctx, false);
1877 *cookie = BLK_QC_T_NONE;
1878 break;
1879 }
1880
1881 return ret;
1882 }
1883
1884 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1885 struct request *rq,
1886 blk_qc_t *cookie,
1887 bool bypass_insert, bool last)
1888 {
1889 struct request_queue *q = rq->q;
1890 bool run_queue = true;
1891
1892 /*
1893 * RCU or SRCU read lock is needed before checking quiesced flag.
1894 *
1895 * When queue is stopped or quiesced, ignore 'bypass_insert' from
1896 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
1897 * and avoid driver to try to dispatch again.
1898 */
1899 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
1900 run_queue = false;
1901 bypass_insert = false;
1902 goto insert;
1903 }
1904
1905 if (q->elevator && !bypass_insert)
1906 goto insert;
1907
1908 if (!blk_mq_get_dispatch_budget(hctx))
1909 goto insert;
1910
1911 if (!blk_mq_get_driver_tag(rq)) {
1912 blk_mq_put_dispatch_budget(hctx);
1913 goto insert;
1914 }
1915
1916 return __blk_mq_issue_directly(hctx, rq, cookie, last);
1917 insert:
1918 if (bypass_insert)
1919 return BLK_STS_RESOURCE;
1920
1921 blk_mq_request_bypass_insert(rq, false, run_queue);
1922 return BLK_STS_OK;
1923 }
1924
1925 /**
1926 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
1927 * @hctx: Pointer of the associated hardware queue.
1928 * @rq: Pointer to request to be sent.
1929 * @cookie: Request queue cookie.
1930 *
1931 * If the device has enough resources to accept a new request now, send the
1932 * request directly to device driver. Else, insert at hctx->dispatch queue, so
1933 * we can try send it another time in the future. Requests inserted at this
1934 * queue have higher priority.
1935 */
1936 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1937 struct request *rq, blk_qc_t *cookie)
1938 {
1939 blk_status_t ret;
1940 int srcu_idx;
1941
1942 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1943
1944 hctx_lock(hctx, &srcu_idx);
1945
1946 ret = __blk_mq_try_issue_directly(hctx, rq, cookie, false, true);
1947 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
1948 blk_mq_request_bypass_insert(rq, false, true);
1949 else if (ret != BLK_STS_OK)
1950 blk_mq_end_request(rq, ret);
1951
1952 hctx_unlock(hctx, srcu_idx);
1953 }
1954
1955 blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
1956 {
1957 blk_status_t ret;
1958 int srcu_idx;
1959 blk_qc_t unused_cookie;
1960 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1961
1962 hctx_lock(hctx, &srcu_idx);
1963 ret = __blk_mq_try_issue_directly(hctx, rq, &unused_cookie, true, last);
1964 hctx_unlock(hctx, srcu_idx);
1965
1966 return ret;
1967 }
1968
1969 void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
1970 struct list_head *list)
1971 {
1972 int queued = 0;
1973
1974 while (!list_empty(list)) {
1975 blk_status_t ret;
1976 struct request *rq = list_first_entry(list, struct request,
1977 queuelist);
1978
1979 list_del_init(&rq->queuelist);
1980 ret = blk_mq_request_issue_directly(rq, list_empty(list));
1981 if (ret != BLK_STS_OK) {
1982 if (ret == BLK_STS_RESOURCE ||
1983 ret == BLK_STS_DEV_RESOURCE) {
1984 blk_mq_request_bypass_insert(rq, false,
1985 list_empty(list));
1986 break;
1987 }
1988 blk_mq_end_request(rq, ret);
1989 } else
1990 queued++;
1991 }
1992
1993 /*
1994 * If we didn't flush the entire list, we could have told
1995 * the driver there was more coming, but that turned out to
1996 * be a lie.
1997 */
1998 if (!list_empty(list) && hctx->queue->mq_ops->commit_rqs && queued)
1999 hctx->queue->mq_ops->commit_rqs(hctx);
2000 }
2001
2002 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2003 {
2004 list_add_tail(&rq->queuelist, &plug->mq_list);
2005 plug->rq_count++;
2006 if (!plug->multiple_queues && !list_is_singular(&plug->mq_list)) {
2007 struct request *tmp;
2008
2009 tmp = list_first_entry(&plug->mq_list, struct request,
2010 queuelist);
2011 if (tmp->q != rq->q)
2012 plug->multiple_queues = true;
2013 }
2014 }
2015
2016 /**
2017 * blk_mq_make_request - Create and send a request to block device.
2018 * @q: Request queue pointer.
2019 * @bio: Bio pointer.
2020 *
2021 * Builds up a request structure from @q and @bio and send to the device. The
2022 * request may not be queued directly to hardware if:
2023 * * This request can be merged with another one
2024 * * We want to place request at plug queue for possible future merging
2025 * * There is an IO scheduler active at this queue
2026 *
2027 * It will not queue the request if there is an error with the bio, or at the
2028 * request creation.
2029 *
2030 * Returns: Request queue cookie.
2031 */
2032 blk_qc_t blk_mq_make_request(struct request_queue *q, struct bio *bio)
2033 {
2034 const int is_sync = op_is_sync(bio->bi_opf);
2035 const int is_flush_fua = op_is_flush(bio->bi_opf);
2036 struct blk_mq_alloc_data data = {
2037 .q = q,
2038 };
2039 struct request *rq;
2040 struct blk_plug *plug;
2041 struct request *same_queue_rq = NULL;
2042 unsigned int nr_segs;
2043 blk_qc_t cookie;
2044 blk_status_t ret;
2045
2046 blk_queue_bounce(q, &bio);
2047 __blk_queue_split(q, &bio, &nr_segs);
2048
2049 if (!bio_integrity_prep(bio))
2050 goto queue_exit;
2051
2052 if (!is_flush_fua && !blk_queue_nomerges(q) &&
2053 blk_attempt_plug_merge(q, bio, nr_segs, &same_queue_rq))
2054 goto queue_exit;
2055
2056 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2057 goto queue_exit;
2058
2059 rq_qos_throttle(q, bio);
2060
2061 data.cmd_flags = bio->bi_opf;
2062 rq = __blk_mq_alloc_request(&data);
2063 if (unlikely(!rq)) {
2064 rq_qos_cleanup(q, bio);
2065 if (bio->bi_opf & REQ_NOWAIT)
2066 bio_wouldblock_error(bio);
2067 goto queue_exit;
2068 }
2069
2070 trace_block_getrq(q, bio, bio->bi_opf);
2071
2072 rq_qos_track(q, rq, bio);
2073
2074 cookie = request_to_qc_t(data.hctx, rq);
2075
2076 blk_mq_bio_to_request(rq, bio, nr_segs);
2077
2078 ret = blk_crypto_init_request(rq);
2079 if (ret != BLK_STS_OK) {
2080 bio->bi_status = ret;
2081 bio_endio(bio);
2082 blk_mq_free_request(rq);
2083 return BLK_QC_T_NONE;
2084 }
2085
2086 plug = blk_mq_plug(q, bio);
2087 if (unlikely(is_flush_fua)) {
2088 /* Bypass scheduler for flush requests */
2089 blk_insert_flush(rq);
2090 blk_mq_run_hw_queue(data.hctx, true);
2091 } else if (plug && (q->nr_hw_queues == 1 || q->mq_ops->commit_rqs ||
2092 !blk_queue_nonrot(q))) {
2093 /*
2094 * Use plugging if we have a ->commit_rqs() hook as well, as
2095 * we know the driver uses bd->last in a smart fashion.
2096 *
2097 * Use normal plugging if this disk is slow HDD, as sequential
2098 * IO may benefit a lot from plug merging.
2099 */
2100 unsigned int request_count = plug->rq_count;
2101 struct request *last = NULL;
2102
2103 if (!request_count)
2104 trace_block_plug(q);
2105 else
2106 last = list_entry_rq(plug->mq_list.prev);
2107
2108 if (request_count >= BLK_MAX_REQUEST_COUNT || (last &&
2109 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
2110 blk_flush_plug_list(plug, false);
2111 trace_block_plug(q);
2112 }
2113
2114 blk_add_rq_to_plug(plug, rq);
2115 } else if (q->elevator) {
2116 /* Insert the request at the IO scheduler queue */
2117 blk_mq_sched_insert_request(rq, false, true, true);
2118 } else if (plug && !blk_queue_nomerges(q)) {
2119 /*
2120 * We do limited plugging. If the bio can be merged, do that.
2121 * Otherwise the existing request in the plug list will be
2122 * issued. So the plug list will have one request at most
2123 * The plug list might get flushed before this. If that happens,
2124 * the plug list is empty, and same_queue_rq is invalid.
2125 */
2126 if (list_empty(&plug->mq_list))
2127 same_queue_rq = NULL;
2128 if (same_queue_rq) {
2129 list_del_init(&same_queue_rq->queuelist);
2130 plug->rq_count--;
2131 }
2132 blk_add_rq_to_plug(plug, rq);
2133 trace_block_plug(q);
2134
2135 if (same_queue_rq) {
2136 data.hctx = same_queue_rq->mq_hctx;
2137 trace_block_unplug(q, 1, true);
2138 blk_mq_try_issue_directly(data.hctx, same_queue_rq,
2139 &cookie);
2140 }
2141 } else if ((q->nr_hw_queues > 1 && is_sync) ||
2142 !data.hctx->dispatch_busy) {
2143 /*
2144 * There is no scheduler and we can try to send directly
2145 * to the hardware.
2146 */
2147 blk_mq_try_issue_directly(data.hctx, rq, &cookie);
2148 } else {
2149 /* Default case. */
2150 blk_mq_sched_insert_request(rq, false, true, true);
2151 }
2152
2153 return cookie;
2154 queue_exit:
2155 blk_queue_exit(q);
2156 return BLK_QC_T_NONE;
2157 }
2158 EXPORT_SYMBOL_GPL(blk_mq_make_request); /* only for request based dm */
2159
2160 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2161 unsigned int hctx_idx)
2162 {
2163 struct page *page;
2164
2165 if (tags->rqs && set->ops->exit_request) {
2166 int i;
2167
2168 for (i = 0; i < tags->nr_tags; i++) {
2169 struct request *rq = tags->static_rqs[i];
2170
2171 if (!rq)
2172 continue;
2173 set->ops->exit_request(set, rq, hctx_idx);
2174 tags->static_rqs[i] = NULL;
2175 }
2176 }
2177
2178 while (!list_empty(&tags->page_list)) {
2179 page = list_first_entry(&tags->page_list, struct page, lru);
2180 list_del_init(&page->lru);
2181 /*
2182 * Remove kmemleak object previously allocated in
2183 * blk_mq_alloc_rqs().
2184 */
2185 kmemleak_free(page_address(page));
2186 __free_pages(page, page->private);
2187 }
2188 }
2189
2190 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
2191 {
2192 kfree(tags->rqs);
2193 tags->rqs = NULL;
2194 kfree(tags->static_rqs);
2195 tags->static_rqs = NULL;
2196
2197 blk_mq_free_tags(tags);
2198 }
2199
2200 struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2201 unsigned int hctx_idx,
2202 unsigned int nr_tags,
2203 unsigned int reserved_tags)
2204 {
2205 struct blk_mq_tags *tags;
2206 int node;
2207
2208 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2209 if (node == NUMA_NO_NODE)
2210 node = set->numa_node;
2211
2212 tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
2213 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
2214 if (!tags)
2215 return NULL;
2216
2217 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2218 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2219 node);
2220 if (!tags->rqs) {
2221 blk_mq_free_tags(tags);
2222 return NULL;
2223 }
2224
2225 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2226 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2227 node);
2228 if (!tags->static_rqs) {
2229 kfree(tags->rqs);
2230 blk_mq_free_tags(tags);
2231 return NULL;
2232 }
2233
2234 return tags;
2235 }
2236
2237 static size_t order_to_size(unsigned int order)
2238 {
2239 return (size_t)PAGE_SIZE << order;
2240 }
2241
2242 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2243 unsigned int hctx_idx, int node)
2244 {
2245 int ret;
2246
2247 if (set->ops->init_request) {
2248 ret = set->ops->init_request(set, rq, hctx_idx, node);
2249 if (ret)
2250 return ret;
2251 }
2252
2253 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
2254 return 0;
2255 }
2256
2257 int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2258 unsigned int hctx_idx, unsigned int depth)
2259 {
2260 unsigned int i, j, entries_per_page, max_order = 4;
2261 size_t rq_size, left;
2262 int node;
2263
2264 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2265 if (node == NUMA_NO_NODE)
2266 node = set->numa_node;
2267
2268 INIT_LIST_HEAD(&tags->page_list);
2269
2270 /*
2271 * rq_size is the size of the request plus driver payload, rounded
2272 * to the cacheline size
2273 */
2274 rq_size = round_up(sizeof(struct request) + set->cmd_size,
2275 cache_line_size());
2276 left = rq_size * depth;
2277
2278 for (i = 0; i < depth; ) {
2279 int this_order = max_order;
2280 struct page *page;
2281 int to_do;
2282 void *p;
2283
2284 while (this_order && left < order_to_size(this_order - 1))
2285 this_order--;
2286
2287 do {
2288 page = alloc_pages_node(node,
2289 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
2290 this_order);
2291 if (page)
2292 break;
2293 if (!this_order--)
2294 break;
2295 if (order_to_size(this_order) < rq_size)
2296 break;
2297 } while (1);
2298
2299 if (!page)
2300 goto fail;
2301
2302 page->private = this_order;
2303 list_add_tail(&page->lru, &tags->page_list);
2304
2305 p = page_address(page);
2306 /*
2307 * Allow kmemleak to scan these pages as they contain pointers
2308 * to additional allocations like via ops->init_request().
2309 */
2310 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
2311 entries_per_page = order_to_size(this_order) / rq_size;
2312 to_do = min(entries_per_page, depth - i);
2313 left -= to_do * rq_size;
2314 for (j = 0; j < to_do; j++) {
2315 struct request *rq = p;
2316
2317 tags->static_rqs[i] = rq;
2318 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2319 tags->static_rqs[i] = NULL;
2320 goto fail;
2321 }
2322
2323 p += rq_size;
2324 i++;
2325 }
2326 }
2327 return 0;
2328
2329 fail:
2330 blk_mq_free_rqs(set, tags, hctx_idx);
2331 return -ENOMEM;
2332 }
2333
2334 /*
2335 * 'cpu' is going away. splice any existing rq_list entries from this
2336 * software queue to the hw queue dispatch list, and ensure that it
2337 * gets run.
2338 */
2339 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
2340 {
2341 struct blk_mq_hw_ctx *hctx;
2342 struct blk_mq_ctx *ctx;
2343 LIST_HEAD(tmp);
2344 enum hctx_type type;
2345
2346 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
2347 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
2348 type = hctx->type;
2349
2350 spin_lock(&ctx->lock);
2351 if (!list_empty(&ctx->rq_lists[type])) {
2352 list_splice_init(&ctx->rq_lists[type], &tmp);
2353 blk_mq_hctx_clear_pending(hctx, ctx);
2354 }
2355 spin_unlock(&ctx->lock);
2356
2357 if (list_empty(&tmp))
2358 return 0;
2359
2360 spin_lock(&hctx->lock);
2361 list_splice_tail_init(&tmp, &hctx->dispatch);
2362 spin_unlock(&hctx->lock);
2363
2364 blk_mq_run_hw_queue(hctx, true);
2365 return 0;
2366 }
2367
2368 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
2369 {
2370 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2371 &hctx->cpuhp_dead);
2372 }
2373
2374 /* hctx->ctxs will be freed in queue's release handler */
2375 static void blk_mq_exit_hctx(struct request_queue *q,
2376 struct blk_mq_tag_set *set,
2377 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
2378 {
2379 if (blk_mq_hw_queue_mapped(hctx))
2380 blk_mq_tag_idle(hctx);
2381
2382 if (set->ops->exit_request)
2383 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
2384
2385 if (set->ops->exit_hctx)
2386 set->ops->exit_hctx(hctx, hctx_idx);
2387
2388 blk_mq_remove_cpuhp(hctx);
2389
2390 spin_lock(&q->unused_hctx_lock);
2391 list_add(&hctx->hctx_list, &q->unused_hctx_list);
2392 spin_unlock(&q->unused_hctx_lock);
2393 }
2394
2395 static void blk_mq_exit_hw_queues(struct request_queue *q,
2396 struct blk_mq_tag_set *set, int nr_queue)
2397 {
2398 struct blk_mq_hw_ctx *hctx;
2399 unsigned int i;
2400
2401 queue_for_each_hw_ctx(q, hctx, i) {
2402 if (i == nr_queue)
2403 break;
2404 blk_mq_debugfs_unregister_hctx(hctx);
2405 blk_mq_exit_hctx(q, set, hctx, i);
2406 }
2407 }
2408
2409 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
2410 {
2411 int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
2412
2413 BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
2414 __alignof__(struct blk_mq_hw_ctx)) !=
2415 sizeof(struct blk_mq_hw_ctx));
2416
2417 if (tag_set->flags & BLK_MQ_F_BLOCKING)
2418 hw_ctx_size += sizeof(struct srcu_struct);
2419
2420 return hw_ctx_size;
2421 }
2422
2423 static int blk_mq_init_hctx(struct request_queue *q,
2424 struct blk_mq_tag_set *set,
2425 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
2426 {
2427 hctx->queue_num = hctx_idx;
2428
2429 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
2430
2431 hctx->tags = set->tags[hctx_idx];
2432
2433 if (set->ops->init_hctx &&
2434 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
2435 goto unregister_cpu_notifier;
2436
2437 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
2438 hctx->numa_node))
2439 goto exit_hctx;
2440 return 0;
2441
2442 exit_hctx:
2443 if (set->ops->exit_hctx)
2444 set->ops->exit_hctx(hctx, hctx_idx);
2445 unregister_cpu_notifier:
2446 blk_mq_remove_cpuhp(hctx);
2447 return -1;
2448 }
2449
2450 static struct blk_mq_hw_ctx *
2451 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
2452 int node)
2453 {
2454 struct blk_mq_hw_ctx *hctx;
2455 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
2456
2457 hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
2458 if (!hctx)
2459 goto fail_alloc_hctx;
2460
2461 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
2462 goto free_hctx;
2463
2464 atomic_set(&hctx->nr_active, 0);
2465 if (node == NUMA_NO_NODE)
2466 node = set->numa_node;
2467 hctx->numa_node = node;
2468
2469 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
2470 spin_lock_init(&hctx->lock);
2471 INIT_LIST_HEAD(&hctx->dispatch);
2472 hctx->queue = q;
2473 hctx->flags = set->flags & ~BLK_MQ_F_TAG_SHARED;
2474
2475 INIT_LIST_HEAD(&hctx->hctx_list);
2476
2477 /*
2478 * Allocate space for all possible cpus to avoid allocation at
2479 * runtime
2480 */
2481 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
2482 gfp, node);
2483 if (!hctx->ctxs)
2484 goto free_cpumask;
2485
2486 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
2487 gfp, node))
2488 goto free_ctxs;
2489 hctx->nr_ctx = 0;
2490
2491 spin_lock_init(&hctx->dispatch_wait_lock);
2492 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
2493 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
2494
2495 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
2496 if (!hctx->fq)
2497 goto free_bitmap;
2498
2499 if (hctx->flags & BLK_MQ_F_BLOCKING)
2500 init_srcu_struct(hctx->srcu);
2501 blk_mq_hctx_kobj_init(hctx);
2502
2503 return hctx;
2504
2505 free_bitmap:
2506 sbitmap_free(&hctx->ctx_map);
2507 free_ctxs:
2508 kfree(hctx->ctxs);
2509 free_cpumask:
2510 free_cpumask_var(hctx->cpumask);
2511 free_hctx:
2512 kfree(hctx);
2513 fail_alloc_hctx:
2514 return NULL;
2515 }
2516
2517 static void blk_mq_init_cpu_queues(struct request_queue *q,
2518 unsigned int nr_hw_queues)
2519 {
2520 struct blk_mq_tag_set *set = q->tag_set;
2521 unsigned int i, j;
2522
2523 for_each_possible_cpu(i) {
2524 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
2525 struct blk_mq_hw_ctx *hctx;
2526 int k;
2527
2528 __ctx->cpu = i;
2529 spin_lock_init(&__ctx->lock);
2530 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
2531 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
2532
2533 __ctx->queue = q;
2534
2535 /*
2536 * Set local node, IFF we have more than one hw queue. If
2537 * not, we remain on the home node of the device
2538 */
2539 for (j = 0; j < set->nr_maps; j++) {
2540 hctx = blk_mq_map_queue_type(q, j, i);
2541 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
2542 hctx->numa_node = local_memory_node(cpu_to_node(i));
2543 }
2544 }
2545 }
2546
2547 static bool __blk_mq_alloc_map_and_request(struct blk_mq_tag_set *set,
2548 int hctx_idx)
2549 {
2550 int ret = 0;
2551
2552 set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
2553 set->queue_depth, set->reserved_tags);
2554 if (!set->tags[hctx_idx])
2555 return false;
2556
2557 ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
2558 set->queue_depth);
2559 if (!ret)
2560 return true;
2561
2562 blk_mq_free_rq_map(set->tags[hctx_idx]);
2563 set->tags[hctx_idx] = NULL;
2564 return false;
2565 }
2566
2567 static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2568 unsigned int hctx_idx)
2569 {
2570 if (set->tags && set->tags[hctx_idx]) {
2571 blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
2572 blk_mq_free_rq_map(set->tags[hctx_idx]);
2573 set->tags[hctx_idx] = NULL;
2574 }
2575 }
2576
2577 static void blk_mq_map_swqueue(struct request_queue *q)
2578 {
2579 unsigned int i, j, hctx_idx;
2580 struct blk_mq_hw_ctx *hctx;
2581 struct blk_mq_ctx *ctx;
2582 struct blk_mq_tag_set *set = q->tag_set;
2583
2584 queue_for_each_hw_ctx(q, hctx, i) {
2585 cpumask_clear(hctx->cpumask);
2586 hctx->nr_ctx = 0;
2587 hctx->dispatch_from = NULL;
2588 }
2589
2590 /*
2591 * Map software to hardware queues.
2592 *
2593 * If the cpu isn't present, the cpu is mapped to first hctx.
2594 */
2595 for_each_possible_cpu(i) {
2596
2597 ctx = per_cpu_ptr(q->queue_ctx, i);
2598 for (j = 0; j < set->nr_maps; j++) {
2599 if (!set->map[j].nr_queues) {
2600 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2601 HCTX_TYPE_DEFAULT, i);
2602 continue;
2603 }
2604 hctx_idx = set->map[j].mq_map[i];
2605 /* unmapped hw queue can be remapped after CPU topo changed */
2606 if (!set->tags[hctx_idx] &&
2607 !__blk_mq_alloc_map_and_request(set, hctx_idx)) {
2608 /*
2609 * If tags initialization fail for some hctx,
2610 * that hctx won't be brought online. In this
2611 * case, remap the current ctx to hctx[0] which
2612 * is guaranteed to always have tags allocated
2613 */
2614 set->map[j].mq_map[i] = 0;
2615 }
2616
2617 hctx = blk_mq_map_queue_type(q, j, i);
2618 ctx->hctxs[j] = hctx;
2619 /*
2620 * If the CPU is already set in the mask, then we've
2621 * mapped this one already. This can happen if
2622 * devices share queues across queue maps.
2623 */
2624 if (cpumask_test_cpu(i, hctx->cpumask))
2625 continue;
2626
2627 cpumask_set_cpu(i, hctx->cpumask);
2628 hctx->type = j;
2629 ctx->index_hw[hctx->type] = hctx->nr_ctx;
2630 hctx->ctxs[hctx->nr_ctx++] = ctx;
2631
2632 /*
2633 * If the nr_ctx type overflows, we have exceeded the
2634 * amount of sw queues we can support.
2635 */
2636 BUG_ON(!hctx->nr_ctx);
2637 }
2638
2639 for (; j < HCTX_MAX_TYPES; j++)
2640 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2641 HCTX_TYPE_DEFAULT, i);
2642 }
2643
2644 queue_for_each_hw_ctx(q, hctx, i) {
2645 /*
2646 * If no software queues are mapped to this hardware queue,
2647 * disable it and free the request entries.
2648 */
2649 if (!hctx->nr_ctx) {
2650 /* Never unmap queue 0. We need it as a
2651 * fallback in case of a new remap fails
2652 * allocation
2653 */
2654 if (i && set->tags[i])
2655 blk_mq_free_map_and_requests(set, i);
2656
2657 hctx->tags = NULL;
2658 continue;
2659 }
2660
2661 hctx->tags = set->tags[i];
2662 WARN_ON(!hctx->tags);
2663
2664 /*
2665 * Set the map size to the number of mapped software queues.
2666 * This is more accurate and more efficient than looping
2667 * over all possibly mapped software queues.
2668 */
2669 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
2670
2671 /*
2672 * Initialize batch roundrobin counts
2673 */
2674 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
2675 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2676 }
2677 }
2678
2679 /*
2680 * Caller needs to ensure that we're either frozen/quiesced, or that
2681 * the queue isn't live yet.
2682 */
2683 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
2684 {
2685 struct blk_mq_hw_ctx *hctx;
2686 int i;
2687
2688 queue_for_each_hw_ctx(q, hctx, i) {
2689 if (shared)
2690 hctx->flags |= BLK_MQ_F_TAG_SHARED;
2691 else
2692 hctx->flags &= ~BLK_MQ_F_TAG_SHARED;
2693 }
2694 }
2695
2696 static void blk_mq_update_tag_set_depth(struct blk_mq_tag_set *set,
2697 bool shared)
2698 {
2699 struct request_queue *q;
2700
2701 lockdep_assert_held(&set->tag_list_lock);
2702
2703 list_for_each_entry(q, &set->tag_list, tag_set_list) {
2704 blk_mq_freeze_queue(q);
2705 queue_set_hctx_shared(q, shared);
2706 blk_mq_unfreeze_queue(q);
2707 }
2708 }
2709
2710 static void blk_mq_del_queue_tag_set(struct request_queue *q)
2711 {
2712 struct blk_mq_tag_set *set = q->tag_set;
2713
2714 mutex_lock(&set->tag_list_lock);
2715 list_del_rcu(&q->tag_set_list);
2716 if (list_is_singular(&set->tag_list)) {
2717 /* just transitioned to unshared */
2718 set->flags &= ~BLK_MQ_F_TAG_SHARED;
2719 /* update existing queue */
2720 blk_mq_update_tag_set_depth(set, false);
2721 }
2722 mutex_unlock(&set->tag_list_lock);
2723 INIT_LIST_HEAD(&q->tag_set_list);
2724 }
2725
2726 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
2727 struct request_queue *q)
2728 {
2729 mutex_lock(&set->tag_list_lock);
2730
2731 /*
2732 * Check to see if we're transitioning to shared (from 1 to 2 queues).
2733 */
2734 if (!list_empty(&set->tag_list) &&
2735 !(set->flags & BLK_MQ_F_TAG_SHARED)) {
2736 set->flags |= BLK_MQ_F_TAG_SHARED;
2737 /* update existing queue */
2738 blk_mq_update_tag_set_depth(set, true);
2739 }
2740 if (set->flags & BLK_MQ_F_TAG_SHARED)
2741 queue_set_hctx_shared(q, true);
2742 list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
2743
2744 mutex_unlock(&set->tag_list_lock);
2745 }
2746
2747 /* All allocations will be freed in release handler of q->mq_kobj */
2748 static int blk_mq_alloc_ctxs(struct request_queue *q)
2749 {
2750 struct blk_mq_ctxs *ctxs;
2751 int cpu;
2752
2753 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
2754 if (!ctxs)
2755 return -ENOMEM;
2756
2757 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
2758 if (!ctxs->queue_ctx)
2759 goto fail;
2760
2761 for_each_possible_cpu(cpu) {
2762 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
2763 ctx->ctxs = ctxs;
2764 }
2765
2766 q->mq_kobj = &ctxs->kobj;
2767 q->queue_ctx = ctxs->queue_ctx;
2768
2769 return 0;
2770 fail:
2771 kfree(ctxs);
2772 return -ENOMEM;
2773 }
2774
2775 /*
2776 * It is the actual release handler for mq, but we do it from
2777 * request queue's release handler for avoiding use-after-free
2778 * and headache because q->mq_kobj shouldn't have been introduced,
2779 * but we can't group ctx/kctx kobj without it.
2780 */
2781 void blk_mq_release(struct request_queue *q)
2782 {
2783 struct blk_mq_hw_ctx *hctx, *next;
2784 int i;
2785
2786 queue_for_each_hw_ctx(q, hctx, i)
2787 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
2788
2789 /* all hctx are in .unused_hctx_list now */
2790 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
2791 list_del_init(&hctx->hctx_list);
2792 kobject_put(&hctx->kobj);
2793 }
2794
2795 kfree(q->queue_hw_ctx);
2796
2797 /*
2798 * release .mq_kobj and sw queue's kobject now because
2799 * both share lifetime with request queue.
2800 */
2801 blk_mq_sysfs_deinit(q);
2802 }
2803
2804 struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
2805 void *queuedata)
2806 {
2807 struct request_queue *uninit_q, *q;
2808
2809 uninit_q = __blk_alloc_queue(set->numa_node);
2810 if (!uninit_q)
2811 return ERR_PTR(-ENOMEM);
2812 uninit_q->queuedata = queuedata;
2813
2814 /*
2815 * Initialize the queue without an elevator. device_add_disk() will do
2816 * the initialization.
2817 */
2818 q = blk_mq_init_allocated_queue(set, uninit_q, false);
2819 if (IS_ERR(q))
2820 blk_cleanup_queue(uninit_q);
2821
2822 return q;
2823 }
2824 EXPORT_SYMBOL_GPL(blk_mq_init_queue_data);
2825
2826 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
2827 {
2828 return blk_mq_init_queue_data(set, NULL);
2829 }
2830 EXPORT_SYMBOL(blk_mq_init_queue);
2831
2832 /*
2833 * Helper for setting up a queue with mq ops, given queue depth, and
2834 * the passed in mq ops flags.
2835 */
2836 struct request_queue *blk_mq_init_sq_queue(struct blk_mq_tag_set *set,
2837 const struct blk_mq_ops *ops,
2838 unsigned int queue_depth,
2839 unsigned int set_flags)
2840 {
2841 struct request_queue *q;
2842 int ret;
2843
2844 memset(set, 0, sizeof(*set));
2845 set->ops = ops;
2846 set->nr_hw_queues = 1;
2847 set->nr_maps = 1;
2848 set->queue_depth = queue_depth;
2849 set->numa_node = NUMA_NO_NODE;
2850 set->flags = set_flags;
2851
2852 ret = blk_mq_alloc_tag_set(set);
2853 if (ret)
2854 return ERR_PTR(ret);
2855
2856 q = blk_mq_init_queue(set);
2857 if (IS_ERR(q)) {
2858 blk_mq_free_tag_set(set);
2859 return q;
2860 }
2861
2862 return q;
2863 }
2864 EXPORT_SYMBOL(blk_mq_init_sq_queue);
2865
2866 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
2867 struct blk_mq_tag_set *set, struct request_queue *q,
2868 int hctx_idx, int node)
2869 {
2870 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
2871
2872 /* reuse dead hctx first */
2873 spin_lock(&q->unused_hctx_lock);
2874 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
2875 if (tmp->numa_node == node) {
2876 hctx = tmp;
2877 break;
2878 }
2879 }
2880 if (hctx)
2881 list_del_init(&hctx->hctx_list);
2882 spin_unlock(&q->unused_hctx_lock);
2883
2884 if (!hctx)
2885 hctx = blk_mq_alloc_hctx(q, set, node);
2886 if (!hctx)
2887 goto fail;
2888
2889 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
2890 goto free_hctx;
2891
2892 return hctx;
2893
2894 free_hctx:
2895 kobject_put(&hctx->kobj);
2896 fail:
2897 return NULL;
2898 }
2899
2900 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
2901 struct request_queue *q)
2902 {
2903 int i, j, end;
2904 struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
2905
2906 if (q->nr_hw_queues < set->nr_hw_queues) {
2907 struct blk_mq_hw_ctx **new_hctxs;
2908
2909 new_hctxs = kcalloc_node(set->nr_hw_queues,
2910 sizeof(*new_hctxs), GFP_KERNEL,
2911 set->numa_node);
2912 if (!new_hctxs)
2913 return;
2914 if (hctxs)
2915 memcpy(new_hctxs, hctxs, q->nr_hw_queues *
2916 sizeof(*hctxs));
2917 q->queue_hw_ctx = new_hctxs;
2918 kfree(hctxs);
2919 hctxs = new_hctxs;
2920 }
2921
2922 /* protect against switching io scheduler */
2923 mutex_lock(&q->sysfs_lock);
2924 for (i = 0; i < set->nr_hw_queues; i++) {
2925 int node;
2926 struct blk_mq_hw_ctx *hctx;
2927
2928 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
2929 /*
2930 * If the hw queue has been mapped to another numa node,
2931 * we need to realloc the hctx. If allocation fails, fallback
2932 * to use the previous one.
2933 */
2934 if (hctxs[i] && (hctxs[i]->numa_node == node))
2935 continue;
2936
2937 hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
2938 if (hctx) {
2939 if (hctxs[i])
2940 blk_mq_exit_hctx(q, set, hctxs[i], i);
2941 hctxs[i] = hctx;
2942 } else {
2943 if (hctxs[i])
2944 pr_warn("Allocate new hctx on node %d fails,\
2945 fallback to previous one on node %d\n",
2946 node, hctxs[i]->numa_node);
2947 else
2948 break;
2949 }
2950 }
2951 /*
2952 * Increasing nr_hw_queues fails. Free the newly allocated
2953 * hctxs and keep the previous q->nr_hw_queues.
2954 */
2955 if (i != set->nr_hw_queues) {
2956 j = q->nr_hw_queues;
2957 end = i;
2958 } else {
2959 j = i;
2960 end = q->nr_hw_queues;
2961 q->nr_hw_queues = set->nr_hw_queues;
2962 }
2963
2964 for (; j < end; j++) {
2965 struct blk_mq_hw_ctx *hctx = hctxs[j];
2966
2967 if (hctx) {
2968 if (hctx->tags)
2969 blk_mq_free_map_and_requests(set, j);
2970 blk_mq_exit_hctx(q, set, hctx, j);
2971 hctxs[j] = NULL;
2972 }
2973 }
2974 mutex_unlock(&q->sysfs_lock);
2975 }
2976
2977 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
2978 struct request_queue *q,
2979 bool elevator_init)
2980 {
2981 /* mark the queue as mq asap */
2982 q->mq_ops = set->ops;
2983
2984 q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
2985 blk_mq_poll_stats_bkt,
2986 BLK_MQ_POLL_STATS_BKTS, q);
2987 if (!q->poll_cb)
2988 goto err_exit;
2989
2990 if (blk_mq_alloc_ctxs(q))
2991 goto err_poll;
2992
2993 /* init q->mq_kobj and sw queues' kobjects */
2994 blk_mq_sysfs_init(q);
2995
2996 INIT_LIST_HEAD(&q->unused_hctx_list);
2997 spin_lock_init(&q->unused_hctx_lock);
2998
2999 blk_mq_realloc_hw_ctxs(set, q);
3000 if (!q->nr_hw_queues)
3001 goto err_hctxs;
3002
3003 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
3004 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
3005
3006 q->tag_set = set;
3007
3008 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
3009 if (set->nr_maps > HCTX_TYPE_POLL &&
3010 set->map[HCTX_TYPE_POLL].nr_queues)
3011 blk_queue_flag_set(QUEUE_FLAG_POLL, q);
3012
3013 q->sg_reserved_size = INT_MAX;
3014
3015 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
3016 INIT_LIST_HEAD(&q->requeue_list);
3017 spin_lock_init(&q->requeue_lock);
3018
3019 q->nr_requests = set->queue_depth;
3020
3021 /*
3022 * Default to classic polling
3023 */
3024 q->poll_nsec = BLK_MQ_POLL_CLASSIC;
3025
3026 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
3027 blk_mq_add_queue_tag_set(set, q);
3028 blk_mq_map_swqueue(q);
3029
3030 if (elevator_init)
3031 elevator_init_mq(q);
3032
3033 return q;
3034
3035 err_hctxs:
3036 kfree(q->queue_hw_ctx);
3037 q->nr_hw_queues = 0;
3038 blk_mq_sysfs_deinit(q);
3039 err_poll:
3040 blk_stat_free_callback(q->poll_cb);
3041 q->poll_cb = NULL;
3042 err_exit:
3043 q->mq_ops = NULL;
3044 return ERR_PTR(-ENOMEM);
3045 }
3046 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
3047
3048 /* tags can _not_ be used after returning from blk_mq_exit_queue */
3049 void blk_mq_exit_queue(struct request_queue *q)
3050 {
3051 struct blk_mq_tag_set *set = q->tag_set;
3052
3053 blk_mq_del_queue_tag_set(q);
3054 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
3055 }
3056
3057 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
3058 {
3059 int i;
3060
3061 for (i = 0; i < set->nr_hw_queues; i++)
3062 if (!__blk_mq_alloc_map_and_request(set, i))
3063 goto out_unwind;
3064
3065 return 0;
3066
3067 out_unwind:
3068 while (--i >= 0)
3069 blk_mq_free_map_and_requests(set, i);
3070
3071 return -ENOMEM;
3072 }
3073
3074 /*
3075 * Allocate the request maps associated with this tag_set. Note that this
3076 * may reduce the depth asked for, if memory is tight. set->queue_depth
3077 * will be updated to reflect the allocated depth.
3078 */
3079 static int blk_mq_alloc_map_and_requests(struct blk_mq_tag_set *set)
3080 {
3081 unsigned int depth;
3082 int err;
3083
3084 depth = set->queue_depth;
3085 do {
3086 err = __blk_mq_alloc_rq_maps(set);
3087 if (!err)
3088 break;
3089
3090 set->queue_depth >>= 1;
3091 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
3092 err = -ENOMEM;
3093 break;
3094 }
3095 } while (set->queue_depth);
3096
3097 if (!set->queue_depth || err) {
3098 pr_err("blk-mq: failed to allocate request map\n");
3099 return -ENOMEM;
3100 }
3101
3102 if (depth != set->queue_depth)
3103 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
3104 depth, set->queue_depth);
3105
3106 return 0;
3107 }
3108
3109 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
3110 {
3111 /*
3112 * blk_mq_map_queues() and multiple .map_queues() implementations
3113 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
3114 * number of hardware queues.
3115 */
3116 if (set->nr_maps == 1)
3117 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
3118
3119 if (set->ops->map_queues && !is_kdump_kernel()) {
3120 int i;
3121
3122 /*
3123 * transport .map_queues is usually done in the following
3124 * way:
3125 *
3126 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
3127 * mask = get_cpu_mask(queue)
3128 * for_each_cpu(cpu, mask)
3129 * set->map[x].mq_map[cpu] = queue;
3130 * }
3131 *
3132 * When we need to remap, the table has to be cleared for
3133 * killing stale mapping since one CPU may not be mapped
3134 * to any hw queue.
3135 */
3136 for (i = 0; i < set->nr_maps; i++)
3137 blk_mq_clear_mq_map(&set->map[i]);
3138
3139 return set->ops->map_queues(set);
3140 } else {
3141 BUG_ON(set->nr_maps > 1);
3142 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3143 }
3144 }
3145
3146 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
3147 int cur_nr_hw_queues, int new_nr_hw_queues)
3148 {
3149 struct blk_mq_tags **new_tags;
3150
3151 if (cur_nr_hw_queues >= new_nr_hw_queues)
3152 return 0;
3153
3154 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
3155 GFP_KERNEL, set->numa_node);
3156 if (!new_tags)
3157 return -ENOMEM;
3158
3159 if (set->tags)
3160 memcpy(new_tags, set->tags, cur_nr_hw_queues *
3161 sizeof(*set->tags));
3162 kfree(set->tags);
3163 set->tags = new_tags;
3164 set->nr_hw_queues = new_nr_hw_queues;
3165
3166 return 0;
3167 }
3168
3169 /*
3170 * Alloc a tag set to be associated with one or more request queues.
3171 * May fail with EINVAL for various error conditions. May adjust the
3172 * requested depth down, if it's too large. In that case, the set
3173 * value will be stored in set->queue_depth.
3174 */
3175 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
3176 {
3177 int i, ret;
3178
3179 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
3180
3181 if (!set->nr_hw_queues)
3182 return -EINVAL;
3183 if (!set->queue_depth)
3184 return -EINVAL;
3185 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
3186 return -EINVAL;
3187
3188 if (!set->ops->queue_rq)
3189 return -EINVAL;
3190
3191 if (!set->ops->get_budget ^ !set->ops->put_budget)
3192 return -EINVAL;
3193
3194 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
3195 pr_info("blk-mq: reduced tag depth to %u\n",
3196 BLK_MQ_MAX_DEPTH);
3197 set->queue_depth = BLK_MQ_MAX_DEPTH;
3198 }
3199
3200 if (!set->nr_maps)
3201 set->nr_maps = 1;
3202 else if (set->nr_maps > HCTX_MAX_TYPES)
3203 return -EINVAL;
3204
3205 /*
3206 * If a crashdump is active, then we are potentially in a very
3207 * memory constrained environment. Limit us to 1 queue and
3208 * 64 tags to prevent using too much memory.
3209 */
3210 if (is_kdump_kernel()) {
3211 set->nr_hw_queues = 1;
3212 set->nr_maps = 1;
3213 set->queue_depth = min(64U, set->queue_depth);
3214 }
3215 /*
3216 * There is no use for more h/w queues than cpus if we just have
3217 * a single map
3218 */
3219 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
3220 set->nr_hw_queues = nr_cpu_ids;
3221
3222 if (blk_mq_realloc_tag_set_tags(set, 0, set->nr_hw_queues) < 0)
3223 return -ENOMEM;
3224
3225 ret = -ENOMEM;
3226 for (i = 0; i < set->nr_maps; i++) {
3227 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
3228 sizeof(set->map[i].mq_map[0]),
3229 GFP_KERNEL, set->numa_node);
3230 if (!set->map[i].mq_map)
3231 goto out_free_mq_map;
3232 set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
3233 }
3234
3235 ret = blk_mq_update_queue_map(set);
3236 if (ret)
3237 goto out_free_mq_map;
3238
3239 ret = blk_mq_alloc_map_and_requests(set);
3240 if (ret)
3241 goto out_free_mq_map;
3242
3243 mutex_init(&set->tag_list_lock);
3244 INIT_LIST_HEAD(&set->tag_list);
3245
3246 return 0;
3247
3248 out_free_mq_map:
3249 for (i = 0; i < set->nr_maps; i++) {
3250 kfree(set->map[i].mq_map);
3251 set->map[i].mq_map = NULL;
3252 }
3253 kfree(set->tags);
3254 set->tags = NULL;
3255 return ret;
3256 }
3257 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
3258
3259 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
3260 {
3261 int i, j;
3262
3263 for (i = 0; i < set->nr_hw_queues; i++)
3264 blk_mq_free_map_and_requests(set, i);
3265
3266 for (j = 0; j < set->nr_maps; j++) {
3267 kfree(set->map[j].mq_map);
3268 set->map[j].mq_map = NULL;
3269 }
3270
3271 kfree(set->tags);
3272 set->tags = NULL;
3273 }
3274 EXPORT_SYMBOL(blk_mq_free_tag_set);
3275
3276 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
3277 {
3278 struct blk_mq_tag_set *set = q->tag_set;
3279 struct blk_mq_hw_ctx *hctx;
3280 int i, ret;
3281
3282 if (!set)
3283 return -EINVAL;
3284
3285 if (q->nr_requests == nr)
3286 return 0;
3287
3288 blk_mq_freeze_queue(q);
3289 blk_mq_quiesce_queue(q);
3290
3291 ret = 0;
3292 queue_for_each_hw_ctx(q, hctx, i) {
3293 if (!hctx->tags)
3294 continue;
3295 /*
3296 * If we're using an MQ scheduler, just update the scheduler
3297 * queue depth. This is similar to what the old code would do.
3298 */
3299 if (!hctx->sched_tags) {
3300 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
3301 false);
3302 } else {
3303 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
3304 nr, true);
3305 }
3306 if (ret)
3307 break;
3308 if (q->elevator && q->elevator->type->ops.depth_updated)
3309 q->elevator->type->ops.depth_updated(hctx);
3310 }
3311
3312 if (!ret)
3313 q->nr_requests = nr;
3314
3315 blk_mq_unquiesce_queue(q);
3316 blk_mq_unfreeze_queue(q);
3317
3318 return ret;
3319 }
3320
3321 /*
3322 * request_queue and elevator_type pair.
3323 * It is just used by __blk_mq_update_nr_hw_queues to cache
3324 * the elevator_type associated with a request_queue.
3325 */
3326 struct blk_mq_qe_pair {
3327 struct list_head node;
3328 struct request_queue *q;
3329 struct elevator_type *type;
3330 };
3331
3332 /*
3333 * Cache the elevator_type in qe pair list and switch the
3334 * io scheduler to 'none'
3335 */
3336 static bool blk_mq_elv_switch_none(struct list_head *head,
3337 struct request_queue *q)
3338 {
3339 struct blk_mq_qe_pair *qe;
3340
3341 if (!q->elevator)
3342 return true;
3343
3344 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
3345 if (!qe)
3346 return false;
3347
3348 INIT_LIST_HEAD(&qe->node);
3349 qe->q = q;
3350 qe->type = q->elevator->type;
3351 list_add(&qe->node, head);
3352
3353 mutex_lock(&q->sysfs_lock);
3354 /*
3355 * After elevator_switch_mq, the previous elevator_queue will be
3356 * released by elevator_release. The reference of the io scheduler
3357 * module get by elevator_get will also be put. So we need to get
3358 * a reference of the io scheduler module here to prevent it to be
3359 * removed.
3360 */
3361 __module_get(qe->type->elevator_owner);
3362 elevator_switch_mq(q, NULL);
3363 mutex_unlock(&q->sysfs_lock);
3364
3365 return true;
3366 }
3367
3368 static void blk_mq_elv_switch_back(struct list_head *head,
3369 struct request_queue *q)
3370 {
3371 struct blk_mq_qe_pair *qe;
3372 struct elevator_type *t = NULL;
3373
3374 list_for_each_entry(qe, head, node)
3375 if (qe->q == q) {
3376 t = qe->type;
3377 break;
3378 }
3379
3380 if (!t)
3381 return;
3382
3383 list_del(&qe->node);
3384 kfree(qe);
3385
3386 mutex_lock(&q->sysfs_lock);
3387 elevator_switch_mq(q, t);
3388 mutex_unlock(&q->sysfs_lock);
3389 }
3390
3391 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
3392 int nr_hw_queues)
3393 {
3394 struct request_queue *q;
3395 LIST_HEAD(head);
3396 int prev_nr_hw_queues;
3397
3398 lockdep_assert_held(&set->tag_list_lock);
3399
3400 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
3401 nr_hw_queues = nr_cpu_ids;
3402 if (nr_hw_queues < 1 || nr_hw_queues == set->nr_hw_queues)
3403 return;
3404
3405 list_for_each_entry(q, &set->tag_list, tag_set_list)
3406 blk_mq_freeze_queue(q);
3407 /*
3408 * Switch IO scheduler to 'none', cleaning up the data associated
3409 * with the previous scheduler. We will switch back once we are done
3410 * updating the new sw to hw queue mappings.
3411 */
3412 list_for_each_entry(q, &set->tag_list, tag_set_list)
3413 if (!blk_mq_elv_switch_none(&head, q))
3414 goto switch_back;
3415
3416 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3417 blk_mq_debugfs_unregister_hctxs(q);
3418 blk_mq_sysfs_unregister(q);
3419 }
3420
3421 prev_nr_hw_queues = set->nr_hw_queues;
3422 if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
3423 0)
3424 goto reregister;
3425
3426 set->nr_hw_queues = nr_hw_queues;
3427 fallback:
3428 blk_mq_update_queue_map(set);
3429 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3430 blk_mq_realloc_hw_ctxs(set, q);
3431 if (q->nr_hw_queues != set->nr_hw_queues) {
3432 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
3433 nr_hw_queues, prev_nr_hw_queues);
3434 set->nr_hw_queues = prev_nr_hw_queues;
3435 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3436 goto fallback;
3437 }
3438 blk_mq_map_swqueue(q);
3439 }
3440
3441 reregister:
3442 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3443 blk_mq_sysfs_register(q);
3444 blk_mq_debugfs_register_hctxs(q);
3445 }
3446
3447 switch_back:
3448 list_for_each_entry(q, &set->tag_list, tag_set_list)
3449 blk_mq_elv_switch_back(&head, q);
3450
3451 list_for_each_entry(q, &set->tag_list, tag_set_list)
3452 blk_mq_unfreeze_queue(q);
3453 }
3454
3455 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
3456 {
3457 mutex_lock(&set->tag_list_lock);
3458 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
3459 mutex_unlock(&set->tag_list_lock);
3460 }
3461 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
3462
3463 /* Enable polling stats and return whether they were already enabled. */
3464 static bool blk_poll_stats_enable(struct request_queue *q)
3465 {
3466 if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3467 blk_queue_flag_test_and_set(QUEUE_FLAG_POLL_STATS, q))
3468 return true;
3469 blk_stat_add_callback(q, q->poll_cb);
3470 return false;
3471 }
3472
3473 static void blk_mq_poll_stats_start(struct request_queue *q)
3474 {
3475 /*
3476 * We don't arm the callback if polling stats are not enabled or the
3477 * callback is already active.
3478 */
3479 if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3480 blk_stat_is_active(q->poll_cb))
3481 return;
3482
3483 blk_stat_activate_msecs(q->poll_cb, 100);
3484 }
3485
3486 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
3487 {
3488 struct request_queue *q = cb->data;
3489 int bucket;
3490
3491 for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
3492 if (cb->stat[bucket].nr_samples)
3493 q->poll_stat[bucket] = cb->stat[bucket];
3494 }
3495 }
3496
3497 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
3498 struct request *rq)
3499 {
3500 unsigned long ret = 0;
3501 int bucket;
3502
3503 /*
3504 * If stats collection isn't on, don't sleep but turn it on for
3505 * future users
3506 */
3507 if (!blk_poll_stats_enable(q))
3508 return 0;
3509
3510 /*
3511 * As an optimistic guess, use half of the mean service time
3512 * for this type of request. We can (and should) make this smarter.
3513 * For instance, if the completion latencies are tight, we can
3514 * get closer than just half the mean. This is especially
3515 * important on devices where the completion latencies are longer
3516 * than ~10 usec. We do use the stats for the relevant IO size
3517 * if available which does lead to better estimates.
3518 */
3519 bucket = blk_mq_poll_stats_bkt(rq);
3520 if (bucket < 0)
3521 return ret;
3522
3523 if (q->poll_stat[bucket].nr_samples)
3524 ret = (q->poll_stat[bucket].mean + 1) / 2;
3525
3526 return ret;
3527 }
3528
3529 static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
3530 struct request *rq)
3531 {
3532 struct hrtimer_sleeper hs;
3533 enum hrtimer_mode mode;
3534 unsigned int nsecs;
3535 ktime_t kt;
3536
3537 if (rq->rq_flags & RQF_MQ_POLL_SLEPT)
3538 return false;
3539
3540 /*
3541 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
3542 *
3543 * 0: use half of prev avg
3544 * >0: use this specific value
3545 */
3546 if (q->poll_nsec > 0)
3547 nsecs = q->poll_nsec;
3548 else
3549 nsecs = blk_mq_poll_nsecs(q, rq);
3550
3551 if (!nsecs)
3552 return false;
3553
3554 rq->rq_flags |= RQF_MQ_POLL_SLEPT;
3555
3556 /*
3557 * This will be replaced with the stats tracking code, using
3558 * 'avg_completion_time / 2' as the pre-sleep target.
3559 */
3560 kt = nsecs;
3561
3562 mode = HRTIMER_MODE_REL;
3563 hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
3564 hrtimer_set_expires(&hs.timer, kt);
3565
3566 do {
3567 if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
3568 break;
3569 set_current_state(TASK_UNINTERRUPTIBLE);
3570 hrtimer_sleeper_start_expires(&hs, mode);
3571 if (hs.task)
3572 io_schedule();
3573 hrtimer_cancel(&hs.timer);
3574 mode = HRTIMER_MODE_ABS;
3575 } while (hs.task && !signal_pending(current));
3576
3577 __set_current_state(TASK_RUNNING);
3578 destroy_hrtimer_on_stack(&hs.timer);
3579 return true;
3580 }
3581
3582 static bool blk_mq_poll_hybrid(struct request_queue *q,
3583 struct blk_mq_hw_ctx *hctx, blk_qc_t cookie)
3584 {
3585 struct request *rq;
3586
3587 if (q->poll_nsec == BLK_MQ_POLL_CLASSIC)
3588 return false;
3589
3590 if (!blk_qc_t_is_internal(cookie))
3591 rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
3592 else {
3593 rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
3594 /*
3595 * With scheduling, if the request has completed, we'll
3596 * get a NULL return here, as we clear the sched tag when
3597 * that happens. The request still remains valid, like always,
3598 * so we should be safe with just the NULL check.
3599 */
3600 if (!rq)
3601 return false;
3602 }
3603
3604 return blk_mq_poll_hybrid_sleep(q, rq);
3605 }
3606
3607 /**
3608 * blk_poll - poll for IO completions
3609 * @q: the queue
3610 * @cookie: cookie passed back at IO submission time
3611 * @spin: whether to spin for completions
3612 *
3613 * Description:
3614 * Poll for completions on the passed in queue. Returns number of
3615 * completed entries found. If @spin is true, then blk_poll will continue
3616 * looping until at least one completion is found, unless the task is
3617 * otherwise marked running (or we need to reschedule).
3618 */
3619 int blk_poll(struct request_queue *q, blk_qc_t cookie, bool spin)
3620 {
3621 struct blk_mq_hw_ctx *hctx;
3622 long state;
3623
3624 if (!blk_qc_t_valid(cookie) ||
3625 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3626 return 0;
3627
3628 if (current->plug)
3629 blk_flush_plug_list(current->plug, false);
3630
3631 hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
3632
3633 /*
3634 * If we sleep, have the caller restart the poll loop to reset
3635 * the state. Like for the other success return cases, the
3636 * caller is responsible for checking if the IO completed. If
3637 * the IO isn't complete, we'll get called again and will go
3638 * straight to the busy poll loop.
3639 */
3640 if (blk_mq_poll_hybrid(q, hctx, cookie))
3641 return 1;
3642
3643 hctx->poll_considered++;
3644
3645 state = current->state;
3646 do {
3647 int ret;
3648
3649 hctx->poll_invoked++;
3650
3651 ret = q->mq_ops->poll(hctx);
3652 if (ret > 0) {
3653 hctx->poll_success++;
3654 __set_current_state(TASK_RUNNING);
3655 return ret;
3656 }
3657
3658 if (signal_pending_state(state, current))
3659 __set_current_state(TASK_RUNNING);
3660
3661 if (current->state == TASK_RUNNING)
3662 return 1;
3663 if (ret < 0 || !spin)
3664 break;
3665 cpu_relax();
3666 } while (!need_resched());
3667
3668 __set_current_state(TASK_RUNNING);
3669 return 0;
3670 }
3671 EXPORT_SYMBOL_GPL(blk_poll);
3672
3673 unsigned int blk_mq_rq_cpu(struct request *rq)
3674 {
3675 return rq->mq_ctx->cpu;
3676 }
3677 EXPORT_SYMBOL(blk_mq_rq_cpu);
3678
3679 static int __init blk_mq_init(void)
3680 {
3681 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
3682 blk_mq_hctx_notify_dead);
3683 return 0;
3684 }
3685 subsys_initcall(blk_mq_init);