drm/imagination: Use the drm_sched_job_has_dependency helper
[drm/drm-misc.git] / block / blk-mq.c
blobaa340b097b6e45e25f52f3762e1e3b4b920e702b
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);
46 static DEFINE_MUTEX(blk_mq_cpuhp_lock);
48 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags);
49 static void blk_mq_request_bypass_insert(struct request *rq,
50 blk_insert_t flags);
51 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
52 struct list_head *list);
53 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
54 struct io_comp_batch *iob, unsigned int flags);
57 * Check if any of the ctx, dispatch list or elevator
58 * have pending work in this hardware queue.
60 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
62 return !list_empty_careful(&hctx->dispatch) ||
63 sbitmap_any_bit_set(&hctx->ctx_map) ||
64 blk_mq_sched_has_work(hctx);
68 * Mark this ctx as having pending work in this hardware queue
70 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
71 struct blk_mq_ctx *ctx)
73 const int bit = ctx->index_hw[hctx->type];
75 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
76 sbitmap_set_bit(&hctx->ctx_map, bit);
79 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
80 struct blk_mq_ctx *ctx)
82 const int bit = ctx->index_hw[hctx->type];
84 sbitmap_clear_bit(&hctx->ctx_map, bit);
87 struct mq_inflight {
88 struct block_device *part;
89 unsigned int inflight[2];
92 static bool blk_mq_check_inflight(struct request *rq, void *priv)
94 struct mq_inflight *mi = priv;
96 if (rq->rq_flags & RQF_IO_STAT &&
97 (!bdev_is_partition(mi->part) || rq->part == mi->part) &&
98 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
99 mi->inflight[rq_data_dir(rq)]++;
101 return true;
104 unsigned int blk_mq_in_flight(struct request_queue *q,
105 struct block_device *part)
107 struct mq_inflight mi = { .part = part };
109 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
111 return mi.inflight[0] + mi.inflight[1];
114 void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
115 unsigned int inflight[2])
117 struct mq_inflight mi = { .part = part };
119 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
120 inflight[0] = mi.inflight[0];
121 inflight[1] = mi.inflight[1];
124 #ifdef CONFIG_LOCKDEP
125 static bool blk_freeze_set_owner(struct request_queue *q,
126 struct task_struct *owner)
128 if (!owner)
129 return false;
131 if (!q->mq_freeze_depth) {
132 q->mq_freeze_owner = owner;
133 q->mq_freeze_owner_depth = 1;
134 return true;
137 if (owner == q->mq_freeze_owner)
138 q->mq_freeze_owner_depth += 1;
139 return false;
142 /* verify the last unfreeze in owner context */
143 static bool blk_unfreeze_check_owner(struct request_queue *q)
145 if (!q->mq_freeze_owner)
146 return false;
147 if (q->mq_freeze_owner != current)
148 return false;
149 if (--q->mq_freeze_owner_depth == 0) {
150 q->mq_freeze_owner = NULL;
151 return true;
153 return false;
156 #else
158 static bool blk_freeze_set_owner(struct request_queue *q,
159 struct task_struct *owner)
161 return false;
164 static bool blk_unfreeze_check_owner(struct request_queue *q)
166 return false;
168 #endif
170 bool __blk_freeze_queue_start(struct request_queue *q,
171 struct task_struct *owner)
173 bool freeze;
175 mutex_lock(&q->mq_freeze_lock);
176 freeze = blk_freeze_set_owner(q, owner);
177 if (++q->mq_freeze_depth == 1) {
178 percpu_ref_kill(&q->q_usage_counter);
179 mutex_unlock(&q->mq_freeze_lock);
180 if (queue_is_mq(q))
181 blk_mq_run_hw_queues(q, false);
182 } else {
183 mutex_unlock(&q->mq_freeze_lock);
186 return freeze;
189 void blk_freeze_queue_start(struct request_queue *q)
191 if (__blk_freeze_queue_start(q, current))
192 blk_freeze_acquire_lock(q, false, false);
194 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
196 void blk_mq_freeze_queue_wait(struct request_queue *q)
198 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
200 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
202 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
203 unsigned long timeout)
205 return wait_event_timeout(q->mq_freeze_wq,
206 percpu_ref_is_zero(&q->q_usage_counter),
207 timeout);
209 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
211 void blk_mq_freeze_queue(struct request_queue *q)
213 blk_freeze_queue_start(q);
214 blk_mq_freeze_queue_wait(q);
216 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
218 bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
220 bool unfreeze;
222 mutex_lock(&q->mq_freeze_lock);
223 if (force_atomic)
224 q->q_usage_counter.data->force_atomic = true;
225 q->mq_freeze_depth--;
226 WARN_ON_ONCE(q->mq_freeze_depth < 0);
227 if (!q->mq_freeze_depth) {
228 percpu_ref_resurrect(&q->q_usage_counter);
229 wake_up_all(&q->mq_freeze_wq);
231 unfreeze = blk_unfreeze_check_owner(q);
232 mutex_unlock(&q->mq_freeze_lock);
234 return unfreeze;
237 void blk_mq_unfreeze_queue(struct request_queue *q)
239 if (__blk_mq_unfreeze_queue(q, false))
240 blk_unfreeze_release_lock(q, false, false);
242 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
245 * non_owner variant of blk_freeze_queue_start
247 * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
248 * by the same task. This is fragile and should not be used if at all
249 * possible.
251 void blk_freeze_queue_start_non_owner(struct request_queue *q)
253 __blk_freeze_queue_start(q, NULL);
255 EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
257 /* non_owner variant of blk_mq_unfreeze_queue */
258 void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
260 __blk_mq_unfreeze_queue(q, false);
262 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
265 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
266 * mpt3sas driver such that this function can be removed.
268 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
270 unsigned long flags;
272 spin_lock_irqsave(&q->queue_lock, flags);
273 if (!q->quiesce_depth++)
274 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
275 spin_unlock_irqrestore(&q->queue_lock, flags);
277 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
280 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
281 * @set: tag_set to wait on
283 * Note: it is driver's responsibility for making sure that quiesce has
284 * been started on or more of the request_queues of the tag_set. This
285 * function only waits for the quiesce on those request_queues that had
286 * the quiesce flag set using blk_mq_quiesce_queue_nowait.
288 void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
290 if (set->flags & BLK_MQ_F_BLOCKING)
291 synchronize_srcu(set->srcu);
292 else
293 synchronize_rcu();
295 EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
298 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
299 * @q: request queue.
301 * Note: this function does not prevent that the struct request end_io()
302 * callback function is invoked. Once this function is returned, we make
303 * sure no dispatch can happen until the queue is unquiesced via
304 * blk_mq_unquiesce_queue().
306 void blk_mq_quiesce_queue(struct request_queue *q)
308 blk_mq_quiesce_queue_nowait(q);
309 /* nothing to wait for non-mq queues */
310 if (queue_is_mq(q))
311 blk_mq_wait_quiesce_done(q->tag_set);
313 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
316 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
317 * @q: request queue.
319 * This function recovers queue into the state before quiescing
320 * which is done by blk_mq_quiesce_queue.
322 void blk_mq_unquiesce_queue(struct request_queue *q)
324 unsigned long flags;
325 bool run_queue = false;
327 spin_lock_irqsave(&q->queue_lock, flags);
328 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
330 } else if (!--q->quiesce_depth) {
331 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
332 run_queue = true;
334 spin_unlock_irqrestore(&q->queue_lock, flags);
336 /* dispatch requests which are inserted during quiescing */
337 if (run_queue)
338 blk_mq_run_hw_queues(q, true);
340 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
342 void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
344 struct request_queue *q;
346 mutex_lock(&set->tag_list_lock);
347 list_for_each_entry(q, &set->tag_list, tag_set_list) {
348 if (!blk_queue_skip_tagset_quiesce(q))
349 blk_mq_quiesce_queue_nowait(q);
351 mutex_unlock(&set->tag_list_lock);
353 blk_mq_wait_quiesce_done(set);
355 EXPORT_SYMBOL_GPL(blk_mq_quiesce_tagset);
357 void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
359 struct request_queue *q;
361 mutex_lock(&set->tag_list_lock);
362 list_for_each_entry(q, &set->tag_list, tag_set_list) {
363 if (!blk_queue_skip_tagset_quiesce(q))
364 blk_mq_unquiesce_queue(q);
366 mutex_unlock(&set->tag_list_lock);
368 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
370 void blk_mq_wake_waiters(struct request_queue *q)
372 struct blk_mq_hw_ctx *hctx;
373 unsigned long i;
375 queue_for_each_hw_ctx(q, hctx, i)
376 if (blk_mq_hw_queue_mapped(hctx))
377 blk_mq_tag_wakeup_all(hctx->tags, true);
380 void blk_rq_init(struct request_queue *q, struct request *rq)
382 memset(rq, 0, sizeof(*rq));
384 INIT_LIST_HEAD(&rq->queuelist);
385 rq->q = q;
386 rq->__sector = (sector_t) -1;
387 INIT_HLIST_NODE(&rq->hash);
388 RB_CLEAR_NODE(&rq->rb_node);
389 rq->tag = BLK_MQ_NO_TAG;
390 rq->internal_tag = BLK_MQ_NO_TAG;
391 rq->start_time_ns = blk_time_get_ns();
392 blk_crypto_rq_set_defaults(rq);
394 EXPORT_SYMBOL(blk_rq_init);
396 /* Set start and alloc time when the allocated request is actually used */
397 static inline void blk_mq_rq_time_init(struct request *rq, u64 alloc_time_ns)
399 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
400 if (blk_queue_rq_alloc_time(rq->q))
401 rq->alloc_time_ns = alloc_time_ns;
402 else
403 rq->alloc_time_ns = 0;
404 #endif
407 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
408 struct blk_mq_tags *tags, unsigned int tag)
410 struct blk_mq_ctx *ctx = data->ctx;
411 struct blk_mq_hw_ctx *hctx = data->hctx;
412 struct request_queue *q = data->q;
413 struct request *rq = tags->static_rqs[tag];
415 rq->q = q;
416 rq->mq_ctx = ctx;
417 rq->mq_hctx = hctx;
418 rq->cmd_flags = data->cmd_flags;
420 if (data->flags & BLK_MQ_REQ_PM)
421 data->rq_flags |= RQF_PM;
422 rq->rq_flags = data->rq_flags;
424 if (data->rq_flags & RQF_SCHED_TAGS) {
425 rq->tag = BLK_MQ_NO_TAG;
426 rq->internal_tag = tag;
427 } else {
428 rq->tag = tag;
429 rq->internal_tag = BLK_MQ_NO_TAG;
431 rq->timeout = 0;
433 rq->part = NULL;
434 rq->io_start_time_ns = 0;
435 rq->stats_sectors = 0;
436 rq->nr_phys_segments = 0;
437 rq->nr_integrity_segments = 0;
438 rq->end_io = NULL;
439 rq->end_io_data = NULL;
441 blk_crypto_rq_set_defaults(rq);
442 INIT_LIST_HEAD(&rq->queuelist);
443 /* tag was already set */
444 WRITE_ONCE(rq->deadline, 0);
445 req_ref_set(rq, 1);
447 if (rq->rq_flags & RQF_USE_SCHED) {
448 struct elevator_queue *e = data->q->elevator;
450 INIT_HLIST_NODE(&rq->hash);
451 RB_CLEAR_NODE(&rq->rb_node);
453 if (e->type->ops.prepare_request)
454 e->type->ops.prepare_request(rq);
457 return rq;
460 static inline struct request *
461 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data)
463 unsigned int tag, tag_offset;
464 struct blk_mq_tags *tags;
465 struct request *rq;
466 unsigned long tag_mask;
467 int i, nr = 0;
469 tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
470 if (unlikely(!tag_mask))
471 return NULL;
473 tags = blk_mq_tags_from_data(data);
474 for (i = 0; tag_mask; i++) {
475 if (!(tag_mask & (1UL << i)))
476 continue;
477 tag = tag_offset + i;
478 prefetch(tags->static_rqs[tag]);
479 tag_mask &= ~(1UL << i);
480 rq = blk_mq_rq_ctx_init(data, tags, tag);
481 rq_list_add_head(data->cached_rqs, rq);
482 nr++;
484 if (!(data->rq_flags & RQF_SCHED_TAGS))
485 blk_mq_add_active_requests(data->hctx, nr);
486 /* caller already holds a reference, add for remainder */
487 percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
488 data->nr_tags -= nr;
490 return rq_list_pop(data->cached_rqs);
493 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
495 struct request_queue *q = data->q;
496 u64 alloc_time_ns = 0;
497 struct request *rq;
498 unsigned int tag;
500 /* alloc_time includes depth and tag waits */
501 if (blk_queue_rq_alloc_time(q))
502 alloc_time_ns = blk_time_get_ns();
504 if (data->cmd_flags & REQ_NOWAIT)
505 data->flags |= BLK_MQ_REQ_NOWAIT;
507 retry:
508 data->ctx = blk_mq_get_ctx(q);
509 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
511 if (q->elevator) {
513 * All requests use scheduler tags when an I/O scheduler is
514 * enabled for the queue.
516 data->rq_flags |= RQF_SCHED_TAGS;
519 * Flush/passthrough requests are special and go directly to the
520 * dispatch list.
522 if ((data->cmd_flags & REQ_OP_MASK) != REQ_OP_FLUSH &&
523 !blk_op_is_passthrough(data->cmd_flags)) {
524 struct elevator_mq_ops *ops = &q->elevator->type->ops;
526 WARN_ON_ONCE(data->flags & BLK_MQ_REQ_RESERVED);
528 data->rq_flags |= RQF_USE_SCHED;
529 if (ops->limit_depth)
530 ops->limit_depth(data->cmd_flags, data);
532 } else {
533 blk_mq_tag_busy(data->hctx);
536 if (data->flags & BLK_MQ_REQ_RESERVED)
537 data->rq_flags |= RQF_RESV;
540 * Try batched alloc if we want more than 1 tag.
542 if (data->nr_tags > 1) {
543 rq = __blk_mq_alloc_requests_batch(data);
544 if (rq) {
545 blk_mq_rq_time_init(rq, alloc_time_ns);
546 return rq;
548 data->nr_tags = 1;
552 * Waiting allocations only fail because of an inactive hctx. In that
553 * case just retry the hctx assignment and tag allocation as CPU hotplug
554 * should have migrated us to an online CPU by now.
556 tag = blk_mq_get_tag(data);
557 if (tag == BLK_MQ_NO_TAG) {
558 if (data->flags & BLK_MQ_REQ_NOWAIT)
559 return NULL;
561 * Give up the CPU and sleep for a random short time to
562 * ensure that thread using a realtime scheduling class
563 * are migrated off the CPU, and thus off the hctx that
564 * is going away.
566 msleep(3);
567 goto retry;
570 if (!(data->rq_flags & RQF_SCHED_TAGS))
571 blk_mq_inc_active_requests(data->hctx);
572 rq = blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag);
573 blk_mq_rq_time_init(rq, alloc_time_ns);
574 return rq;
577 static struct request *blk_mq_rq_cache_fill(struct request_queue *q,
578 struct blk_plug *plug,
579 blk_opf_t opf,
580 blk_mq_req_flags_t flags)
582 struct blk_mq_alloc_data data = {
583 .q = q,
584 .flags = flags,
585 .cmd_flags = opf,
586 .nr_tags = plug->nr_ios,
587 .cached_rqs = &plug->cached_rqs,
589 struct request *rq;
591 if (blk_queue_enter(q, flags))
592 return NULL;
594 plug->nr_ios = 1;
596 rq = __blk_mq_alloc_requests(&data);
597 if (unlikely(!rq))
598 blk_queue_exit(q);
599 return rq;
602 static struct request *blk_mq_alloc_cached_request(struct request_queue *q,
603 blk_opf_t opf,
604 blk_mq_req_flags_t flags)
606 struct blk_plug *plug = current->plug;
607 struct request *rq;
609 if (!plug)
610 return NULL;
612 if (rq_list_empty(&plug->cached_rqs)) {
613 if (plug->nr_ios == 1)
614 return NULL;
615 rq = blk_mq_rq_cache_fill(q, plug, opf, flags);
616 if (!rq)
617 return NULL;
618 } else {
619 rq = rq_list_peek(&plug->cached_rqs);
620 if (!rq || rq->q != q)
621 return NULL;
623 if (blk_mq_get_hctx_type(opf) != rq->mq_hctx->type)
624 return NULL;
625 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
626 return NULL;
628 rq_list_pop(&plug->cached_rqs);
629 blk_mq_rq_time_init(rq, blk_time_get_ns());
632 rq->cmd_flags = opf;
633 INIT_LIST_HEAD(&rq->queuelist);
634 return rq;
637 struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
638 blk_mq_req_flags_t flags)
640 struct request *rq;
642 rq = blk_mq_alloc_cached_request(q, opf, flags);
643 if (!rq) {
644 struct blk_mq_alloc_data data = {
645 .q = q,
646 .flags = flags,
647 .cmd_flags = opf,
648 .nr_tags = 1,
650 int ret;
652 ret = blk_queue_enter(q, flags);
653 if (ret)
654 return ERR_PTR(ret);
656 rq = __blk_mq_alloc_requests(&data);
657 if (!rq)
658 goto out_queue_exit;
660 rq->__data_len = 0;
661 rq->__sector = (sector_t) -1;
662 rq->bio = rq->biotail = NULL;
663 return rq;
664 out_queue_exit:
665 blk_queue_exit(q);
666 return ERR_PTR(-EWOULDBLOCK);
668 EXPORT_SYMBOL(blk_mq_alloc_request);
670 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
671 blk_opf_t opf, blk_mq_req_flags_t flags, unsigned int hctx_idx)
673 struct blk_mq_alloc_data data = {
674 .q = q,
675 .flags = flags,
676 .cmd_flags = opf,
677 .nr_tags = 1,
679 u64 alloc_time_ns = 0;
680 struct request *rq;
681 unsigned int cpu;
682 unsigned int tag;
683 int ret;
685 /* alloc_time includes depth and tag waits */
686 if (blk_queue_rq_alloc_time(q))
687 alloc_time_ns = blk_time_get_ns();
690 * If the tag allocator sleeps we could get an allocation for a
691 * different hardware context. No need to complicate the low level
692 * allocator for this for the rare use case of a command tied to
693 * a specific queue.
695 if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)) ||
696 WARN_ON_ONCE(!(flags & BLK_MQ_REQ_RESERVED)))
697 return ERR_PTR(-EINVAL);
699 if (hctx_idx >= q->nr_hw_queues)
700 return ERR_PTR(-EIO);
702 ret = blk_queue_enter(q, flags);
703 if (ret)
704 return ERR_PTR(ret);
707 * Check if the hardware context is actually mapped to anything.
708 * If not tell the caller that it should skip this queue.
710 ret = -EXDEV;
711 data.hctx = xa_load(&q->hctx_table, hctx_idx);
712 if (!blk_mq_hw_queue_mapped(data.hctx))
713 goto out_queue_exit;
714 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
715 if (cpu >= nr_cpu_ids)
716 goto out_queue_exit;
717 data.ctx = __blk_mq_get_ctx(q, cpu);
719 if (q->elevator)
720 data.rq_flags |= RQF_SCHED_TAGS;
721 else
722 blk_mq_tag_busy(data.hctx);
724 if (flags & BLK_MQ_REQ_RESERVED)
725 data.rq_flags |= RQF_RESV;
727 ret = -EWOULDBLOCK;
728 tag = blk_mq_get_tag(&data);
729 if (tag == BLK_MQ_NO_TAG)
730 goto out_queue_exit;
731 if (!(data.rq_flags & RQF_SCHED_TAGS))
732 blk_mq_inc_active_requests(data.hctx);
733 rq = blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag);
734 blk_mq_rq_time_init(rq, alloc_time_ns);
735 rq->__data_len = 0;
736 rq->__sector = (sector_t) -1;
737 rq->bio = rq->biotail = NULL;
738 return rq;
740 out_queue_exit:
741 blk_queue_exit(q);
742 return ERR_PTR(ret);
744 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
746 static void blk_mq_finish_request(struct request *rq)
748 struct request_queue *q = rq->q;
750 blk_zone_finish_request(rq);
752 if (rq->rq_flags & RQF_USE_SCHED) {
753 q->elevator->type->ops.finish_request(rq);
755 * For postflush request that may need to be
756 * completed twice, we should clear this flag
757 * to avoid double finish_request() on the rq.
759 rq->rq_flags &= ~RQF_USE_SCHED;
763 static void __blk_mq_free_request(struct request *rq)
765 struct request_queue *q = rq->q;
766 struct blk_mq_ctx *ctx = rq->mq_ctx;
767 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
768 const int sched_tag = rq->internal_tag;
770 blk_crypto_free_request(rq);
771 blk_pm_mark_last_busy(rq);
772 rq->mq_hctx = NULL;
774 if (rq->tag != BLK_MQ_NO_TAG) {
775 blk_mq_dec_active_requests(hctx);
776 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
778 if (sched_tag != BLK_MQ_NO_TAG)
779 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
780 blk_mq_sched_restart(hctx);
781 blk_queue_exit(q);
784 void blk_mq_free_request(struct request *rq)
786 struct request_queue *q = rq->q;
788 blk_mq_finish_request(rq);
790 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
791 laptop_io_completion(q->disk->bdi);
793 rq_qos_done(q, rq);
795 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
796 if (req_ref_put_and_test(rq))
797 __blk_mq_free_request(rq);
799 EXPORT_SYMBOL_GPL(blk_mq_free_request);
801 void blk_mq_free_plug_rqs(struct blk_plug *plug)
803 struct request *rq;
805 while ((rq = rq_list_pop(&plug->cached_rqs)) != NULL)
806 blk_mq_free_request(rq);
809 void blk_dump_rq_flags(struct request *rq, char *msg)
811 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
812 rq->q->disk ? rq->q->disk->disk_name : "?",
813 (__force unsigned long long) rq->cmd_flags);
815 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
816 (unsigned long long)blk_rq_pos(rq),
817 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
818 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
819 rq->bio, rq->biotail, blk_rq_bytes(rq));
821 EXPORT_SYMBOL(blk_dump_rq_flags);
823 static void blk_account_io_completion(struct request *req, unsigned int bytes)
825 if (req->rq_flags & RQF_IO_STAT) {
826 const int sgrp = op_stat_group(req_op(req));
828 part_stat_lock();
829 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
830 part_stat_unlock();
834 static void blk_print_req_error(struct request *req, blk_status_t status)
836 printk_ratelimited(KERN_ERR
837 "%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
838 "phys_seg %u prio class %u\n",
839 blk_status_to_str(status),
840 req->q->disk ? req->q->disk->disk_name : "?",
841 blk_rq_pos(req), (__force u32)req_op(req),
842 blk_op_str(req_op(req)),
843 (__force u32)(req->cmd_flags & ~REQ_OP_MASK),
844 req->nr_phys_segments,
845 IOPRIO_PRIO_CLASS(req_get_ioprio(req)));
849 * Fully end IO on a request. Does not support partial completions, or
850 * errors.
852 static void blk_complete_request(struct request *req)
854 const bool is_flush = (req->rq_flags & RQF_FLUSH_SEQ) != 0;
855 int total_bytes = blk_rq_bytes(req);
856 struct bio *bio = req->bio;
858 trace_block_rq_complete(req, BLK_STS_OK, total_bytes);
860 if (!bio)
861 return;
863 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ)
864 blk_integrity_complete(req, total_bytes);
867 * Upper layers may call blk_crypto_evict_key() anytime after the last
868 * bio_endio(). Therefore, the keyslot must be released before that.
870 blk_crypto_rq_put_keyslot(req);
872 blk_account_io_completion(req, total_bytes);
874 do {
875 struct bio *next = bio->bi_next;
877 /* Completion has already been traced */
878 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
880 blk_zone_update_request_bio(req, bio);
882 if (!is_flush)
883 bio_endio(bio);
884 bio = next;
885 } while (bio);
888 * Reset counters so that the request stacking driver
889 * can find how many bytes remain in the request
890 * later.
892 if (!req->end_io) {
893 req->bio = NULL;
894 req->__data_len = 0;
899 * blk_update_request - Complete multiple bytes without completing the request
900 * @req: the request being processed
901 * @error: block status code
902 * @nr_bytes: number of bytes to complete for @req
904 * Description:
905 * Ends I/O on a number of bytes attached to @req, but doesn't complete
906 * the request structure even if @req doesn't have leftover.
907 * If @req has leftover, sets it up for the next range of segments.
909 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
910 * %false return from this function.
912 * Note:
913 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
914 * except in the consistency check at the end of this function.
916 * Return:
917 * %false - this request doesn't have any more data
918 * %true - this request has more data
920 bool blk_update_request(struct request *req, blk_status_t error,
921 unsigned int nr_bytes)
923 bool is_flush = req->rq_flags & RQF_FLUSH_SEQ;
924 bool quiet = req->rq_flags & RQF_QUIET;
925 int total_bytes;
927 trace_block_rq_complete(req, error, nr_bytes);
929 if (!req->bio)
930 return false;
932 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
933 error == BLK_STS_OK)
934 blk_integrity_complete(req, nr_bytes);
937 * Upper layers may call blk_crypto_evict_key() anytime after the last
938 * bio_endio(). Therefore, the keyslot must be released before that.
940 if (blk_crypto_rq_has_keyslot(req) && nr_bytes >= blk_rq_bytes(req))
941 __blk_crypto_rq_put_keyslot(req);
943 if (unlikely(error && !blk_rq_is_passthrough(req) && !quiet) &&
944 !test_bit(GD_DEAD, &req->q->disk->state)) {
945 blk_print_req_error(req, error);
946 trace_block_rq_error(req, error, nr_bytes);
949 blk_account_io_completion(req, nr_bytes);
951 total_bytes = 0;
952 while (req->bio) {
953 struct bio *bio = req->bio;
954 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
956 if (unlikely(error))
957 bio->bi_status = error;
959 if (bio_bytes == bio->bi_iter.bi_size) {
960 req->bio = bio->bi_next;
961 } else if (bio_is_zone_append(bio) && error == BLK_STS_OK) {
963 * Partial zone append completions cannot be supported
964 * as the BIO fragments may end up not being written
965 * sequentially.
967 bio->bi_status = BLK_STS_IOERR;
970 /* Completion has already been traced */
971 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
972 if (unlikely(quiet))
973 bio_set_flag(bio, BIO_QUIET);
975 bio_advance(bio, bio_bytes);
977 /* Don't actually finish bio if it's part of flush sequence */
978 if (!bio->bi_iter.bi_size) {
979 blk_zone_update_request_bio(req, bio);
980 if (!is_flush)
981 bio_endio(bio);
984 total_bytes += bio_bytes;
985 nr_bytes -= bio_bytes;
987 if (!nr_bytes)
988 break;
992 * completely done
994 if (!req->bio) {
996 * Reset counters so that the request stacking driver
997 * can find how many bytes remain in the request
998 * later.
1000 req->__data_len = 0;
1001 return false;
1004 req->__data_len -= total_bytes;
1006 /* update sector only for requests with clear definition of sector */
1007 if (!blk_rq_is_passthrough(req))
1008 req->__sector += total_bytes >> 9;
1010 /* mixed attributes always follow the first bio */
1011 if (req->rq_flags & RQF_MIXED_MERGE) {
1012 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1013 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1016 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1018 * If total number of sectors is less than the first segment
1019 * size, something has gone terribly wrong.
1021 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1022 blk_dump_rq_flags(req, "request botched");
1023 req->__data_len = blk_rq_cur_bytes(req);
1026 /* recalculate the number of segments */
1027 req->nr_phys_segments = blk_recalc_rq_segments(req);
1030 return true;
1032 EXPORT_SYMBOL_GPL(blk_update_request);
1034 static inline void blk_account_io_done(struct request *req, u64 now)
1036 trace_block_io_done(req);
1039 * Account IO completion. flush_rq isn't accounted as a
1040 * normal IO on queueing nor completion. Accounting the
1041 * containing request is enough.
1043 if ((req->rq_flags & (RQF_IO_STAT|RQF_FLUSH_SEQ)) == RQF_IO_STAT) {
1044 const int sgrp = op_stat_group(req_op(req));
1046 part_stat_lock();
1047 update_io_ticks(req->part, jiffies, true);
1048 part_stat_inc(req->part, ios[sgrp]);
1049 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1050 part_stat_local_dec(req->part,
1051 in_flight[op_is_write(req_op(req))]);
1052 part_stat_unlock();
1056 static inline bool blk_rq_passthrough_stats(struct request *req)
1058 struct bio *bio = req->bio;
1060 if (!blk_queue_passthrough_stat(req->q))
1061 return false;
1063 /* Requests without a bio do not transfer data. */
1064 if (!bio)
1065 return false;
1068 * Stats are accumulated in the bdev, so must have one attached to a
1069 * bio to track stats. Most drivers do not set the bdev for passthrough
1070 * requests, but nvme is one that will set it.
1072 if (!bio->bi_bdev)
1073 return false;
1076 * We don't know what a passthrough command does, but we know the
1077 * payload size and data direction. Ensuring the size is aligned to the
1078 * block size filters out most commands with payloads that don't
1079 * represent sector access.
1081 if (blk_rq_bytes(req) & (bdev_logical_block_size(bio->bi_bdev) - 1))
1082 return false;
1083 return true;
1086 static inline void blk_account_io_start(struct request *req)
1088 trace_block_io_start(req);
1090 if (!blk_queue_io_stat(req->q))
1091 return;
1092 if (blk_rq_is_passthrough(req) && !blk_rq_passthrough_stats(req))
1093 return;
1095 req->rq_flags |= RQF_IO_STAT;
1096 req->start_time_ns = blk_time_get_ns();
1099 * All non-passthrough requests are created from a bio with one
1100 * exception: when a flush command that is part of a flush sequence
1101 * generated by the state machine in blk-flush.c is cloned onto the
1102 * lower device by dm-multipath we can get here without a bio.
1104 if (req->bio)
1105 req->part = req->bio->bi_bdev;
1106 else
1107 req->part = req->q->disk->part0;
1109 part_stat_lock();
1110 update_io_ticks(req->part, jiffies, false);
1111 part_stat_local_inc(req->part, in_flight[op_is_write(req_op(req))]);
1112 part_stat_unlock();
1115 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
1117 if (rq->rq_flags & RQF_STATS)
1118 blk_stat_add(rq, now);
1120 blk_mq_sched_completed_request(rq, now);
1121 blk_account_io_done(rq, now);
1124 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
1126 if (blk_mq_need_time_stamp(rq))
1127 __blk_mq_end_request_acct(rq, blk_time_get_ns());
1129 blk_mq_finish_request(rq);
1131 if (rq->end_io) {
1132 rq_qos_done(rq->q, rq);
1133 if (rq->end_io(rq, error) == RQ_END_IO_FREE)
1134 blk_mq_free_request(rq);
1135 } else {
1136 blk_mq_free_request(rq);
1139 EXPORT_SYMBOL(__blk_mq_end_request);
1141 void blk_mq_end_request(struct request *rq, blk_status_t error)
1143 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
1144 BUG();
1145 __blk_mq_end_request(rq, error);
1147 EXPORT_SYMBOL(blk_mq_end_request);
1149 #define TAG_COMP_BATCH 32
1151 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
1152 int *tag_array, int nr_tags)
1154 struct request_queue *q = hctx->queue;
1156 blk_mq_sub_active_requests(hctx, nr_tags);
1158 blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
1159 percpu_ref_put_many(&q->q_usage_counter, nr_tags);
1162 void blk_mq_end_request_batch(struct io_comp_batch *iob)
1164 int tags[TAG_COMP_BATCH], nr_tags = 0;
1165 struct blk_mq_hw_ctx *cur_hctx = NULL;
1166 struct request *rq;
1167 u64 now = 0;
1169 if (iob->need_ts)
1170 now = blk_time_get_ns();
1172 while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
1173 prefetch(rq->bio);
1174 prefetch(rq->rq_next);
1176 blk_complete_request(rq);
1177 if (iob->need_ts)
1178 __blk_mq_end_request_acct(rq, now);
1180 blk_mq_finish_request(rq);
1182 rq_qos_done(rq->q, rq);
1185 * If end_io handler returns NONE, then it still has
1186 * ownership of the request.
1188 if (rq->end_io && rq->end_io(rq, 0) == RQ_END_IO_NONE)
1189 continue;
1191 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1192 if (!req_ref_put_and_test(rq))
1193 continue;
1195 blk_crypto_free_request(rq);
1196 blk_pm_mark_last_busy(rq);
1198 if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
1199 if (cur_hctx)
1200 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1201 nr_tags = 0;
1202 cur_hctx = rq->mq_hctx;
1204 tags[nr_tags++] = rq->tag;
1207 if (nr_tags)
1208 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1210 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
1212 static void blk_complete_reqs(struct llist_head *list)
1214 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
1215 struct request *rq, *next;
1217 llist_for_each_entry_safe(rq, next, entry, ipi_list)
1218 rq->q->mq_ops->complete(rq);
1221 static __latent_entropy void blk_done_softirq(void)
1223 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
1226 static int blk_softirq_cpu_dead(unsigned int cpu)
1228 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
1229 return 0;
1232 static void __blk_mq_complete_request_remote(void *data)
1234 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
1237 static inline bool blk_mq_complete_need_ipi(struct request *rq)
1239 int cpu = raw_smp_processor_id();
1241 if (!IS_ENABLED(CONFIG_SMP) ||
1242 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
1243 return false;
1245 * With force threaded interrupts enabled, raising softirq from an SMP
1246 * function call will always result in waking the ksoftirqd thread.
1247 * This is probably worse than completing the request on a different
1248 * cache domain.
1250 if (force_irqthreads())
1251 return false;
1253 /* same CPU or cache domain and capacity? Complete locally */
1254 if (cpu == rq->mq_ctx->cpu ||
1255 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1256 cpus_share_cache(cpu, rq->mq_ctx->cpu) &&
1257 cpus_equal_capacity(cpu, rq->mq_ctx->cpu)))
1258 return false;
1260 /* don't try to IPI to an offline CPU */
1261 return cpu_online(rq->mq_ctx->cpu);
1264 static void blk_mq_complete_send_ipi(struct request *rq)
1266 unsigned int cpu;
1268 cpu = rq->mq_ctx->cpu;
1269 if (llist_add(&rq->ipi_list, &per_cpu(blk_cpu_done, cpu)))
1270 smp_call_function_single_async(cpu, &per_cpu(blk_cpu_csd, cpu));
1273 static void blk_mq_raise_softirq(struct request *rq)
1275 struct llist_head *list;
1277 preempt_disable();
1278 list = this_cpu_ptr(&blk_cpu_done);
1279 if (llist_add(&rq->ipi_list, list))
1280 raise_softirq(BLOCK_SOFTIRQ);
1281 preempt_enable();
1284 bool blk_mq_complete_request_remote(struct request *rq)
1286 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1289 * For request which hctx has only one ctx mapping,
1290 * or a polled request, always complete locally,
1291 * it's pointless to redirect the completion.
1293 if ((rq->mq_hctx->nr_ctx == 1 &&
1294 rq->mq_ctx->cpu == raw_smp_processor_id()) ||
1295 rq->cmd_flags & REQ_POLLED)
1296 return false;
1298 if (blk_mq_complete_need_ipi(rq)) {
1299 blk_mq_complete_send_ipi(rq);
1300 return true;
1303 if (rq->q->nr_hw_queues == 1) {
1304 blk_mq_raise_softirq(rq);
1305 return true;
1307 return false;
1309 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1312 * blk_mq_complete_request - end I/O on a request
1313 * @rq: the request being processed
1315 * Description:
1316 * Complete a request by scheduling the ->complete_rq operation.
1318 void blk_mq_complete_request(struct request *rq)
1320 if (!blk_mq_complete_request_remote(rq))
1321 rq->q->mq_ops->complete(rq);
1323 EXPORT_SYMBOL(blk_mq_complete_request);
1326 * blk_mq_start_request - Start processing a request
1327 * @rq: Pointer to request to be started
1329 * Function used by device drivers to notify the block layer that a request
1330 * is going to be processed now, so blk layer can do proper initializations
1331 * such as starting the timeout timer.
1333 void blk_mq_start_request(struct request *rq)
1335 struct request_queue *q = rq->q;
1337 trace_block_rq_issue(rq);
1339 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags) &&
1340 !blk_rq_is_passthrough(rq)) {
1341 rq->io_start_time_ns = blk_time_get_ns();
1342 rq->stats_sectors = blk_rq_sectors(rq);
1343 rq->rq_flags |= RQF_STATS;
1344 rq_qos_issue(q, rq);
1347 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1349 blk_add_timer(rq);
1350 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1351 rq->mq_hctx->tags->rqs[rq->tag] = rq;
1353 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1354 blk_integrity_prepare(rq);
1356 if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1357 WRITE_ONCE(rq->bio->bi_cookie, rq->mq_hctx->queue_num);
1359 EXPORT_SYMBOL(blk_mq_start_request);
1362 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
1363 * queues. This is important for md arrays to benefit from merging
1364 * requests.
1366 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
1368 if (plug->multiple_queues)
1369 return BLK_MAX_REQUEST_COUNT * 2;
1370 return BLK_MAX_REQUEST_COUNT;
1373 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
1375 struct request *last = rq_list_peek(&plug->mq_list);
1377 if (!plug->rq_count) {
1378 trace_block_plug(rq->q);
1379 } else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
1380 (!blk_queue_nomerges(rq->q) &&
1381 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1382 blk_mq_flush_plug_list(plug, false);
1383 last = NULL;
1384 trace_block_plug(rq->q);
1387 if (!plug->multiple_queues && last && last->q != rq->q)
1388 plug->multiple_queues = true;
1390 * Any request allocated from sched tags can't be issued to
1391 * ->queue_rqs() directly
1393 if (!plug->has_elevator && (rq->rq_flags & RQF_SCHED_TAGS))
1394 plug->has_elevator = true;
1395 rq_list_add_tail(&plug->mq_list, rq);
1396 plug->rq_count++;
1400 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1401 * @rq: request to insert
1402 * @at_head: insert request at head or tail of queue
1404 * Description:
1405 * Insert a fully prepared request at the back of the I/O scheduler queue
1406 * for execution. Don't wait for completion.
1408 * Note:
1409 * This function will invoke @done directly if the queue is dead.
1411 void blk_execute_rq_nowait(struct request *rq, bool at_head)
1413 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1415 WARN_ON(irqs_disabled());
1416 WARN_ON(!blk_rq_is_passthrough(rq));
1418 blk_account_io_start(rq);
1420 if (current->plug && !at_head) {
1421 blk_add_rq_to_plug(current->plug, rq);
1422 return;
1425 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1426 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
1428 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1430 struct blk_rq_wait {
1431 struct completion done;
1432 blk_status_t ret;
1435 static enum rq_end_io_ret blk_end_sync_rq(struct request *rq, blk_status_t ret)
1437 struct blk_rq_wait *wait = rq->end_io_data;
1439 wait->ret = ret;
1440 complete(&wait->done);
1441 return RQ_END_IO_NONE;
1444 bool blk_rq_is_poll(struct request *rq)
1446 if (!rq->mq_hctx)
1447 return false;
1448 if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1449 return false;
1450 return true;
1452 EXPORT_SYMBOL_GPL(blk_rq_is_poll);
1454 static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1456 do {
1457 blk_hctx_poll(rq->q, rq->mq_hctx, NULL, 0);
1458 cond_resched();
1459 } while (!completion_done(wait));
1463 * blk_execute_rq - insert a request into queue for execution
1464 * @rq: request to insert
1465 * @at_head: insert request at head or tail of queue
1467 * Description:
1468 * Insert a fully prepared request at the back of the I/O scheduler queue
1469 * for execution and wait for completion.
1470 * Return: The blk_status_t result provided to blk_mq_end_request().
1472 blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1474 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1475 struct blk_rq_wait wait = {
1476 .done = COMPLETION_INITIALIZER_ONSTACK(wait.done),
1479 WARN_ON(irqs_disabled());
1480 WARN_ON(!blk_rq_is_passthrough(rq));
1482 rq->end_io_data = &wait;
1483 rq->end_io = blk_end_sync_rq;
1485 blk_account_io_start(rq);
1486 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1487 blk_mq_run_hw_queue(hctx, false);
1489 if (blk_rq_is_poll(rq))
1490 blk_rq_poll_completion(rq, &wait.done);
1491 else
1492 blk_wait_io(&wait.done);
1494 return wait.ret;
1496 EXPORT_SYMBOL(blk_execute_rq);
1498 static void __blk_mq_requeue_request(struct request *rq)
1500 struct request_queue *q = rq->q;
1502 blk_mq_put_driver_tag(rq);
1504 trace_block_rq_requeue(rq);
1505 rq_qos_requeue(q, rq);
1507 if (blk_mq_request_started(rq)) {
1508 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1509 rq->rq_flags &= ~RQF_TIMED_OUT;
1513 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1515 struct request_queue *q = rq->q;
1516 unsigned long flags;
1518 __blk_mq_requeue_request(rq);
1520 /* this request will be re-inserted to io scheduler queue */
1521 blk_mq_sched_requeue_request(rq);
1523 spin_lock_irqsave(&q->requeue_lock, flags);
1524 list_add_tail(&rq->queuelist, &q->requeue_list);
1525 spin_unlock_irqrestore(&q->requeue_lock, flags);
1527 if (kick_requeue_list)
1528 blk_mq_kick_requeue_list(q);
1530 EXPORT_SYMBOL(blk_mq_requeue_request);
1532 static void blk_mq_requeue_work(struct work_struct *work)
1534 struct request_queue *q =
1535 container_of(work, struct request_queue, requeue_work.work);
1536 LIST_HEAD(rq_list);
1537 LIST_HEAD(flush_list);
1538 struct request *rq;
1540 spin_lock_irq(&q->requeue_lock);
1541 list_splice_init(&q->requeue_list, &rq_list);
1542 list_splice_init(&q->flush_list, &flush_list);
1543 spin_unlock_irq(&q->requeue_lock);
1545 while (!list_empty(&rq_list)) {
1546 rq = list_entry(rq_list.next, struct request, queuelist);
1548 * If RQF_DONTPREP ist set, the request has been started by the
1549 * driver already and might have driver-specific data allocated
1550 * already. Insert it into the hctx dispatch list to avoid
1551 * block layer merges for the request.
1553 if (rq->rq_flags & RQF_DONTPREP) {
1554 list_del_init(&rq->queuelist);
1555 blk_mq_request_bypass_insert(rq, 0);
1556 } else {
1557 list_del_init(&rq->queuelist);
1558 blk_mq_insert_request(rq, BLK_MQ_INSERT_AT_HEAD);
1562 while (!list_empty(&flush_list)) {
1563 rq = list_entry(flush_list.next, struct request, queuelist);
1564 list_del_init(&rq->queuelist);
1565 blk_mq_insert_request(rq, 0);
1568 blk_mq_run_hw_queues(q, false);
1571 void blk_mq_kick_requeue_list(struct request_queue *q)
1573 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1575 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1577 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1578 unsigned long msecs)
1580 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1581 msecs_to_jiffies(msecs));
1583 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1585 static bool blk_is_flush_data_rq(struct request *rq)
1587 return (rq->rq_flags & RQF_FLUSH_SEQ) && !is_flush_rq(rq);
1590 static bool blk_mq_rq_inflight(struct request *rq, void *priv)
1593 * If we find a request that isn't idle we know the queue is busy
1594 * as it's checked in the iter.
1595 * Return false to stop the iteration.
1597 * In case of queue quiesce, if one flush data request is completed,
1598 * don't count it as inflight given the flush sequence is suspended,
1599 * and the original flush data request is invisible to driver, just
1600 * like other pending requests because of quiesce
1602 if (blk_mq_request_started(rq) && !(blk_queue_quiesced(rq->q) &&
1603 blk_is_flush_data_rq(rq) &&
1604 blk_mq_request_completed(rq))) {
1605 bool *busy = priv;
1607 *busy = true;
1608 return false;
1611 return true;
1614 bool blk_mq_queue_inflight(struct request_queue *q)
1616 bool busy = false;
1618 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1619 return busy;
1621 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1623 static void blk_mq_rq_timed_out(struct request *req)
1625 req->rq_flags |= RQF_TIMED_OUT;
1626 if (req->q->mq_ops->timeout) {
1627 enum blk_eh_timer_return ret;
1629 ret = req->q->mq_ops->timeout(req);
1630 if (ret == BLK_EH_DONE)
1631 return;
1632 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1635 blk_add_timer(req);
1638 struct blk_expired_data {
1639 bool has_timedout_rq;
1640 unsigned long next;
1641 unsigned long timeout_start;
1644 static bool blk_mq_req_expired(struct request *rq, struct blk_expired_data *expired)
1646 unsigned long deadline;
1648 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1649 return false;
1650 if (rq->rq_flags & RQF_TIMED_OUT)
1651 return false;
1653 deadline = READ_ONCE(rq->deadline);
1654 if (time_after_eq(expired->timeout_start, deadline))
1655 return true;
1657 if (expired->next == 0)
1658 expired->next = deadline;
1659 else if (time_after(expired->next, deadline))
1660 expired->next = deadline;
1661 return false;
1664 void blk_mq_put_rq_ref(struct request *rq)
1666 if (is_flush_rq(rq)) {
1667 if (rq->end_io(rq, 0) == RQ_END_IO_FREE)
1668 blk_mq_free_request(rq);
1669 } else if (req_ref_put_and_test(rq)) {
1670 __blk_mq_free_request(rq);
1674 static bool blk_mq_check_expired(struct request *rq, void *priv)
1676 struct blk_expired_data *expired = priv;
1679 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1680 * be reallocated underneath the timeout handler's processing, then
1681 * the expire check is reliable. If the request is not expired, then
1682 * it was completed and reallocated as a new request after returning
1683 * from blk_mq_check_expired().
1685 if (blk_mq_req_expired(rq, expired)) {
1686 expired->has_timedout_rq = true;
1687 return false;
1689 return true;
1692 static bool blk_mq_handle_expired(struct request *rq, void *priv)
1694 struct blk_expired_data *expired = priv;
1696 if (blk_mq_req_expired(rq, expired))
1697 blk_mq_rq_timed_out(rq);
1698 return true;
1701 static void blk_mq_timeout_work(struct work_struct *work)
1703 struct request_queue *q =
1704 container_of(work, struct request_queue, timeout_work);
1705 struct blk_expired_data expired = {
1706 .timeout_start = jiffies,
1708 struct blk_mq_hw_ctx *hctx;
1709 unsigned long i;
1711 /* A deadlock might occur if a request is stuck requiring a
1712 * timeout at the same time a queue freeze is waiting
1713 * completion, since the timeout code would not be able to
1714 * acquire the queue reference here.
1716 * That's why we don't use blk_queue_enter here; instead, we use
1717 * percpu_ref_tryget directly, because we need to be able to
1718 * obtain a reference even in the short window between the queue
1719 * starting to freeze, by dropping the first reference in
1720 * blk_freeze_queue_start, and the moment the last request is
1721 * consumed, marked by the instant q_usage_counter reaches
1722 * zero.
1724 if (!percpu_ref_tryget(&q->q_usage_counter))
1725 return;
1727 /* check if there is any timed-out request */
1728 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &expired);
1729 if (expired.has_timedout_rq) {
1731 * Before walking tags, we must ensure any submit started
1732 * before the current time has finished. Since the submit
1733 * uses srcu or rcu, wait for a synchronization point to
1734 * ensure all running submits have finished
1736 blk_mq_wait_quiesce_done(q->tag_set);
1738 expired.next = 0;
1739 blk_mq_queue_tag_busy_iter(q, blk_mq_handle_expired, &expired);
1742 if (expired.next != 0) {
1743 mod_timer(&q->timeout, expired.next);
1744 } else {
1746 * Request timeouts are handled as a forward rolling timer. If
1747 * we end up here it means that no requests are pending and
1748 * also that no request has been pending for a while. Mark
1749 * each hctx as idle.
1751 queue_for_each_hw_ctx(q, hctx, i) {
1752 /* the hctx may be unmapped, so check it here */
1753 if (blk_mq_hw_queue_mapped(hctx))
1754 blk_mq_tag_idle(hctx);
1757 blk_queue_exit(q);
1760 struct flush_busy_ctx_data {
1761 struct blk_mq_hw_ctx *hctx;
1762 struct list_head *list;
1765 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1767 struct flush_busy_ctx_data *flush_data = data;
1768 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1769 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1770 enum hctx_type type = hctx->type;
1772 spin_lock(&ctx->lock);
1773 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1774 sbitmap_clear_bit(sb, bitnr);
1775 spin_unlock(&ctx->lock);
1776 return true;
1780 * Process software queues that have been marked busy, splicing them
1781 * to the for-dispatch
1783 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1785 struct flush_busy_ctx_data data = {
1786 .hctx = hctx,
1787 .list = list,
1790 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1793 struct dispatch_rq_data {
1794 struct blk_mq_hw_ctx *hctx;
1795 struct request *rq;
1798 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1799 void *data)
1801 struct dispatch_rq_data *dispatch_data = data;
1802 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1803 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1804 enum hctx_type type = hctx->type;
1806 spin_lock(&ctx->lock);
1807 if (!list_empty(&ctx->rq_lists[type])) {
1808 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1809 list_del_init(&dispatch_data->rq->queuelist);
1810 if (list_empty(&ctx->rq_lists[type]))
1811 sbitmap_clear_bit(sb, bitnr);
1813 spin_unlock(&ctx->lock);
1815 return !dispatch_data->rq;
1818 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1819 struct blk_mq_ctx *start)
1821 unsigned off = start ? start->index_hw[hctx->type] : 0;
1822 struct dispatch_rq_data data = {
1823 .hctx = hctx,
1824 .rq = NULL,
1827 __sbitmap_for_each_set(&hctx->ctx_map, off,
1828 dispatch_rq_from_ctx, &data);
1830 return data.rq;
1833 bool __blk_mq_alloc_driver_tag(struct request *rq)
1835 struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1836 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1837 int tag;
1839 blk_mq_tag_busy(rq->mq_hctx);
1841 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1842 bt = &rq->mq_hctx->tags->breserved_tags;
1843 tag_offset = 0;
1844 } else {
1845 if (!hctx_may_queue(rq->mq_hctx, bt))
1846 return false;
1849 tag = __sbitmap_queue_get(bt);
1850 if (tag == BLK_MQ_NO_TAG)
1851 return false;
1853 rq->tag = tag + tag_offset;
1854 blk_mq_inc_active_requests(rq->mq_hctx);
1855 return true;
1858 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1859 int flags, void *key)
1861 struct blk_mq_hw_ctx *hctx;
1863 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1865 spin_lock(&hctx->dispatch_wait_lock);
1866 if (!list_empty(&wait->entry)) {
1867 struct sbitmap_queue *sbq;
1869 list_del_init(&wait->entry);
1870 sbq = &hctx->tags->bitmap_tags;
1871 atomic_dec(&sbq->ws_active);
1873 spin_unlock(&hctx->dispatch_wait_lock);
1875 blk_mq_run_hw_queue(hctx, true);
1876 return 1;
1880 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1881 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1882 * restart. For both cases, take care to check the condition again after
1883 * marking us as waiting.
1885 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1886 struct request *rq)
1888 struct sbitmap_queue *sbq;
1889 struct wait_queue_head *wq;
1890 wait_queue_entry_t *wait;
1891 bool ret;
1893 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1894 !(blk_mq_is_shared_tags(hctx->flags))) {
1895 blk_mq_sched_mark_restart_hctx(hctx);
1898 * It's possible that a tag was freed in the window between the
1899 * allocation failure and adding the hardware queue to the wait
1900 * queue.
1902 * Don't clear RESTART here, someone else could have set it.
1903 * At most this will cost an extra queue run.
1905 return blk_mq_get_driver_tag(rq);
1908 wait = &hctx->dispatch_wait;
1909 if (!list_empty_careful(&wait->entry))
1910 return false;
1912 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag))
1913 sbq = &hctx->tags->breserved_tags;
1914 else
1915 sbq = &hctx->tags->bitmap_tags;
1916 wq = &bt_wait_ptr(sbq, hctx)->wait;
1918 spin_lock_irq(&wq->lock);
1919 spin_lock(&hctx->dispatch_wait_lock);
1920 if (!list_empty(&wait->entry)) {
1921 spin_unlock(&hctx->dispatch_wait_lock);
1922 spin_unlock_irq(&wq->lock);
1923 return false;
1926 atomic_inc(&sbq->ws_active);
1927 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1928 __add_wait_queue(wq, wait);
1931 * Add one explicit barrier since blk_mq_get_driver_tag() may
1932 * not imply barrier in case of failure.
1934 * Order adding us to wait queue and allocating driver tag.
1936 * The pair is the one implied in sbitmap_queue_wake_up() which
1937 * orders clearing sbitmap tag bits and waitqueue_active() in
1938 * __sbitmap_queue_wake_up(), since waitqueue_active() is lockless
1940 * Otherwise, re-order of adding wait queue and getting driver tag
1941 * may cause __sbitmap_queue_wake_up() to wake up nothing because
1942 * the waitqueue_active() may not observe us in wait queue.
1944 smp_mb();
1947 * It's possible that a tag was freed in the window between the
1948 * allocation failure and adding the hardware queue to the wait
1949 * queue.
1951 ret = blk_mq_get_driver_tag(rq);
1952 if (!ret) {
1953 spin_unlock(&hctx->dispatch_wait_lock);
1954 spin_unlock_irq(&wq->lock);
1955 return false;
1959 * We got a tag, remove ourselves from the wait queue to ensure
1960 * someone else gets the wakeup.
1962 list_del_init(&wait->entry);
1963 atomic_dec(&sbq->ws_active);
1964 spin_unlock(&hctx->dispatch_wait_lock);
1965 spin_unlock_irq(&wq->lock);
1967 return true;
1970 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1971 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1973 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1974 * - EWMA is one simple way to compute running average value
1975 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1976 * - take 4 as factor for avoiding to get too small(0) result, and this
1977 * factor doesn't matter because EWMA decreases exponentially
1979 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1981 unsigned int ewma;
1983 ewma = hctx->dispatch_busy;
1985 if (!ewma && !busy)
1986 return;
1988 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1989 if (busy)
1990 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1991 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1993 hctx->dispatch_busy = ewma;
1996 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1998 static void blk_mq_handle_dev_resource(struct request *rq,
1999 struct list_head *list)
2001 list_add(&rq->queuelist, list);
2002 __blk_mq_requeue_request(rq);
2005 enum prep_dispatch {
2006 PREP_DISPATCH_OK,
2007 PREP_DISPATCH_NO_TAG,
2008 PREP_DISPATCH_NO_BUDGET,
2011 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
2012 bool need_budget)
2014 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2015 int budget_token = -1;
2017 if (need_budget) {
2018 budget_token = blk_mq_get_dispatch_budget(rq->q);
2019 if (budget_token < 0) {
2020 blk_mq_put_driver_tag(rq);
2021 return PREP_DISPATCH_NO_BUDGET;
2023 blk_mq_set_rq_budget_token(rq, budget_token);
2026 if (!blk_mq_get_driver_tag(rq)) {
2028 * The initial allocation attempt failed, so we need to
2029 * rerun the hardware queue when a tag is freed. The
2030 * waitqueue takes care of that. If the queue is run
2031 * before we add this entry back on the dispatch list,
2032 * we'll re-run it below.
2034 if (!blk_mq_mark_tag_wait(hctx, rq)) {
2036 * All budgets not got from this function will be put
2037 * together during handling partial dispatch
2039 if (need_budget)
2040 blk_mq_put_dispatch_budget(rq->q, budget_token);
2041 return PREP_DISPATCH_NO_TAG;
2045 return PREP_DISPATCH_OK;
2048 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
2049 static void blk_mq_release_budgets(struct request_queue *q,
2050 struct list_head *list)
2052 struct request *rq;
2054 list_for_each_entry(rq, list, queuelist) {
2055 int budget_token = blk_mq_get_rq_budget_token(rq);
2057 if (budget_token >= 0)
2058 blk_mq_put_dispatch_budget(q, budget_token);
2063 * blk_mq_commit_rqs will notify driver using bd->last that there is no
2064 * more requests. (See comment in struct blk_mq_ops for commit_rqs for
2065 * details)
2066 * Attention, we should explicitly call this in unusual cases:
2067 * 1) did not queue everything initially scheduled to queue
2068 * 2) the last attempt to queue a request failed
2070 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int queued,
2071 bool from_schedule)
2073 if (hctx->queue->mq_ops->commit_rqs && queued) {
2074 trace_block_unplug(hctx->queue, queued, !from_schedule);
2075 hctx->queue->mq_ops->commit_rqs(hctx);
2080 * Returns true if we did some work AND can potentially do more.
2082 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
2083 unsigned int nr_budgets)
2085 enum prep_dispatch prep;
2086 struct request_queue *q = hctx->queue;
2087 struct request *rq;
2088 int queued;
2089 blk_status_t ret = BLK_STS_OK;
2090 bool needs_resource = false;
2092 if (list_empty(list))
2093 return false;
2096 * Now process all the entries, sending them to the driver.
2098 queued = 0;
2099 do {
2100 struct blk_mq_queue_data bd;
2102 rq = list_first_entry(list, struct request, queuelist);
2104 WARN_ON_ONCE(hctx != rq->mq_hctx);
2105 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
2106 if (prep != PREP_DISPATCH_OK)
2107 break;
2109 list_del_init(&rq->queuelist);
2111 bd.rq = rq;
2112 bd.last = list_empty(list);
2115 * once the request is queued to lld, no need to cover the
2116 * budget any more
2118 if (nr_budgets)
2119 nr_budgets--;
2120 ret = q->mq_ops->queue_rq(hctx, &bd);
2121 switch (ret) {
2122 case BLK_STS_OK:
2123 queued++;
2124 break;
2125 case BLK_STS_RESOURCE:
2126 needs_resource = true;
2127 fallthrough;
2128 case BLK_STS_DEV_RESOURCE:
2129 blk_mq_handle_dev_resource(rq, list);
2130 goto out;
2131 default:
2132 blk_mq_end_request(rq, ret);
2134 } while (!list_empty(list));
2135 out:
2136 /* If we didn't flush the entire list, we could have told the driver
2137 * there was more coming, but that turned out to be a lie.
2139 if (!list_empty(list) || ret != BLK_STS_OK)
2140 blk_mq_commit_rqs(hctx, queued, false);
2143 * Any items that need requeuing? Stuff them into hctx->dispatch,
2144 * that is where we will continue on next queue run.
2146 if (!list_empty(list)) {
2147 bool needs_restart;
2148 /* For non-shared tags, the RESTART check will suffice */
2149 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
2150 ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) ||
2151 blk_mq_is_shared_tags(hctx->flags));
2153 if (nr_budgets)
2154 blk_mq_release_budgets(q, list);
2156 spin_lock(&hctx->lock);
2157 list_splice_tail_init(list, &hctx->dispatch);
2158 spin_unlock(&hctx->lock);
2161 * Order adding requests to hctx->dispatch and checking
2162 * SCHED_RESTART flag. The pair of this smp_mb() is the one
2163 * in blk_mq_sched_restart(). Avoid restart code path to
2164 * miss the new added requests to hctx->dispatch, meantime
2165 * SCHED_RESTART is observed here.
2167 smp_mb();
2170 * If SCHED_RESTART was set by the caller of this function and
2171 * it is no longer set that means that it was cleared by another
2172 * thread and hence that a queue rerun is needed.
2174 * If 'no_tag' is set, that means that we failed getting
2175 * a driver tag with an I/O scheduler attached. If our dispatch
2176 * waitqueue is no longer active, ensure that we run the queue
2177 * AFTER adding our entries back to the list.
2179 * If no I/O scheduler has been configured it is possible that
2180 * the hardware queue got stopped and restarted before requests
2181 * were pushed back onto the dispatch list. Rerun the queue to
2182 * avoid starvation. Notes:
2183 * - blk_mq_run_hw_queue() checks whether or not a queue has
2184 * been stopped before rerunning a queue.
2185 * - Some but not all block drivers stop a queue before
2186 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
2187 * and dm-rq.
2189 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
2190 * bit is set, run queue after a delay to avoid IO stalls
2191 * that could otherwise occur if the queue is idle. We'll do
2192 * similar if we couldn't get budget or couldn't lock a zone
2193 * and SCHED_RESTART is set.
2195 needs_restart = blk_mq_sched_needs_restart(hctx);
2196 if (prep == PREP_DISPATCH_NO_BUDGET)
2197 needs_resource = true;
2198 if (!needs_restart ||
2199 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
2200 blk_mq_run_hw_queue(hctx, true);
2201 else if (needs_resource)
2202 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
2204 blk_mq_update_dispatch_busy(hctx, true);
2205 return false;
2208 blk_mq_update_dispatch_busy(hctx, false);
2209 return true;
2212 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
2214 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
2216 if (cpu >= nr_cpu_ids)
2217 cpu = cpumask_first(hctx->cpumask);
2218 return cpu;
2222 * ->next_cpu is always calculated from hctx->cpumask, so simply use
2223 * it for speeding up the check
2225 static bool blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx *hctx)
2227 return hctx->next_cpu >= nr_cpu_ids;
2231 * It'd be great if the workqueue API had a way to pass
2232 * in a mask and had some smarts for more clever placement.
2233 * For now we just round-robin here, switching for every
2234 * BLK_MQ_CPU_WORK_BATCH queued items.
2236 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
2238 bool tried = false;
2239 int next_cpu = hctx->next_cpu;
2241 /* Switch to unbound if no allowable CPUs in this hctx */
2242 if (hctx->queue->nr_hw_queues == 1 || blk_mq_hctx_empty_cpumask(hctx))
2243 return WORK_CPU_UNBOUND;
2245 if (--hctx->next_cpu_batch <= 0) {
2246 select_cpu:
2247 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
2248 cpu_online_mask);
2249 if (next_cpu >= nr_cpu_ids)
2250 next_cpu = blk_mq_first_mapped_cpu(hctx);
2251 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2255 * Do unbound schedule if we can't find a online CPU for this hctx,
2256 * and it should only happen in the path of handling CPU DEAD.
2258 if (!cpu_online(next_cpu)) {
2259 if (!tried) {
2260 tried = true;
2261 goto select_cpu;
2265 * Make sure to re-select CPU next time once after CPUs
2266 * in hctx->cpumask become online again.
2268 hctx->next_cpu = next_cpu;
2269 hctx->next_cpu_batch = 1;
2270 return WORK_CPU_UNBOUND;
2273 hctx->next_cpu = next_cpu;
2274 return next_cpu;
2278 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2279 * @hctx: Pointer to the hardware queue to run.
2280 * @msecs: Milliseconds of delay to wait before running the queue.
2282 * Run a hardware queue asynchronously with a delay of @msecs.
2284 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2286 if (unlikely(blk_mq_hctx_stopped(hctx)))
2287 return;
2288 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2289 msecs_to_jiffies(msecs));
2291 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2293 static inline bool blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx *hctx)
2295 bool need_run;
2298 * When queue is quiesced, we may be switching io scheduler, or
2299 * updating nr_hw_queues, or other things, and we can't run queue
2300 * any more, even blk_mq_hctx_has_pending() can't be called safely.
2302 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2303 * quiesced.
2305 __blk_mq_run_dispatch_ops(hctx->queue, false,
2306 need_run = !blk_queue_quiesced(hctx->queue) &&
2307 blk_mq_hctx_has_pending(hctx));
2308 return need_run;
2312 * blk_mq_run_hw_queue - Start to run a hardware queue.
2313 * @hctx: Pointer to the hardware queue to run.
2314 * @async: If we want to run the queue asynchronously.
2316 * Check if the request queue is not in a quiesced state and if there are
2317 * pending requests to be sent. If this is true, run the queue to send requests
2318 * to hardware.
2320 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2322 bool need_run;
2325 * We can't run the queue inline with interrupts disabled.
2327 WARN_ON_ONCE(!async && in_interrupt());
2329 might_sleep_if(!async && hctx->flags & BLK_MQ_F_BLOCKING);
2331 need_run = blk_mq_hw_queue_need_run(hctx);
2332 if (!need_run) {
2333 unsigned long flags;
2336 * Synchronize with blk_mq_unquiesce_queue(), because we check
2337 * if hw queue is quiesced locklessly above, we need the use
2338 * ->queue_lock to make sure we see the up-to-date status to
2339 * not miss rerunning the hw queue.
2341 spin_lock_irqsave(&hctx->queue->queue_lock, flags);
2342 need_run = blk_mq_hw_queue_need_run(hctx);
2343 spin_unlock_irqrestore(&hctx->queue->queue_lock, flags);
2345 if (!need_run)
2346 return;
2349 if (async || !cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask)) {
2350 blk_mq_delay_run_hw_queue(hctx, 0);
2351 return;
2354 blk_mq_run_dispatch_ops(hctx->queue,
2355 blk_mq_sched_dispatch_requests(hctx));
2357 EXPORT_SYMBOL(blk_mq_run_hw_queue);
2360 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2361 * scheduler.
2363 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2365 struct blk_mq_ctx *ctx = blk_mq_get_ctx(q);
2367 * If the IO scheduler does not respect hardware queues when
2368 * dispatching, we just don't bother with multiple HW queues and
2369 * dispatch from hctx for the current CPU since running multiple queues
2370 * just causes lock contention inside the scheduler and pointless cache
2371 * bouncing.
2373 struct blk_mq_hw_ctx *hctx = ctx->hctxs[HCTX_TYPE_DEFAULT];
2375 if (!blk_mq_hctx_stopped(hctx))
2376 return hctx;
2377 return NULL;
2381 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2382 * @q: Pointer to the request queue to run.
2383 * @async: If we want to run the queue asynchronously.
2385 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2387 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2388 unsigned long i;
2390 sq_hctx = NULL;
2391 if (blk_queue_sq_sched(q))
2392 sq_hctx = blk_mq_get_sq_hctx(q);
2393 queue_for_each_hw_ctx(q, hctx, i) {
2394 if (blk_mq_hctx_stopped(hctx))
2395 continue;
2397 * Dispatch from this hctx either if there's no hctx preferred
2398 * by IO scheduler or if it has requests that bypass the
2399 * scheduler.
2401 if (!sq_hctx || sq_hctx == hctx ||
2402 !list_empty_careful(&hctx->dispatch))
2403 blk_mq_run_hw_queue(hctx, async);
2406 EXPORT_SYMBOL(blk_mq_run_hw_queues);
2409 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2410 * @q: Pointer to the request queue to run.
2411 * @msecs: Milliseconds of delay to wait before running the queues.
2413 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2415 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2416 unsigned long i;
2418 sq_hctx = NULL;
2419 if (blk_queue_sq_sched(q))
2420 sq_hctx = blk_mq_get_sq_hctx(q);
2421 queue_for_each_hw_ctx(q, hctx, i) {
2422 if (blk_mq_hctx_stopped(hctx))
2423 continue;
2425 * If there is already a run_work pending, leave the
2426 * pending delay untouched. Otherwise, a hctx can stall
2427 * if another hctx is re-delaying the other's work
2428 * before the work executes.
2430 if (delayed_work_pending(&hctx->run_work))
2431 continue;
2433 * Dispatch from this hctx either if there's no hctx preferred
2434 * by IO scheduler or if it has requests that bypass the
2435 * scheduler.
2437 if (!sq_hctx || sq_hctx == hctx ||
2438 !list_empty_careful(&hctx->dispatch))
2439 blk_mq_delay_run_hw_queue(hctx, msecs);
2442 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2445 * This function is often used for pausing .queue_rq() by driver when
2446 * there isn't enough resource or some conditions aren't satisfied, and
2447 * BLK_STS_RESOURCE is usually returned.
2449 * We do not guarantee that dispatch can be drained or blocked
2450 * after blk_mq_stop_hw_queue() returns. Please use
2451 * blk_mq_quiesce_queue() for that requirement.
2453 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2455 cancel_delayed_work(&hctx->run_work);
2457 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2459 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2462 * This function is often used for pausing .queue_rq() by driver when
2463 * there isn't enough resource or some conditions aren't satisfied, and
2464 * BLK_STS_RESOURCE is usually returned.
2466 * We do not guarantee that dispatch can be drained or blocked
2467 * after blk_mq_stop_hw_queues() returns. Please use
2468 * blk_mq_quiesce_queue() for that requirement.
2470 void blk_mq_stop_hw_queues(struct request_queue *q)
2472 struct blk_mq_hw_ctx *hctx;
2473 unsigned long i;
2475 queue_for_each_hw_ctx(q, hctx, i)
2476 blk_mq_stop_hw_queue(hctx);
2478 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2480 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2482 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2484 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
2486 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2488 void blk_mq_start_hw_queues(struct request_queue *q)
2490 struct blk_mq_hw_ctx *hctx;
2491 unsigned long i;
2493 queue_for_each_hw_ctx(q, hctx, i)
2494 blk_mq_start_hw_queue(hctx);
2496 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2498 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2500 if (!blk_mq_hctx_stopped(hctx))
2501 return;
2503 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2505 * Pairs with the smp_mb() in blk_mq_hctx_stopped() to order the
2506 * clearing of BLK_MQ_S_STOPPED above and the checking of dispatch
2507 * list in the subsequent routine.
2509 smp_mb__after_atomic();
2510 blk_mq_run_hw_queue(hctx, async);
2512 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2514 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2516 struct blk_mq_hw_ctx *hctx;
2517 unsigned long i;
2519 queue_for_each_hw_ctx(q, hctx, i)
2520 blk_mq_start_stopped_hw_queue(hctx, async ||
2521 (hctx->flags & BLK_MQ_F_BLOCKING));
2523 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2525 static void blk_mq_run_work_fn(struct work_struct *work)
2527 struct blk_mq_hw_ctx *hctx =
2528 container_of(work, struct blk_mq_hw_ctx, run_work.work);
2530 blk_mq_run_dispatch_ops(hctx->queue,
2531 blk_mq_sched_dispatch_requests(hctx));
2535 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2536 * @rq: Pointer to request to be inserted.
2537 * @flags: BLK_MQ_INSERT_*
2539 * Should only be used carefully, when the caller knows we want to
2540 * bypass a potential IO scheduler on the target device.
2542 static void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
2544 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2546 spin_lock(&hctx->lock);
2547 if (flags & BLK_MQ_INSERT_AT_HEAD)
2548 list_add(&rq->queuelist, &hctx->dispatch);
2549 else
2550 list_add_tail(&rq->queuelist, &hctx->dispatch);
2551 spin_unlock(&hctx->lock);
2554 static void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx,
2555 struct blk_mq_ctx *ctx, struct list_head *list,
2556 bool run_queue_async)
2558 struct request *rq;
2559 enum hctx_type type = hctx->type;
2562 * Try to issue requests directly if the hw queue isn't busy to save an
2563 * extra enqueue & dequeue to the sw queue.
2565 if (!hctx->dispatch_busy && !run_queue_async) {
2566 blk_mq_run_dispatch_ops(hctx->queue,
2567 blk_mq_try_issue_list_directly(hctx, list));
2568 if (list_empty(list))
2569 goto out;
2573 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2574 * offline now
2576 list_for_each_entry(rq, list, queuelist) {
2577 BUG_ON(rq->mq_ctx != ctx);
2578 trace_block_rq_insert(rq);
2579 if (rq->cmd_flags & REQ_NOWAIT)
2580 run_queue_async = true;
2583 spin_lock(&ctx->lock);
2584 list_splice_tail_init(list, &ctx->rq_lists[type]);
2585 blk_mq_hctx_mark_pending(hctx, ctx);
2586 spin_unlock(&ctx->lock);
2587 out:
2588 blk_mq_run_hw_queue(hctx, run_queue_async);
2591 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags)
2593 struct request_queue *q = rq->q;
2594 struct blk_mq_ctx *ctx = rq->mq_ctx;
2595 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2597 if (blk_rq_is_passthrough(rq)) {
2599 * Passthrough request have to be added to hctx->dispatch
2600 * directly. The device may be in a situation where it can't
2601 * handle FS request, and always returns BLK_STS_RESOURCE for
2602 * them, which gets them added to hctx->dispatch.
2604 * If a passthrough request is required to unblock the queues,
2605 * and it is added to the scheduler queue, there is no chance to
2606 * dispatch it given we prioritize requests in hctx->dispatch.
2608 blk_mq_request_bypass_insert(rq, flags);
2609 } else if (req_op(rq) == REQ_OP_FLUSH) {
2611 * Firstly normal IO request is inserted to scheduler queue or
2612 * sw queue, meantime we add flush request to dispatch queue(
2613 * hctx->dispatch) directly and there is at most one in-flight
2614 * flush request for each hw queue, so it doesn't matter to add
2615 * flush request to tail or front of the dispatch queue.
2617 * Secondly in case of NCQ, flush request belongs to non-NCQ
2618 * command, and queueing it will fail when there is any
2619 * in-flight normal IO request(NCQ command). When adding flush
2620 * rq to the front of hctx->dispatch, it is easier to introduce
2621 * extra time to flush rq's latency because of S_SCHED_RESTART
2622 * compared with adding to the tail of dispatch queue, then
2623 * chance of flush merge is increased, and less flush requests
2624 * will be issued to controller. It is observed that ~10% time
2625 * is saved in blktests block/004 on disk attached to AHCI/NCQ
2626 * drive when adding flush rq to the front of hctx->dispatch.
2628 * Simply queue flush rq to the front of hctx->dispatch so that
2629 * intensive flush workloads can benefit in case of NCQ HW.
2631 blk_mq_request_bypass_insert(rq, BLK_MQ_INSERT_AT_HEAD);
2632 } else if (q->elevator) {
2633 LIST_HEAD(list);
2635 WARN_ON_ONCE(rq->tag != BLK_MQ_NO_TAG);
2637 list_add(&rq->queuelist, &list);
2638 q->elevator->type->ops.insert_requests(hctx, &list, flags);
2639 } else {
2640 trace_block_rq_insert(rq);
2642 spin_lock(&ctx->lock);
2643 if (flags & BLK_MQ_INSERT_AT_HEAD)
2644 list_add(&rq->queuelist, &ctx->rq_lists[hctx->type]);
2645 else
2646 list_add_tail(&rq->queuelist,
2647 &ctx->rq_lists[hctx->type]);
2648 blk_mq_hctx_mark_pending(hctx, ctx);
2649 spin_unlock(&ctx->lock);
2653 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2654 unsigned int nr_segs)
2656 int err;
2658 if (bio->bi_opf & REQ_RAHEAD)
2659 rq->cmd_flags |= REQ_FAILFAST_MASK;
2661 rq->__sector = bio->bi_iter.bi_sector;
2662 blk_rq_bio_prep(rq, bio, nr_segs);
2663 if (bio_integrity(bio))
2664 rq->nr_integrity_segments = blk_rq_count_integrity_sg(rq->q,
2665 bio);
2667 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2668 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2669 WARN_ON_ONCE(err);
2671 blk_account_io_start(rq);
2674 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2675 struct request *rq, bool last)
2677 struct request_queue *q = rq->q;
2678 struct blk_mq_queue_data bd = {
2679 .rq = rq,
2680 .last = last,
2682 blk_status_t ret;
2685 * For OK queue, we are done. For error, caller may kill it.
2686 * Any other error (busy), just add it to our list as we
2687 * previously would have done.
2689 ret = q->mq_ops->queue_rq(hctx, &bd);
2690 switch (ret) {
2691 case BLK_STS_OK:
2692 blk_mq_update_dispatch_busy(hctx, false);
2693 break;
2694 case BLK_STS_RESOURCE:
2695 case BLK_STS_DEV_RESOURCE:
2696 blk_mq_update_dispatch_busy(hctx, true);
2697 __blk_mq_requeue_request(rq);
2698 break;
2699 default:
2700 blk_mq_update_dispatch_busy(hctx, false);
2701 break;
2704 return ret;
2707 static bool blk_mq_get_budget_and_tag(struct request *rq)
2709 int budget_token;
2711 budget_token = blk_mq_get_dispatch_budget(rq->q);
2712 if (budget_token < 0)
2713 return false;
2714 blk_mq_set_rq_budget_token(rq, budget_token);
2715 if (!blk_mq_get_driver_tag(rq)) {
2716 blk_mq_put_dispatch_budget(rq->q, budget_token);
2717 return false;
2719 return true;
2723 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2724 * @hctx: Pointer of the associated hardware queue.
2725 * @rq: Pointer to request to be sent.
2727 * If the device has enough resources to accept a new request now, send the
2728 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2729 * we can try send it another time in the future. Requests inserted at this
2730 * queue have higher priority.
2732 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2733 struct request *rq)
2735 blk_status_t ret;
2737 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2738 blk_mq_insert_request(rq, 0);
2739 blk_mq_run_hw_queue(hctx, false);
2740 return;
2743 if ((rq->rq_flags & RQF_USE_SCHED) || !blk_mq_get_budget_and_tag(rq)) {
2744 blk_mq_insert_request(rq, 0);
2745 blk_mq_run_hw_queue(hctx, rq->cmd_flags & REQ_NOWAIT);
2746 return;
2749 ret = __blk_mq_issue_directly(hctx, rq, true);
2750 switch (ret) {
2751 case BLK_STS_OK:
2752 break;
2753 case BLK_STS_RESOURCE:
2754 case BLK_STS_DEV_RESOURCE:
2755 blk_mq_request_bypass_insert(rq, 0);
2756 blk_mq_run_hw_queue(hctx, false);
2757 break;
2758 default:
2759 blk_mq_end_request(rq, ret);
2760 break;
2764 static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2766 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2768 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2769 blk_mq_insert_request(rq, 0);
2770 blk_mq_run_hw_queue(hctx, false);
2771 return BLK_STS_OK;
2774 if (!blk_mq_get_budget_and_tag(rq))
2775 return BLK_STS_RESOURCE;
2776 return __blk_mq_issue_directly(hctx, rq, last);
2779 static void blk_mq_plug_issue_direct(struct blk_plug *plug)
2781 struct blk_mq_hw_ctx *hctx = NULL;
2782 struct request *rq;
2783 int queued = 0;
2784 blk_status_t ret = BLK_STS_OK;
2786 while ((rq = rq_list_pop(&plug->mq_list))) {
2787 bool last = rq_list_empty(&plug->mq_list);
2789 if (hctx != rq->mq_hctx) {
2790 if (hctx) {
2791 blk_mq_commit_rqs(hctx, queued, false);
2792 queued = 0;
2794 hctx = rq->mq_hctx;
2797 ret = blk_mq_request_issue_directly(rq, last);
2798 switch (ret) {
2799 case BLK_STS_OK:
2800 queued++;
2801 break;
2802 case BLK_STS_RESOURCE:
2803 case BLK_STS_DEV_RESOURCE:
2804 blk_mq_request_bypass_insert(rq, 0);
2805 blk_mq_run_hw_queue(hctx, false);
2806 goto out;
2807 default:
2808 blk_mq_end_request(rq, ret);
2809 break;
2813 out:
2814 if (ret != BLK_STS_OK)
2815 blk_mq_commit_rqs(hctx, queued, false);
2818 static void __blk_mq_flush_plug_list(struct request_queue *q,
2819 struct blk_plug *plug)
2821 if (blk_queue_quiesced(q))
2822 return;
2823 q->mq_ops->queue_rqs(&plug->mq_list);
2826 static void blk_mq_dispatch_plug_list(struct blk_plug *plug, bool from_sched)
2828 struct blk_mq_hw_ctx *this_hctx = NULL;
2829 struct blk_mq_ctx *this_ctx = NULL;
2830 struct rq_list requeue_list = {};
2831 unsigned int depth = 0;
2832 bool is_passthrough = false;
2833 LIST_HEAD(list);
2835 do {
2836 struct request *rq = rq_list_pop(&plug->mq_list);
2838 if (!this_hctx) {
2839 this_hctx = rq->mq_hctx;
2840 this_ctx = rq->mq_ctx;
2841 is_passthrough = blk_rq_is_passthrough(rq);
2842 } else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx ||
2843 is_passthrough != blk_rq_is_passthrough(rq)) {
2844 rq_list_add_tail(&requeue_list, rq);
2845 continue;
2847 list_add_tail(&rq->queuelist, &list);
2848 depth++;
2849 } while (!rq_list_empty(&plug->mq_list));
2851 plug->mq_list = requeue_list;
2852 trace_block_unplug(this_hctx->queue, depth, !from_sched);
2854 percpu_ref_get(&this_hctx->queue->q_usage_counter);
2855 /* passthrough requests should never be issued to the I/O scheduler */
2856 if (is_passthrough) {
2857 spin_lock(&this_hctx->lock);
2858 list_splice_tail_init(&list, &this_hctx->dispatch);
2859 spin_unlock(&this_hctx->lock);
2860 blk_mq_run_hw_queue(this_hctx, from_sched);
2861 } else if (this_hctx->queue->elevator) {
2862 this_hctx->queue->elevator->type->ops.insert_requests(this_hctx,
2863 &list, 0);
2864 blk_mq_run_hw_queue(this_hctx, from_sched);
2865 } else {
2866 blk_mq_insert_requests(this_hctx, this_ctx, &list, from_sched);
2868 percpu_ref_put(&this_hctx->queue->q_usage_counter);
2871 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2873 struct request *rq;
2874 unsigned int depth;
2877 * We may have been called recursively midway through handling
2878 * plug->mq_list via a schedule() in the driver's queue_rq() callback.
2879 * To avoid mq_list changing under our feet, clear rq_count early and
2880 * bail out specifically if rq_count is 0 rather than checking
2881 * whether the mq_list is empty.
2883 if (plug->rq_count == 0)
2884 return;
2885 depth = plug->rq_count;
2886 plug->rq_count = 0;
2888 if (!plug->multiple_queues && !plug->has_elevator && !from_schedule) {
2889 struct request_queue *q;
2891 rq = rq_list_peek(&plug->mq_list);
2892 q = rq->q;
2893 trace_block_unplug(q, depth, true);
2896 * Peek first request and see if we have a ->queue_rqs() hook.
2897 * If we do, we can dispatch the whole plug list in one go. We
2898 * already know at this point that all requests belong to the
2899 * same queue, caller must ensure that's the case.
2901 if (q->mq_ops->queue_rqs) {
2902 blk_mq_run_dispatch_ops(q,
2903 __blk_mq_flush_plug_list(q, plug));
2904 if (rq_list_empty(&plug->mq_list))
2905 return;
2908 blk_mq_run_dispatch_ops(q,
2909 blk_mq_plug_issue_direct(plug));
2910 if (rq_list_empty(&plug->mq_list))
2911 return;
2914 do {
2915 blk_mq_dispatch_plug_list(plug, from_schedule);
2916 } while (!rq_list_empty(&plug->mq_list));
2919 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2920 struct list_head *list)
2922 int queued = 0;
2923 blk_status_t ret = BLK_STS_OK;
2925 while (!list_empty(list)) {
2926 struct request *rq = list_first_entry(list, struct request,
2927 queuelist);
2929 list_del_init(&rq->queuelist);
2930 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2931 switch (ret) {
2932 case BLK_STS_OK:
2933 queued++;
2934 break;
2935 case BLK_STS_RESOURCE:
2936 case BLK_STS_DEV_RESOURCE:
2937 blk_mq_request_bypass_insert(rq, 0);
2938 if (list_empty(list))
2939 blk_mq_run_hw_queue(hctx, false);
2940 goto out;
2941 default:
2942 blk_mq_end_request(rq, ret);
2943 break;
2947 out:
2948 if (ret != BLK_STS_OK)
2949 blk_mq_commit_rqs(hctx, queued, false);
2952 static bool blk_mq_attempt_bio_merge(struct request_queue *q,
2953 struct bio *bio, unsigned int nr_segs)
2955 if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
2956 if (blk_attempt_plug_merge(q, bio, nr_segs))
2957 return true;
2958 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2959 return true;
2961 return false;
2964 static struct request *blk_mq_get_new_requests(struct request_queue *q,
2965 struct blk_plug *plug,
2966 struct bio *bio,
2967 unsigned int nsegs)
2969 struct blk_mq_alloc_data data = {
2970 .q = q,
2971 .nr_tags = 1,
2972 .cmd_flags = bio->bi_opf,
2974 struct request *rq;
2976 rq_qos_throttle(q, bio);
2978 if (plug) {
2979 data.nr_tags = plug->nr_ios;
2980 plug->nr_ios = 1;
2981 data.cached_rqs = &plug->cached_rqs;
2984 rq = __blk_mq_alloc_requests(&data);
2985 if (rq)
2986 return rq;
2987 rq_qos_cleanup(q, bio);
2988 if (bio->bi_opf & REQ_NOWAIT)
2989 bio_wouldblock_error(bio);
2990 return NULL;
2994 * Check if there is a suitable cached request and return it.
2996 static struct request *blk_mq_peek_cached_request(struct blk_plug *plug,
2997 struct request_queue *q, blk_opf_t opf)
2999 enum hctx_type type = blk_mq_get_hctx_type(opf);
3000 struct request *rq;
3002 if (!plug)
3003 return NULL;
3004 rq = rq_list_peek(&plug->cached_rqs);
3005 if (!rq || rq->q != q)
3006 return NULL;
3007 if (type != rq->mq_hctx->type &&
3008 (type != HCTX_TYPE_READ || rq->mq_hctx->type != HCTX_TYPE_DEFAULT))
3009 return NULL;
3010 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
3011 return NULL;
3012 return rq;
3015 static void blk_mq_use_cached_rq(struct request *rq, struct blk_plug *plug,
3016 struct bio *bio)
3018 if (rq_list_pop(&plug->cached_rqs) != rq)
3019 WARN_ON_ONCE(1);
3022 * If any qos ->throttle() end up blocking, we will have flushed the
3023 * plug and hence killed the cached_rq list as well. Pop this entry
3024 * before we throttle.
3026 rq_qos_throttle(rq->q, bio);
3028 blk_mq_rq_time_init(rq, blk_time_get_ns());
3029 rq->cmd_flags = bio->bi_opf;
3030 INIT_LIST_HEAD(&rq->queuelist);
3033 static bool bio_unaligned(const struct bio *bio, struct request_queue *q)
3035 unsigned int bs_mask = queue_logical_block_size(q) - 1;
3037 /* .bi_sector of any zero sized bio need to be initialized */
3038 if ((bio->bi_iter.bi_size & bs_mask) ||
3039 ((bio->bi_iter.bi_sector << SECTOR_SHIFT) & bs_mask))
3040 return true;
3041 return false;
3045 * blk_mq_submit_bio - Create and send a request to block device.
3046 * @bio: Bio pointer.
3048 * Builds up a request structure from @q and @bio and send to the device. The
3049 * request may not be queued directly to hardware if:
3050 * * This request can be merged with another one
3051 * * We want to place request at plug queue for possible future merging
3052 * * There is an IO scheduler active at this queue
3054 * It will not queue the request if there is an error with the bio, or at the
3055 * request creation.
3057 void blk_mq_submit_bio(struct bio *bio)
3059 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
3060 struct blk_plug *plug = current->plug;
3061 const int is_sync = op_is_sync(bio->bi_opf);
3062 struct blk_mq_hw_ctx *hctx;
3063 unsigned int nr_segs;
3064 struct request *rq;
3065 blk_status_t ret;
3068 * If the plug has a cached request for this queue, try to use it.
3070 rq = blk_mq_peek_cached_request(plug, q, bio->bi_opf);
3073 * A BIO that was released from a zone write plug has already been
3074 * through the preparation in this function, already holds a reference
3075 * on the queue usage counter, and is the only write BIO in-flight for
3076 * the target zone. Go straight to preparing a request for it.
3078 if (bio_zone_write_plugging(bio)) {
3079 nr_segs = bio->__bi_nr_segments;
3080 if (rq)
3081 blk_queue_exit(q);
3082 goto new_request;
3085 bio = blk_queue_bounce(bio, q);
3088 * The cached request already holds a q_usage_counter reference and we
3089 * don't have to acquire a new one if we use it.
3091 if (!rq) {
3092 if (unlikely(bio_queue_enter(bio)))
3093 return;
3097 * Device reconfiguration may change logical block size, so alignment
3098 * check has to be done with queue usage counter held
3100 if (unlikely(bio_unaligned(bio, q))) {
3101 bio_io_error(bio);
3102 goto queue_exit;
3105 bio = __bio_split_to_limits(bio, &q->limits, &nr_segs);
3106 if (!bio)
3107 goto queue_exit;
3109 if (!bio_integrity_prep(bio))
3110 goto queue_exit;
3112 if (blk_mq_attempt_bio_merge(q, bio, nr_segs))
3113 goto queue_exit;
3115 if (blk_queue_is_zoned(q) && blk_zone_plug_bio(bio, nr_segs))
3116 goto queue_exit;
3118 new_request:
3119 if (!rq) {
3120 rq = blk_mq_get_new_requests(q, plug, bio, nr_segs);
3121 if (unlikely(!rq))
3122 goto queue_exit;
3123 } else {
3124 blk_mq_use_cached_rq(rq, plug, bio);
3127 trace_block_getrq(bio);
3129 rq_qos_track(q, rq, bio);
3131 blk_mq_bio_to_request(rq, bio, nr_segs);
3133 ret = blk_crypto_rq_get_keyslot(rq);
3134 if (ret != BLK_STS_OK) {
3135 bio->bi_status = ret;
3136 bio_endio(bio);
3137 blk_mq_free_request(rq);
3138 return;
3141 if (bio_zone_write_plugging(bio))
3142 blk_zone_write_plug_init_request(rq);
3144 if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
3145 return;
3147 if (plug) {
3148 blk_add_rq_to_plug(plug, rq);
3149 return;
3152 hctx = rq->mq_hctx;
3153 if ((rq->rq_flags & RQF_USE_SCHED) ||
3154 (hctx->dispatch_busy && (q->nr_hw_queues == 1 || !is_sync))) {
3155 blk_mq_insert_request(rq, 0);
3156 blk_mq_run_hw_queue(hctx, true);
3157 } else {
3158 blk_mq_run_dispatch_ops(q, blk_mq_try_issue_directly(hctx, rq));
3160 return;
3162 queue_exit:
3164 * Don't drop the queue reference if we were trying to use a cached
3165 * request and thus didn't acquire one.
3167 if (!rq)
3168 blk_queue_exit(q);
3171 #ifdef CONFIG_BLK_MQ_STACKING
3173 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
3174 * @rq: the request being queued
3176 blk_status_t blk_insert_cloned_request(struct request *rq)
3178 struct request_queue *q = rq->q;
3179 unsigned int max_sectors = blk_queue_get_max_sectors(rq);
3180 unsigned int max_segments = blk_rq_get_max_segments(rq);
3181 blk_status_t ret;
3183 if (blk_rq_sectors(rq) > max_sectors) {
3185 * SCSI device does not have a good way to return if
3186 * Write Same/Zero is actually supported. If a device rejects
3187 * a non-read/write command (discard, write same,etc.) the
3188 * low-level device driver will set the relevant queue limit to
3189 * 0 to prevent blk-lib from issuing more of the offending
3190 * operations. Commands queued prior to the queue limit being
3191 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
3192 * errors being propagated to upper layers.
3194 if (max_sectors == 0)
3195 return BLK_STS_NOTSUPP;
3197 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
3198 __func__, blk_rq_sectors(rq), max_sectors);
3199 return BLK_STS_IOERR;
3203 * The queue settings related to segment counting may differ from the
3204 * original queue.
3206 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
3207 if (rq->nr_phys_segments > max_segments) {
3208 printk(KERN_ERR "%s: over max segments limit. (%u > %u)\n",
3209 __func__, rq->nr_phys_segments, max_segments);
3210 return BLK_STS_IOERR;
3213 if (q->disk && should_fail_request(q->disk->part0, blk_rq_bytes(rq)))
3214 return BLK_STS_IOERR;
3216 ret = blk_crypto_rq_get_keyslot(rq);
3217 if (ret != BLK_STS_OK)
3218 return ret;
3220 blk_account_io_start(rq);
3223 * Since we have a scheduler attached on the top device,
3224 * bypass a potential scheduler on the bottom device for
3225 * insert.
3227 blk_mq_run_dispatch_ops(q,
3228 ret = blk_mq_request_issue_directly(rq, true));
3229 if (ret)
3230 blk_account_io_done(rq, blk_time_get_ns());
3231 return ret;
3233 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
3236 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3237 * @rq: the clone request to be cleaned up
3239 * Description:
3240 * Free all bios in @rq for a cloned request.
3242 void blk_rq_unprep_clone(struct request *rq)
3244 struct bio *bio;
3246 while ((bio = rq->bio) != NULL) {
3247 rq->bio = bio->bi_next;
3249 bio_put(bio);
3252 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3255 * blk_rq_prep_clone - Helper function to setup clone request
3256 * @rq: the request to be setup
3257 * @rq_src: original request to be cloned
3258 * @bs: bio_set that bios for clone are allocated from
3259 * @gfp_mask: memory allocation mask for bio
3260 * @bio_ctr: setup function to be called for each clone bio.
3261 * Returns %0 for success, non %0 for failure.
3262 * @data: private data to be passed to @bio_ctr
3264 * Description:
3265 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3266 * Also, pages which the original bios are pointing to are not copied
3267 * and the cloned bios just point same pages.
3268 * So cloned bios must be completed before original bios, which means
3269 * the caller must complete @rq before @rq_src.
3271 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3272 struct bio_set *bs, gfp_t gfp_mask,
3273 int (*bio_ctr)(struct bio *, struct bio *, void *),
3274 void *data)
3276 struct bio *bio_src;
3278 if (!bs)
3279 bs = &fs_bio_set;
3281 __rq_for_each_bio(bio_src, rq_src) {
3282 struct bio *bio = bio_alloc_clone(rq->q->disk->part0, bio_src,
3283 gfp_mask, bs);
3284 if (!bio)
3285 goto free_and_out;
3287 if (bio_ctr && bio_ctr(bio, bio_src, data)) {
3288 bio_put(bio);
3289 goto free_and_out;
3292 if (rq->bio) {
3293 rq->biotail->bi_next = bio;
3294 rq->biotail = bio;
3295 } else {
3296 rq->bio = rq->biotail = bio;
3300 /* Copy attributes of the original request to the clone request. */
3301 rq->__sector = blk_rq_pos(rq_src);
3302 rq->__data_len = blk_rq_bytes(rq_src);
3303 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
3304 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
3305 rq->special_vec = rq_src->special_vec;
3307 rq->nr_phys_segments = rq_src->nr_phys_segments;
3309 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
3310 goto free_and_out;
3312 return 0;
3314 free_and_out:
3315 blk_rq_unprep_clone(rq);
3317 return -ENOMEM;
3319 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3320 #endif /* CONFIG_BLK_MQ_STACKING */
3323 * Steal bios from a request and add them to a bio list.
3324 * The request must not have been partially completed before.
3326 void blk_steal_bios(struct bio_list *list, struct request *rq)
3328 if (rq->bio) {
3329 if (list->tail)
3330 list->tail->bi_next = rq->bio;
3331 else
3332 list->head = rq->bio;
3333 list->tail = rq->biotail;
3335 rq->bio = NULL;
3336 rq->biotail = NULL;
3339 rq->__data_len = 0;
3341 EXPORT_SYMBOL_GPL(blk_steal_bios);
3343 static size_t order_to_size(unsigned int order)
3345 return (size_t)PAGE_SIZE << order;
3348 /* called before freeing request pool in @tags */
3349 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3350 struct blk_mq_tags *tags)
3352 struct page *page;
3353 unsigned long flags;
3356 * There is no need to clear mapping if driver tags is not initialized
3357 * or the mapping belongs to the driver tags.
3359 if (!drv_tags || drv_tags == tags)
3360 return;
3362 list_for_each_entry(page, &tags->page_list, lru) {
3363 unsigned long start = (unsigned long)page_address(page);
3364 unsigned long end = start + order_to_size(page->private);
3365 int i;
3367 for (i = 0; i < drv_tags->nr_tags; i++) {
3368 struct request *rq = drv_tags->rqs[i];
3369 unsigned long rq_addr = (unsigned long)rq;
3371 if (rq_addr >= start && rq_addr < end) {
3372 WARN_ON_ONCE(req_ref_read(rq) != 0);
3373 cmpxchg(&drv_tags->rqs[i], rq, NULL);
3379 * Wait until all pending iteration is done.
3381 * Request reference is cleared and it is guaranteed to be observed
3382 * after the ->lock is released.
3384 spin_lock_irqsave(&drv_tags->lock, flags);
3385 spin_unlock_irqrestore(&drv_tags->lock, flags);
3388 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3389 unsigned int hctx_idx)
3391 struct blk_mq_tags *drv_tags;
3392 struct page *page;
3394 if (list_empty(&tags->page_list))
3395 return;
3397 if (blk_mq_is_shared_tags(set->flags))
3398 drv_tags = set->shared_tags;
3399 else
3400 drv_tags = set->tags[hctx_idx];
3402 if (tags->static_rqs && set->ops->exit_request) {
3403 int i;
3405 for (i = 0; i < tags->nr_tags; i++) {
3406 struct request *rq = tags->static_rqs[i];
3408 if (!rq)
3409 continue;
3410 set->ops->exit_request(set, rq, hctx_idx);
3411 tags->static_rqs[i] = NULL;
3415 blk_mq_clear_rq_mapping(drv_tags, tags);
3417 while (!list_empty(&tags->page_list)) {
3418 page = list_first_entry(&tags->page_list, struct page, lru);
3419 list_del_init(&page->lru);
3421 * Remove kmemleak object previously allocated in
3422 * blk_mq_alloc_rqs().
3424 kmemleak_free(page_address(page));
3425 __free_pages(page, page->private);
3429 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
3431 kfree(tags->rqs);
3432 tags->rqs = NULL;
3433 kfree(tags->static_rqs);
3434 tags->static_rqs = NULL;
3436 blk_mq_free_tags(tags);
3439 static enum hctx_type hctx_idx_to_type(struct blk_mq_tag_set *set,
3440 unsigned int hctx_idx)
3442 int i;
3444 for (i = 0; i < set->nr_maps; i++) {
3445 unsigned int start = set->map[i].queue_offset;
3446 unsigned int end = start + set->map[i].nr_queues;
3448 if (hctx_idx >= start && hctx_idx < end)
3449 break;
3452 if (i >= set->nr_maps)
3453 i = HCTX_TYPE_DEFAULT;
3455 return i;
3458 static int blk_mq_get_hctx_node(struct blk_mq_tag_set *set,
3459 unsigned int hctx_idx)
3461 enum hctx_type type = hctx_idx_to_type(set, hctx_idx);
3463 return blk_mq_hw_queue_to_node(&set->map[type], hctx_idx);
3466 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3467 unsigned int hctx_idx,
3468 unsigned int nr_tags,
3469 unsigned int reserved_tags)
3471 int node = blk_mq_get_hctx_node(set, hctx_idx);
3472 struct blk_mq_tags *tags;
3474 if (node == NUMA_NO_NODE)
3475 node = set->numa_node;
3477 tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
3478 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
3479 if (!tags)
3480 return NULL;
3482 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3483 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3484 node);
3485 if (!tags->rqs)
3486 goto err_free_tags;
3488 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3489 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3490 node);
3491 if (!tags->static_rqs)
3492 goto err_free_rqs;
3494 return tags;
3496 err_free_rqs:
3497 kfree(tags->rqs);
3498 err_free_tags:
3499 blk_mq_free_tags(tags);
3500 return NULL;
3503 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3504 unsigned int hctx_idx, int node)
3506 int ret;
3508 if (set->ops->init_request) {
3509 ret = set->ops->init_request(set, rq, hctx_idx, node);
3510 if (ret)
3511 return ret;
3514 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3515 return 0;
3518 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3519 struct blk_mq_tags *tags,
3520 unsigned int hctx_idx, unsigned int depth)
3522 unsigned int i, j, entries_per_page, max_order = 4;
3523 int node = blk_mq_get_hctx_node(set, hctx_idx);
3524 size_t rq_size, left;
3526 if (node == NUMA_NO_NODE)
3527 node = set->numa_node;
3529 INIT_LIST_HEAD(&tags->page_list);
3532 * rq_size is the size of the request plus driver payload, rounded
3533 * to the cacheline size
3535 rq_size = round_up(sizeof(struct request) + set->cmd_size,
3536 cache_line_size());
3537 left = rq_size * depth;
3539 for (i = 0; i < depth; ) {
3540 int this_order = max_order;
3541 struct page *page;
3542 int to_do;
3543 void *p;
3545 while (this_order && left < order_to_size(this_order - 1))
3546 this_order--;
3548 do {
3549 page = alloc_pages_node(node,
3550 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3551 this_order);
3552 if (page)
3553 break;
3554 if (!this_order--)
3555 break;
3556 if (order_to_size(this_order) < rq_size)
3557 break;
3558 } while (1);
3560 if (!page)
3561 goto fail;
3563 page->private = this_order;
3564 list_add_tail(&page->lru, &tags->page_list);
3566 p = page_address(page);
3568 * Allow kmemleak to scan these pages as they contain pointers
3569 * to additional allocations like via ops->init_request().
3571 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3572 entries_per_page = order_to_size(this_order) / rq_size;
3573 to_do = min(entries_per_page, depth - i);
3574 left -= to_do * rq_size;
3575 for (j = 0; j < to_do; j++) {
3576 struct request *rq = p;
3578 tags->static_rqs[i] = rq;
3579 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3580 tags->static_rqs[i] = NULL;
3581 goto fail;
3584 p += rq_size;
3585 i++;
3588 return 0;
3590 fail:
3591 blk_mq_free_rqs(set, tags, hctx_idx);
3592 return -ENOMEM;
3595 struct rq_iter_data {
3596 struct blk_mq_hw_ctx *hctx;
3597 bool has_rq;
3600 static bool blk_mq_has_request(struct request *rq, void *data)
3602 struct rq_iter_data *iter_data = data;
3604 if (rq->mq_hctx != iter_data->hctx)
3605 return true;
3606 iter_data->has_rq = true;
3607 return false;
3610 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3612 struct blk_mq_tags *tags = hctx->sched_tags ?
3613 hctx->sched_tags : hctx->tags;
3614 struct rq_iter_data data = {
3615 .hctx = hctx,
3618 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3619 return data.has_rq;
3622 static bool blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx *hctx,
3623 unsigned int this_cpu)
3625 enum hctx_type type = hctx->type;
3626 int cpu;
3629 * hctx->cpumask has to rule out isolated CPUs, but userspace still
3630 * might submit IOs on these isolated CPUs, so use the queue map to
3631 * check if all CPUs mapped to this hctx are offline
3633 for_each_online_cpu(cpu) {
3634 struct blk_mq_hw_ctx *h = blk_mq_map_queue_type(hctx->queue,
3635 type, cpu);
3637 if (h != hctx)
3638 continue;
3640 /* this hctx has at least one online CPU */
3641 if (this_cpu != cpu)
3642 return true;
3645 return false;
3648 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3650 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3651 struct blk_mq_hw_ctx, cpuhp_online);
3653 if (blk_mq_hctx_has_online_cpu(hctx, cpu))
3654 return 0;
3657 * Prevent new request from being allocated on the current hctx.
3659 * The smp_mb__after_atomic() Pairs with the implied barrier in
3660 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
3661 * seen once we return from the tag allocator.
3663 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3664 smp_mb__after_atomic();
3667 * Try to grab a reference to the queue and wait for any outstanding
3668 * requests. If we could not grab a reference the queue has been
3669 * frozen and there are no requests.
3671 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3672 while (blk_mq_hctx_has_requests(hctx))
3673 msleep(5);
3674 percpu_ref_put(&hctx->queue->q_usage_counter);
3677 return 0;
3681 * Check if one CPU is mapped to the specified hctx
3683 * Isolated CPUs have been ruled out from hctx->cpumask, which is supposed
3684 * to be used for scheduling kworker only. For other usage, please call this
3685 * helper for checking if one CPU belongs to the specified hctx
3687 static bool blk_mq_cpu_mapped_to_hctx(unsigned int cpu,
3688 const struct blk_mq_hw_ctx *hctx)
3690 struct blk_mq_hw_ctx *mapped_hctx = blk_mq_map_queue_type(hctx->queue,
3691 hctx->type, cpu);
3693 return mapped_hctx == hctx;
3696 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3698 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3699 struct blk_mq_hw_ctx, cpuhp_online);
3701 if (blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3702 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3703 return 0;
3707 * 'cpu' is going away. splice any existing rq_list entries from this
3708 * software queue to the hw queue dispatch list, and ensure that it
3709 * gets run.
3711 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3713 struct blk_mq_hw_ctx *hctx;
3714 struct blk_mq_ctx *ctx;
3715 LIST_HEAD(tmp);
3716 enum hctx_type type;
3718 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3719 if (!blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3720 return 0;
3722 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3723 type = hctx->type;
3725 spin_lock(&ctx->lock);
3726 if (!list_empty(&ctx->rq_lists[type])) {
3727 list_splice_init(&ctx->rq_lists[type], &tmp);
3728 blk_mq_hctx_clear_pending(hctx, ctx);
3730 spin_unlock(&ctx->lock);
3732 if (list_empty(&tmp))
3733 return 0;
3735 spin_lock(&hctx->lock);
3736 list_splice_tail_init(&tmp, &hctx->dispatch);
3737 spin_unlock(&hctx->lock);
3739 blk_mq_run_hw_queue(hctx, true);
3740 return 0;
3743 static void __blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3745 lockdep_assert_held(&blk_mq_cpuhp_lock);
3747 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3748 !hlist_unhashed(&hctx->cpuhp_online)) {
3749 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3750 &hctx->cpuhp_online);
3751 INIT_HLIST_NODE(&hctx->cpuhp_online);
3754 if (!hlist_unhashed(&hctx->cpuhp_dead)) {
3755 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3756 &hctx->cpuhp_dead);
3757 INIT_HLIST_NODE(&hctx->cpuhp_dead);
3761 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3763 mutex_lock(&blk_mq_cpuhp_lock);
3764 __blk_mq_remove_cpuhp(hctx);
3765 mutex_unlock(&blk_mq_cpuhp_lock);
3768 static void __blk_mq_add_cpuhp(struct blk_mq_hw_ctx *hctx)
3770 lockdep_assert_held(&blk_mq_cpuhp_lock);
3772 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3773 hlist_unhashed(&hctx->cpuhp_online))
3774 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3775 &hctx->cpuhp_online);
3777 if (hlist_unhashed(&hctx->cpuhp_dead))
3778 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3779 &hctx->cpuhp_dead);
3782 static void __blk_mq_remove_cpuhp_list(struct list_head *head)
3784 struct blk_mq_hw_ctx *hctx;
3786 lockdep_assert_held(&blk_mq_cpuhp_lock);
3788 list_for_each_entry(hctx, head, hctx_list)
3789 __blk_mq_remove_cpuhp(hctx);
3793 * Unregister cpuhp callbacks from exited hw queues
3795 * Safe to call if this `request_queue` is live
3797 static void blk_mq_remove_hw_queues_cpuhp(struct request_queue *q)
3799 LIST_HEAD(hctx_list);
3801 spin_lock(&q->unused_hctx_lock);
3802 list_splice_init(&q->unused_hctx_list, &hctx_list);
3803 spin_unlock(&q->unused_hctx_lock);
3805 mutex_lock(&blk_mq_cpuhp_lock);
3806 __blk_mq_remove_cpuhp_list(&hctx_list);
3807 mutex_unlock(&blk_mq_cpuhp_lock);
3809 spin_lock(&q->unused_hctx_lock);
3810 list_splice(&hctx_list, &q->unused_hctx_list);
3811 spin_unlock(&q->unused_hctx_lock);
3815 * Register cpuhp callbacks from all hw queues
3817 * Safe to call if this `request_queue` is live
3819 static void blk_mq_add_hw_queues_cpuhp(struct request_queue *q)
3821 struct blk_mq_hw_ctx *hctx;
3822 unsigned long i;
3824 mutex_lock(&blk_mq_cpuhp_lock);
3825 queue_for_each_hw_ctx(q, hctx, i)
3826 __blk_mq_add_cpuhp(hctx);
3827 mutex_unlock(&blk_mq_cpuhp_lock);
3831 * Before freeing hw queue, clearing the flush request reference in
3832 * tags->rqs[] for avoiding potential UAF.
3834 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3835 unsigned int queue_depth, struct request *flush_rq)
3837 int i;
3838 unsigned long flags;
3840 /* The hw queue may not be mapped yet */
3841 if (!tags)
3842 return;
3844 WARN_ON_ONCE(req_ref_read(flush_rq) != 0);
3846 for (i = 0; i < queue_depth; i++)
3847 cmpxchg(&tags->rqs[i], flush_rq, NULL);
3850 * Wait until all pending iteration is done.
3852 * Request reference is cleared and it is guaranteed to be observed
3853 * after the ->lock is released.
3855 spin_lock_irqsave(&tags->lock, flags);
3856 spin_unlock_irqrestore(&tags->lock, flags);
3859 /* hctx->ctxs will be freed in queue's release handler */
3860 static void blk_mq_exit_hctx(struct request_queue *q,
3861 struct blk_mq_tag_set *set,
3862 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3864 struct request *flush_rq = hctx->fq->flush_rq;
3866 if (blk_mq_hw_queue_mapped(hctx))
3867 blk_mq_tag_idle(hctx);
3869 if (blk_queue_init_done(q))
3870 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3871 set->queue_depth, flush_rq);
3872 if (set->ops->exit_request)
3873 set->ops->exit_request(set, flush_rq, hctx_idx);
3875 if (set->ops->exit_hctx)
3876 set->ops->exit_hctx(hctx, hctx_idx);
3878 xa_erase(&q->hctx_table, hctx_idx);
3880 spin_lock(&q->unused_hctx_lock);
3881 list_add(&hctx->hctx_list, &q->unused_hctx_list);
3882 spin_unlock(&q->unused_hctx_lock);
3885 static void blk_mq_exit_hw_queues(struct request_queue *q,
3886 struct blk_mq_tag_set *set, int nr_queue)
3888 struct blk_mq_hw_ctx *hctx;
3889 unsigned long i;
3891 queue_for_each_hw_ctx(q, hctx, i) {
3892 if (i == nr_queue)
3893 break;
3894 blk_mq_remove_cpuhp(hctx);
3895 blk_mq_exit_hctx(q, set, hctx, i);
3899 static int blk_mq_init_hctx(struct request_queue *q,
3900 struct blk_mq_tag_set *set,
3901 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3903 hctx->queue_num = hctx_idx;
3905 hctx->tags = set->tags[hctx_idx];
3907 if (set->ops->init_hctx &&
3908 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3909 goto fail;
3911 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3912 hctx->numa_node))
3913 goto exit_hctx;
3915 if (xa_insert(&q->hctx_table, hctx_idx, hctx, GFP_KERNEL))
3916 goto exit_flush_rq;
3918 return 0;
3920 exit_flush_rq:
3921 if (set->ops->exit_request)
3922 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
3923 exit_hctx:
3924 if (set->ops->exit_hctx)
3925 set->ops->exit_hctx(hctx, hctx_idx);
3926 fail:
3927 return -1;
3930 static struct blk_mq_hw_ctx *
3931 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3932 int node)
3934 struct blk_mq_hw_ctx *hctx;
3935 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3937 hctx = kzalloc_node(sizeof(struct blk_mq_hw_ctx), gfp, node);
3938 if (!hctx)
3939 goto fail_alloc_hctx;
3941 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
3942 goto free_hctx;
3944 atomic_set(&hctx->nr_active, 0);
3945 if (node == NUMA_NO_NODE)
3946 node = set->numa_node;
3947 hctx->numa_node = node;
3949 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
3950 spin_lock_init(&hctx->lock);
3951 INIT_LIST_HEAD(&hctx->dispatch);
3952 INIT_HLIST_NODE(&hctx->cpuhp_dead);
3953 INIT_HLIST_NODE(&hctx->cpuhp_online);
3954 hctx->queue = q;
3955 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
3957 INIT_LIST_HEAD(&hctx->hctx_list);
3960 * Allocate space for all possible cpus to avoid allocation at
3961 * runtime
3963 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
3964 gfp, node);
3965 if (!hctx->ctxs)
3966 goto free_cpumask;
3968 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
3969 gfp, node, false, false))
3970 goto free_ctxs;
3971 hctx->nr_ctx = 0;
3973 spin_lock_init(&hctx->dispatch_wait_lock);
3974 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
3975 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
3977 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
3978 if (!hctx->fq)
3979 goto free_bitmap;
3981 blk_mq_hctx_kobj_init(hctx);
3983 return hctx;
3985 free_bitmap:
3986 sbitmap_free(&hctx->ctx_map);
3987 free_ctxs:
3988 kfree(hctx->ctxs);
3989 free_cpumask:
3990 free_cpumask_var(hctx->cpumask);
3991 free_hctx:
3992 kfree(hctx);
3993 fail_alloc_hctx:
3994 return NULL;
3997 static void blk_mq_init_cpu_queues(struct request_queue *q,
3998 unsigned int nr_hw_queues)
4000 struct blk_mq_tag_set *set = q->tag_set;
4001 unsigned int i, j;
4003 for_each_possible_cpu(i) {
4004 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
4005 struct blk_mq_hw_ctx *hctx;
4006 int k;
4008 __ctx->cpu = i;
4009 spin_lock_init(&__ctx->lock);
4010 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
4011 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
4013 __ctx->queue = q;
4016 * Set local node, IFF we have more than one hw queue. If
4017 * not, we remain on the home node of the device
4019 for (j = 0; j < set->nr_maps; j++) {
4020 hctx = blk_mq_map_queue_type(q, j, i);
4021 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
4022 hctx->numa_node = cpu_to_node(i);
4027 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4028 unsigned int hctx_idx,
4029 unsigned int depth)
4031 struct blk_mq_tags *tags;
4032 int ret;
4034 tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
4035 if (!tags)
4036 return NULL;
4038 ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
4039 if (ret) {
4040 blk_mq_free_rq_map(tags);
4041 return NULL;
4044 return tags;
4047 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4048 int hctx_idx)
4050 if (blk_mq_is_shared_tags(set->flags)) {
4051 set->tags[hctx_idx] = set->shared_tags;
4053 return true;
4056 set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
4057 set->queue_depth);
4059 return set->tags[hctx_idx];
4062 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4063 struct blk_mq_tags *tags,
4064 unsigned int hctx_idx)
4066 if (tags) {
4067 blk_mq_free_rqs(set, tags, hctx_idx);
4068 blk_mq_free_rq_map(tags);
4072 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4073 unsigned int hctx_idx)
4075 if (!blk_mq_is_shared_tags(set->flags))
4076 blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
4078 set->tags[hctx_idx] = NULL;
4081 static void blk_mq_map_swqueue(struct request_queue *q)
4083 unsigned int j, hctx_idx;
4084 unsigned long i;
4085 struct blk_mq_hw_ctx *hctx;
4086 struct blk_mq_ctx *ctx;
4087 struct blk_mq_tag_set *set = q->tag_set;
4089 queue_for_each_hw_ctx(q, hctx, i) {
4090 cpumask_clear(hctx->cpumask);
4091 hctx->nr_ctx = 0;
4092 hctx->dispatch_from = NULL;
4096 * Map software to hardware queues.
4098 * If the cpu isn't present, the cpu is mapped to first hctx.
4100 for_each_possible_cpu(i) {
4102 ctx = per_cpu_ptr(q->queue_ctx, i);
4103 for (j = 0; j < set->nr_maps; j++) {
4104 if (!set->map[j].nr_queues) {
4105 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4106 HCTX_TYPE_DEFAULT, i);
4107 continue;
4109 hctx_idx = set->map[j].mq_map[i];
4110 /* unmapped hw queue can be remapped after CPU topo changed */
4111 if (!set->tags[hctx_idx] &&
4112 !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4114 * If tags initialization fail for some hctx,
4115 * that hctx won't be brought online. In this
4116 * case, remap the current ctx to hctx[0] which
4117 * is guaranteed to always have tags allocated
4119 set->map[j].mq_map[i] = 0;
4122 hctx = blk_mq_map_queue_type(q, j, i);
4123 ctx->hctxs[j] = hctx;
4125 * If the CPU is already set in the mask, then we've
4126 * mapped this one already. This can happen if
4127 * devices share queues across queue maps.
4129 if (cpumask_test_cpu(i, hctx->cpumask))
4130 continue;
4132 cpumask_set_cpu(i, hctx->cpumask);
4133 hctx->type = j;
4134 ctx->index_hw[hctx->type] = hctx->nr_ctx;
4135 hctx->ctxs[hctx->nr_ctx++] = ctx;
4138 * If the nr_ctx type overflows, we have exceeded the
4139 * amount of sw queues we can support.
4141 BUG_ON(!hctx->nr_ctx);
4144 for (; j < HCTX_MAX_TYPES; j++)
4145 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4146 HCTX_TYPE_DEFAULT, i);
4149 queue_for_each_hw_ctx(q, hctx, i) {
4150 int cpu;
4153 * If no software queues are mapped to this hardware queue,
4154 * disable it and free the request entries.
4156 if (!hctx->nr_ctx) {
4157 /* Never unmap queue 0. We need it as a
4158 * fallback in case of a new remap fails
4159 * allocation
4161 if (i)
4162 __blk_mq_free_map_and_rqs(set, i);
4164 hctx->tags = NULL;
4165 continue;
4168 hctx->tags = set->tags[i];
4169 WARN_ON(!hctx->tags);
4172 * Set the map size to the number of mapped software queues.
4173 * This is more accurate and more efficient than looping
4174 * over all possibly mapped software queues.
4176 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4179 * Rule out isolated CPUs from hctx->cpumask to avoid
4180 * running block kworker on isolated CPUs
4182 for_each_cpu(cpu, hctx->cpumask) {
4183 if (cpu_is_isolated(cpu))
4184 cpumask_clear_cpu(cpu, hctx->cpumask);
4188 * Initialize batch roundrobin counts
4190 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4191 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4196 * Caller needs to ensure that we're either frozen/quiesced, or that
4197 * the queue isn't live yet.
4199 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
4201 struct blk_mq_hw_ctx *hctx;
4202 unsigned long i;
4204 queue_for_each_hw_ctx(q, hctx, i) {
4205 if (shared) {
4206 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4207 } else {
4208 blk_mq_tag_idle(hctx);
4209 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4214 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
4215 bool shared)
4217 struct request_queue *q;
4219 lockdep_assert_held(&set->tag_list_lock);
4221 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4222 blk_mq_freeze_queue(q);
4223 queue_set_hctx_shared(q, shared);
4224 blk_mq_unfreeze_queue(q);
4228 static void blk_mq_del_queue_tag_set(struct request_queue *q)
4230 struct blk_mq_tag_set *set = q->tag_set;
4232 mutex_lock(&set->tag_list_lock);
4233 list_del(&q->tag_set_list);
4234 if (list_is_singular(&set->tag_list)) {
4235 /* just transitioned to unshared */
4236 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4237 /* update existing queue */
4238 blk_mq_update_tag_set_shared(set, false);
4240 mutex_unlock(&set->tag_list_lock);
4241 INIT_LIST_HEAD(&q->tag_set_list);
4244 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4245 struct request_queue *q)
4247 mutex_lock(&set->tag_list_lock);
4250 * Check to see if we're transitioning to shared (from 1 to 2 queues).
4252 if (!list_empty(&set->tag_list) &&
4253 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4254 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4255 /* update existing queue */
4256 blk_mq_update_tag_set_shared(set, true);
4258 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4259 queue_set_hctx_shared(q, true);
4260 list_add_tail(&q->tag_set_list, &set->tag_list);
4262 mutex_unlock(&set->tag_list_lock);
4265 /* All allocations will be freed in release handler of q->mq_kobj */
4266 static int blk_mq_alloc_ctxs(struct request_queue *q)
4268 struct blk_mq_ctxs *ctxs;
4269 int cpu;
4271 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
4272 if (!ctxs)
4273 return -ENOMEM;
4275 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
4276 if (!ctxs->queue_ctx)
4277 goto fail;
4279 for_each_possible_cpu(cpu) {
4280 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
4281 ctx->ctxs = ctxs;
4284 q->mq_kobj = &ctxs->kobj;
4285 q->queue_ctx = ctxs->queue_ctx;
4287 return 0;
4288 fail:
4289 kfree(ctxs);
4290 return -ENOMEM;
4294 * It is the actual release handler for mq, but we do it from
4295 * request queue's release handler for avoiding use-after-free
4296 * and headache because q->mq_kobj shouldn't have been introduced,
4297 * but we can't group ctx/kctx kobj without it.
4299 void blk_mq_release(struct request_queue *q)
4301 struct blk_mq_hw_ctx *hctx, *next;
4302 unsigned long i;
4304 queue_for_each_hw_ctx(q, hctx, i)
4305 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
4307 /* all hctx are in .unused_hctx_list now */
4308 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
4309 list_del_init(&hctx->hctx_list);
4310 kobject_put(&hctx->kobj);
4313 xa_destroy(&q->hctx_table);
4316 * release .mq_kobj and sw queue's kobject now because
4317 * both share lifetime with request queue.
4319 blk_mq_sysfs_deinit(q);
4322 static bool blk_mq_can_poll(struct blk_mq_tag_set *set)
4324 return set->nr_maps > HCTX_TYPE_POLL &&
4325 set->map[HCTX_TYPE_POLL].nr_queues;
4328 struct request_queue *blk_mq_alloc_queue(struct blk_mq_tag_set *set,
4329 struct queue_limits *lim, void *queuedata)
4331 struct queue_limits default_lim = { };
4332 struct request_queue *q;
4333 int ret;
4335 if (!lim)
4336 lim = &default_lim;
4337 lim->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT;
4338 if (blk_mq_can_poll(set))
4339 lim->features |= BLK_FEAT_POLL;
4341 q = blk_alloc_queue(lim, set->numa_node);
4342 if (IS_ERR(q))
4343 return q;
4344 q->queuedata = queuedata;
4345 ret = blk_mq_init_allocated_queue(set, q);
4346 if (ret) {
4347 blk_put_queue(q);
4348 return ERR_PTR(ret);
4350 return q;
4352 EXPORT_SYMBOL(blk_mq_alloc_queue);
4355 * blk_mq_destroy_queue - shutdown a request queue
4356 * @q: request queue to shutdown
4358 * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4359 * requests will be failed with -ENODEV. The caller is responsible for dropping
4360 * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4362 * Context: can sleep
4364 void blk_mq_destroy_queue(struct request_queue *q)
4366 WARN_ON_ONCE(!queue_is_mq(q));
4367 WARN_ON_ONCE(blk_queue_registered(q));
4369 might_sleep();
4371 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4372 blk_queue_start_drain(q);
4373 blk_mq_freeze_queue_wait(q);
4375 blk_sync_queue(q);
4376 blk_mq_cancel_work_sync(q);
4377 blk_mq_exit_queue(q);
4379 EXPORT_SYMBOL(blk_mq_destroy_queue);
4381 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4382 struct queue_limits *lim, void *queuedata,
4383 struct lock_class_key *lkclass)
4385 struct request_queue *q;
4386 struct gendisk *disk;
4388 q = blk_mq_alloc_queue(set, lim, queuedata);
4389 if (IS_ERR(q))
4390 return ERR_CAST(q);
4392 disk = __alloc_disk_node(q, set->numa_node, lkclass);
4393 if (!disk) {
4394 blk_mq_destroy_queue(q);
4395 blk_put_queue(q);
4396 return ERR_PTR(-ENOMEM);
4398 set_bit(GD_OWNS_QUEUE, &disk->state);
4399 return disk;
4401 EXPORT_SYMBOL(__blk_mq_alloc_disk);
4403 struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
4404 struct lock_class_key *lkclass)
4406 struct gendisk *disk;
4408 if (!blk_get_queue(q))
4409 return NULL;
4410 disk = __alloc_disk_node(q, NUMA_NO_NODE, lkclass);
4411 if (!disk)
4412 blk_put_queue(q);
4413 return disk;
4415 EXPORT_SYMBOL(blk_mq_alloc_disk_for_queue);
4417 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
4418 struct blk_mq_tag_set *set, struct request_queue *q,
4419 int hctx_idx, int node)
4421 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
4423 /* reuse dead hctx first */
4424 spin_lock(&q->unused_hctx_lock);
4425 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
4426 if (tmp->numa_node == node) {
4427 hctx = tmp;
4428 break;
4431 if (hctx)
4432 list_del_init(&hctx->hctx_list);
4433 spin_unlock(&q->unused_hctx_lock);
4435 if (!hctx)
4436 hctx = blk_mq_alloc_hctx(q, set, node);
4437 if (!hctx)
4438 goto fail;
4440 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
4441 goto free_hctx;
4443 return hctx;
4445 free_hctx:
4446 kobject_put(&hctx->kobj);
4447 fail:
4448 return NULL;
4451 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4452 struct request_queue *q)
4454 struct blk_mq_hw_ctx *hctx;
4455 unsigned long i, j;
4457 /* protect against switching io scheduler */
4458 mutex_lock(&q->sysfs_lock);
4459 for (i = 0; i < set->nr_hw_queues; i++) {
4460 int old_node;
4461 int node = blk_mq_get_hctx_node(set, i);
4462 struct blk_mq_hw_ctx *old_hctx = xa_load(&q->hctx_table, i);
4464 if (old_hctx) {
4465 old_node = old_hctx->numa_node;
4466 blk_mq_exit_hctx(q, set, old_hctx, i);
4469 if (!blk_mq_alloc_and_init_hctx(set, q, i, node)) {
4470 if (!old_hctx)
4471 break;
4472 pr_warn("Allocate new hctx on node %d fails, fallback to previous one on node %d\n",
4473 node, old_node);
4474 hctx = blk_mq_alloc_and_init_hctx(set, q, i, old_node);
4475 WARN_ON_ONCE(!hctx);
4479 * Increasing nr_hw_queues fails. Free the newly allocated
4480 * hctxs and keep the previous q->nr_hw_queues.
4482 if (i != set->nr_hw_queues) {
4483 j = q->nr_hw_queues;
4484 } else {
4485 j = i;
4486 q->nr_hw_queues = set->nr_hw_queues;
4489 xa_for_each_start(&q->hctx_table, j, hctx, j)
4490 blk_mq_exit_hctx(q, set, hctx, j);
4491 mutex_unlock(&q->sysfs_lock);
4493 /* unregister cpuhp callbacks for exited hctxs */
4494 blk_mq_remove_hw_queues_cpuhp(q);
4496 /* register cpuhp for new initialized hctxs */
4497 blk_mq_add_hw_queues_cpuhp(q);
4500 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4501 struct request_queue *q)
4503 /* mark the queue as mq asap */
4504 q->mq_ops = set->ops;
4507 * ->tag_set has to be setup before initialize hctx, which cpuphp
4508 * handler needs it for checking queue mapping
4510 q->tag_set = set;
4512 if (blk_mq_alloc_ctxs(q))
4513 goto err_exit;
4515 /* init q->mq_kobj and sw queues' kobjects */
4516 blk_mq_sysfs_init(q);
4518 INIT_LIST_HEAD(&q->unused_hctx_list);
4519 spin_lock_init(&q->unused_hctx_lock);
4521 xa_init(&q->hctx_table);
4523 blk_mq_realloc_hw_ctxs(set, q);
4524 if (!q->nr_hw_queues)
4525 goto err_hctxs;
4527 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4528 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4530 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4532 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4533 INIT_LIST_HEAD(&q->flush_list);
4534 INIT_LIST_HEAD(&q->requeue_list);
4535 spin_lock_init(&q->requeue_lock);
4537 q->nr_requests = set->queue_depth;
4539 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4540 blk_mq_add_queue_tag_set(set, q);
4541 blk_mq_map_swqueue(q);
4542 return 0;
4544 err_hctxs:
4545 blk_mq_release(q);
4546 err_exit:
4547 q->mq_ops = NULL;
4548 return -ENOMEM;
4550 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4552 /* tags can _not_ be used after returning from blk_mq_exit_queue */
4553 void blk_mq_exit_queue(struct request_queue *q)
4555 struct blk_mq_tag_set *set = q->tag_set;
4557 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4558 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4559 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4560 blk_mq_del_queue_tag_set(q);
4563 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4565 int i;
4567 if (blk_mq_is_shared_tags(set->flags)) {
4568 set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4569 BLK_MQ_NO_HCTX_IDX,
4570 set->queue_depth);
4571 if (!set->shared_tags)
4572 return -ENOMEM;
4575 for (i = 0; i < set->nr_hw_queues; i++) {
4576 if (!__blk_mq_alloc_map_and_rqs(set, i))
4577 goto out_unwind;
4578 cond_resched();
4581 return 0;
4583 out_unwind:
4584 while (--i >= 0)
4585 __blk_mq_free_map_and_rqs(set, i);
4587 if (blk_mq_is_shared_tags(set->flags)) {
4588 blk_mq_free_map_and_rqs(set, set->shared_tags,
4589 BLK_MQ_NO_HCTX_IDX);
4592 return -ENOMEM;
4596 * Allocate the request maps associated with this tag_set. Note that this
4597 * may reduce the depth asked for, if memory is tight. set->queue_depth
4598 * will be updated to reflect the allocated depth.
4600 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4602 unsigned int depth;
4603 int err;
4605 depth = set->queue_depth;
4606 do {
4607 err = __blk_mq_alloc_rq_maps(set);
4608 if (!err)
4609 break;
4611 set->queue_depth >>= 1;
4612 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4613 err = -ENOMEM;
4614 break;
4616 } while (set->queue_depth);
4618 if (!set->queue_depth || err) {
4619 pr_err("blk-mq: failed to allocate request map\n");
4620 return -ENOMEM;
4623 if (depth != set->queue_depth)
4624 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4625 depth, set->queue_depth);
4627 return 0;
4630 static void blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4633 * blk_mq_map_queues() and multiple .map_queues() implementations
4634 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4635 * number of hardware queues.
4637 if (set->nr_maps == 1)
4638 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4640 if (set->ops->map_queues) {
4641 int i;
4644 * transport .map_queues is usually done in the following
4645 * way:
4647 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4648 * mask = get_cpu_mask(queue)
4649 * for_each_cpu(cpu, mask)
4650 * set->map[x].mq_map[cpu] = queue;
4653 * When we need to remap, the table has to be cleared for
4654 * killing stale mapping since one CPU may not be mapped
4655 * to any hw queue.
4657 for (i = 0; i < set->nr_maps; i++)
4658 blk_mq_clear_mq_map(&set->map[i]);
4660 set->ops->map_queues(set);
4661 } else {
4662 BUG_ON(set->nr_maps > 1);
4663 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4667 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
4668 int new_nr_hw_queues)
4670 struct blk_mq_tags **new_tags;
4671 int i;
4673 if (set->nr_hw_queues >= new_nr_hw_queues)
4674 goto done;
4676 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4677 GFP_KERNEL, set->numa_node);
4678 if (!new_tags)
4679 return -ENOMEM;
4681 if (set->tags)
4682 memcpy(new_tags, set->tags, set->nr_hw_queues *
4683 sizeof(*set->tags));
4684 kfree(set->tags);
4685 set->tags = new_tags;
4687 for (i = set->nr_hw_queues; i < new_nr_hw_queues; i++) {
4688 if (!__blk_mq_alloc_map_and_rqs(set, i)) {
4689 while (--i >= set->nr_hw_queues)
4690 __blk_mq_free_map_and_rqs(set, i);
4691 return -ENOMEM;
4693 cond_resched();
4696 done:
4697 set->nr_hw_queues = new_nr_hw_queues;
4698 return 0;
4702 * Alloc a tag set to be associated with one or more request queues.
4703 * May fail with EINVAL for various error conditions. May adjust the
4704 * requested depth down, if it's too large. In that case, the set
4705 * value will be stored in set->queue_depth.
4707 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4709 int i, ret;
4711 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4713 if (!set->nr_hw_queues)
4714 return -EINVAL;
4715 if (!set->queue_depth)
4716 return -EINVAL;
4717 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4718 return -EINVAL;
4720 if (!set->ops->queue_rq)
4721 return -EINVAL;
4723 if (!set->ops->get_budget ^ !set->ops->put_budget)
4724 return -EINVAL;
4726 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4727 pr_info("blk-mq: reduced tag depth to %u\n",
4728 BLK_MQ_MAX_DEPTH);
4729 set->queue_depth = BLK_MQ_MAX_DEPTH;
4732 if (!set->nr_maps)
4733 set->nr_maps = 1;
4734 else if (set->nr_maps > HCTX_MAX_TYPES)
4735 return -EINVAL;
4738 * If a crashdump is active, then we are potentially in a very
4739 * memory constrained environment. Limit us to 64 tags to prevent
4740 * using too much memory.
4742 if (is_kdump_kernel())
4743 set->queue_depth = min(64U, set->queue_depth);
4746 * There is no use for more h/w queues than cpus if we just have
4747 * a single map
4749 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4750 set->nr_hw_queues = nr_cpu_ids;
4752 if (set->flags & BLK_MQ_F_BLOCKING) {
4753 set->srcu = kmalloc(sizeof(*set->srcu), GFP_KERNEL);
4754 if (!set->srcu)
4755 return -ENOMEM;
4756 ret = init_srcu_struct(set->srcu);
4757 if (ret)
4758 goto out_free_srcu;
4761 ret = -ENOMEM;
4762 set->tags = kcalloc_node(set->nr_hw_queues,
4763 sizeof(struct blk_mq_tags *), GFP_KERNEL,
4764 set->numa_node);
4765 if (!set->tags)
4766 goto out_cleanup_srcu;
4768 for (i = 0; i < set->nr_maps; i++) {
4769 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4770 sizeof(set->map[i].mq_map[0]),
4771 GFP_KERNEL, set->numa_node);
4772 if (!set->map[i].mq_map)
4773 goto out_free_mq_map;
4774 set->map[i].nr_queues = set->nr_hw_queues;
4777 blk_mq_update_queue_map(set);
4779 ret = blk_mq_alloc_set_map_and_rqs(set);
4780 if (ret)
4781 goto out_free_mq_map;
4783 mutex_init(&set->tag_list_lock);
4784 INIT_LIST_HEAD(&set->tag_list);
4786 return 0;
4788 out_free_mq_map:
4789 for (i = 0; i < set->nr_maps; i++) {
4790 kfree(set->map[i].mq_map);
4791 set->map[i].mq_map = NULL;
4793 kfree(set->tags);
4794 set->tags = NULL;
4795 out_cleanup_srcu:
4796 if (set->flags & BLK_MQ_F_BLOCKING)
4797 cleanup_srcu_struct(set->srcu);
4798 out_free_srcu:
4799 if (set->flags & BLK_MQ_F_BLOCKING)
4800 kfree(set->srcu);
4801 return ret;
4803 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4805 /* allocate and initialize a tagset for a simple single-queue device */
4806 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4807 const struct blk_mq_ops *ops, unsigned int queue_depth,
4808 unsigned int set_flags)
4810 memset(set, 0, sizeof(*set));
4811 set->ops = ops;
4812 set->nr_hw_queues = 1;
4813 set->nr_maps = 1;
4814 set->queue_depth = queue_depth;
4815 set->numa_node = NUMA_NO_NODE;
4816 set->flags = set_flags;
4817 return blk_mq_alloc_tag_set(set);
4819 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4821 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4823 int i, j;
4825 for (i = 0; i < set->nr_hw_queues; i++)
4826 __blk_mq_free_map_and_rqs(set, i);
4828 if (blk_mq_is_shared_tags(set->flags)) {
4829 blk_mq_free_map_and_rqs(set, set->shared_tags,
4830 BLK_MQ_NO_HCTX_IDX);
4833 for (j = 0; j < set->nr_maps; j++) {
4834 kfree(set->map[j].mq_map);
4835 set->map[j].mq_map = NULL;
4838 kfree(set->tags);
4839 set->tags = NULL;
4840 if (set->flags & BLK_MQ_F_BLOCKING) {
4841 cleanup_srcu_struct(set->srcu);
4842 kfree(set->srcu);
4845 EXPORT_SYMBOL(blk_mq_free_tag_set);
4847 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
4849 struct blk_mq_tag_set *set = q->tag_set;
4850 struct blk_mq_hw_ctx *hctx;
4851 int ret;
4852 unsigned long i;
4854 if (WARN_ON_ONCE(!q->mq_freeze_depth))
4855 return -EINVAL;
4857 if (!set)
4858 return -EINVAL;
4860 if (q->nr_requests == nr)
4861 return 0;
4863 blk_mq_quiesce_queue(q);
4865 ret = 0;
4866 queue_for_each_hw_ctx(q, hctx, i) {
4867 if (!hctx->tags)
4868 continue;
4870 * If we're using an MQ scheduler, just update the scheduler
4871 * queue depth. This is similar to what the old code would do.
4873 if (hctx->sched_tags) {
4874 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
4875 nr, true);
4876 } else {
4877 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
4878 false);
4880 if (ret)
4881 break;
4882 if (q->elevator && q->elevator->type->ops.depth_updated)
4883 q->elevator->type->ops.depth_updated(hctx);
4885 if (!ret) {
4886 q->nr_requests = nr;
4887 if (blk_mq_is_shared_tags(set->flags)) {
4888 if (q->elevator)
4889 blk_mq_tag_update_sched_shared_tags(q);
4890 else
4891 blk_mq_tag_resize_shared_tags(set, nr);
4895 blk_mq_unquiesce_queue(q);
4897 return ret;
4901 * request_queue and elevator_type pair.
4902 * It is just used by __blk_mq_update_nr_hw_queues to cache
4903 * the elevator_type associated with a request_queue.
4905 struct blk_mq_qe_pair {
4906 struct list_head node;
4907 struct request_queue *q;
4908 struct elevator_type *type;
4912 * Cache the elevator_type in qe pair list and switch the
4913 * io scheduler to 'none'
4915 static bool blk_mq_elv_switch_none(struct list_head *head,
4916 struct request_queue *q)
4918 struct blk_mq_qe_pair *qe;
4920 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
4921 if (!qe)
4922 return false;
4924 /* q->elevator needs protection from ->sysfs_lock */
4925 mutex_lock(&q->sysfs_lock);
4927 /* the check has to be done with holding sysfs_lock */
4928 if (!q->elevator) {
4929 kfree(qe);
4930 goto unlock;
4933 INIT_LIST_HEAD(&qe->node);
4934 qe->q = q;
4935 qe->type = q->elevator->type;
4936 /* keep a reference to the elevator module as we'll switch back */
4937 __elevator_get(qe->type);
4938 list_add(&qe->node, head);
4939 elevator_disable(q);
4940 unlock:
4941 mutex_unlock(&q->sysfs_lock);
4943 return true;
4946 static struct blk_mq_qe_pair *blk_lookup_qe_pair(struct list_head *head,
4947 struct request_queue *q)
4949 struct blk_mq_qe_pair *qe;
4951 list_for_each_entry(qe, head, node)
4952 if (qe->q == q)
4953 return qe;
4955 return NULL;
4958 static void blk_mq_elv_switch_back(struct list_head *head,
4959 struct request_queue *q)
4961 struct blk_mq_qe_pair *qe;
4962 struct elevator_type *t;
4964 qe = blk_lookup_qe_pair(head, q);
4965 if (!qe)
4966 return;
4967 t = qe->type;
4968 list_del(&qe->node);
4969 kfree(qe);
4971 mutex_lock(&q->sysfs_lock);
4972 elevator_switch(q, t);
4973 /* drop the reference acquired in blk_mq_elv_switch_none */
4974 elevator_put(t);
4975 mutex_unlock(&q->sysfs_lock);
4978 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
4979 int nr_hw_queues)
4981 struct request_queue *q;
4982 LIST_HEAD(head);
4983 int prev_nr_hw_queues = set->nr_hw_queues;
4984 int i;
4986 lockdep_assert_held(&set->tag_list_lock);
4988 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
4989 nr_hw_queues = nr_cpu_ids;
4990 if (nr_hw_queues < 1)
4991 return;
4992 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
4993 return;
4995 list_for_each_entry(q, &set->tag_list, tag_set_list)
4996 blk_mq_freeze_queue(q);
4998 * Switch IO scheduler to 'none', cleaning up the data associated
4999 * with the previous scheduler. We will switch back once we are done
5000 * updating the new sw to hw queue mappings.
5002 list_for_each_entry(q, &set->tag_list, tag_set_list)
5003 if (!blk_mq_elv_switch_none(&head, q))
5004 goto switch_back;
5006 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5007 blk_mq_debugfs_unregister_hctxs(q);
5008 blk_mq_sysfs_unregister_hctxs(q);
5011 if (blk_mq_realloc_tag_set_tags(set, nr_hw_queues) < 0)
5012 goto reregister;
5014 fallback:
5015 blk_mq_update_queue_map(set);
5016 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5017 struct queue_limits lim;
5019 blk_mq_realloc_hw_ctxs(set, q);
5021 if (q->nr_hw_queues != set->nr_hw_queues) {
5022 int i = prev_nr_hw_queues;
5024 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
5025 nr_hw_queues, prev_nr_hw_queues);
5026 for (; i < set->nr_hw_queues; i++)
5027 __blk_mq_free_map_and_rqs(set, i);
5029 set->nr_hw_queues = prev_nr_hw_queues;
5030 goto fallback;
5032 lim = queue_limits_start_update(q);
5033 if (blk_mq_can_poll(set))
5034 lim.features |= BLK_FEAT_POLL;
5035 else
5036 lim.features &= ~BLK_FEAT_POLL;
5037 if (queue_limits_commit_update(q, &lim) < 0)
5038 pr_warn("updating the poll flag failed\n");
5039 blk_mq_map_swqueue(q);
5042 reregister:
5043 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5044 blk_mq_sysfs_register_hctxs(q);
5045 blk_mq_debugfs_register_hctxs(q);
5048 switch_back:
5049 list_for_each_entry(q, &set->tag_list, tag_set_list)
5050 blk_mq_elv_switch_back(&head, q);
5052 list_for_each_entry(q, &set->tag_list, tag_set_list)
5053 blk_mq_unfreeze_queue(q);
5055 /* Free the excess tags when nr_hw_queues shrink. */
5056 for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
5057 __blk_mq_free_map_and_rqs(set, i);
5060 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
5062 mutex_lock(&set->tag_list_lock);
5063 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
5064 mutex_unlock(&set->tag_list_lock);
5066 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
5068 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
5069 struct io_comp_batch *iob, unsigned int flags)
5071 long state = get_current_state();
5072 int ret;
5074 do {
5075 ret = q->mq_ops->poll(hctx, iob);
5076 if (ret > 0) {
5077 __set_current_state(TASK_RUNNING);
5078 return ret;
5081 if (signal_pending_state(state, current))
5082 __set_current_state(TASK_RUNNING);
5083 if (task_is_running(current))
5084 return 1;
5086 if (ret < 0 || (flags & BLK_POLL_ONESHOT))
5087 break;
5088 cpu_relax();
5089 } while (!need_resched());
5091 __set_current_state(TASK_RUNNING);
5092 return 0;
5095 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
5096 struct io_comp_batch *iob, unsigned int flags)
5098 struct blk_mq_hw_ctx *hctx = xa_load(&q->hctx_table, cookie);
5100 return blk_hctx_poll(q, hctx, iob, flags);
5103 int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
5104 unsigned int poll_flags)
5106 struct request_queue *q = rq->q;
5107 int ret;
5109 if (!blk_rq_is_poll(rq))
5110 return 0;
5111 if (!percpu_ref_tryget(&q->q_usage_counter))
5112 return 0;
5114 ret = blk_hctx_poll(q, rq->mq_hctx, iob, poll_flags);
5115 blk_queue_exit(q);
5117 return ret;
5119 EXPORT_SYMBOL_GPL(blk_rq_poll);
5121 unsigned int blk_mq_rq_cpu(struct request *rq)
5123 return rq->mq_ctx->cpu;
5125 EXPORT_SYMBOL(blk_mq_rq_cpu);
5127 void blk_mq_cancel_work_sync(struct request_queue *q)
5129 struct blk_mq_hw_ctx *hctx;
5130 unsigned long i;
5132 cancel_delayed_work_sync(&q->requeue_work);
5134 queue_for_each_hw_ctx(q, hctx, i)
5135 cancel_delayed_work_sync(&hctx->run_work);
5138 static int __init blk_mq_init(void)
5140 int i;
5142 for_each_possible_cpu(i)
5143 init_llist_head(&per_cpu(blk_cpu_done, i));
5144 for_each_possible_cpu(i)
5145 INIT_CSD(&per_cpu(blk_cpu_csd, i),
5146 __blk_mq_complete_request_remote, NULL);
5147 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
5149 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
5150 "block/softirq:dead", NULL,
5151 blk_softirq_cpu_dead);
5152 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
5153 blk_mq_hctx_notify_dead);
5154 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
5155 blk_mq_hctx_notify_online,
5156 blk_mq_hctx_notify_offline);
5157 return 0;
5159 subsys_initcall(blk_mq_init);