Merge tag 'trace-printf-v6.13' of git://git.kernel.org/pub/scm/linux/kernel/git/trace...
[drm/drm-misc.git] / block / blk-mq.c
blob424239c075e28c301d0d17e03bf114bc8f582780
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Block multiqueue core code
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/blk-integrity.h>
14 #include <linux/kmemleak.h>
15 #include <linux/mm.h>
16 #include <linux/init.h>
17 #include <linux/slab.h>
18 #include <linux/workqueue.h>
19 #include <linux/smp.h>
20 #include <linux/interrupt.h>
21 #include <linux/llist.h>
22 #include <linux/cpu.h>
23 #include <linux/cache.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 #include <linux/part_stat.h>
31 #include <linux/sched/isolation.h>
33 #include <trace/events/block.h>
35 #include <linux/t10-pi.h>
36 #include "blk.h"
37 #include "blk-mq.h"
38 #include "blk-mq-debugfs.h"
39 #include "blk-pm.h"
40 #include "blk-stat.h"
41 #include "blk-mq-sched.h"
42 #include "blk-rq-qos.h"
44 static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
45 static DEFINE_PER_CPU(call_single_data_t, blk_cpu_csd);
47 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags);
48 static void blk_mq_request_bypass_insert(struct request *rq,
49 blk_insert_t flags);
50 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
51 struct list_head *list);
52 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
53 struct io_comp_batch *iob, unsigned int flags);
56 * Check if any of the ctx, dispatch list or elevator
57 * have pending work in this hardware queue.
59 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
61 return !list_empty_careful(&hctx->dispatch) ||
62 sbitmap_any_bit_set(&hctx->ctx_map) ||
63 blk_mq_sched_has_work(hctx);
67 * Mark this ctx as having pending work in this hardware queue
69 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
70 struct blk_mq_ctx *ctx)
72 const int bit = ctx->index_hw[hctx->type];
74 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
75 sbitmap_set_bit(&hctx->ctx_map, bit);
78 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
79 struct blk_mq_ctx *ctx)
81 const int bit = ctx->index_hw[hctx->type];
83 sbitmap_clear_bit(&hctx->ctx_map, bit);
86 struct mq_inflight {
87 struct block_device *part;
88 unsigned int inflight[2];
91 static bool blk_mq_check_inflight(struct request *rq, void *priv)
93 struct mq_inflight *mi = priv;
95 if (rq->rq_flags & RQF_IO_STAT &&
96 (!bdev_is_partition(mi->part) || rq->part == mi->part) &&
97 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
98 mi->inflight[rq_data_dir(rq)]++;
100 return true;
103 unsigned int blk_mq_in_flight(struct request_queue *q,
104 struct block_device *part)
106 struct mq_inflight mi = { .part = part };
108 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
110 return mi.inflight[0] + mi.inflight[1];
113 void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
114 unsigned int inflight[2])
116 struct mq_inflight mi = { .part = part };
118 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
119 inflight[0] = mi.inflight[0];
120 inflight[1] = mi.inflight[1];
123 #ifdef CONFIG_LOCKDEP
124 static bool blk_freeze_set_owner(struct request_queue *q,
125 struct task_struct *owner)
127 if (!owner)
128 return false;
130 if (!q->mq_freeze_depth) {
131 q->mq_freeze_owner = owner;
132 q->mq_freeze_owner_depth = 1;
133 return true;
136 if (owner == q->mq_freeze_owner)
137 q->mq_freeze_owner_depth += 1;
138 return false;
141 /* verify the last unfreeze in owner context */
142 static bool blk_unfreeze_check_owner(struct request_queue *q)
144 if (!q->mq_freeze_owner)
145 return false;
146 if (q->mq_freeze_owner != current)
147 return false;
148 if (--q->mq_freeze_owner_depth == 0) {
149 q->mq_freeze_owner = NULL;
150 return true;
152 return false;
155 #else
157 static bool blk_freeze_set_owner(struct request_queue *q,
158 struct task_struct *owner)
160 return false;
163 static bool blk_unfreeze_check_owner(struct request_queue *q)
165 return false;
167 #endif
169 bool __blk_freeze_queue_start(struct request_queue *q,
170 struct task_struct *owner)
172 bool freeze;
174 mutex_lock(&q->mq_freeze_lock);
175 freeze = blk_freeze_set_owner(q, owner);
176 if (++q->mq_freeze_depth == 1) {
177 percpu_ref_kill(&q->q_usage_counter);
178 mutex_unlock(&q->mq_freeze_lock);
179 if (queue_is_mq(q))
180 blk_mq_run_hw_queues(q, false);
181 } else {
182 mutex_unlock(&q->mq_freeze_lock);
185 return freeze;
188 void blk_freeze_queue_start(struct request_queue *q)
190 if (__blk_freeze_queue_start(q, current))
191 blk_freeze_acquire_lock(q, false, false);
193 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
195 void blk_mq_freeze_queue_wait(struct request_queue *q)
197 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
199 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
201 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
202 unsigned long timeout)
204 return wait_event_timeout(q->mq_freeze_wq,
205 percpu_ref_is_zero(&q->q_usage_counter),
206 timeout);
208 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
210 void blk_mq_freeze_queue(struct request_queue *q)
212 blk_freeze_queue_start(q);
213 blk_mq_freeze_queue_wait(q);
215 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
217 bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
219 bool unfreeze;
221 mutex_lock(&q->mq_freeze_lock);
222 if (force_atomic)
223 q->q_usage_counter.data->force_atomic = true;
224 q->mq_freeze_depth--;
225 WARN_ON_ONCE(q->mq_freeze_depth < 0);
226 if (!q->mq_freeze_depth) {
227 percpu_ref_resurrect(&q->q_usage_counter);
228 wake_up_all(&q->mq_freeze_wq);
230 unfreeze = blk_unfreeze_check_owner(q);
231 mutex_unlock(&q->mq_freeze_lock);
233 return unfreeze;
236 void blk_mq_unfreeze_queue(struct request_queue *q)
238 if (__blk_mq_unfreeze_queue(q, false))
239 blk_unfreeze_release_lock(q, false, false);
241 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
244 * non_owner variant of blk_freeze_queue_start
246 * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
247 * by the same task. This is fragile and should not be used if at all
248 * possible.
250 void blk_freeze_queue_start_non_owner(struct request_queue *q)
252 __blk_freeze_queue_start(q, NULL);
254 EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
256 /* non_owner variant of blk_mq_unfreeze_queue */
257 void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
259 __blk_mq_unfreeze_queue(q, false);
261 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
264 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
265 * mpt3sas driver such that this function can be removed.
267 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
269 unsigned long flags;
271 spin_lock_irqsave(&q->queue_lock, flags);
272 if (!q->quiesce_depth++)
273 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
274 spin_unlock_irqrestore(&q->queue_lock, flags);
276 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
279 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
280 * @set: tag_set to wait on
282 * Note: it is driver's responsibility for making sure that quiesce has
283 * been started on or more of the request_queues of the tag_set. This
284 * function only waits for the quiesce on those request_queues that had
285 * the quiesce flag set using blk_mq_quiesce_queue_nowait.
287 void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
289 if (set->flags & BLK_MQ_F_BLOCKING)
290 synchronize_srcu(set->srcu);
291 else
292 synchronize_rcu();
294 EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
297 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
298 * @q: request queue.
300 * Note: this function does not prevent that the struct request end_io()
301 * callback function is invoked. Once this function is returned, we make
302 * sure no dispatch can happen until the queue is unquiesced via
303 * blk_mq_unquiesce_queue().
305 void blk_mq_quiesce_queue(struct request_queue *q)
307 blk_mq_quiesce_queue_nowait(q);
308 /* nothing to wait for non-mq queues */
309 if (queue_is_mq(q))
310 blk_mq_wait_quiesce_done(q->tag_set);
312 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
315 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
316 * @q: request queue.
318 * This function recovers queue into the state before quiescing
319 * which is done by blk_mq_quiesce_queue.
321 void blk_mq_unquiesce_queue(struct request_queue *q)
323 unsigned long flags;
324 bool run_queue = false;
326 spin_lock_irqsave(&q->queue_lock, flags);
327 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
329 } else if (!--q->quiesce_depth) {
330 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
331 run_queue = true;
333 spin_unlock_irqrestore(&q->queue_lock, flags);
335 /* dispatch requests which are inserted during quiescing */
336 if (run_queue)
337 blk_mq_run_hw_queues(q, true);
339 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
341 void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
343 struct request_queue *q;
345 mutex_lock(&set->tag_list_lock);
346 list_for_each_entry(q, &set->tag_list, tag_set_list) {
347 if (!blk_queue_skip_tagset_quiesce(q))
348 blk_mq_quiesce_queue_nowait(q);
350 mutex_unlock(&set->tag_list_lock);
352 blk_mq_wait_quiesce_done(set);
354 EXPORT_SYMBOL_GPL(blk_mq_quiesce_tagset);
356 void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
358 struct request_queue *q;
360 mutex_lock(&set->tag_list_lock);
361 list_for_each_entry(q, &set->tag_list, tag_set_list) {
362 if (!blk_queue_skip_tagset_quiesce(q))
363 blk_mq_unquiesce_queue(q);
365 mutex_unlock(&set->tag_list_lock);
367 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
369 void blk_mq_wake_waiters(struct request_queue *q)
371 struct blk_mq_hw_ctx *hctx;
372 unsigned long i;
374 queue_for_each_hw_ctx(q, hctx, i)
375 if (blk_mq_hw_queue_mapped(hctx))
376 blk_mq_tag_wakeup_all(hctx->tags, true);
379 void blk_rq_init(struct request_queue *q, struct request *rq)
381 memset(rq, 0, sizeof(*rq));
383 INIT_LIST_HEAD(&rq->queuelist);
384 rq->q = q;
385 rq->__sector = (sector_t) -1;
386 INIT_HLIST_NODE(&rq->hash);
387 RB_CLEAR_NODE(&rq->rb_node);
388 rq->tag = BLK_MQ_NO_TAG;
389 rq->internal_tag = BLK_MQ_NO_TAG;
390 rq->start_time_ns = blk_time_get_ns();
391 blk_crypto_rq_set_defaults(rq);
393 EXPORT_SYMBOL(blk_rq_init);
395 /* Set start and alloc time when the allocated request is actually used */
396 static inline void blk_mq_rq_time_init(struct request *rq, u64 alloc_time_ns)
398 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
399 if (blk_queue_rq_alloc_time(rq->q))
400 rq->alloc_time_ns = alloc_time_ns;
401 else
402 rq->alloc_time_ns = 0;
403 #endif
406 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
407 struct blk_mq_tags *tags, unsigned int tag)
409 struct blk_mq_ctx *ctx = data->ctx;
410 struct blk_mq_hw_ctx *hctx = data->hctx;
411 struct request_queue *q = data->q;
412 struct request *rq = tags->static_rqs[tag];
414 rq->q = q;
415 rq->mq_ctx = ctx;
416 rq->mq_hctx = hctx;
417 rq->cmd_flags = data->cmd_flags;
419 if (data->flags & BLK_MQ_REQ_PM)
420 data->rq_flags |= RQF_PM;
421 rq->rq_flags = data->rq_flags;
423 if (data->rq_flags & RQF_SCHED_TAGS) {
424 rq->tag = BLK_MQ_NO_TAG;
425 rq->internal_tag = tag;
426 } else {
427 rq->tag = tag;
428 rq->internal_tag = BLK_MQ_NO_TAG;
430 rq->timeout = 0;
432 rq->part = NULL;
433 rq->io_start_time_ns = 0;
434 rq->stats_sectors = 0;
435 rq->nr_phys_segments = 0;
436 rq->nr_integrity_segments = 0;
437 rq->end_io = NULL;
438 rq->end_io_data = NULL;
440 blk_crypto_rq_set_defaults(rq);
441 INIT_LIST_HEAD(&rq->queuelist);
442 /* tag was already set */
443 WRITE_ONCE(rq->deadline, 0);
444 req_ref_set(rq, 1);
446 if (rq->rq_flags & RQF_USE_SCHED) {
447 struct elevator_queue *e = data->q->elevator;
449 INIT_HLIST_NODE(&rq->hash);
450 RB_CLEAR_NODE(&rq->rb_node);
452 if (e->type->ops.prepare_request)
453 e->type->ops.prepare_request(rq);
456 return rq;
459 static inline struct request *
460 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data)
462 unsigned int tag, tag_offset;
463 struct blk_mq_tags *tags;
464 struct request *rq;
465 unsigned long tag_mask;
466 int i, nr = 0;
468 tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
469 if (unlikely(!tag_mask))
470 return NULL;
472 tags = blk_mq_tags_from_data(data);
473 for (i = 0; tag_mask; i++) {
474 if (!(tag_mask & (1UL << i)))
475 continue;
476 tag = tag_offset + i;
477 prefetch(tags->static_rqs[tag]);
478 tag_mask &= ~(1UL << i);
479 rq = blk_mq_rq_ctx_init(data, tags, tag);
480 rq_list_add_head(data->cached_rqs, rq);
481 nr++;
483 if (!(data->rq_flags & RQF_SCHED_TAGS))
484 blk_mq_add_active_requests(data->hctx, nr);
485 /* caller already holds a reference, add for remainder */
486 percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
487 data->nr_tags -= nr;
489 return rq_list_pop(data->cached_rqs);
492 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
494 struct request_queue *q = data->q;
495 u64 alloc_time_ns = 0;
496 struct request *rq;
497 unsigned int tag;
499 /* alloc_time includes depth and tag waits */
500 if (blk_queue_rq_alloc_time(q))
501 alloc_time_ns = blk_time_get_ns();
503 if (data->cmd_flags & REQ_NOWAIT)
504 data->flags |= BLK_MQ_REQ_NOWAIT;
506 retry:
507 data->ctx = blk_mq_get_ctx(q);
508 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
510 if (q->elevator) {
512 * All requests use scheduler tags when an I/O scheduler is
513 * enabled for the queue.
515 data->rq_flags |= RQF_SCHED_TAGS;
518 * Flush/passthrough requests are special and go directly to the
519 * dispatch list.
521 if ((data->cmd_flags & REQ_OP_MASK) != REQ_OP_FLUSH &&
522 !blk_op_is_passthrough(data->cmd_flags)) {
523 struct elevator_mq_ops *ops = &q->elevator->type->ops;
525 WARN_ON_ONCE(data->flags & BLK_MQ_REQ_RESERVED);
527 data->rq_flags |= RQF_USE_SCHED;
528 if (ops->limit_depth)
529 ops->limit_depth(data->cmd_flags, data);
531 } else {
532 blk_mq_tag_busy(data->hctx);
535 if (data->flags & BLK_MQ_REQ_RESERVED)
536 data->rq_flags |= RQF_RESV;
539 * Try batched alloc if we want more than 1 tag.
541 if (data->nr_tags > 1) {
542 rq = __blk_mq_alloc_requests_batch(data);
543 if (rq) {
544 blk_mq_rq_time_init(rq, alloc_time_ns);
545 return rq;
547 data->nr_tags = 1;
551 * Waiting allocations only fail because of an inactive hctx. In that
552 * case just retry the hctx assignment and tag allocation as CPU hotplug
553 * should have migrated us to an online CPU by now.
555 tag = blk_mq_get_tag(data);
556 if (tag == BLK_MQ_NO_TAG) {
557 if (data->flags & BLK_MQ_REQ_NOWAIT)
558 return NULL;
560 * Give up the CPU and sleep for a random short time to
561 * ensure that thread using a realtime scheduling class
562 * are migrated off the CPU, and thus off the hctx that
563 * is going away.
565 msleep(3);
566 goto retry;
569 if (!(data->rq_flags & RQF_SCHED_TAGS))
570 blk_mq_inc_active_requests(data->hctx);
571 rq = blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag);
572 blk_mq_rq_time_init(rq, alloc_time_ns);
573 return rq;
576 static struct request *blk_mq_rq_cache_fill(struct request_queue *q,
577 struct blk_plug *plug,
578 blk_opf_t opf,
579 blk_mq_req_flags_t flags)
581 struct blk_mq_alloc_data data = {
582 .q = q,
583 .flags = flags,
584 .cmd_flags = opf,
585 .nr_tags = plug->nr_ios,
586 .cached_rqs = &plug->cached_rqs,
588 struct request *rq;
590 if (blk_queue_enter(q, flags))
591 return NULL;
593 plug->nr_ios = 1;
595 rq = __blk_mq_alloc_requests(&data);
596 if (unlikely(!rq))
597 blk_queue_exit(q);
598 return rq;
601 static struct request *blk_mq_alloc_cached_request(struct request_queue *q,
602 blk_opf_t opf,
603 blk_mq_req_flags_t flags)
605 struct blk_plug *plug = current->plug;
606 struct request *rq;
608 if (!plug)
609 return NULL;
611 if (rq_list_empty(&plug->cached_rqs)) {
612 if (plug->nr_ios == 1)
613 return NULL;
614 rq = blk_mq_rq_cache_fill(q, plug, opf, flags);
615 if (!rq)
616 return NULL;
617 } else {
618 rq = rq_list_peek(&plug->cached_rqs);
619 if (!rq || rq->q != q)
620 return NULL;
622 if (blk_mq_get_hctx_type(opf) != rq->mq_hctx->type)
623 return NULL;
624 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
625 return NULL;
627 rq_list_pop(&plug->cached_rqs);
628 blk_mq_rq_time_init(rq, blk_time_get_ns());
631 rq->cmd_flags = opf;
632 INIT_LIST_HEAD(&rq->queuelist);
633 return rq;
636 struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
637 blk_mq_req_flags_t flags)
639 struct request *rq;
641 rq = blk_mq_alloc_cached_request(q, opf, flags);
642 if (!rq) {
643 struct blk_mq_alloc_data data = {
644 .q = q,
645 .flags = flags,
646 .cmd_flags = opf,
647 .nr_tags = 1,
649 int ret;
651 ret = blk_queue_enter(q, flags);
652 if (ret)
653 return ERR_PTR(ret);
655 rq = __blk_mq_alloc_requests(&data);
656 if (!rq)
657 goto out_queue_exit;
659 rq->__data_len = 0;
660 rq->__sector = (sector_t) -1;
661 rq->bio = rq->biotail = NULL;
662 return rq;
663 out_queue_exit:
664 blk_queue_exit(q);
665 return ERR_PTR(-EWOULDBLOCK);
667 EXPORT_SYMBOL(blk_mq_alloc_request);
669 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
670 blk_opf_t opf, blk_mq_req_flags_t flags, unsigned int hctx_idx)
672 struct blk_mq_alloc_data data = {
673 .q = q,
674 .flags = flags,
675 .cmd_flags = opf,
676 .nr_tags = 1,
678 u64 alloc_time_ns = 0;
679 struct request *rq;
680 unsigned int cpu;
681 unsigned int tag;
682 int ret;
684 /* alloc_time includes depth and tag waits */
685 if (blk_queue_rq_alloc_time(q))
686 alloc_time_ns = blk_time_get_ns();
689 * If the tag allocator sleeps we could get an allocation for a
690 * different hardware context. No need to complicate the low level
691 * allocator for this for the rare use case of a command tied to
692 * a specific queue.
694 if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)) ||
695 WARN_ON_ONCE(!(flags & BLK_MQ_REQ_RESERVED)))
696 return ERR_PTR(-EINVAL);
698 if (hctx_idx >= q->nr_hw_queues)
699 return ERR_PTR(-EIO);
701 ret = blk_queue_enter(q, flags);
702 if (ret)
703 return ERR_PTR(ret);
706 * Check if the hardware context is actually mapped to anything.
707 * If not tell the caller that it should skip this queue.
709 ret = -EXDEV;
710 data.hctx = xa_load(&q->hctx_table, hctx_idx);
711 if (!blk_mq_hw_queue_mapped(data.hctx))
712 goto out_queue_exit;
713 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
714 if (cpu >= nr_cpu_ids)
715 goto out_queue_exit;
716 data.ctx = __blk_mq_get_ctx(q, cpu);
718 if (q->elevator)
719 data.rq_flags |= RQF_SCHED_TAGS;
720 else
721 blk_mq_tag_busy(data.hctx);
723 if (flags & BLK_MQ_REQ_RESERVED)
724 data.rq_flags |= RQF_RESV;
726 ret = -EWOULDBLOCK;
727 tag = blk_mq_get_tag(&data);
728 if (tag == BLK_MQ_NO_TAG)
729 goto out_queue_exit;
730 if (!(data.rq_flags & RQF_SCHED_TAGS))
731 blk_mq_inc_active_requests(data.hctx);
732 rq = blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag);
733 blk_mq_rq_time_init(rq, alloc_time_ns);
734 rq->__data_len = 0;
735 rq->__sector = (sector_t) -1;
736 rq->bio = rq->biotail = NULL;
737 return rq;
739 out_queue_exit:
740 blk_queue_exit(q);
741 return ERR_PTR(ret);
743 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
745 static void blk_mq_finish_request(struct request *rq)
747 struct request_queue *q = rq->q;
749 blk_zone_finish_request(rq);
751 if (rq->rq_flags & RQF_USE_SCHED) {
752 q->elevator->type->ops.finish_request(rq);
754 * For postflush request that may need to be
755 * completed twice, we should clear this flag
756 * to avoid double finish_request() on the rq.
758 rq->rq_flags &= ~RQF_USE_SCHED;
762 static void __blk_mq_free_request(struct request *rq)
764 struct request_queue *q = rq->q;
765 struct blk_mq_ctx *ctx = rq->mq_ctx;
766 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
767 const int sched_tag = rq->internal_tag;
769 blk_crypto_free_request(rq);
770 blk_pm_mark_last_busy(rq);
771 rq->mq_hctx = NULL;
773 if (rq->tag != BLK_MQ_NO_TAG) {
774 blk_mq_dec_active_requests(hctx);
775 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
777 if (sched_tag != BLK_MQ_NO_TAG)
778 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
779 blk_mq_sched_restart(hctx);
780 blk_queue_exit(q);
783 void blk_mq_free_request(struct request *rq)
785 struct request_queue *q = rq->q;
787 blk_mq_finish_request(rq);
789 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
790 laptop_io_completion(q->disk->bdi);
792 rq_qos_done(q, rq);
794 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
795 if (req_ref_put_and_test(rq))
796 __blk_mq_free_request(rq);
798 EXPORT_SYMBOL_GPL(blk_mq_free_request);
800 void blk_mq_free_plug_rqs(struct blk_plug *plug)
802 struct request *rq;
804 while ((rq = rq_list_pop(&plug->cached_rqs)) != NULL)
805 blk_mq_free_request(rq);
808 void blk_dump_rq_flags(struct request *rq, char *msg)
810 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
811 rq->q->disk ? rq->q->disk->disk_name : "?",
812 (__force unsigned long long) rq->cmd_flags);
814 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
815 (unsigned long long)blk_rq_pos(rq),
816 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
817 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
818 rq->bio, rq->biotail, blk_rq_bytes(rq));
820 EXPORT_SYMBOL(blk_dump_rq_flags);
822 static void blk_account_io_completion(struct request *req, unsigned int bytes)
824 if (req->rq_flags & RQF_IO_STAT) {
825 const int sgrp = op_stat_group(req_op(req));
827 part_stat_lock();
828 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
829 part_stat_unlock();
833 static void blk_print_req_error(struct request *req, blk_status_t status)
835 printk_ratelimited(KERN_ERR
836 "%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
837 "phys_seg %u prio class %u\n",
838 blk_status_to_str(status),
839 req->q->disk ? req->q->disk->disk_name : "?",
840 blk_rq_pos(req), (__force u32)req_op(req),
841 blk_op_str(req_op(req)),
842 (__force u32)(req->cmd_flags & ~REQ_OP_MASK),
843 req->nr_phys_segments,
844 IOPRIO_PRIO_CLASS(req_get_ioprio(req)));
848 * Fully end IO on a request. Does not support partial completions, or
849 * errors.
851 static void blk_complete_request(struct request *req)
853 const bool is_flush = (req->rq_flags & RQF_FLUSH_SEQ) != 0;
854 int total_bytes = blk_rq_bytes(req);
855 struct bio *bio = req->bio;
857 trace_block_rq_complete(req, BLK_STS_OK, total_bytes);
859 if (!bio)
860 return;
862 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ)
863 blk_integrity_complete(req, total_bytes);
866 * Upper layers may call blk_crypto_evict_key() anytime after the last
867 * bio_endio(). Therefore, the keyslot must be released before that.
869 blk_crypto_rq_put_keyslot(req);
871 blk_account_io_completion(req, total_bytes);
873 do {
874 struct bio *next = bio->bi_next;
876 /* Completion has already been traced */
877 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
879 blk_zone_update_request_bio(req, bio);
881 if (!is_flush)
882 bio_endio(bio);
883 bio = next;
884 } while (bio);
887 * Reset counters so that the request stacking driver
888 * can find how many bytes remain in the request
889 * later.
891 if (!req->end_io) {
892 req->bio = NULL;
893 req->__data_len = 0;
898 * blk_update_request - Complete multiple bytes without completing the request
899 * @req: the request being processed
900 * @error: block status code
901 * @nr_bytes: number of bytes to complete for @req
903 * Description:
904 * Ends I/O on a number of bytes attached to @req, but doesn't complete
905 * the request structure even if @req doesn't have leftover.
906 * If @req has leftover, sets it up for the next range of segments.
908 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
909 * %false return from this function.
911 * Note:
912 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
913 * except in the consistency check at the end of this function.
915 * Return:
916 * %false - this request doesn't have any more data
917 * %true - this request has more data
919 bool blk_update_request(struct request *req, blk_status_t error,
920 unsigned int nr_bytes)
922 bool is_flush = req->rq_flags & RQF_FLUSH_SEQ;
923 bool quiet = req->rq_flags & RQF_QUIET;
924 int total_bytes;
926 trace_block_rq_complete(req, error, nr_bytes);
928 if (!req->bio)
929 return false;
931 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
932 error == BLK_STS_OK)
933 blk_integrity_complete(req, nr_bytes);
936 * Upper layers may call blk_crypto_evict_key() anytime after the last
937 * bio_endio(). Therefore, the keyslot must be released before that.
939 if (blk_crypto_rq_has_keyslot(req) && nr_bytes >= blk_rq_bytes(req))
940 __blk_crypto_rq_put_keyslot(req);
942 if (unlikely(error && !blk_rq_is_passthrough(req) && !quiet) &&
943 !test_bit(GD_DEAD, &req->q->disk->state)) {
944 blk_print_req_error(req, error);
945 trace_block_rq_error(req, error, nr_bytes);
948 blk_account_io_completion(req, nr_bytes);
950 total_bytes = 0;
951 while (req->bio) {
952 struct bio *bio = req->bio;
953 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
955 if (unlikely(error))
956 bio->bi_status = error;
958 if (bio_bytes == bio->bi_iter.bi_size) {
959 req->bio = bio->bi_next;
960 } else if (bio_is_zone_append(bio) && error == BLK_STS_OK) {
962 * Partial zone append completions cannot be supported
963 * as the BIO fragments may end up not being written
964 * sequentially.
966 bio->bi_status = BLK_STS_IOERR;
969 /* Completion has already been traced */
970 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
971 if (unlikely(quiet))
972 bio_set_flag(bio, BIO_QUIET);
974 bio_advance(bio, bio_bytes);
976 /* Don't actually finish bio if it's part of flush sequence */
977 if (!bio->bi_iter.bi_size) {
978 blk_zone_update_request_bio(req, bio);
979 if (!is_flush)
980 bio_endio(bio);
983 total_bytes += bio_bytes;
984 nr_bytes -= bio_bytes;
986 if (!nr_bytes)
987 break;
991 * completely done
993 if (!req->bio) {
995 * Reset counters so that the request stacking driver
996 * can find how many bytes remain in the request
997 * later.
999 req->__data_len = 0;
1000 return false;
1003 req->__data_len -= total_bytes;
1005 /* update sector only for requests with clear definition of sector */
1006 if (!blk_rq_is_passthrough(req))
1007 req->__sector += total_bytes >> 9;
1009 /* mixed attributes always follow the first bio */
1010 if (req->rq_flags & RQF_MIXED_MERGE) {
1011 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1012 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1015 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1017 * If total number of sectors is less than the first segment
1018 * size, something has gone terribly wrong.
1020 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1021 blk_dump_rq_flags(req, "request botched");
1022 req->__data_len = blk_rq_cur_bytes(req);
1025 /* recalculate the number of segments */
1026 req->nr_phys_segments = blk_recalc_rq_segments(req);
1029 return true;
1031 EXPORT_SYMBOL_GPL(blk_update_request);
1033 static inline void blk_account_io_done(struct request *req, u64 now)
1035 trace_block_io_done(req);
1038 * Account IO completion. flush_rq isn't accounted as a
1039 * normal IO on queueing nor completion. Accounting the
1040 * containing request is enough.
1042 if ((req->rq_flags & (RQF_IO_STAT|RQF_FLUSH_SEQ)) == RQF_IO_STAT) {
1043 const int sgrp = op_stat_group(req_op(req));
1045 part_stat_lock();
1046 update_io_ticks(req->part, jiffies, true);
1047 part_stat_inc(req->part, ios[sgrp]);
1048 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1049 part_stat_local_dec(req->part,
1050 in_flight[op_is_write(req_op(req))]);
1051 part_stat_unlock();
1055 static inline bool blk_rq_passthrough_stats(struct request *req)
1057 struct bio *bio = req->bio;
1059 if (!blk_queue_passthrough_stat(req->q))
1060 return false;
1062 /* Requests without a bio do not transfer data. */
1063 if (!bio)
1064 return false;
1067 * Stats are accumulated in the bdev, so must have one attached to a
1068 * bio to track stats. Most drivers do not set the bdev for passthrough
1069 * requests, but nvme is one that will set it.
1071 if (!bio->bi_bdev)
1072 return false;
1075 * We don't know what a passthrough command does, but we know the
1076 * payload size and data direction. Ensuring the size is aligned to the
1077 * block size filters out most commands with payloads that don't
1078 * represent sector access.
1080 if (blk_rq_bytes(req) & (bdev_logical_block_size(bio->bi_bdev) - 1))
1081 return false;
1082 return true;
1085 static inline void blk_account_io_start(struct request *req)
1087 trace_block_io_start(req);
1089 if (!blk_queue_io_stat(req->q))
1090 return;
1091 if (blk_rq_is_passthrough(req) && !blk_rq_passthrough_stats(req))
1092 return;
1094 req->rq_flags |= RQF_IO_STAT;
1095 req->start_time_ns = blk_time_get_ns();
1098 * All non-passthrough requests are created from a bio with one
1099 * exception: when a flush command that is part of a flush sequence
1100 * generated by the state machine in blk-flush.c is cloned onto the
1101 * lower device by dm-multipath we can get here without a bio.
1103 if (req->bio)
1104 req->part = req->bio->bi_bdev;
1105 else
1106 req->part = req->q->disk->part0;
1108 part_stat_lock();
1109 update_io_ticks(req->part, jiffies, false);
1110 part_stat_local_inc(req->part, in_flight[op_is_write(req_op(req))]);
1111 part_stat_unlock();
1114 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
1116 if (rq->rq_flags & RQF_STATS)
1117 blk_stat_add(rq, now);
1119 blk_mq_sched_completed_request(rq, now);
1120 blk_account_io_done(rq, now);
1123 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
1125 if (blk_mq_need_time_stamp(rq))
1126 __blk_mq_end_request_acct(rq, blk_time_get_ns());
1128 blk_mq_finish_request(rq);
1130 if (rq->end_io) {
1131 rq_qos_done(rq->q, rq);
1132 if (rq->end_io(rq, error) == RQ_END_IO_FREE)
1133 blk_mq_free_request(rq);
1134 } else {
1135 blk_mq_free_request(rq);
1138 EXPORT_SYMBOL(__blk_mq_end_request);
1140 void blk_mq_end_request(struct request *rq, blk_status_t error)
1142 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
1143 BUG();
1144 __blk_mq_end_request(rq, error);
1146 EXPORT_SYMBOL(blk_mq_end_request);
1148 #define TAG_COMP_BATCH 32
1150 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
1151 int *tag_array, int nr_tags)
1153 struct request_queue *q = hctx->queue;
1155 blk_mq_sub_active_requests(hctx, nr_tags);
1157 blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
1158 percpu_ref_put_many(&q->q_usage_counter, nr_tags);
1161 void blk_mq_end_request_batch(struct io_comp_batch *iob)
1163 int tags[TAG_COMP_BATCH], nr_tags = 0;
1164 struct blk_mq_hw_ctx *cur_hctx = NULL;
1165 struct request *rq;
1166 u64 now = 0;
1168 if (iob->need_ts)
1169 now = blk_time_get_ns();
1171 while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
1172 prefetch(rq->bio);
1173 prefetch(rq->rq_next);
1175 blk_complete_request(rq);
1176 if (iob->need_ts)
1177 __blk_mq_end_request_acct(rq, now);
1179 blk_mq_finish_request(rq);
1181 rq_qos_done(rq->q, rq);
1184 * If end_io handler returns NONE, then it still has
1185 * ownership of the request.
1187 if (rq->end_io && rq->end_io(rq, 0) == RQ_END_IO_NONE)
1188 continue;
1190 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1191 if (!req_ref_put_and_test(rq))
1192 continue;
1194 blk_crypto_free_request(rq);
1195 blk_pm_mark_last_busy(rq);
1197 if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
1198 if (cur_hctx)
1199 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1200 nr_tags = 0;
1201 cur_hctx = rq->mq_hctx;
1203 tags[nr_tags++] = rq->tag;
1206 if (nr_tags)
1207 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1209 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
1211 static void blk_complete_reqs(struct llist_head *list)
1213 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
1214 struct request *rq, *next;
1216 llist_for_each_entry_safe(rq, next, entry, ipi_list)
1217 rq->q->mq_ops->complete(rq);
1220 static __latent_entropy void blk_done_softirq(void)
1222 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
1225 static int blk_softirq_cpu_dead(unsigned int cpu)
1227 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
1228 return 0;
1231 static void __blk_mq_complete_request_remote(void *data)
1233 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
1236 static inline bool blk_mq_complete_need_ipi(struct request *rq)
1238 int cpu = raw_smp_processor_id();
1240 if (!IS_ENABLED(CONFIG_SMP) ||
1241 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
1242 return false;
1244 * With force threaded interrupts enabled, raising softirq from an SMP
1245 * function call will always result in waking the ksoftirqd thread.
1246 * This is probably worse than completing the request on a different
1247 * cache domain.
1249 if (force_irqthreads())
1250 return false;
1252 /* same CPU or cache domain and capacity? Complete locally */
1253 if (cpu == rq->mq_ctx->cpu ||
1254 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1255 cpus_share_cache(cpu, rq->mq_ctx->cpu) &&
1256 cpus_equal_capacity(cpu, rq->mq_ctx->cpu)))
1257 return false;
1259 /* don't try to IPI to an offline CPU */
1260 return cpu_online(rq->mq_ctx->cpu);
1263 static void blk_mq_complete_send_ipi(struct request *rq)
1265 unsigned int cpu;
1267 cpu = rq->mq_ctx->cpu;
1268 if (llist_add(&rq->ipi_list, &per_cpu(blk_cpu_done, cpu)))
1269 smp_call_function_single_async(cpu, &per_cpu(blk_cpu_csd, cpu));
1272 static void blk_mq_raise_softirq(struct request *rq)
1274 struct llist_head *list;
1276 preempt_disable();
1277 list = this_cpu_ptr(&blk_cpu_done);
1278 if (llist_add(&rq->ipi_list, list))
1279 raise_softirq(BLOCK_SOFTIRQ);
1280 preempt_enable();
1283 bool blk_mq_complete_request_remote(struct request *rq)
1285 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1288 * For request which hctx has only one ctx mapping,
1289 * or a polled request, always complete locally,
1290 * it's pointless to redirect the completion.
1292 if ((rq->mq_hctx->nr_ctx == 1 &&
1293 rq->mq_ctx->cpu == raw_smp_processor_id()) ||
1294 rq->cmd_flags & REQ_POLLED)
1295 return false;
1297 if (blk_mq_complete_need_ipi(rq)) {
1298 blk_mq_complete_send_ipi(rq);
1299 return true;
1302 if (rq->q->nr_hw_queues == 1) {
1303 blk_mq_raise_softirq(rq);
1304 return true;
1306 return false;
1308 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1311 * blk_mq_complete_request - end I/O on a request
1312 * @rq: the request being processed
1314 * Description:
1315 * Complete a request by scheduling the ->complete_rq operation.
1317 void blk_mq_complete_request(struct request *rq)
1319 if (!blk_mq_complete_request_remote(rq))
1320 rq->q->mq_ops->complete(rq);
1322 EXPORT_SYMBOL(blk_mq_complete_request);
1325 * blk_mq_start_request - Start processing a request
1326 * @rq: Pointer to request to be started
1328 * Function used by device drivers to notify the block layer that a request
1329 * is going to be processed now, so blk layer can do proper initializations
1330 * such as starting the timeout timer.
1332 void blk_mq_start_request(struct request *rq)
1334 struct request_queue *q = rq->q;
1336 trace_block_rq_issue(rq);
1338 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags) &&
1339 !blk_rq_is_passthrough(rq)) {
1340 rq->io_start_time_ns = blk_time_get_ns();
1341 rq->stats_sectors = blk_rq_sectors(rq);
1342 rq->rq_flags |= RQF_STATS;
1343 rq_qos_issue(q, rq);
1346 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1348 blk_add_timer(rq);
1349 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1350 rq->mq_hctx->tags->rqs[rq->tag] = rq;
1352 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1353 blk_integrity_prepare(rq);
1355 if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1356 WRITE_ONCE(rq->bio->bi_cookie, rq->mq_hctx->queue_num);
1358 EXPORT_SYMBOL(blk_mq_start_request);
1361 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
1362 * queues. This is important for md arrays to benefit from merging
1363 * requests.
1365 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
1367 if (plug->multiple_queues)
1368 return BLK_MAX_REQUEST_COUNT * 2;
1369 return BLK_MAX_REQUEST_COUNT;
1372 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
1374 struct request *last = rq_list_peek(&plug->mq_list);
1376 if (!plug->rq_count) {
1377 trace_block_plug(rq->q);
1378 } else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
1379 (!blk_queue_nomerges(rq->q) &&
1380 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1381 blk_mq_flush_plug_list(plug, false);
1382 last = NULL;
1383 trace_block_plug(rq->q);
1386 if (!plug->multiple_queues && last && last->q != rq->q)
1387 plug->multiple_queues = true;
1389 * Any request allocated from sched tags can't be issued to
1390 * ->queue_rqs() directly
1392 if (!plug->has_elevator && (rq->rq_flags & RQF_SCHED_TAGS))
1393 plug->has_elevator = true;
1394 rq_list_add_tail(&plug->mq_list, rq);
1395 plug->rq_count++;
1399 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1400 * @rq: request to insert
1401 * @at_head: insert request at head or tail of queue
1403 * Description:
1404 * Insert a fully prepared request at the back of the I/O scheduler queue
1405 * for execution. Don't wait for completion.
1407 * Note:
1408 * This function will invoke @done directly if the queue is dead.
1410 void blk_execute_rq_nowait(struct request *rq, bool at_head)
1412 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1414 WARN_ON(irqs_disabled());
1415 WARN_ON(!blk_rq_is_passthrough(rq));
1417 blk_account_io_start(rq);
1419 if (current->plug && !at_head) {
1420 blk_add_rq_to_plug(current->plug, rq);
1421 return;
1424 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1425 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
1427 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1429 struct blk_rq_wait {
1430 struct completion done;
1431 blk_status_t ret;
1434 static enum rq_end_io_ret blk_end_sync_rq(struct request *rq, blk_status_t ret)
1436 struct blk_rq_wait *wait = rq->end_io_data;
1438 wait->ret = ret;
1439 complete(&wait->done);
1440 return RQ_END_IO_NONE;
1443 bool blk_rq_is_poll(struct request *rq)
1445 if (!rq->mq_hctx)
1446 return false;
1447 if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1448 return false;
1449 return true;
1451 EXPORT_SYMBOL_GPL(blk_rq_is_poll);
1453 static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1455 do {
1456 blk_hctx_poll(rq->q, rq->mq_hctx, NULL, 0);
1457 cond_resched();
1458 } while (!completion_done(wait));
1462 * blk_execute_rq - insert a request into queue for execution
1463 * @rq: request to insert
1464 * @at_head: insert request at head or tail of queue
1466 * Description:
1467 * Insert a fully prepared request at the back of the I/O scheduler queue
1468 * for execution and wait for completion.
1469 * Return: The blk_status_t result provided to blk_mq_end_request().
1471 blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1473 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1474 struct blk_rq_wait wait = {
1475 .done = COMPLETION_INITIALIZER_ONSTACK(wait.done),
1478 WARN_ON(irqs_disabled());
1479 WARN_ON(!blk_rq_is_passthrough(rq));
1481 rq->end_io_data = &wait;
1482 rq->end_io = blk_end_sync_rq;
1484 blk_account_io_start(rq);
1485 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1486 blk_mq_run_hw_queue(hctx, false);
1488 if (blk_rq_is_poll(rq))
1489 blk_rq_poll_completion(rq, &wait.done);
1490 else
1491 blk_wait_io(&wait.done);
1493 return wait.ret;
1495 EXPORT_SYMBOL(blk_execute_rq);
1497 static void __blk_mq_requeue_request(struct request *rq)
1499 struct request_queue *q = rq->q;
1501 blk_mq_put_driver_tag(rq);
1503 trace_block_rq_requeue(rq);
1504 rq_qos_requeue(q, rq);
1506 if (blk_mq_request_started(rq)) {
1507 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1508 rq->rq_flags &= ~RQF_TIMED_OUT;
1512 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1514 struct request_queue *q = rq->q;
1515 unsigned long flags;
1517 __blk_mq_requeue_request(rq);
1519 /* this request will be re-inserted to io scheduler queue */
1520 blk_mq_sched_requeue_request(rq);
1522 spin_lock_irqsave(&q->requeue_lock, flags);
1523 list_add_tail(&rq->queuelist, &q->requeue_list);
1524 spin_unlock_irqrestore(&q->requeue_lock, flags);
1526 if (kick_requeue_list)
1527 blk_mq_kick_requeue_list(q);
1529 EXPORT_SYMBOL(blk_mq_requeue_request);
1531 static void blk_mq_requeue_work(struct work_struct *work)
1533 struct request_queue *q =
1534 container_of(work, struct request_queue, requeue_work.work);
1535 LIST_HEAD(rq_list);
1536 LIST_HEAD(flush_list);
1537 struct request *rq;
1539 spin_lock_irq(&q->requeue_lock);
1540 list_splice_init(&q->requeue_list, &rq_list);
1541 list_splice_init(&q->flush_list, &flush_list);
1542 spin_unlock_irq(&q->requeue_lock);
1544 while (!list_empty(&rq_list)) {
1545 rq = list_entry(rq_list.next, struct request, queuelist);
1547 * If RQF_DONTPREP ist set, the request has been started by the
1548 * driver already and might have driver-specific data allocated
1549 * already. Insert it into the hctx dispatch list to avoid
1550 * block layer merges for the request.
1552 if (rq->rq_flags & RQF_DONTPREP) {
1553 list_del_init(&rq->queuelist);
1554 blk_mq_request_bypass_insert(rq, 0);
1555 } else {
1556 list_del_init(&rq->queuelist);
1557 blk_mq_insert_request(rq, BLK_MQ_INSERT_AT_HEAD);
1561 while (!list_empty(&flush_list)) {
1562 rq = list_entry(flush_list.next, struct request, queuelist);
1563 list_del_init(&rq->queuelist);
1564 blk_mq_insert_request(rq, 0);
1567 blk_mq_run_hw_queues(q, false);
1570 void blk_mq_kick_requeue_list(struct request_queue *q)
1572 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1574 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1576 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1577 unsigned long msecs)
1579 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1580 msecs_to_jiffies(msecs));
1582 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1584 static bool blk_is_flush_data_rq(struct request *rq)
1586 return (rq->rq_flags & RQF_FLUSH_SEQ) && !is_flush_rq(rq);
1589 static bool blk_mq_rq_inflight(struct request *rq, void *priv)
1592 * If we find a request that isn't idle we know the queue is busy
1593 * as it's checked in the iter.
1594 * Return false to stop the iteration.
1596 * In case of queue quiesce, if one flush data request is completed,
1597 * don't count it as inflight given the flush sequence is suspended,
1598 * and the original flush data request is invisible to driver, just
1599 * like other pending requests because of quiesce
1601 if (blk_mq_request_started(rq) && !(blk_queue_quiesced(rq->q) &&
1602 blk_is_flush_data_rq(rq) &&
1603 blk_mq_request_completed(rq))) {
1604 bool *busy = priv;
1606 *busy = true;
1607 return false;
1610 return true;
1613 bool blk_mq_queue_inflight(struct request_queue *q)
1615 bool busy = false;
1617 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1618 return busy;
1620 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1622 static void blk_mq_rq_timed_out(struct request *req)
1624 req->rq_flags |= RQF_TIMED_OUT;
1625 if (req->q->mq_ops->timeout) {
1626 enum blk_eh_timer_return ret;
1628 ret = req->q->mq_ops->timeout(req);
1629 if (ret == BLK_EH_DONE)
1630 return;
1631 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1634 blk_add_timer(req);
1637 struct blk_expired_data {
1638 bool has_timedout_rq;
1639 unsigned long next;
1640 unsigned long timeout_start;
1643 static bool blk_mq_req_expired(struct request *rq, struct blk_expired_data *expired)
1645 unsigned long deadline;
1647 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1648 return false;
1649 if (rq->rq_flags & RQF_TIMED_OUT)
1650 return false;
1652 deadline = READ_ONCE(rq->deadline);
1653 if (time_after_eq(expired->timeout_start, deadline))
1654 return true;
1656 if (expired->next == 0)
1657 expired->next = deadline;
1658 else if (time_after(expired->next, deadline))
1659 expired->next = deadline;
1660 return false;
1663 void blk_mq_put_rq_ref(struct request *rq)
1665 if (is_flush_rq(rq)) {
1666 if (rq->end_io(rq, 0) == RQ_END_IO_FREE)
1667 blk_mq_free_request(rq);
1668 } else if (req_ref_put_and_test(rq)) {
1669 __blk_mq_free_request(rq);
1673 static bool blk_mq_check_expired(struct request *rq, void *priv)
1675 struct blk_expired_data *expired = priv;
1678 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1679 * be reallocated underneath the timeout handler's processing, then
1680 * the expire check is reliable. If the request is not expired, then
1681 * it was completed and reallocated as a new request after returning
1682 * from blk_mq_check_expired().
1684 if (blk_mq_req_expired(rq, expired)) {
1685 expired->has_timedout_rq = true;
1686 return false;
1688 return true;
1691 static bool blk_mq_handle_expired(struct request *rq, void *priv)
1693 struct blk_expired_data *expired = priv;
1695 if (blk_mq_req_expired(rq, expired))
1696 blk_mq_rq_timed_out(rq);
1697 return true;
1700 static void blk_mq_timeout_work(struct work_struct *work)
1702 struct request_queue *q =
1703 container_of(work, struct request_queue, timeout_work);
1704 struct blk_expired_data expired = {
1705 .timeout_start = jiffies,
1707 struct blk_mq_hw_ctx *hctx;
1708 unsigned long i;
1710 /* A deadlock might occur if a request is stuck requiring a
1711 * timeout at the same time a queue freeze is waiting
1712 * completion, since the timeout code would not be able to
1713 * acquire the queue reference here.
1715 * That's why we don't use blk_queue_enter here; instead, we use
1716 * percpu_ref_tryget directly, because we need to be able to
1717 * obtain a reference even in the short window between the queue
1718 * starting to freeze, by dropping the first reference in
1719 * blk_freeze_queue_start, and the moment the last request is
1720 * consumed, marked by the instant q_usage_counter reaches
1721 * zero.
1723 if (!percpu_ref_tryget(&q->q_usage_counter))
1724 return;
1726 /* check if there is any timed-out request */
1727 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &expired);
1728 if (expired.has_timedout_rq) {
1730 * Before walking tags, we must ensure any submit started
1731 * before the current time has finished. Since the submit
1732 * uses srcu or rcu, wait for a synchronization point to
1733 * ensure all running submits have finished
1735 blk_mq_wait_quiesce_done(q->tag_set);
1737 expired.next = 0;
1738 blk_mq_queue_tag_busy_iter(q, blk_mq_handle_expired, &expired);
1741 if (expired.next != 0) {
1742 mod_timer(&q->timeout, expired.next);
1743 } else {
1745 * Request timeouts are handled as a forward rolling timer. If
1746 * we end up here it means that no requests are pending and
1747 * also that no request has been pending for a while. Mark
1748 * each hctx as idle.
1750 queue_for_each_hw_ctx(q, hctx, i) {
1751 /* the hctx may be unmapped, so check it here */
1752 if (blk_mq_hw_queue_mapped(hctx))
1753 blk_mq_tag_idle(hctx);
1756 blk_queue_exit(q);
1759 struct flush_busy_ctx_data {
1760 struct blk_mq_hw_ctx *hctx;
1761 struct list_head *list;
1764 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1766 struct flush_busy_ctx_data *flush_data = data;
1767 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1768 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1769 enum hctx_type type = hctx->type;
1771 spin_lock(&ctx->lock);
1772 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1773 sbitmap_clear_bit(sb, bitnr);
1774 spin_unlock(&ctx->lock);
1775 return true;
1779 * Process software queues that have been marked busy, splicing them
1780 * to the for-dispatch
1782 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1784 struct flush_busy_ctx_data data = {
1785 .hctx = hctx,
1786 .list = list,
1789 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1792 struct dispatch_rq_data {
1793 struct blk_mq_hw_ctx *hctx;
1794 struct request *rq;
1797 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1798 void *data)
1800 struct dispatch_rq_data *dispatch_data = data;
1801 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1802 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1803 enum hctx_type type = hctx->type;
1805 spin_lock(&ctx->lock);
1806 if (!list_empty(&ctx->rq_lists[type])) {
1807 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1808 list_del_init(&dispatch_data->rq->queuelist);
1809 if (list_empty(&ctx->rq_lists[type]))
1810 sbitmap_clear_bit(sb, bitnr);
1812 spin_unlock(&ctx->lock);
1814 return !dispatch_data->rq;
1817 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1818 struct blk_mq_ctx *start)
1820 unsigned off = start ? start->index_hw[hctx->type] : 0;
1821 struct dispatch_rq_data data = {
1822 .hctx = hctx,
1823 .rq = NULL,
1826 __sbitmap_for_each_set(&hctx->ctx_map, off,
1827 dispatch_rq_from_ctx, &data);
1829 return data.rq;
1832 bool __blk_mq_alloc_driver_tag(struct request *rq)
1834 struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1835 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1836 int tag;
1838 blk_mq_tag_busy(rq->mq_hctx);
1840 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1841 bt = &rq->mq_hctx->tags->breserved_tags;
1842 tag_offset = 0;
1843 } else {
1844 if (!hctx_may_queue(rq->mq_hctx, bt))
1845 return false;
1848 tag = __sbitmap_queue_get(bt);
1849 if (tag == BLK_MQ_NO_TAG)
1850 return false;
1852 rq->tag = tag + tag_offset;
1853 blk_mq_inc_active_requests(rq->mq_hctx);
1854 return true;
1857 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1858 int flags, void *key)
1860 struct blk_mq_hw_ctx *hctx;
1862 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1864 spin_lock(&hctx->dispatch_wait_lock);
1865 if (!list_empty(&wait->entry)) {
1866 struct sbitmap_queue *sbq;
1868 list_del_init(&wait->entry);
1869 sbq = &hctx->tags->bitmap_tags;
1870 atomic_dec(&sbq->ws_active);
1872 spin_unlock(&hctx->dispatch_wait_lock);
1874 blk_mq_run_hw_queue(hctx, true);
1875 return 1;
1879 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1880 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1881 * restart. For both cases, take care to check the condition again after
1882 * marking us as waiting.
1884 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1885 struct request *rq)
1887 struct sbitmap_queue *sbq;
1888 struct wait_queue_head *wq;
1889 wait_queue_entry_t *wait;
1890 bool ret;
1892 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1893 !(blk_mq_is_shared_tags(hctx->flags))) {
1894 blk_mq_sched_mark_restart_hctx(hctx);
1897 * It's possible that a tag was freed in the window between the
1898 * allocation failure and adding the hardware queue to the wait
1899 * queue.
1901 * Don't clear RESTART here, someone else could have set it.
1902 * At most this will cost an extra queue run.
1904 return blk_mq_get_driver_tag(rq);
1907 wait = &hctx->dispatch_wait;
1908 if (!list_empty_careful(&wait->entry))
1909 return false;
1911 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag))
1912 sbq = &hctx->tags->breserved_tags;
1913 else
1914 sbq = &hctx->tags->bitmap_tags;
1915 wq = &bt_wait_ptr(sbq, hctx)->wait;
1917 spin_lock_irq(&wq->lock);
1918 spin_lock(&hctx->dispatch_wait_lock);
1919 if (!list_empty(&wait->entry)) {
1920 spin_unlock(&hctx->dispatch_wait_lock);
1921 spin_unlock_irq(&wq->lock);
1922 return false;
1925 atomic_inc(&sbq->ws_active);
1926 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1927 __add_wait_queue(wq, wait);
1930 * Add one explicit barrier since blk_mq_get_driver_tag() may
1931 * not imply barrier in case of failure.
1933 * Order adding us to wait queue and allocating driver tag.
1935 * The pair is the one implied in sbitmap_queue_wake_up() which
1936 * orders clearing sbitmap tag bits and waitqueue_active() in
1937 * __sbitmap_queue_wake_up(), since waitqueue_active() is lockless
1939 * Otherwise, re-order of adding wait queue and getting driver tag
1940 * may cause __sbitmap_queue_wake_up() to wake up nothing because
1941 * the waitqueue_active() may not observe us in wait queue.
1943 smp_mb();
1946 * It's possible that a tag was freed in the window between the
1947 * allocation failure and adding the hardware queue to the wait
1948 * queue.
1950 ret = blk_mq_get_driver_tag(rq);
1951 if (!ret) {
1952 spin_unlock(&hctx->dispatch_wait_lock);
1953 spin_unlock_irq(&wq->lock);
1954 return false;
1958 * We got a tag, remove ourselves from the wait queue to ensure
1959 * someone else gets the wakeup.
1961 list_del_init(&wait->entry);
1962 atomic_dec(&sbq->ws_active);
1963 spin_unlock(&hctx->dispatch_wait_lock);
1964 spin_unlock_irq(&wq->lock);
1966 return true;
1969 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1970 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1972 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1973 * - EWMA is one simple way to compute running average value
1974 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1975 * - take 4 as factor for avoiding to get too small(0) result, and this
1976 * factor doesn't matter because EWMA decreases exponentially
1978 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1980 unsigned int ewma;
1982 ewma = hctx->dispatch_busy;
1984 if (!ewma && !busy)
1985 return;
1987 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1988 if (busy)
1989 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1990 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1992 hctx->dispatch_busy = ewma;
1995 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1997 static void blk_mq_handle_dev_resource(struct request *rq,
1998 struct list_head *list)
2000 list_add(&rq->queuelist, list);
2001 __blk_mq_requeue_request(rq);
2004 enum prep_dispatch {
2005 PREP_DISPATCH_OK,
2006 PREP_DISPATCH_NO_TAG,
2007 PREP_DISPATCH_NO_BUDGET,
2010 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
2011 bool need_budget)
2013 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2014 int budget_token = -1;
2016 if (need_budget) {
2017 budget_token = blk_mq_get_dispatch_budget(rq->q);
2018 if (budget_token < 0) {
2019 blk_mq_put_driver_tag(rq);
2020 return PREP_DISPATCH_NO_BUDGET;
2022 blk_mq_set_rq_budget_token(rq, budget_token);
2025 if (!blk_mq_get_driver_tag(rq)) {
2027 * The initial allocation attempt failed, so we need to
2028 * rerun the hardware queue when a tag is freed. The
2029 * waitqueue takes care of that. If the queue is run
2030 * before we add this entry back on the dispatch list,
2031 * we'll re-run it below.
2033 if (!blk_mq_mark_tag_wait(hctx, rq)) {
2035 * All budgets not got from this function will be put
2036 * together during handling partial dispatch
2038 if (need_budget)
2039 blk_mq_put_dispatch_budget(rq->q, budget_token);
2040 return PREP_DISPATCH_NO_TAG;
2044 return PREP_DISPATCH_OK;
2047 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
2048 static void blk_mq_release_budgets(struct request_queue *q,
2049 struct list_head *list)
2051 struct request *rq;
2053 list_for_each_entry(rq, list, queuelist) {
2054 int budget_token = blk_mq_get_rq_budget_token(rq);
2056 if (budget_token >= 0)
2057 blk_mq_put_dispatch_budget(q, budget_token);
2062 * blk_mq_commit_rqs will notify driver using bd->last that there is no
2063 * more requests. (See comment in struct blk_mq_ops for commit_rqs for
2064 * details)
2065 * Attention, we should explicitly call this in unusual cases:
2066 * 1) did not queue everything initially scheduled to queue
2067 * 2) the last attempt to queue a request failed
2069 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int queued,
2070 bool from_schedule)
2072 if (hctx->queue->mq_ops->commit_rqs && queued) {
2073 trace_block_unplug(hctx->queue, queued, !from_schedule);
2074 hctx->queue->mq_ops->commit_rqs(hctx);
2079 * Returns true if we did some work AND can potentially do more.
2081 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
2082 unsigned int nr_budgets)
2084 enum prep_dispatch prep;
2085 struct request_queue *q = hctx->queue;
2086 struct request *rq;
2087 int queued;
2088 blk_status_t ret = BLK_STS_OK;
2089 bool needs_resource = false;
2091 if (list_empty(list))
2092 return false;
2095 * Now process all the entries, sending them to the driver.
2097 queued = 0;
2098 do {
2099 struct blk_mq_queue_data bd;
2101 rq = list_first_entry(list, struct request, queuelist);
2103 WARN_ON_ONCE(hctx != rq->mq_hctx);
2104 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
2105 if (prep != PREP_DISPATCH_OK)
2106 break;
2108 list_del_init(&rq->queuelist);
2110 bd.rq = rq;
2111 bd.last = list_empty(list);
2114 * once the request is queued to lld, no need to cover the
2115 * budget any more
2117 if (nr_budgets)
2118 nr_budgets--;
2119 ret = q->mq_ops->queue_rq(hctx, &bd);
2120 switch (ret) {
2121 case BLK_STS_OK:
2122 queued++;
2123 break;
2124 case BLK_STS_RESOURCE:
2125 needs_resource = true;
2126 fallthrough;
2127 case BLK_STS_DEV_RESOURCE:
2128 blk_mq_handle_dev_resource(rq, list);
2129 goto out;
2130 default:
2131 blk_mq_end_request(rq, ret);
2133 } while (!list_empty(list));
2134 out:
2135 /* If we didn't flush the entire list, we could have told the driver
2136 * there was more coming, but that turned out to be a lie.
2138 if (!list_empty(list) || ret != BLK_STS_OK)
2139 blk_mq_commit_rqs(hctx, queued, false);
2142 * Any items that need requeuing? Stuff them into hctx->dispatch,
2143 * that is where we will continue on next queue run.
2145 if (!list_empty(list)) {
2146 bool needs_restart;
2147 /* For non-shared tags, the RESTART check will suffice */
2148 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
2149 ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) ||
2150 blk_mq_is_shared_tags(hctx->flags));
2152 if (nr_budgets)
2153 blk_mq_release_budgets(q, list);
2155 spin_lock(&hctx->lock);
2156 list_splice_tail_init(list, &hctx->dispatch);
2157 spin_unlock(&hctx->lock);
2160 * Order adding requests to hctx->dispatch and checking
2161 * SCHED_RESTART flag. The pair of this smp_mb() is the one
2162 * in blk_mq_sched_restart(). Avoid restart code path to
2163 * miss the new added requests to hctx->dispatch, meantime
2164 * SCHED_RESTART is observed here.
2166 smp_mb();
2169 * If SCHED_RESTART was set by the caller of this function and
2170 * it is no longer set that means that it was cleared by another
2171 * thread and hence that a queue rerun is needed.
2173 * If 'no_tag' is set, that means that we failed getting
2174 * a driver tag with an I/O scheduler attached. If our dispatch
2175 * waitqueue is no longer active, ensure that we run the queue
2176 * AFTER adding our entries back to the list.
2178 * If no I/O scheduler has been configured it is possible that
2179 * the hardware queue got stopped and restarted before requests
2180 * were pushed back onto the dispatch list. Rerun the queue to
2181 * avoid starvation. Notes:
2182 * - blk_mq_run_hw_queue() checks whether or not a queue has
2183 * been stopped before rerunning a queue.
2184 * - Some but not all block drivers stop a queue before
2185 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
2186 * and dm-rq.
2188 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
2189 * bit is set, run queue after a delay to avoid IO stalls
2190 * that could otherwise occur if the queue is idle. We'll do
2191 * similar if we couldn't get budget or couldn't lock a zone
2192 * and SCHED_RESTART is set.
2194 needs_restart = blk_mq_sched_needs_restart(hctx);
2195 if (prep == PREP_DISPATCH_NO_BUDGET)
2196 needs_resource = true;
2197 if (!needs_restart ||
2198 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
2199 blk_mq_run_hw_queue(hctx, true);
2200 else if (needs_resource)
2201 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
2203 blk_mq_update_dispatch_busy(hctx, true);
2204 return false;
2207 blk_mq_update_dispatch_busy(hctx, false);
2208 return true;
2211 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
2213 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
2215 if (cpu >= nr_cpu_ids)
2216 cpu = cpumask_first(hctx->cpumask);
2217 return cpu;
2221 * ->next_cpu is always calculated from hctx->cpumask, so simply use
2222 * it for speeding up the check
2224 static bool blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx *hctx)
2226 return hctx->next_cpu >= nr_cpu_ids;
2230 * It'd be great if the workqueue API had a way to pass
2231 * in a mask and had some smarts for more clever placement.
2232 * For now we just round-robin here, switching for every
2233 * BLK_MQ_CPU_WORK_BATCH queued items.
2235 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
2237 bool tried = false;
2238 int next_cpu = hctx->next_cpu;
2240 /* Switch to unbound if no allowable CPUs in this hctx */
2241 if (hctx->queue->nr_hw_queues == 1 || blk_mq_hctx_empty_cpumask(hctx))
2242 return WORK_CPU_UNBOUND;
2244 if (--hctx->next_cpu_batch <= 0) {
2245 select_cpu:
2246 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
2247 cpu_online_mask);
2248 if (next_cpu >= nr_cpu_ids)
2249 next_cpu = blk_mq_first_mapped_cpu(hctx);
2250 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2254 * Do unbound schedule if we can't find a online CPU for this hctx,
2255 * and it should only happen in the path of handling CPU DEAD.
2257 if (!cpu_online(next_cpu)) {
2258 if (!tried) {
2259 tried = true;
2260 goto select_cpu;
2264 * Make sure to re-select CPU next time once after CPUs
2265 * in hctx->cpumask become online again.
2267 hctx->next_cpu = next_cpu;
2268 hctx->next_cpu_batch = 1;
2269 return WORK_CPU_UNBOUND;
2272 hctx->next_cpu = next_cpu;
2273 return next_cpu;
2277 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2278 * @hctx: Pointer to the hardware queue to run.
2279 * @msecs: Milliseconds of delay to wait before running the queue.
2281 * Run a hardware queue asynchronously with a delay of @msecs.
2283 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2285 if (unlikely(blk_mq_hctx_stopped(hctx)))
2286 return;
2287 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2288 msecs_to_jiffies(msecs));
2290 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2292 static inline bool blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx *hctx)
2294 bool need_run;
2297 * When queue is quiesced, we may be switching io scheduler, or
2298 * updating nr_hw_queues, or other things, and we can't run queue
2299 * any more, even blk_mq_hctx_has_pending() can't be called safely.
2301 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2302 * quiesced.
2304 __blk_mq_run_dispatch_ops(hctx->queue, false,
2305 need_run = !blk_queue_quiesced(hctx->queue) &&
2306 blk_mq_hctx_has_pending(hctx));
2307 return need_run;
2311 * blk_mq_run_hw_queue - Start to run a hardware queue.
2312 * @hctx: Pointer to the hardware queue to run.
2313 * @async: If we want to run the queue asynchronously.
2315 * Check if the request queue is not in a quiesced state and if there are
2316 * pending requests to be sent. If this is true, run the queue to send requests
2317 * to hardware.
2319 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2321 bool need_run;
2324 * We can't run the queue inline with interrupts disabled.
2326 WARN_ON_ONCE(!async && in_interrupt());
2328 might_sleep_if(!async && hctx->flags & BLK_MQ_F_BLOCKING);
2330 need_run = blk_mq_hw_queue_need_run(hctx);
2331 if (!need_run) {
2332 unsigned long flags;
2335 * Synchronize with blk_mq_unquiesce_queue(), because we check
2336 * if hw queue is quiesced locklessly above, we need the use
2337 * ->queue_lock to make sure we see the up-to-date status to
2338 * not miss rerunning the hw queue.
2340 spin_lock_irqsave(&hctx->queue->queue_lock, flags);
2341 need_run = blk_mq_hw_queue_need_run(hctx);
2342 spin_unlock_irqrestore(&hctx->queue->queue_lock, flags);
2344 if (!need_run)
2345 return;
2348 if (async || !cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask)) {
2349 blk_mq_delay_run_hw_queue(hctx, 0);
2350 return;
2353 blk_mq_run_dispatch_ops(hctx->queue,
2354 blk_mq_sched_dispatch_requests(hctx));
2356 EXPORT_SYMBOL(blk_mq_run_hw_queue);
2359 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2360 * scheduler.
2362 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2364 struct blk_mq_ctx *ctx = blk_mq_get_ctx(q);
2366 * If the IO scheduler does not respect hardware queues when
2367 * dispatching, we just don't bother with multiple HW queues and
2368 * dispatch from hctx for the current CPU since running multiple queues
2369 * just causes lock contention inside the scheduler and pointless cache
2370 * bouncing.
2372 struct blk_mq_hw_ctx *hctx = ctx->hctxs[HCTX_TYPE_DEFAULT];
2374 if (!blk_mq_hctx_stopped(hctx))
2375 return hctx;
2376 return NULL;
2380 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2381 * @q: Pointer to the request queue to run.
2382 * @async: If we want to run the queue asynchronously.
2384 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2386 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2387 unsigned long i;
2389 sq_hctx = NULL;
2390 if (blk_queue_sq_sched(q))
2391 sq_hctx = blk_mq_get_sq_hctx(q);
2392 queue_for_each_hw_ctx(q, hctx, i) {
2393 if (blk_mq_hctx_stopped(hctx))
2394 continue;
2396 * Dispatch from this hctx either if there's no hctx preferred
2397 * by IO scheduler or if it has requests that bypass the
2398 * scheduler.
2400 if (!sq_hctx || sq_hctx == hctx ||
2401 !list_empty_careful(&hctx->dispatch))
2402 blk_mq_run_hw_queue(hctx, async);
2405 EXPORT_SYMBOL(blk_mq_run_hw_queues);
2408 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2409 * @q: Pointer to the request queue to run.
2410 * @msecs: Milliseconds of delay to wait before running the queues.
2412 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2414 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2415 unsigned long i;
2417 sq_hctx = NULL;
2418 if (blk_queue_sq_sched(q))
2419 sq_hctx = blk_mq_get_sq_hctx(q);
2420 queue_for_each_hw_ctx(q, hctx, i) {
2421 if (blk_mq_hctx_stopped(hctx))
2422 continue;
2424 * If there is already a run_work pending, leave the
2425 * pending delay untouched. Otherwise, a hctx can stall
2426 * if another hctx is re-delaying the other's work
2427 * before the work executes.
2429 if (delayed_work_pending(&hctx->run_work))
2430 continue;
2432 * Dispatch from this hctx either if there's no hctx preferred
2433 * by IO scheduler or if it has requests that bypass the
2434 * scheduler.
2436 if (!sq_hctx || sq_hctx == hctx ||
2437 !list_empty_careful(&hctx->dispatch))
2438 blk_mq_delay_run_hw_queue(hctx, msecs);
2441 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2444 * This function is often used for pausing .queue_rq() by driver when
2445 * there isn't enough resource or some conditions aren't satisfied, and
2446 * BLK_STS_RESOURCE is usually returned.
2448 * We do not guarantee that dispatch can be drained or blocked
2449 * after blk_mq_stop_hw_queue() returns. Please use
2450 * blk_mq_quiesce_queue() for that requirement.
2452 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2454 cancel_delayed_work(&hctx->run_work);
2456 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2458 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2461 * This function is often used for pausing .queue_rq() by driver when
2462 * there isn't enough resource or some conditions aren't satisfied, and
2463 * BLK_STS_RESOURCE is usually returned.
2465 * We do not guarantee that dispatch can be drained or blocked
2466 * after blk_mq_stop_hw_queues() returns. Please use
2467 * blk_mq_quiesce_queue() for that requirement.
2469 void blk_mq_stop_hw_queues(struct request_queue *q)
2471 struct blk_mq_hw_ctx *hctx;
2472 unsigned long i;
2474 queue_for_each_hw_ctx(q, hctx, i)
2475 blk_mq_stop_hw_queue(hctx);
2477 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2479 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2481 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2483 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
2485 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2487 void blk_mq_start_hw_queues(struct request_queue *q)
2489 struct blk_mq_hw_ctx *hctx;
2490 unsigned long i;
2492 queue_for_each_hw_ctx(q, hctx, i)
2493 blk_mq_start_hw_queue(hctx);
2495 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2497 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2499 if (!blk_mq_hctx_stopped(hctx))
2500 return;
2502 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2504 * Pairs with the smp_mb() in blk_mq_hctx_stopped() to order the
2505 * clearing of BLK_MQ_S_STOPPED above and the checking of dispatch
2506 * list in the subsequent routine.
2508 smp_mb__after_atomic();
2509 blk_mq_run_hw_queue(hctx, async);
2511 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2513 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2515 struct blk_mq_hw_ctx *hctx;
2516 unsigned long i;
2518 queue_for_each_hw_ctx(q, hctx, i)
2519 blk_mq_start_stopped_hw_queue(hctx, async ||
2520 (hctx->flags & BLK_MQ_F_BLOCKING));
2522 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2524 static void blk_mq_run_work_fn(struct work_struct *work)
2526 struct blk_mq_hw_ctx *hctx =
2527 container_of(work, struct blk_mq_hw_ctx, run_work.work);
2529 blk_mq_run_dispatch_ops(hctx->queue,
2530 blk_mq_sched_dispatch_requests(hctx));
2534 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2535 * @rq: Pointer to request to be inserted.
2536 * @flags: BLK_MQ_INSERT_*
2538 * Should only be used carefully, when the caller knows we want to
2539 * bypass a potential IO scheduler on the target device.
2541 static void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
2543 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2545 spin_lock(&hctx->lock);
2546 if (flags & BLK_MQ_INSERT_AT_HEAD)
2547 list_add(&rq->queuelist, &hctx->dispatch);
2548 else
2549 list_add_tail(&rq->queuelist, &hctx->dispatch);
2550 spin_unlock(&hctx->lock);
2553 static void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx,
2554 struct blk_mq_ctx *ctx, struct list_head *list,
2555 bool run_queue_async)
2557 struct request *rq;
2558 enum hctx_type type = hctx->type;
2561 * Try to issue requests directly if the hw queue isn't busy to save an
2562 * extra enqueue & dequeue to the sw queue.
2564 if (!hctx->dispatch_busy && !run_queue_async) {
2565 blk_mq_run_dispatch_ops(hctx->queue,
2566 blk_mq_try_issue_list_directly(hctx, list));
2567 if (list_empty(list))
2568 goto out;
2572 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2573 * offline now
2575 list_for_each_entry(rq, list, queuelist) {
2576 BUG_ON(rq->mq_ctx != ctx);
2577 trace_block_rq_insert(rq);
2578 if (rq->cmd_flags & REQ_NOWAIT)
2579 run_queue_async = true;
2582 spin_lock(&ctx->lock);
2583 list_splice_tail_init(list, &ctx->rq_lists[type]);
2584 blk_mq_hctx_mark_pending(hctx, ctx);
2585 spin_unlock(&ctx->lock);
2586 out:
2587 blk_mq_run_hw_queue(hctx, run_queue_async);
2590 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags)
2592 struct request_queue *q = rq->q;
2593 struct blk_mq_ctx *ctx = rq->mq_ctx;
2594 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2596 if (blk_rq_is_passthrough(rq)) {
2598 * Passthrough request have to be added to hctx->dispatch
2599 * directly. The device may be in a situation where it can't
2600 * handle FS request, and always returns BLK_STS_RESOURCE for
2601 * them, which gets them added to hctx->dispatch.
2603 * If a passthrough request is required to unblock the queues,
2604 * and it is added to the scheduler queue, there is no chance to
2605 * dispatch it given we prioritize requests in hctx->dispatch.
2607 blk_mq_request_bypass_insert(rq, flags);
2608 } else if (req_op(rq) == REQ_OP_FLUSH) {
2610 * Firstly normal IO request is inserted to scheduler queue or
2611 * sw queue, meantime we add flush request to dispatch queue(
2612 * hctx->dispatch) directly and there is at most one in-flight
2613 * flush request for each hw queue, so it doesn't matter to add
2614 * flush request to tail or front of the dispatch queue.
2616 * Secondly in case of NCQ, flush request belongs to non-NCQ
2617 * command, and queueing it will fail when there is any
2618 * in-flight normal IO request(NCQ command). When adding flush
2619 * rq to the front of hctx->dispatch, it is easier to introduce
2620 * extra time to flush rq's latency because of S_SCHED_RESTART
2621 * compared with adding to the tail of dispatch queue, then
2622 * chance of flush merge is increased, and less flush requests
2623 * will be issued to controller. It is observed that ~10% time
2624 * is saved in blktests block/004 on disk attached to AHCI/NCQ
2625 * drive when adding flush rq to the front of hctx->dispatch.
2627 * Simply queue flush rq to the front of hctx->dispatch so that
2628 * intensive flush workloads can benefit in case of NCQ HW.
2630 blk_mq_request_bypass_insert(rq, BLK_MQ_INSERT_AT_HEAD);
2631 } else if (q->elevator) {
2632 LIST_HEAD(list);
2634 WARN_ON_ONCE(rq->tag != BLK_MQ_NO_TAG);
2636 list_add(&rq->queuelist, &list);
2637 q->elevator->type->ops.insert_requests(hctx, &list, flags);
2638 } else {
2639 trace_block_rq_insert(rq);
2641 spin_lock(&ctx->lock);
2642 if (flags & BLK_MQ_INSERT_AT_HEAD)
2643 list_add(&rq->queuelist, &ctx->rq_lists[hctx->type]);
2644 else
2645 list_add_tail(&rq->queuelist,
2646 &ctx->rq_lists[hctx->type]);
2647 blk_mq_hctx_mark_pending(hctx, ctx);
2648 spin_unlock(&ctx->lock);
2652 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2653 unsigned int nr_segs)
2655 int err;
2657 if (bio->bi_opf & REQ_RAHEAD)
2658 rq->cmd_flags |= REQ_FAILFAST_MASK;
2660 rq->__sector = bio->bi_iter.bi_sector;
2661 blk_rq_bio_prep(rq, bio, nr_segs);
2662 if (bio_integrity(bio))
2663 rq->nr_integrity_segments = blk_rq_count_integrity_sg(rq->q,
2664 bio);
2666 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2667 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2668 WARN_ON_ONCE(err);
2670 blk_account_io_start(rq);
2673 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2674 struct request *rq, bool last)
2676 struct request_queue *q = rq->q;
2677 struct blk_mq_queue_data bd = {
2678 .rq = rq,
2679 .last = last,
2681 blk_status_t ret;
2684 * For OK queue, we are done. For error, caller may kill it.
2685 * Any other error (busy), just add it to our list as we
2686 * previously would have done.
2688 ret = q->mq_ops->queue_rq(hctx, &bd);
2689 switch (ret) {
2690 case BLK_STS_OK:
2691 blk_mq_update_dispatch_busy(hctx, false);
2692 break;
2693 case BLK_STS_RESOURCE:
2694 case BLK_STS_DEV_RESOURCE:
2695 blk_mq_update_dispatch_busy(hctx, true);
2696 __blk_mq_requeue_request(rq);
2697 break;
2698 default:
2699 blk_mq_update_dispatch_busy(hctx, false);
2700 break;
2703 return ret;
2706 static bool blk_mq_get_budget_and_tag(struct request *rq)
2708 int budget_token;
2710 budget_token = blk_mq_get_dispatch_budget(rq->q);
2711 if (budget_token < 0)
2712 return false;
2713 blk_mq_set_rq_budget_token(rq, budget_token);
2714 if (!blk_mq_get_driver_tag(rq)) {
2715 blk_mq_put_dispatch_budget(rq->q, budget_token);
2716 return false;
2718 return true;
2722 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2723 * @hctx: Pointer of the associated hardware queue.
2724 * @rq: Pointer to request to be sent.
2726 * If the device has enough resources to accept a new request now, send the
2727 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2728 * we can try send it another time in the future. Requests inserted at this
2729 * queue have higher priority.
2731 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2732 struct request *rq)
2734 blk_status_t ret;
2736 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2737 blk_mq_insert_request(rq, 0);
2738 blk_mq_run_hw_queue(hctx, false);
2739 return;
2742 if ((rq->rq_flags & RQF_USE_SCHED) || !blk_mq_get_budget_and_tag(rq)) {
2743 blk_mq_insert_request(rq, 0);
2744 blk_mq_run_hw_queue(hctx, rq->cmd_flags & REQ_NOWAIT);
2745 return;
2748 ret = __blk_mq_issue_directly(hctx, rq, true);
2749 switch (ret) {
2750 case BLK_STS_OK:
2751 break;
2752 case BLK_STS_RESOURCE:
2753 case BLK_STS_DEV_RESOURCE:
2754 blk_mq_request_bypass_insert(rq, 0);
2755 blk_mq_run_hw_queue(hctx, false);
2756 break;
2757 default:
2758 blk_mq_end_request(rq, ret);
2759 break;
2763 static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2765 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2767 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2768 blk_mq_insert_request(rq, 0);
2769 blk_mq_run_hw_queue(hctx, false);
2770 return BLK_STS_OK;
2773 if (!blk_mq_get_budget_and_tag(rq))
2774 return BLK_STS_RESOURCE;
2775 return __blk_mq_issue_directly(hctx, rq, last);
2778 static void blk_mq_plug_issue_direct(struct blk_plug *plug)
2780 struct blk_mq_hw_ctx *hctx = NULL;
2781 struct request *rq;
2782 int queued = 0;
2783 blk_status_t ret = BLK_STS_OK;
2785 while ((rq = rq_list_pop(&plug->mq_list))) {
2786 bool last = rq_list_empty(&plug->mq_list);
2788 if (hctx != rq->mq_hctx) {
2789 if (hctx) {
2790 blk_mq_commit_rqs(hctx, queued, false);
2791 queued = 0;
2793 hctx = rq->mq_hctx;
2796 ret = blk_mq_request_issue_directly(rq, last);
2797 switch (ret) {
2798 case BLK_STS_OK:
2799 queued++;
2800 break;
2801 case BLK_STS_RESOURCE:
2802 case BLK_STS_DEV_RESOURCE:
2803 blk_mq_request_bypass_insert(rq, 0);
2804 blk_mq_run_hw_queue(hctx, false);
2805 goto out;
2806 default:
2807 blk_mq_end_request(rq, ret);
2808 break;
2812 out:
2813 if (ret != BLK_STS_OK)
2814 blk_mq_commit_rqs(hctx, queued, false);
2817 static void __blk_mq_flush_plug_list(struct request_queue *q,
2818 struct blk_plug *plug)
2820 if (blk_queue_quiesced(q))
2821 return;
2822 q->mq_ops->queue_rqs(&plug->mq_list);
2825 static void blk_mq_dispatch_plug_list(struct blk_plug *plug, bool from_sched)
2827 struct blk_mq_hw_ctx *this_hctx = NULL;
2828 struct blk_mq_ctx *this_ctx = NULL;
2829 struct rq_list requeue_list = {};
2830 unsigned int depth = 0;
2831 bool is_passthrough = false;
2832 LIST_HEAD(list);
2834 do {
2835 struct request *rq = rq_list_pop(&plug->mq_list);
2837 if (!this_hctx) {
2838 this_hctx = rq->mq_hctx;
2839 this_ctx = rq->mq_ctx;
2840 is_passthrough = blk_rq_is_passthrough(rq);
2841 } else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx ||
2842 is_passthrough != blk_rq_is_passthrough(rq)) {
2843 rq_list_add_tail(&requeue_list, rq);
2844 continue;
2846 list_add_tail(&rq->queuelist, &list);
2847 depth++;
2848 } while (!rq_list_empty(&plug->mq_list));
2850 plug->mq_list = requeue_list;
2851 trace_block_unplug(this_hctx->queue, depth, !from_sched);
2853 percpu_ref_get(&this_hctx->queue->q_usage_counter);
2854 /* passthrough requests should never be issued to the I/O scheduler */
2855 if (is_passthrough) {
2856 spin_lock(&this_hctx->lock);
2857 list_splice_tail_init(&list, &this_hctx->dispatch);
2858 spin_unlock(&this_hctx->lock);
2859 blk_mq_run_hw_queue(this_hctx, from_sched);
2860 } else if (this_hctx->queue->elevator) {
2861 this_hctx->queue->elevator->type->ops.insert_requests(this_hctx,
2862 &list, 0);
2863 blk_mq_run_hw_queue(this_hctx, from_sched);
2864 } else {
2865 blk_mq_insert_requests(this_hctx, this_ctx, &list, from_sched);
2867 percpu_ref_put(&this_hctx->queue->q_usage_counter);
2870 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2872 struct request *rq;
2873 unsigned int depth;
2876 * We may have been called recursively midway through handling
2877 * plug->mq_list via a schedule() in the driver's queue_rq() callback.
2878 * To avoid mq_list changing under our feet, clear rq_count early and
2879 * bail out specifically if rq_count is 0 rather than checking
2880 * whether the mq_list is empty.
2882 if (plug->rq_count == 0)
2883 return;
2884 depth = plug->rq_count;
2885 plug->rq_count = 0;
2887 if (!plug->multiple_queues && !plug->has_elevator && !from_schedule) {
2888 struct request_queue *q;
2890 rq = rq_list_peek(&plug->mq_list);
2891 q = rq->q;
2892 trace_block_unplug(q, depth, true);
2895 * Peek first request and see if we have a ->queue_rqs() hook.
2896 * If we do, we can dispatch the whole plug list in one go. We
2897 * already know at this point that all requests belong to the
2898 * same queue, caller must ensure that's the case.
2900 if (q->mq_ops->queue_rqs) {
2901 blk_mq_run_dispatch_ops(q,
2902 __blk_mq_flush_plug_list(q, plug));
2903 if (rq_list_empty(&plug->mq_list))
2904 return;
2907 blk_mq_run_dispatch_ops(q,
2908 blk_mq_plug_issue_direct(plug));
2909 if (rq_list_empty(&plug->mq_list))
2910 return;
2913 do {
2914 blk_mq_dispatch_plug_list(plug, from_schedule);
2915 } while (!rq_list_empty(&plug->mq_list));
2918 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2919 struct list_head *list)
2921 int queued = 0;
2922 blk_status_t ret = BLK_STS_OK;
2924 while (!list_empty(list)) {
2925 struct request *rq = list_first_entry(list, struct request,
2926 queuelist);
2928 list_del_init(&rq->queuelist);
2929 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2930 switch (ret) {
2931 case BLK_STS_OK:
2932 queued++;
2933 break;
2934 case BLK_STS_RESOURCE:
2935 case BLK_STS_DEV_RESOURCE:
2936 blk_mq_request_bypass_insert(rq, 0);
2937 if (list_empty(list))
2938 blk_mq_run_hw_queue(hctx, false);
2939 goto out;
2940 default:
2941 blk_mq_end_request(rq, ret);
2942 break;
2946 out:
2947 if (ret != BLK_STS_OK)
2948 blk_mq_commit_rqs(hctx, queued, false);
2951 static bool blk_mq_attempt_bio_merge(struct request_queue *q,
2952 struct bio *bio, unsigned int nr_segs)
2954 if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
2955 if (blk_attempt_plug_merge(q, bio, nr_segs))
2956 return true;
2957 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2958 return true;
2960 return false;
2963 static struct request *blk_mq_get_new_requests(struct request_queue *q,
2964 struct blk_plug *plug,
2965 struct bio *bio,
2966 unsigned int nsegs)
2968 struct blk_mq_alloc_data data = {
2969 .q = q,
2970 .nr_tags = 1,
2971 .cmd_flags = bio->bi_opf,
2973 struct request *rq;
2975 rq_qos_throttle(q, bio);
2977 if (plug) {
2978 data.nr_tags = plug->nr_ios;
2979 plug->nr_ios = 1;
2980 data.cached_rqs = &plug->cached_rqs;
2983 rq = __blk_mq_alloc_requests(&data);
2984 if (rq)
2985 return rq;
2986 rq_qos_cleanup(q, bio);
2987 if (bio->bi_opf & REQ_NOWAIT)
2988 bio_wouldblock_error(bio);
2989 return NULL;
2993 * Check if there is a suitable cached request and return it.
2995 static struct request *blk_mq_peek_cached_request(struct blk_plug *plug,
2996 struct request_queue *q, blk_opf_t opf)
2998 enum hctx_type type = blk_mq_get_hctx_type(opf);
2999 struct request *rq;
3001 if (!plug)
3002 return NULL;
3003 rq = rq_list_peek(&plug->cached_rqs);
3004 if (!rq || rq->q != q)
3005 return NULL;
3006 if (type != rq->mq_hctx->type &&
3007 (type != HCTX_TYPE_READ || rq->mq_hctx->type != HCTX_TYPE_DEFAULT))
3008 return NULL;
3009 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
3010 return NULL;
3011 return rq;
3014 static void blk_mq_use_cached_rq(struct request *rq, struct blk_plug *plug,
3015 struct bio *bio)
3017 if (rq_list_pop(&plug->cached_rqs) != rq)
3018 WARN_ON_ONCE(1);
3021 * If any qos ->throttle() end up blocking, we will have flushed the
3022 * plug and hence killed the cached_rq list as well. Pop this entry
3023 * before we throttle.
3025 rq_qos_throttle(rq->q, bio);
3027 blk_mq_rq_time_init(rq, blk_time_get_ns());
3028 rq->cmd_flags = bio->bi_opf;
3029 INIT_LIST_HEAD(&rq->queuelist);
3032 static bool bio_unaligned(const struct bio *bio, struct request_queue *q)
3034 unsigned int bs_mask = queue_logical_block_size(q) - 1;
3036 /* .bi_sector of any zero sized bio need to be initialized */
3037 if ((bio->bi_iter.bi_size & bs_mask) ||
3038 ((bio->bi_iter.bi_sector << SECTOR_SHIFT) & bs_mask))
3039 return true;
3040 return false;
3044 * blk_mq_submit_bio - Create and send a request to block device.
3045 * @bio: Bio pointer.
3047 * Builds up a request structure from @q and @bio and send to the device. The
3048 * request may not be queued directly to hardware if:
3049 * * This request can be merged with another one
3050 * * We want to place request at plug queue for possible future merging
3051 * * There is an IO scheduler active at this queue
3053 * It will not queue the request if there is an error with the bio, or at the
3054 * request creation.
3056 void blk_mq_submit_bio(struct bio *bio)
3058 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
3059 struct blk_plug *plug = current->plug;
3060 const int is_sync = op_is_sync(bio->bi_opf);
3061 struct blk_mq_hw_ctx *hctx;
3062 unsigned int nr_segs;
3063 struct request *rq;
3064 blk_status_t ret;
3067 * If the plug has a cached request for this queue, try to use it.
3069 rq = blk_mq_peek_cached_request(plug, q, bio->bi_opf);
3072 * A BIO that was released from a zone write plug has already been
3073 * through the preparation in this function, already holds a reference
3074 * on the queue usage counter, and is the only write BIO in-flight for
3075 * the target zone. Go straight to preparing a request for it.
3077 if (bio_zone_write_plugging(bio)) {
3078 nr_segs = bio->__bi_nr_segments;
3079 if (rq)
3080 blk_queue_exit(q);
3081 goto new_request;
3084 bio = blk_queue_bounce(bio, q);
3087 * The cached request already holds a q_usage_counter reference and we
3088 * don't have to acquire a new one if we use it.
3090 if (!rq) {
3091 if (unlikely(bio_queue_enter(bio)))
3092 return;
3096 * Device reconfiguration may change logical block size, so alignment
3097 * check has to be done with queue usage counter held
3099 if (unlikely(bio_unaligned(bio, q))) {
3100 bio_io_error(bio);
3101 goto queue_exit;
3104 bio = __bio_split_to_limits(bio, &q->limits, &nr_segs);
3105 if (!bio)
3106 goto queue_exit;
3108 if (!bio_integrity_prep(bio))
3109 goto queue_exit;
3111 if (blk_mq_attempt_bio_merge(q, bio, nr_segs))
3112 goto queue_exit;
3114 if (blk_queue_is_zoned(q) && blk_zone_plug_bio(bio, nr_segs))
3115 goto queue_exit;
3117 new_request:
3118 if (!rq) {
3119 rq = blk_mq_get_new_requests(q, plug, bio, nr_segs);
3120 if (unlikely(!rq))
3121 goto queue_exit;
3122 } else {
3123 blk_mq_use_cached_rq(rq, plug, bio);
3126 trace_block_getrq(bio);
3128 rq_qos_track(q, rq, bio);
3130 blk_mq_bio_to_request(rq, bio, nr_segs);
3132 ret = blk_crypto_rq_get_keyslot(rq);
3133 if (ret != BLK_STS_OK) {
3134 bio->bi_status = ret;
3135 bio_endio(bio);
3136 blk_mq_free_request(rq);
3137 return;
3140 if (bio_zone_write_plugging(bio))
3141 blk_zone_write_plug_init_request(rq);
3143 if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
3144 return;
3146 if (plug) {
3147 blk_add_rq_to_plug(plug, rq);
3148 return;
3151 hctx = rq->mq_hctx;
3152 if ((rq->rq_flags & RQF_USE_SCHED) ||
3153 (hctx->dispatch_busy && (q->nr_hw_queues == 1 || !is_sync))) {
3154 blk_mq_insert_request(rq, 0);
3155 blk_mq_run_hw_queue(hctx, true);
3156 } else {
3157 blk_mq_run_dispatch_ops(q, blk_mq_try_issue_directly(hctx, rq));
3159 return;
3161 queue_exit:
3163 * Don't drop the queue reference if we were trying to use a cached
3164 * request and thus didn't acquire one.
3166 if (!rq)
3167 blk_queue_exit(q);
3170 #ifdef CONFIG_BLK_MQ_STACKING
3172 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
3173 * @rq: the request being queued
3175 blk_status_t blk_insert_cloned_request(struct request *rq)
3177 struct request_queue *q = rq->q;
3178 unsigned int max_sectors = blk_queue_get_max_sectors(rq);
3179 unsigned int max_segments = blk_rq_get_max_segments(rq);
3180 blk_status_t ret;
3182 if (blk_rq_sectors(rq) > max_sectors) {
3184 * SCSI device does not have a good way to return if
3185 * Write Same/Zero is actually supported. If a device rejects
3186 * a non-read/write command (discard, write same,etc.) the
3187 * low-level device driver will set the relevant queue limit to
3188 * 0 to prevent blk-lib from issuing more of the offending
3189 * operations. Commands queued prior to the queue limit being
3190 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
3191 * errors being propagated to upper layers.
3193 if (max_sectors == 0)
3194 return BLK_STS_NOTSUPP;
3196 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
3197 __func__, blk_rq_sectors(rq), max_sectors);
3198 return BLK_STS_IOERR;
3202 * The queue settings related to segment counting may differ from the
3203 * original queue.
3205 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
3206 if (rq->nr_phys_segments > max_segments) {
3207 printk(KERN_ERR "%s: over max segments limit. (%u > %u)\n",
3208 __func__, rq->nr_phys_segments, max_segments);
3209 return BLK_STS_IOERR;
3212 if (q->disk && should_fail_request(q->disk->part0, blk_rq_bytes(rq)))
3213 return BLK_STS_IOERR;
3215 ret = blk_crypto_rq_get_keyslot(rq);
3216 if (ret != BLK_STS_OK)
3217 return ret;
3219 blk_account_io_start(rq);
3222 * Since we have a scheduler attached on the top device,
3223 * bypass a potential scheduler on the bottom device for
3224 * insert.
3226 blk_mq_run_dispatch_ops(q,
3227 ret = blk_mq_request_issue_directly(rq, true));
3228 if (ret)
3229 blk_account_io_done(rq, blk_time_get_ns());
3230 return ret;
3232 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
3235 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3236 * @rq: the clone request to be cleaned up
3238 * Description:
3239 * Free all bios in @rq for a cloned request.
3241 void blk_rq_unprep_clone(struct request *rq)
3243 struct bio *bio;
3245 while ((bio = rq->bio) != NULL) {
3246 rq->bio = bio->bi_next;
3248 bio_put(bio);
3251 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3254 * blk_rq_prep_clone - Helper function to setup clone request
3255 * @rq: the request to be setup
3256 * @rq_src: original request to be cloned
3257 * @bs: bio_set that bios for clone are allocated from
3258 * @gfp_mask: memory allocation mask for bio
3259 * @bio_ctr: setup function to be called for each clone bio.
3260 * Returns %0 for success, non %0 for failure.
3261 * @data: private data to be passed to @bio_ctr
3263 * Description:
3264 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3265 * Also, pages which the original bios are pointing to are not copied
3266 * and the cloned bios just point same pages.
3267 * So cloned bios must be completed before original bios, which means
3268 * the caller must complete @rq before @rq_src.
3270 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3271 struct bio_set *bs, gfp_t gfp_mask,
3272 int (*bio_ctr)(struct bio *, struct bio *, void *),
3273 void *data)
3275 struct bio *bio_src;
3277 if (!bs)
3278 bs = &fs_bio_set;
3280 __rq_for_each_bio(bio_src, rq_src) {
3281 struct bio *bio = bio_alloc_clone(rq->q->disk->part0, bio_src,
3282 gfp_mask, bs);
3283 if (!bio)
3284 goto free_and_out;
3286 if (bio_ctr && bio_ctr(bio, bio_src, data)) {
3287 bio_put(bio);
3288 goto free_and_out;
3291 if (rq->bio) {
3292 rq->biotail->bi_next = bio;
3293 rq->biotail = bio;
3294 } else {
3295 rq->bio = rq->biotail = bio;
3299 /* Copy attributes of the original request to the clone request. */
3300 rq->__sector = blk_rq_pos(rq_src);
3301 rq->__data_len = blk_rq_bytes(rq_src);
3302 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
3303 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
3304 rq->special_vec = rq_src->special_vec;
3306 rq->nr_phys_segments = rq_src->nr_phys_segments;
3308 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
3309 goto free_and_out;
3311 return 0;
3313 free_and_out:
3314 blk_rq_unprep_clone(rq);
3316 return -ENOMEM;
3318 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3319 #endif /* CONFIG_BLK_MQ_STACKING */
3322 * Steal bios from a request and add them to a bio list.
3323 * The request must not have been partially completed before.
3325 void blk_steal_bios(struct bio_list *list, struct request *rq)
3327 if (rq->bio) {
3328 if (list->tail)
3329 list->tail->bi_next = rq->bio;
3330 else
3331 list->head = rq->bio;
3332 list->tail = rq->biotail;
3334 rq->bio = NULL;
3335 rq->biotail = NULL;
3338 rq->__data_len = 0;
3340 EXPORT_SYMBOL_GPL(blk_steal_bios);
3342 static size_t order_to_size(unsigned int order)
3344 return (size_t)PAGE_SIZE << order;
3347 /* called before freeing request pool in @tags */
3348 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3349 struct blk_mq_tags *tags)
3351 struct page *page;
3352 unsigned long flags;
3355 * There is no need to clear mapping if driver tags is not initialized
3356 * or the mapping belongs to the driver tags.
3358 if (!drv_tags || drv_tags == tags)
3359 return;
3361 list_for_each_entry(page, &tags->page_list, lru) {
3362 unsigned long start = (unsigned long)page_address(page);
3363 unsigned long end = start + order_to_size(page->private);
3364 int i;
3366 for (i = 0; i < drv_tags->nr_tags; i++) {
3367 struct request *rq = drv_tags->rqs[i];
3368 unsigned long rq_addr = (unsigned long)rq;
3370 if (rq_addr >= start && rq_addr < end) {
3371 WARN_ON_ONCE(req_ref_read(rq) != 0);
3372 cmpxchg(&drv_tags->rqs[i], rq, NULL);
3378 * Wait until all pending iteration is done.
3380 * Request reference is cleared and it is guaranteed to be observed
3381 * after the ->lock is released.
3383 spin_lock_irqsave(&drv_tags->lock, flags);
3384 spin_unlock_irqrestore(&drv_tags->lock, flags);
3387 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3388 unsigned int hctx_idx)
3390 struct blk_mq_tags *drv_tags;
3391 struct page *page;
3393 if (list_empty(&tags->page_list))
3394 return;
3396 if (blk_mq_is_shared_tags(set->flags))
3397 drv_tags = set->shared_tags;
3398 else
3399 drv_tags = set->tags[hctx_idx];
3401 if (tags->static_rqs && set->ops->exit_request) {
3402 int i;
3404 for (i = 0; i < tags->nr_tags; i++) {
3405 struct request *rq = tags->static_rqs[i];
3407 if (!rq)
3408 continue;
3409 set->ops->exit_request(set, rq, hctx_idx);
3410 tags->static_rqs[i] = NULL;
3414 blk_mq_clear_rq_mapping(drv_tags, tags);
3416 while (!list_empty(&tags->page_list)) {
3417 page = list_first_entry(&tags->page_list, struct page, lru);
3418 list_del_init(&page->lru);
3420 * Remove kmemleak object previously allocated in
3421 * blk_mq_alloc_rqs().
3423 kmemleak_free(page_address(page));
3424 __free_pages(page, page->private);
3428 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
3430 kfree(tags->rqs);
3431 tags->rqs = NULL;
3432 kfree(tags->static_rqs);
3433 tags->static_rqs = NULL;
3435 blk_mq_free_tags(tags);
3438 static enum hctx_type hctx_idx_to_type(struct blk_mq_tag_set *set,
3439 unsigned int hctx_idx)
3441 int i;
3443 for (i = 0; i < set->nr_maps; i++) {
3444 unsigned int start = set->map[i].queue_offset;
3445 unsigned int end = start + set->map[i].nr_queues;
3447 if (hctx_idx >= start && hctx_idx < end)
3448 break;
3451 if (i >= set->nr_maps)
3452 i = HCTX_TYPE_DEFAULT;
3454 return i;
3457 static int blk_mq_get_hctx_node(struct blk_mq_tag_set *set,
3458 unsigned int hctx_idx)
3460 enum hctx_type type = hctx_idx_to_type(set, hctx_idx);
3462 return blk_mq_hw_queue_to_node(&set->map[type], hctx_idx);
3465 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3466 unsigned int hctx_idx,
3467 unsigned int nr_tags,
3468 unsigned int reserved_tags)
3470 int node = blk_mq_get_hctx_node(set, hctx_idx);
3471 struct blk_mq_tags *tags;
3473 if (node == NUMA_NO_NODE)
3474 node = set->numa_node;
3476 tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
3477 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
3478 if (!tags)
3479 return NULL;
3481 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3482 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3483 node);
3484 if (!tags->rqs)
3485 goto err_free_tags;
3487 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3488 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3489 node);
3490 if (!tags->static_rqs)
3491 goto err_free_rqs;
3493 return tags;
3495 err_free_rqs:
3496 kfree(tags->rqs);
3497 err_free_tags:
3498 blk_mq_free_tags(tags);
3499 return NULL;
3502 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3503 unsigned int hctx_idx, int node)
3505 int ret;
3507 if (set->ops->init_request) {
3508 ret = set->ops->init_request(set, rq, hctx_idx, node);
3509 if (ret)
3510 return ret;
3513 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3514 return 0;
3517 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3518 struct blk_mq_tags *tags,
3519 unsigned int hctx_idx, unsigned int depth)
3521 unsigned int i, j, entries_per_page, max_order = 4;
3522 int node = blk_mq_get_hctx_node(set, hctx_idx);
3523 size_t rq_size, left;
3525 if (node == NUMA_NO_NODE)
3526 node = set->numa_node;
3528 INIT_LIST_HEAD(&tags->page_list);
3531 * rq_size is the size of the request plus driver payload, rounded
3532 * to the cacheline size
3534 rq_size = round_up(sizeof(struct request) + set->cmd_size,
3535 cache_line_size());
3536 left = rq_size * depth;
3538 for (i = 0; i < depth; ) {
3539 int this_order = max_order;
3540 struct page *page;
3541 int to_do;
3542 void *p;
3544 while (this_order && left < order_to_size(this_order - 1))
3545 this_order--;
3547 do {
3548 page = alloc_pages_node(node,
3549 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3550 this_order);
3551 if (page)
3552 break;
3553 if (!this_order--)
3554 break;
3555 if (order_to_size(this_order) < rq_size)
3556 break;
3557 } while (1);
3559 if (!page)
3560 goto fail;
3562 page->private = this_order;
3563 list_add_tail(&page->lru, &tags->page_list);
3565 p = page_address(page);
3567 * Allow kmemleak to scan these pages as they contain pointers
3568 * to additional allocations like via ops->init_request().
3570 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3571 entries_per_page = order_to_size(this_order) / rq_size;
3572 to_do = min(entries_per_page, depth - i);
3573 left -= to_do * rq_size;
3574 for (j = 0; j < to_do; j++) {
3575 struct request *rq = p;
3577 tags->static_rqs[i] = rq;
3578 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3579 tags->static_rqs[i] = NULL;
3580 goto fail;
3583 p += rq_size;
3584 i++;
3587 return 0;
3589 fail:
3590 blk_mq_free_rqs(set, tags, hctx_idx);
3591 return -ENOMEM;
3594 struct rq_iter_data {
3595 struct blk_mq_hw_ctx *hctx;
3596 bool has_rq;
3599 static bool blk_mq_has_request(struct request *rq, void *data)
3601 struct rq_iter_data *iter_data = data;
3603 if (rq->mq_hctx != iter_data->hctx)
3604 return true;
3605 iter_data->has_rq = true;
3606 return false;
3609 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3611 struct blk_mq_tags *tags = hctx->sched_tags ?
3612 hctx->sched_tags : hctx->tags;
3613 struct rq_iter_data data = {
3614 .hctx = hctx,
3617 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3618 return data.has_rq;
3621 static bool blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx *hctx,
3622 unsigned int this_cpu)
3624 enum hctx_type type = hctx->type;
3625 int cpu;
3628 * hctx->cpumask has to rule out isolated CPUs, but userspace still
3629 * might submit IOs on these isolated CPUs, so use the queue map to
3630 * check if all CPUs mapped to this hctx are offline
3632 for_each_online_cpu(cpu) {
3633 struct blk_mq_hw_ctx *h = blk_mq_map_queue_type(hctx->queue,
3634 type, cpu);
3636 if (h != hctx)
3637 continue;
3639 /* this hctx has at least one online CPU */
3640 if (this_cpu != cpu)
3641 return true;
3644 return false;
3647 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3649 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3650 struct blk_mq_hw_ctx, cpuhp_online);
3652 if (blk_mq_hctx_has_online_cpu(hctx, cpu))
3653 return 0;
3656 * Prevent new request from being allocated on the current hctx.
3658 * The smp_mb__after_atomic() Pairs with the implied barrier in
3659 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
3660 * seen once we return from the tag allocator.
3662 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3663 smp_mb__after_atomic();
3666 * Try to grab a reference to the queue and wait for any outstanding
3667 * requests. If we could not grab a reference the queue has been
3668 * frozen and there are no requests.
3670 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3671 while (blk_mq_hctx_has_requests(hctx))
3672 msleep(5);
3673 percpu_ref_put(&hctx->queue->q_usage_counter);
3676 return 0;
3680 * Check if one CPU is mapped to the specified hctx
3682 * Isolated CPUs have been ruled out from hctx->cpumask, which is supposed
3683 * to be used for scheduling kworker only. For other usage, please call this
3684 * helper for checking if one CPU belongs to the specified hctx
3686 static bool blk_mq_cpu_mapped_to_hctx(unsigned int cpu,
3687 const struct blk_mq_hw_ctx *hctx)
3689 struct blk_mq_hw_ctx *mapped_hctx = blk_mq_map_queue_type(hctx->queue,
3690 hctx->type, cpu);
3692 return mapped_hctx == hctx;
3695 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3697 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3698 struct blk_mq_hw_ctx, cpuhp_online);
3700 if (blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3701 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3702 return 0;
3706 * 'cpu' is going away. splice any existing rq_list entries from this
3707 * software queue to the hw queue dispatch list, and ensure that it
3708 * gets run.
3710 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3712 struct blk_mq_hw_ctx *hctx;
3713 struct blk_mq_ctx *ctx;
3714 LIST_HEAD(tmp);
3715 enum hctx_type type;
3717 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3718 if (!blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3719 return 0;
3721 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3722 type = hctx->type;
3724 spin_lock(&ctx->lock);
3725 if (!list_empty(&ctx->rq_lists[type])) {
3726 list_splice_init(&ctx->rq_lists[type], &tmp);
3727 blk_mq_hctx_clear_pending(hctx, ctx);
3729 spin_unlock(&ctx->lock);
3731 if (list_empty(&tmp))
3732 return 0;
3734 spin_lock(&hctx->lock);
3735 list_splice_tail_init(&tmp, &hctx->dispatch);
3736 spin_unlock(&hctx->lock);
3738 blk_mq_run_hw_queue(hctx, true);
3739 return 0;
3742 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3744 if (!(hctx->flags & BLK_MQ_F_STACKING))
3745 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3746 &hctx->cpuhp_online);
3747 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3748 &hctx->cpuhp_dead);
3752 * Before freeing hw queue, clearing the flush request reference in
3753 * tags->rqs[] for avoiding potential UAF.
3755 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3756 unsigned int queue_depth, struct request *flush_rq)
3758 int i;
3759 unsigned long flags;
3761 /* The hw queue may not be mapped yet */
3762 if (!tags)
3763 return;
3765 WARN_ON_ONCE(req_ref_read(flush_rq) != 0);
3767 for (i = 0; i < queue_depth; i++)
3768 cmpxchg(&tags->rqs[i], flush_rq, NULL);
3771 * Wait until all pending iteration is done.
3773 * Request reference is cleared and it is guaranteed to be observed
3774 * after the ->lock is released.
3776 spin_lock_irqsave(&tags->lock, flags);
3777 spin_unlock_irqrestore(&tags->lock, flags);
3780 /* hctx->ctxs will be freed in queue's release handler */
3781 static void blk_mq_exit_hctx(struct request_queue *q,
3782 struct blk_mq_tag_set *set,
3783 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3785 struct request *flush_rq = hctx->fq->flush_rq;
3787 if (blk_mq_hw_queue_mapped(hctx))
3788 blk_mq_tag_idle(hctx);
3790 if (blk_queue_init_done(q))
3791 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3792 set->queue_depth, flush_rq);
3793 if (set->ops->exit_request)
3794 set->ops->exit_request(set, flush_rq, hctx_idx);
3796 if (set->ops->exit_hctx)
3797 set->ops->exit_hctx(hctx, hctx_idx);
3799 blk_mq_remove_cpuhp(hctx);
3801 xa_erase(&q->hctx_table, hctx_idx);
3803 spin_lock(&q->unused_hctx_lock);
3804 list_add(&hctx->hctx_list, &q->unused_hctx_list);
3805 spin_unlock(&q->unused_hctx_lock);
3808 static void blk_mq_exit_hw_queues(struct request_queue *q,
3809 struct blk_mq_tag_set *set, int nr_queue)
3811 struct blk_mq_hw_ctx *hctx;
3812 unsigned long i;
3814 queue_for_each_hw_ctx(q, hctx, i) {
3815 if (i == nr_queue)
3816 break;
3817 blk_mq_exit_hctx(q, set, hctx, i);
3821 static int blk_mq_init_hctx(struct request_queue *q,
3822 struct blk_mq_tag_set *set,
3823 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3825 hctx->queue_num = hctx_idx;
3827 if (!(hctx->flags & BLK_MQ_F_STACKING))
3828 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3829 &hctx->cpuhp_online);
3830 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
3832 hctx->tags = set->tags[hctx_idx];
3834 if (set->ops->init_hctx &&
3835 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3836 goto unregister_cpu_notifier;
3838 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3839 hctx->numa_node))
3840 goto exit_hctx;
3842 if (xa_insert(&q->hctx_table, hctx_idx, hctx, GFP_KERNEL))
3843 goto exit_flush_rq;
3845 return 0;
3847 exit_flush_rq:
3848 if (set->ops->exit_request)
3849 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
3850 exit_hctx:
3851 if (set->ops->exit_hctx)
3852 set->ops->exit_hctx(hctx, hctx_idx);
3853 unregister_cpu_notifier:
3854 blk_mq_remove_cpuhp(hctx);
3855 return -1;
3858 static struct blk_mq_hw_ctx *
3859 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3860 int node)
3862 struct blk_mq_hw_ctx *hctx;
3863 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3865 hctx = kzalloc_node(sizeof(struct blk_mq_hw_ctx), gfp, node);
3866 if (!hctx)
3867 goto fail_alloc_hctx;
3869 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
3870 goto free_hctx;
3872 atomic_set(&hctx->nr_active, 0);
3873 if (node == NUMA_NO_NODE)
3874 node = set->numa_node;
3875 hctx->numa_node = node;
3877 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
3878 spin_lock_init(&hctx->lock);
3879 INIT_LIST_HEAD(&hctx->dispatch);
3880 hctx->queue = q;
3881 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
3883 INIT_LIST_HEAD(&hctx->hctx_list);
3886 * Allocate space for all possible cpus to avoid allocation at
3887 * runtime
3889 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
3890 gfp, node);
3891 if (!hctx->ctxs)
3892 goto free_cpumask;
3894 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
3895 gfp, node, false, false))
3896 goto free_ctxs;
3897 hctx->nr_ctx = 0;
3899 spin_lock_init(&hctx->dispatch_wait_lock);
3900 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
3901 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
3903 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
3904 if (!hctx->fq)
3905 goto free_bitmap;
3907 blk_mq_hctx_kobj_init(hctx);
3909 return hctx;
3911 free_bitmap:
3912 sbitmap_free(&hctx->ctx_map);
3913 free_ctxs:
3914 kfree(hctx->ctxs);
3915 free_cpumask:
3916 free_cpumask_var(hctx->cpumask);
3917 free_hctx:
3918 kfree(hctx);
3919 fail_alloc_hctx:
3920 return NULL;
3923 static void blk_mq_init_cpu_queues(struct request_queue *q,
3924 unsigned int nr_hw_queues)
3926 struct blk_mq_tag_set *set = q->tag_set;
3927 unsigned int i, j;
3929 for_each_possible_cpu(i) {
3930 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
3931 struct blk_mq_hw_ctx *hctx;
3932 int k;
3934 __ctx->cpu = i;
3935 spin_lock_init(&__ctx->lock);
3936 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
3937 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
3939 __ctx->queue = q;
3942 * Set local node, IFF we have more than one hw queue. If
3943 * not, we remain on the home node of the device
3945 for (j = 0; j < set->nr_maps; j++) {
3946 hctx = blk_mq_map_queue_type(q, j, i);
3947 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
3948 hctx->numa_node = cpu_to_node(i);
3953 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3954 unsigned int hctx_idx,
3955 unsigned int depth)
3957 struct blk_mq_tags *tags;
3958 int ret;
3960 tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
3961 if (!tags)
3962 return NULL;
3964 ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
3965 if (ret) {
3966 blk_mq_free_rq_map(tags);
3967 return NULL;
3970 return tags;
3973 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3974 int hctx_idx)
3976 if (blk_mq_is_shared_tags(set->flags)) {
3977 set->tags[hctx_idx] = set->shared_tags;
3979 return true;
3982 set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
3983 set->queue_depth);
3985 return set->tags[hctx_idx];
3988 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3989 struct blk_mq_tags *tags,
3990 unsigned int hctx_idx)
3992 if (tags) {
3993 blk_mq_free_rqs(set, tags, hctx_idx);
3994 blk_mq_free_rq_map(tags);
3998 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3999 unsigned int hctx_idx)
4001 if (!blk_mq_is_shared_tags(set->flags))
4002 blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
4004 set->tags[hctx_idx] = NULL;
4007 static void blk_mq_map_swqueue(struct request_queue *q)
4009 unsigned int j, hctx_idx;
4010 unsigned long i;
4011 struct blk_mq_hw_ctx *hctx;
4012 struct blk_mq_ctx *ctx;
4013 struct blk_mq_tag_set *set = q->tag_set;
4015 queue_for_each_hw_ctx(q, hctx, i) {
4016 cpumask_clear(hctx->cpumask);
4017 hctx->nr_ctx = 0;
4018 hctx->dispatch_from = NULL;
4022 * Map software to hardware queues.
4024 * If the cpu isn't present, the cpu is mapped to first hctx.
4026 for_each_possible_cpu(i) {
4028 ctx = per_cpu_ptr(q->queue_ctx, i);
4029 for (j = 0; j < set->nr_maps; j++) {
4030 if (!set->map[j].nr_queues) {
4031 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4032 HCTX_TYPE_DEFAULT, i);
4033 continue;
4035 hctx_idx = set->map[j].mq_map[i];
4036 /* unmapped hw queue can be remapped after CPU topo changed */
4037 if (!set->tags[hctx_idx] &&
4038 !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4040 * If tags initialization fail for some hctx,
4041 * that hctx won't be brought online. In this
4042 * case, remap the current ctx to hctx[0] which
4043 * is guaranteed to always have tags allocated
4045 set->map[j].mq_map[i] = 0;
4048 hctx = blk_mq_map_queue_type(q, j, i);
4049 ctx->hctxs[j] = hctx;
4051 * If the CPU is already set in the mask, then we've
4052 * mapped this one already. This can happen if
4053 * devices share queues across queue maps.
4055 if (cpumask_test_cpu(i, hctx->cpumask))
4056 continue;
4058 cpumask_set_cpu(i, hctx->cpumask);
4059 hctx->type = j;
4060 ctx->index_hw[hctx->type] = hctx->nr_ctx;
4061 hctx->ctxs[hctx->nr_ctx++] = ctx;
4064 * If the nr_ctx type overflows, we have exceeded the
4065 * amount of sw queues we can support.
4067 BUG_ON(!hctx->nr_ctx);
4070 for (; j < HCTX_MAX_TYPES; j++)
4071 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4072 HCTX_TYPE_DEFAULT, i);
4075 queue_for_each_hw_ctx(q, hctx, i) {
4076 int cpu;
4079 * If no software queues are mapped to this hardware queue,
4080 * disable it and free the request entries.
4082 if (!hctx->nr_ctx) {
4083 /* Never unmap queue 0. We need it as a
4084 * fallback in case of a new remap fails
4085 * allocation
4087 if (i)
4088 __blk_mq_free_map_and_rqs(set, i);
4090 hctx->tags = NULL;
4091 continue;
4094 hctx->tags = set->tags[i];
4095 WARN_ON(!hctx->tags);
4098 * Set the map size to the number of mapped software queues.
4099 * This is more accurate and more efficient than looping
4100 * over all possibly mapped software queues.
4102 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4105 * Rule out isolated CPUs from hctx->cpumask to avoid
4106 * running block kworker on isolated CPUs
4108 for_each_cpu(cpu, hctx->cpumask) {
4109 if (cpu_is_isolated(cpu))
4110 cpumask_clear_cpu(cpu, hctx->cpumask);
4114 * Initialize batch roundrobin counts
4116 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4117 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4122 * Caller needs to ensure that we're either frozen/quiesced, or that
4123 * the queue isn't live yet.
4125 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
4127 struct blk_mq_hw_ctx *hctx;
4128 unsigned long i;
4130 queue_for_each_hw_ctx(q, hctx, i) {
4131 if (shared) {
4132 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4133 } else {
4134 blk_mq_tag_idle(hctx);
4135 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4140 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
4141 bool shared)
4143 struct request_queue *q;
4145 lockdep_assert_held(&set->tag_list_lock);
4147 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4148 blk_mq_freeze_queue(q);
4149 queue_set_hctx_shared(q, shared);
4150 blk_mq_unfreeze_queue(q);
4154 static void blk_mq_del_queue_tag_set(struct request_queue *q)
4156 struct blk_mq_tag_set *set = q->tag_set;
4158 mutex_lock(&set->tag_list_lock);
4159 list_del(&q->tag_set_list);
4160 if (list_is_singular(&set->tag_list)) {
4161 /* just transitioned to unshared */
4162 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4163 /* update existing queue */
4164 blk_mq_update_tag_set_shared(set, false);
4166 mutex_unlock(&set->tag_list_lock);
4167 INIT_LIST_HEAD(&q->tag_set_list);
4170 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4171 struct request_queue *q)
4173 mutex_lock(&set->tag_list_lock);
4176 * Check to see if we're transitioning to shared (from 1 to 2 queues).
4178 if (!list_empty(&set->tag_list) &&
4179 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4180 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4181 /* update existing queue */
4182 blk_mq_update_tag_set_shared(set, true);
4184 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4185 queue_set_hctx_shared(q, true);
4186 list_add_tail(&q->tag_set_list, &set->tag_list);
4188 mutex_unlock(&set->tag_list_lock);
4191 /* All allocations will be freed in release handler of q->mq_kobj */
4192 static int blk_mq_alloc_ctxs(struct request_queue *q)
4194 struct blk_mq_ctxs *ctxs;
4195 int cpu;
4197 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
4198 if (!ctxs)
4199 return -ENOMEM;
4201 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
4202 if (!ctxs->queue_ctx)
4203 goto fail;
4205 for_each_possible_cpu(cpu) {
4206 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
4207 ctx->ctxs = ctxs;
4210 q->mq_kobj = &ctxs->kobj;
4211 q->queue_ctx = ctxs->queue_ctx;
4213 return 0;
4214 fail:
4215 kfree(ctxs);
4216 return -ENOMEM;
4220 * It is the actual release handler for mq, but we do it from
4221 * request queue's release handler for avoiding use-after-free
4222 * and headache because q->mq_kobj shouldn't have been introduced,
4223 * but we can't group ctx/kctx kobj without it.
4225 void blk_mq_release(struct request_queue *q)
4227 struct blk_mq_hw_ctx *hctx, *next;
4228 unsigned long i;
4230 queue_for_each_hw_ctx(q, hctx, i)
4231 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
4233 /* all hctx are in .unused_hctx_list now */
4234 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
4235 list_del_init(&hctx->hctx_list);
4236 kobject_put(&hctx->kobj);
4239 xa_destroy(&q->hctx_table);
4242 * release .mq_kobj and sw queue's kobject now because
4243 * both share lifetime with request queue.
4245 blk_mq_sysfs_deinit(q);
4248 static bool blk_mq_can_poll(struct blk_mq_tag_set *set)
4250 return set->nr_maps > HCTX_TYPE_POLL &&
4251 set->map[HCTX_TYPE_POLL].nr_queues;
4254 struct request_queue *blk_mq_alloc_queue(struct blk_mq_tag_set *set,
4255 struct queue_limits *lim, void *queuedata)
4257 struct queue_limits default_lim = { };
4258 struct request_queue *q;
4259 int ret;
4261 if (!lim)
4262 lim = &default_lim;
4263 lim->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT;
4264 if (blk_mq_can_poll(set))
4265 lim->features |= BLK_FEAT_POLL;
4267 q = blk_alloc_queue(lim, set->numa_node);
4268 if (IS_ERR(q))
4269 return q;
4270 q->queuedata = queuedata;
4271 ret = blk_mq_init_allocated_queue(set, q);
4272 if (ret) {
4273 blk_put_queue(q);
4274 return ERR_PTR(ret);
4276 return q;
4278 EXPORT_SYMBOL(blk_mq_alloc_queue);
4281 * blk_mq_destroy_queue - shutdown a request queue
4282 * @q: request queue to shutdown
4284 * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4285 * requests will be failed with -ENODEV. The caller is responsible for dropping
4286 * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4288 * Context: can sleep
4290 void blk_mq_destroy_queue(struct request_queue *q)
4292 WARN_ON_ONCE(!queue_is_mq(q));
4293 WARN_ON_ONCE(blk_queue_registered(q));
4295 might_sleep();
4297 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4298 blk_queue_start_drain(q);
4299 blk_mq_freeze_queue_wait(q);
4301 blk_sync_queue(q);
4302 blk_mq_cancel_work_sync(q);
4303 blk_mq_exit_queue(q);
4305 EXPORT_SYMBOL(blk_mq_destroy_queue);
4307 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4308 struct queue_limits *lim, void *queuedata,
4309 struct lock_class_key *lkclass)
4311 struct request_queue *q;
4312 struct gendisk *disk;
4314 q = blk_mq_alloc_queue(set, lim, queuedata);
4315 if (IS_ERR(q))
4316 return ERR_CAST(q);
4318 disk = __alloc_disk_node(q, set->numa_node, lkclass);
4319 if (!disk) {
4320 blk_mq_destroy_queue(q);
4321 blk_put_queue(q);
4322 return ERR_PTR(-ENOMEM);
4324 set_bit(GD_OWNS_QUEUE, &disk->state);
4325 return disk;
4327 EXPORT_SYMBOL(__blk_mq_alloc_disk);
4329 struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
4330 struct lock_class_key *lkclass)
4332 struct gendisk *disk;
4334 if (!blk_get_queue(q))
4335 return NULL;
4336 disk = __alloc_disk_node(q, NUMA_NO_NODE, lkclass);
4337 if (!disk)
4338 blk_put_queue(q);
4339 return disk;
4341 EXPORT_SYMBOL(blk_mq_alloc_disk_for_queue);
4343 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
4344 struct blk_mq_tag_set *set, struct request_queue *q,
4345 int hctx_idx, int node)
4347 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
4349 /* reuse dead hctx first */
4350 spin_lock(&q->unused_hctx_lock);
4351 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
4352 if (tmp->numa_node == node) {
4353 hctx = tmp;
4354 break;
4357 if (hctx)
4358 list_del_init(&hctx->hctx_list);
4359 spin_unlock(&q->unused_hctx_lock);
4361 if (!hctx)
4362 hctx = blk_mq_alloc_hctx(q, set, node);
4363 if (!hctx)
4364 goto fail;
4366 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
4367 goto free_hctx;
4369 return hctx;
4371 free_hctx:
4372 kobject_put(&hctx->kobj);
4373 fail:
4374 return NULL;
4377 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4378 struct request_queue *q)
4380 struct blk_mq_hw_ctx *hctx;
4381 unsigned long i, j;
4383 /* protect against switching io scheduler */
4384 mutex_lock(&q->sysfs_lock);
4385 for (i = 0; i < set->nr_hw_queues; i++) {
4386 int old_node;
4387 int node = blk_mq_get_hctx_node(set, i);
4388 struct blk_mq_hw_ctx *old_hctx = xa_load(&q->hctx_table, i);
4390 if (old_hctx) {
4391 old_node = old_hctx->numa_node;
4392 blk_mq_exit_hctx(q, set, old_hctx, i);
4395 if (!blk_mq_alloc_and_init_hctx(set, q, i, node)) {
4396 if (!old_hctx)
4397 break;
4398 pr_warn("Allocate new hctx on node %d fails, fallback to previous one on node %d\n",
4399 node, old_node);
4400 hctx = blk_mq_alloc_and_init_hctx(set, q, i, old_node);
4401 WARN_ON_ONCE(!hctx);
4405 * Increasing nr_hw_queues fails. Free the newly allocated
4406 * hctxs and keep the previous q->nr_hw_queues.
4408 if (i != set->nr_hw_queues) {
4409 j = q->nr_hw_queues;
4410 } else {
4411 j = i;
4412 q->nr_hw_queues = set->nr_hw_queues;
4415 xa_for_each_start(&q->hctx_table, j, hctx, j)
4416 blk_mq_exit_hctx(q, set, hctx, j);
4417 mutex_unlock(&q->sysfs_lock);
4420 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4421 struct request_queue *q)
4423 /* mark the queue as mq asap */
4424 q->mq_ops = set->ops;
4427 * ->tag_set has to be setup before initialize hctx, which cpuphp
4428 * handler needs it for checking queue mapping
4430 q->tag_set = set;
4432 if (blk_mq_alloc_ctxs(q))
4433 goto err_exit;
4435 /* init q->mq_kobj and sw queues' kobjects */
4436 blk_mq_sysfs_init(q);
4438 INIT_LIST_HEAD(&q->unused_hctx_list);
4439 spin_lock_init(&q->unused_hctx_lock);
4441 xa_init(&q->hctx_table);
4443 blk_mq_realloc_hw_ctxs(set, q);
4444 if (!q->nr_hw_queues)
4445 goto err_hctxs;
4447 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4448 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4450 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4452 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4453 INIT_LIST_HEAD(&q->flush_list);
4454 INIT_LIST_HEAD(&q->requeue_list);
4455 spin_lock_init(&q->requeue_lock);
4457 q->nr_requests = set->queue_depth;
4459 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4460 blk_mq_add_queue_tag_set(set, q);
4461 blk_mq_map_swqueue(q);
4462 return 0;
4464 err_hctxs:
4465 blk_mq_release(q);
4466 err_exit:
4467 q->mq_ops = NULL;
4468 return -ENOMEM;
4470 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4472 /* tags can _not_ be used after returning from blk_mq_exit_queue */
4473 void blk_mq_exit_queue(struct request_queue *q)
4475 struct blk_mq_tag_set *set = q->tag_set;
4477 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4478 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4479 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4480 blk_mq_del_queue_tag_set(q);
4483 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4485 int i;
4487 if (blk_mq_is_shared_tags(set->flags)) {
4488 set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4489 BLK_MQ_NO_HCTX_IDX,
4490 set->queue_depth);
4491 if (!set->shared_tags)
4492 return -ENOMEM;
4495 for (i = 0; i < set->nr_hw_queues; i++) {
4496 if (!__blk_mq_alloc_map_and_rqs(set, i))
4497 goto out_unwind;
4498 cond_resched();
4501 return 0;
4503 out_unwind:
4504 while (--i >= 0)
4505 __blk_mq_free_map_and_rqs(set, i);
4507 if (blk_mq_is_shared_tags(set->flags)) {
4508 blk_mq_free_map_and_rqs(set, set->shared_tags,
4509 BLK_MQ_NO_HCTX_IDX);
4512 return -ENOMEM;
4516 * Allocate the request maps associated with this tag_set. Note that this
4517 * may reduce the depth asked for, if memory is tight. set->queue_depth
4518 * will be updated to reflect the allocated depth.
4520 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4522 unsigned int depth;
4523 int err;
4525 depth = set->queue_depth;
4526 do {
4527 err = __blk_mq_alloc_rq_maps(set);
4528 if (!err)
4529 break;
4531 set->queue_depth >>= 1;
4532 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4533 err = -ENOMEM;
4534 break;
4536 } while (set->queue_depth);
4538 if (!set->queue_depth || err) {
4539 pr_err("blk-mq: failed to allocate request map\n");
4540 return -ENOMEM;
4543 if (depth != set->queue_depth)
4544 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4545 depth, set->queue_depth);
4547 return 0;
4550 static void blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4553 * blk_mq_map_queues() and multiple .map_queues() implementations
4554 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4555 * number of hardware queues.
4557 if (set->nr_maps == 1)
4558 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4560 if (set->ops->map_queues) {
4561 int i;
4564 * transport .map_queues is usually done in the following
4565 * way:
4567 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4568 * mask = get_cpu_mask(queue)
4569 * for_each_cpu(cpu, mask)
4570 * set->map[x].mq_map[cpu] = queue;
4573 * When we need to remap, the table has to be cleared for
4574 * killing stale mapping since one CPU may not be mapped
4575 * to any hw queue.
4577 for (i = 0; i < set->nr_maps; i++)
4578 blk_mq_clear_mq_map(&set->map[i]);
4580 set->ops->map_queues(set);
4581 } else {
4582 BUG_ON(set->nr_maps > 1);
4583 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4587 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
4588 int new_nr_hw_queues)
4590 struct blk_mq_tags **new_tags;
4591 int i;
4593 if (set->nr_hw_queues >= new_nr_hw_queues)
4594 goto done;
4596 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4597 GFP_KERNEL, set->numa_node);
4598 if (!new_tags)
4599 return -ENOMEM;
4601 if (set->tags)
4602 memcpy(new_tags, set->tags, set->nr_hw_queues *
4603 sizeof(*set->tags));
4604 kfree(set->tags);
4605 set->tags = new_tags;
4607 for (i = set->nr_hw_queues; i < new_nr_hw_queues; i++) {
4608 if (!__blk_mq_alloc_map_and_rqs(set, i)) {
4609 while (--i >= set->nr_hw_queues)
4610 __blk_mq_free_map_and_rqs(set, i);
4611 return -ENOMEM;
4613 cond_resched();
4616 done:
4617 set->nr_hw_queues = new_nr_hw_queues;
4618 return 0;
4622 * Alloc a tag set to be associated with one or more request queues.
4623 * May fail with EINVAL for various error conditions. May adjust the
4624 * requested depth down, if it's too large. In that case, the set
4625 * value will be stored in set->queue_depth.
4627 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4629 int i, ret;
4631 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4633 if (!set->nr_hw_queues)
4634 return -EINVAL;
4635 if (!set->queue_depth)
4636 return -EINVAL;
4637 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4638 return -EINVAL;
4640 if (!set->ops->queue_rq)
4641 return -EINVAL;
4643 if (!set->ops->get_budget ^ !set->ops->put_budget)
4644 return -EINVAL;
4646 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4647 pr_info("blk-mq: reduced tag depth to %u\n",
4648 BLK_MQ_MAX_DEPTH);
4649 set->queue_depth = BLK_MQ_MAX_DEPTH;
4652 if (!set->nr_maps)
4653 set->nr_maps = 1;
4654 else if (set->nr_maps > HCTX_MAX_TYPES)
4655 return -EINVAL;
4658 * If a crashdump is active, then we are potentially in a very
4659 * memory constrained environment. Limit us to 64 tags to prevent
4660 * using too much memory.
4662 if (is_kdump_kernel())
4663 set->queue_depth = min(64U, set->queue_depth);
4666 * There is no use for more h/w queues than cpus if we just have
4667 * a single map
4669 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4670 set->nr_hw_queues = nr_cpu_ids;
4672 if (set->flags & BLK_MQ_F_BLOCKING) {
4673 set->srcu = kmalloc(sizeof(*set->srcu), GFP_KERNEL);
4674 if (!set->srcu)
4675 return -ENOMEM;
4676 ret = init_srcu_struct(set->srcu);
4677 if (ret)
4678 goto out_free_srcu;
4681 ret = -ENOMEM;
4682 set->tags = kcalloc_node(set->nr_hw_queues,
4683 sizeof(struct blk_mq_tags *), GFP_KERNEL,
4684 set->numa_node);
4685 if (!set->tags)
4686 goto out_cleanup_srcu;
4688 for (i = 0; i < set->nr_maps; i++) {
4689 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4690 sizeof(set->map[i].mq_map[0]),
4691 GFP_KERNEL, set->numa_node);
4692 if (!set->map[i].mq_map)
4693 goto out_free_mq_map;
4694 set->map[i].nr_queues = set->nr_hw_queues;
4697 blk_mq_update_queue_map(set);
4699 ret = blk_mq_alloc_set_map_and_rqs(set);
4700 if (ret)
4701 goto out_free_mq_map;
4703 mutex_init(&set->tag_list_lock);
4704 INIT_LIST_HEAD(&set->tag_list);
4706 return 0;
4708 out_free_mq_map:
4709 for (i = 0; i < set->nr_maps; i++) {
4710 kfree(set->map[i].mq_map);
4711 set->map[i].mq_map = NULL;
4713 kfree(set->tags);
4714 set->tags = NULL;
4715 out_cleanup_srcu:
4716 if (set->flags & BLK_MQ_F_BLOCKING)
4717 cleanup_srcu_struct(set->srcu);
4718 out_free_srcu:
4719 if (set->flags & BLK_MQ_F_BLOCKING)
4720 kfree(set->srcu);
4721 return ret;
4723 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4725 /* allocate and initialize a tagset for a simple single-queue device */
4726 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4727 const struct blk_mq_ops *ops, unsigned int queue_depth,
4728 unsigned int set_flags)
4730 memset(set, 0, sizeof(*set));
4731 set->ops = ops;
4732 set->nr_hw_queues = 1;
4733 set->nr_maps = 1;
4734 set->queue_depth = queue_depth;
4735 set->numa_node = NUMA_NO_NODE;
4736 set->flags = set_flags;
4737 return blk_mq_alloc_tag_set(set);
4739 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4741 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4743 int i, j;
4745 for (i = 0; i < set->nr_hw_queues; i++)
4746 __blk_mq_free_map_and_rqs(set, i);
4748 if (blk_mq_is_shared_tags(set->flags)) {
4749 blk_mq_free_map_and_rqs(set, set->shared_tags,
4750 BLK_MQ_NO_HCTX_IDX);
4753 for (j = 0; j < set->nr_maps; j++) {
4754 kfree(set->map[j].mq_map);
4755 set->map[j].mq_map = NULL;
4758 kfree(set->tags);
4759 set->tags = NULL;
4760 if (set->flags & BLK_MQ_F_BLOCKING) {
4761 cleanup_srcu_struct(set->srcu);
4762 kfree(set->srcu);
4765 EXPORT_SYMBOL(blk_mq_free_tag_set);
4767 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
4769 struct blk_mq_tag_set *set = q->tag_set;
4770 struct blk_mq_hw_ctx *hctx;
4771 int ret;
4772 unsigned long i;
4774 if (WARN_ON_ONCE(!q->mq_freeze_depth))
4775 return -EINVAL;
4777 if (!set)
4778 return -EINVAL;
4780 if (q->nr_requests == nr)
4781 return 0;
4783 blk_mq_quiesce_queue(q);
4785 ret = 0;
4786 queue_for_each_hw_ctx(q, hctx, i) {
4787 if (!hctx->tags)
4788 continue;
4790 * If we're using an MQ scheduler, just update the scheduler
4791 * queue depth. This is similar to what the old code would do.
4793 if (hctx->sched_tags) {
4794 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
4795 nr, true);
4796 } else {
4797 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
4798 false);
4800 if (ret)
4801 break;
4802 if (q->elevator && q->elevator->type->ops.depth_updated)
4803 q->elevator->type->ops.depth_updated(hctx);
4805 if (!ret) {
4806 q->nr_requests = nr;
4807 if (blk_mq_is_shared_tags(set->flags)) {
4808 if (q->elevator)
4809 blk_mq_tag_update_sched_shared_tags(q);
4810 else
4811 blk_mq_tag_resize_shared_tags(set, nr);
4815 blk_mq_unquiesce_queue(q);
4817 return ret;
4821 * request_queue and elevator_type pair.
4822 * It is just used by __blk_mq_update_nr_hw_queues to cache
4823 * the elevator_type associated with a request_queue.
4825 struct blk_mq_qe_pair {
4826 struct list_head node;
4827 struct request_queue *q;
4828 struct elevator_type *type;
4832 * Cache the elevator_type in qe pair list and switch the
4833 * io scheduler to 'none'
4835 static bool blk_mq_elv_switch_none(struct list_head *head,
4836 struct request_queue *q)
4838 struct blk_mq_qe_pair *qe;
4840 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
4841 if (!qe)
4842 return false;
4844 /* q->elevator needs protection from ->sysfs_lock */
4845 mutex_lock(&q->sysfs_lock);
4847 /* the check has to be done with holding sysfs_lock */
4848 if (!q->elevator) {
4849 kfree(qe);
4850 goto unlock;
4853 INIT_LIST_HEAD(&qe->node);
4854 qe->q = q;
4855 qe->type = q->elevator->type;
4856 /* keep a reference to the elevator module as we'll switch back */
4857 __elevator_get(qe->type);
4858 list_add(&qe->node, head);
4859 elevator_disable(q);
4860 unlock:
4861 mutex_unlock(&q->sysfs_lock);
4863 return true;
4866 static struct blk_mq_qe_pair *blk_lookup_qe_pair(struct list_head *head,
4867 struct request_queue *q)
4869 struct blk_mq_qe_pair *qe;
4871 list_for_each_entry(qe, head, node)
4872 if (qe->q == q)
4873 return qe;
4875 return NULL;
4878 static void blk_mq_elv_switch_back(struct list_head *head,
4879 struct request_queue *q)
4881 struct blk_mq_qe_pair *qe;
4882 struct elevator_type *t;
4884 qe = blk_lookup_qe_pair(head, q);
4885 if (!qe)
4886 return;
4887 t = qe->type;
4888 list_del(&qe->node);
4889 kfree(qe);
4891 mutex_lock(&q->sysfs_lock);
4892 elevator_switch(q, t);
4893 /* drop the reference acquired in blk_mq_elv_switch_none */
4894 elevator_put(t);
4895 mutex_unlock(&q->sysfs_lock);
4898 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
4899 int nr_hw_queues)
4901 struct request_queue *q;
4902 LIST_HEAD(head);
4903 int prev_nr_hw_queues = set->nr_hw_queues;
4904 int i;
4906 lockdep_assert_held(&set->tag_list_lock);
4908 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
4909 nr_hw_queues = nr_cpu_ids;
4910 if (nr_hw_queues < 1)
4911 return;
4912 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
4913 return;
4915 list_for_each_entry(q, &set->tag_list, tag_set_list)
4916 blk_mq_freeze_queue(q);
4918 * Switch IO scheduler to 'none', cleaning up the data associated
4919 * with the previous scheduler. We will switch back once we are done
4920 * updating the new sw to hw queue mappings.
4922 list_for_each_entry(q, &set->tag_list, tag_set_list)
4923 if (!blk_mq_elv_switch_none(&head, q))
4924 goto switch_back;
4926 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4927 blk_mq_debugfs_unregister_hctxs(q);
4928 blk_mq_sysfs_unregister_hctxs(q);
4931 if (blk_mq_realloc_tag_set_tags(set, nr_hw_queues) < 0)
4932 goto reregister;
4934 fallback:
4935 blk_mq_update_queue_map(set);
4936 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4937 struct queue_limits lim;
4939 blk_mq_realloc_hw_ctxs(set, q);
4941 if (q->nr_hw_queues != set->nr_hw_queues) {
4942 int i = prev_nr_hw_queues;
4944 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
4945 nr_hw_queues, prev_nr_hw_queues);
4946 for (; i < set->nr_hw_queues; i++)
4947 __blk_mq_free_map_and_rqs(set, i);
4949 set->nr_hw_queues = prev_nr_hw_queues;
4950 goto fallback;
4952 lim = queue_limits_start_update(q);
4953 if (blk_mq_can_poll(set))
4954 lim.features |= BLK_FEAT_POLL;
4955 else
4956 lim.features &= ~BLK_FEAT_POLL;
4957 if (queue_limits_commit_update(q, &lim) < 0)
4958 pr_warn("updating the poll flag failed\n");
4959 blk_mq_map_swqueue(q);
4962 reregister:
4963 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4964 blk_mq_sysfs_register_hctxs(q);
4965 blk_mq_debugfs_register_hctxs(q);
4968 switch_back:
4969 list_for_each_entry(q, &set->tag_list, tag_set_list)
4970 blk_mq_elv_switch_back(&head, q);
4972 list_for_each_entry(q, &set->tag_list, tag_set_list)
4973 blk_mq_unfreeze_queue(q);
4975 /* Free the excess tags when nr_hw_queues shrink. */
4976 for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
4977 __blk_mq_free_map_and_rqs(set, i);
4980 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
4982 mutex_lock(&set->tag_list_lock);
4983 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
4984 mutex_unlock(&set->tag_list_lock);
4986 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
4988 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
4989 struct io_comp_batch *iob, unsigned int flags)
4991 long state = get_current_state();
4992 int ret;
4994 do {
4995 ret = q->mq_ops->poll(hctx, iob);
4996 if (ret > 0) {
4997 __set_current_state(TASK_RUNNING);
4998 return ret;
5001 if (signal_pending_state(state, current))
5002 __set_current_state(TASK_RUNNING);
5003 if (task_is_running(current))
5004 return 1;
5006 if (ret < 0 || (flags & BLK_POLL_ONESHOT))
5007 break;
5008 cpu_relax();
5009 } while (!need_resched());
5011 __set_current_state(TASK_RUNNING);
5012 return 0;
5015 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
5016 struct io_comp_batch *iob, unsigned int flags)
5018 struct blk_mq_hw_ctx *hctx = xa_load(&q->hctx_table, cookie);
5020 return blk_hctx_poll(q, hctx, iob, flags);
5023 int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
5024 unsigned int poll_flags)
5026 struct request_queue *q = rq->q;
5027 int ret;
5029 if (!blk_rq_is_poll(rq))
5030 return 0;
5031 if (!percpu_ref_tryget(&q->q_usage_counter))
5032 return 0;
5034 ret = blk_hctx_poll(q, rq->mq_hctx, iob, poll_flags);
5035 blk_queue_exit(q);
5037 return ret;
5039 EXPORT_SYMBOL_GPL(blk_rq_poll);
5041 unsigned int blk_mq_rq_cpu(struct request *rq)
5043 return rq->mq_ctx->cpu;
5045 EXPORT_SYMBOL(blk_mq_rq_cpu);
5047 void blk_mq_cancel_work_sync(struct request_queue *q)
5049 struct blk_mq_hw_ctx *hctx;
5050 unsigned long i;
5052 cancel_delayed_work_sync(&q->requeue_work);
5054 queue_for_each_hw_ctx(q, hctx, i)
5055 cancel_delayed_work_sync(&hctx->run_work);
5058 static int __init blk_mq_init(void)
5060 int i;
5062 for_each_possible_cpu(i)
5063 init_llist_head(&per_cpu(blk_cpu_done, i));
5064 for_each_possible_cpu(i)
5065 INIT_CSD(&per_cpu(blk_cpu_csd, i),
5066 __blk_mq_complete_request_remote, NULL);
5067 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
5069 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
5070 "block/softirq:dead", NULL,
5071 blk_softirq_cpu_dead);
5072 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
5073 blk_mq_hctx_notify_dead);
5074 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
5075 blk_mq_hctx_notify_online,
5076 blk_mq_hctx_notify_offline);
5077 return 0;
5079 subsys_initcall(blk_mq_init);