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