1 // SPDX-License-Identifier: GPL-2.0
3 * Block multiqueue core code
5 * Copyright (C) 2013-2014 Jens Axboe
6 * Copyright (C) 2013-2014 Christoph Hellwig
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>
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>
38 #include "blk-mq-debugfs.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,
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);
88 struct block_device *part;
89 unsigned int inflight[2];
92 static bool blk_mq_check_in_driver(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)]++;
104 void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
106 struct mq_inflight mi = { .part = part };
108 blk_mq_queue_tag_busy_iter(bdev_get_queue(part), blk_mq_check_in_driver,
110 inflight[READ] = mi.inflight[READ];
111 inflight[WRITE] = mi.inflight[WRITE];
114 #ifdef CONFIG_LOCKDEP
115 static bool blk_freeze_set_owner(struct request_queue *q,
116 struct task_struct *owner)
121 if (!q->mq_freeze_depth) {
122 q->mq_freeze_owner = owner;
123 q->mq_freeze_owner_depth = 1;
124 q->mq_freeze_disk_dead = !q->disk ||
125 test_bit(GD_DEAD, &q->disk->state) ||
126 !blk_queue_registered(q);
127 q->mq_freeze_queue_dying = blk_queue_dying(q);
131 if (owner == q->mq_freeze_owner)
132 q->mq_freeze_owner_depth += 1;
136 /* verify the last unfreeze in owner context */
137 static bool blk_unfreeze_check_owner(struct request_queue *q)
139 if (q->mq_freeze_owner != current)
141 if (--q->mq_freeze_owner_depth == 0) {
142 q->mq_freeze_owner = NULL;
150 static bool blk_freeze_set_owner(struct request_queue *q,
151 struct task_struct *owner)
156 static bool blk_unfreeze_check_owner(struct request_queue *q)
162 bool __blk_freeze_queue_start(struct request_queue *q,
163 struct task_struct *owner)
167 mutex_lock(&q->mq_freeze_lock);
168 freeze = blk_freeze_set_owner(q, owner);
169 if (++q->mq_freeze_depth == 1) {
170 percpu_ref_kill(&q->q_usage_counter);
171 mutex_unlock(&q->mq_freeze_lock);
173 blk_mq_run_hw_queues(q, false);
175 mutex_unlock(&q->mq_freeze_lock);
181 void blk_freeze_queue_start(struct request_queue *q)
183 if (__blk_freeze_queue_start(q, current))
184 blk_freeze_acquire_lock(q);
186 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
188 void blk_mq_freeze_queue_wait(struct request_queue *q)
190 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
192 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
194 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
195 unsigned long timeout)
197 return wait_event_timeout(q->mq_freeze_wq,
198 percpu_ref_is_zero(&q->q_usage_counter),
201 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
203 void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
205 blk_freeze_queue_start(q);
206 blk_mq_freeze_queue_wait(q);
208 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
210 bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
214 mutex_lock(&q->mq_freeze_lock);
216 q->q_usage_counter.data->force_atomic = true;
217 q->mq_freeze_depth--;
218 WARN_ON_ONCE(q->mq_freeze_depth < 0);
219 if (!q->mq_freeze_depth) {
220 percpu_ref_resurrect(&q->q_usage_counter);
221 wake_up_all(&q->mq_freeze_wq);
223 unfreeze = blk_unfreeze_check_owner(q);
224 mutex_unlock(&q->mq_freeze_lock);
229 void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
231 if (__blk_mq_unfreeze_queue(q, false))
232 blk_unfreeze_release_lock(q);
234 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
237 * non_owner variant of blk_freeze_queue_start
239 * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
240 * by the same task. This is fragile and should not be used if at all
243 void blk_freeze_queue_start_non_owner(struct request_queue *q)
245 __blk_freeze_queue_start(q, NULL);
247 EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
249 /* non_owner variant of blk_mq_unfreeze_queue */
250 void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
252 __blk_mq_unfreeze_queue(q, false);
254 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
257 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
258 * mpt3sas driver such that this function can be removed.
260 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
264 spin_lock_irqsave(&q->queue_lock, flags);
265 if (!q->quiesce_depth++)
266 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
267 spin_unlock_irqrestore(&q->queue_lock, flags);
269 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
272 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
273 * @set: tag_set to wait on
275 * Note: it is driver's responsibility for making sure that quiesce has
276 * been started on or more of the request_queues of the tag_set. This
277 * function only waits for the quiesce on those request_queues that had
278 * the quiesce flag set using blk_mq_quiesce_queue_nowait.
280 void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
282 if (set->flags & BLK_MQ_F_BLOCKING)
283 synchronize_srcu(set->srcu);
287 EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
290 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
293 * Note: this function does not prevent that the struct request end_io()
294 * callback function is invoked. Once this function is returned, we make
295 * sure no dispatch can happen until the queue is unquiesced via
296 * blk_mq_unquiesce_queue().
298 void blk_mq_quiesce_queue(struct request_queue *q)
300 blk_mq_quiesce_queue_nowait(q);
301 /* nothing to wait for non-mq queues */
303 blk_mq_wait_quiesce_done(q->tag_set);
305 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
308 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
311 * This function recovers queue into the state before quiescing
312 * which is done by blk_mq_quiesce_queue.
314 void blk_mq_unquiesce_queue(struct request_queue *q)
317 bool run_queue = false;
319 spin_lock_irqsave(&q->queue_lock, flags);
320 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
322 } else if (!--q->quiesce_depth) {
323 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
326 spin_unlock_irqrestore(&q->queue_lock, flags);
328 /* dispatch requests which are inserted during quiescing */
330 blk_mq_run_hw_queues(q, true);
332 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
334 void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
336 struct request_queue *q;
338 mutex_lock(&set->tag_list_lock);
339 list_for_each_entry(q, &set->tag_list, tag_set_list) {
340 if (!blk_queue_skip_tagset_quiesce(q))
341 blk_mq_quiesce_queue_nowait(q);
343 mutex_unlock(&set->tag_list_lock);
345 blk_mq_wait_quiesce_done(set);
347 EXPORT_SYMBOL_GPL(blk_mq_quiesce_tagset);
349 void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
351 struct request_queue *q;
353 mutex_lock(&set->tag_list_lock);
354 list_for_each_entry(q, &set->tag_list, tag_set_list) {
355 if (!blk_queue_skip_tagset_quiesce(q))
356 blk_mq_unquiesce_queue(q);
358 mutex_unlock(&set->tag_list_lock);
360 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
362 void blk_mq_wake_waiters(struct request_queue *q)
364 struct blk_mq_hw_ctx *hctx;
367 queue_for_each_hw_ctx(q, hctx, i)
368 if (blk_mq_hw_queue_mapped(hctx))
369 blk_mq_tag_wakeup_all(hctx->tags, true);
372 void blk_rq_init(struct request_queue *q, struct request *rq)
374 memset(rq, 0, sizeof(*rq));
376 INIT_LIST_HEAD(&rq->queuelist);
378 rq->__sector = (sector_t) -1;
379 INIT_HLIST_NODE(&rq->hash);
380 RB_CLEAR_NODE(&rq->rb_node);
381 rq->tag = BLK_MQ_NO_TAG;
382 rq->internal_tag = BLK_MQ_NO_TAG;
383 rq->start_time_ns = blk_time_get_ns();
384 blk_crypto_rq_set_defaults(rq);
386 EXPORT_SYMBOL(blk_rq_init);
388 /* Set start and alloc time when the allocated request is actually used */
389 static inline void blk_mq_rq_time_init(struct request *rq, u64 alloc_time_ns)
391 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
392 if (blk_queue_rq_alloc_time(rq->q))
393 rq->alloc_time_ns = alloc_time_ns;
395 rq->alloc_time_ns = 0;
399 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
400 struct blk_mq_tags *tags, unsigned int tag)
402 struct blk_mq_ctx *ctx = data->ctx;
403 struct blk_mq_hw_ctx *hctx = data->hctx;
404 struct request_queue *q = data->q;
405 struct request *rq = tags->static_rqs[tag];
410 rq->cmd_flags = data->cmd_flags;
412 if (data->flags & BLK_MQ_REQ_PM)
413 data->rq_flags |= RQF_PM;
414 rq->rq_flags = data->rq_flags;
416 if (data->rq_flags & RQF_SCHED_TAGS) {
417 rq->tag = BLK_MQ_NO_TAG;
418 rq->internal_tag = tag;
421 rq->internal_tag = BLK_MQ_NO_TAG;
426 rq->io_start_time_ns = 0;
427 rq->stats_sectors = 0;
428 rq->nr_phys_segments = 0;
429 rq->nr_integrity_segments = 0;
431 rq->end_io_data = NULL;
433 blk_crypto_rq_set_defaults(rq);
434 INIT_LIST_HEAD(&rq->queuelist);
435 /* tag was already set */
436 WRITE_ONCE(rq->deadline, 0);
439 if (rq->rq_flags & RQF_USE_SCHED) {
440 struct elevator_queue *e = data->q->elevator;
442 INIT_HLIST_NODE(&rq->hash);
443 RB_CLEAR_NODE(&rq->rb_node);
445 if (e->type->ops.prepare_request)
446 e->type->ops.prepare_request(rq);
452 static inline struct request *
453 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data)
455 unsigned int tag, tag_offset;
456 struct blk_mq_tags *tags;
458 unsigned long tag_mask;
461 tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
462 if (unlikely(!tag_mask))
465 tags = blk_mq_tags_from_data(data);
466 for (i = 0; tag_mask; i++) {
467 if (!(tag_mask & (1UL << i)))
469 tag = tag_offset + i;
470 prefetch(tags->static_rqs[tag]);
471 tag_mask &= ~(1UL << i);
472 rq = blk_mq_rq_ctx_init(data, tags, tag);
473 rq_list_add_head(data->cached_rqs, rq);
476 if (!(data->rq_flags & RQF_SCHED_TAGS))
477 blk_mq_add_active_requests(data->hctx, nr);
478 /* caller already holds a reference, add for remainder */
479 percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
482 return rq_list_pop(data->cached_rqs);
485 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
487 struct request_queue *q = data->q;
488 u64 alloc_time_ns = 0;
492 /* alloc_time includes depth and tag waits */
493 if (blk_queue_rq_alloc_time(q))
494 alloc_time_ns = blk_time_get_ns();
496 if (data->cmd_flags & REQ_NOWAIT)
497 data->flags |= BLK_MQ_REQ_NOWAIT;
500 data->ctx = blk_mq_get_ctx(q);
501 data->hctx = blk_mq_map_queue(data->cmd_flags, data->ctx);
505 * All requests use scheduler tags when an I/O scheduler is
506 * enabled for the queue.
508 data->rq_flags |= RQF_SCHED_TAGS;
511 * Flush/passthrough requests are special and go directly to the
514 if ((data->cmd_flags & REQ_OP_MASK) != REQ_OP_FLUSH &&
515 !blk_op_is_passthrough(data->cmd_flags)) {
516 struct elevator_mq_ops *ops = &q->elevator->type->ops;
518 WARN_ON_ONCE(data->flags & BLK_MQ_REQ_RESERVED);
520 data->rq_flags |= RQF_USE_SCHED;
521 if (ops->limit_depth)
522 ops->limit_depth(data->cmd_flags, data);
525 blk_mq_tag_busy(data->hctx);
528 if (data->flags & BLK_MQ_REQ_RESERVED)
529 data->rq_flags |= RQF_RESV;
532 * Try batched alloc if we want more than 1 tag.
534 if (data->nr_tags > 1) {
535 rq = __blk_mq_alloc_requests_batch(data);
537 blk_mq_rq_time_init(rq, alloc_time_ns);
544 * Waiting allocations only fail because of an inactive hctx. In that
545 * case just retry the hctx assignment and tag allocation as CPU hotplug
546 * should have migrated us to an online CPU by now.
548 tag = blk_mq_get_tag(data);
549 if (tag == BLK_MQ_NO_TAG) {
550 if (data->flags & BLK_MQ_REQ_NOWAIT)
553 * Give up the CPU and sleep for a random short time to
554 * ensure that thread using a realtime scheduling class
555 * are migrated off the CPU, and thus off the hctx that
562 if (!(data->rq_flags & RQF_SCHED_TAGS))
563 blk_mq_inc_active_requests(data->hctx);
564 rq = blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag);
565 blk_mq_rq_time_init(rq, alloc_time_ns);
569 static struct request *blk_mq_rq_cache_fill(struct request_queue *q,
570 struct blk_plug *plug,
572 blk_mq_req_flags_t flags)
574 struct blk_mq_alloc_data data = {
580 .nr_tags = plug->nr_ios,
581 .cached_rqs = &plug->cached_rqs,
587 if (blk_queue_enter(q, flags))
592 rq = __blk_mq_alloc_requests(&data);
598 static struct request *blk_mq_alloc_cached_request(struct request_queue *q,
600 blk_mq_req_flags_t flags)
602 struct blk_plug *plug = current->plug;
608 if (rq_list_empty(&plug->cached_rqs)) {
609 if (plug->nr_ios == 1)
611 rq = blk_mq_rq_cache_fill(q, plug, opf, flags);
615 rq = rq_list_peek(&plug->cached_rqs);
616 if (!rq || rq->q != q)
619 if (blk_mq_get_hctx_type(opf) != rq->mq_hctx->type)
621 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
624 rq_list_pop(&plug->cached_rqs);
625 blk_mq_rq_time_init(rq, blk_time_get_ns());
629 INIT_LIST_HEAD(&rq->queuelist);
633 struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
634 blk_mq_req_flags_t flags)
638 rq = blk_mq_alloc_cached_request(q, opf, flags);
640 struct blk_mq_alloc_data data = {
653 ret = blk_queue_enter(q, flags);
657 rq = __blk_mq_alloc_requests(&data);
662 rq->__sector = (sector_t) -1;
663 rq->bio = rq->biotail = NULL;
667 return ERR_PTR(-EWOULDBLOCK);
669 EXPORT_SYMBOL(blk_mq_alloc_request);
671 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
672 blk_opf_t opf, blk_mq_req_flags_t flags, unsigned int hctx_idx)
674 struct blk_mq_alloc_data data = {
685 u64 alloc_time_ns = 0;
691 /* alloc_time includes depth and tag waits */
692 if (blk_queue_rq_alloc_time(q))
693 alloc_time_ns = blk_time_get_ns();
696 * If the tag allocator sleeps we could get an allocation for a
697 * different hardware context. No need to complicate the low level
698 * allocator for this for the rare use case of a command tied to
701 if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)) ||
702 WARN_ON_ONCE(!(flags & BLK_MQ_REQ_RESERVED)))
703 return ERR_PTR(-EINVAL);
705 if (hctx_idx >= q->nr_hw_queues)
706 return ERR_PTR(-EIO);
708 ret = blk_queue_enter(q, flags);
713 * Check if the hardware context is actually mapped to anything.
714 * If not tell the caller that it should skip this queue.
717 data.hctx = xa_load(&q->hctx_table, hctx_idx);
718 if (!blk_mq_hw_queue_mapped(data.hctx))
720 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
721 if (cpu >= nr_cpu_ids)
723 data.ctx = __blk_mq_get_ctx(q, cpu);
726 data.rq_flags |= RQF_SCHED_TAGS;
728 blk_mq_tag_busy(data.hctx);
730 if (flags & BLK_MQ_REQ_RESERVED)
731 data.rq_flags |= RQF_RESV;
734 tag = blk_mq_get_tag(&data);
735 if (tag == BLK_MQ_NO_TAG)
737 if (!(data.rq_flags & RQF_SCHED_TAGS))
738 blk_mq_inc_active_requests(data.hctx);
739 rq = blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag);
740 blk_mq_rq_time_init(rq, alloc_time_ns);
742 rq->__sector = (sector_t) -1;
743 rq->bio = rq->biotail = NULL;
750 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
752 static void blk_mq_finish_request(struct request *rq)
754 struct request_queue *q = rq->q;
756 blk_zone_finish_request(rq);
758 if (rq->rq_flags & RQF_USE_SCHED) {
759 q->elevator->type->ops.finish_request(rq);
761 * For postflush request that may need to be
762 * completed twice, we should clear this flag
763 * to avoid double finish_request() on the rq.
765 rq->rq_flags &= ~RQF_USE_SCHED;
769 static void __blk_mq_free_request(struct request *rq)
771 struct request_queue *q = rq->q;
772 struct blk_mq_ctx *ctx = rq->mq_ctx;
773 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
774 const int sched_tag = rq->internal_tag;
776 blk_crypto_free_request(rq);
777 blk_pm_mark_last_busy(rq);
780 if (rq->tag != BLK_MQ_NO_TAG) {
781 blk_mq_dec_active_requests(hctx);
782 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
784 if (sched_tag != BLK_MQ_NO_TAG)
785 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
786 blk_mq_sched_restart(hctx);
790 void blk_mq_free_request(struct request *rq)
792 struct request_queue *q = rq->q;
794 blk_mq_finish_request(rq);
796 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
797 laptop_io_completion(q->disk->bdi);
801 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
802 if (req_ref_put_and_test(rq))
803 __blk_mq_free_request(rq);
805 EXPORT_SYMBOL_GPL(blk_mq_free_request);
807 void blk_mq_free_plug_rqs(struct blk_plug *plug)
811 while ((rq = rq_list_pop(&plug->cached_rqs)) != NULL)
812 blk_mq_free_request(rq);
815 void blk_dump_rq_flags(struct request *rq, char *msg)
817 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
818 rq->q->disk ? rq->q->disk->disk_name : "?",
819 (__force unsigned long long) rq->cmd_flags);
821 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
822 (unsigned long long)blk_rq_pos(rq),
823 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
824 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
825 rq->bio, rq->biotail, blk_rq_bytes(rq));
827 EXPORT_SYMBOL(blk_dump_rq_flags);
829 static void blk_account_io_completion(struct request *req, unsigned int bytes)
831 if (req->rq_flags & RQF_IO_STAT) {
832 const int sgrp = op_stat_group(req_op(req));
835 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
840 static void blk_print_req_error(struct request *req, blk_status_t status)
842 printk_ratelimited(KERN_ERR
843 "%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
844 "phys_seg %u prio class %u\n",
845 blk_status_to_str(status),
846 req->q->disk ? req->q->disk->disk_name : "?",
847 blk_rq_pos(req), (__force u32)req_op(req),
848 blk_op_str(req_op(req)),
849 (__force u32)(req->cmd_flags & ~REQ_OP_MASK),
850 req->nr_phys_segments,
851 IOPRIO_PRIO_CLASS(req_get_ioprio(req)));
855 * Fully end IO on a request. Does not support partial completions, or
858 static void blk_complete_request(struct request *req)
860 const bool is_flush = (req->rq_flags & RQF_FLUSH_SEQ) != 0;
861 int total_bytes = blk_rq_bytes(req);
862 struct bio *bio = req->bio;
864 trace_block_rq_complete(req, BLK_STS_OK, total_bytes);
869 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ)
870 blk_integrity_complete(req, total_bytes);
873 * Upper layers may call blk_crypto_evict_key() anytime after the last
874 * bio_endio(). Therefore, the keyslot must be released before that.
876 blk_crypto_rq_put_keyslot(req);
878 blk_account_io_completion(req, total_bytes);
881 struct bio *next = bio->bi_next;
883 /* Completion has already been traced */
884 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
886 blk_zone_update_request_bio(req, bio);
894 * Reset counters so that the request stacking driver
895 * can find how many bytes remain in the request
905 * blk_update_request - Complete multiple bytes without completing the request
906 * @req: the request being processed
907 * @error: block status code
908 * @nr_bytes: number of bytes to complete for @req
911 * Ends I/O on a number of bytes attached to @req, but doesn't complete
912 * the request structure even if @req doesn't have leftover.
913 * If @req has leftover, sets it up for the next range of segments.
915 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
916 * %false return from this function.
919 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
920 * except in the consistency check at the end of this function.
923 * %false - this request doesn't have any more data
924 * %true - this request has more data
926 bool blk_update_request(struct request *req, blk_status_t error,
927 unsigned int nr_bytes)
929 bool is_flush = req->rq_flags & RQF_FLUSH_SEQ;
930 bool quiet = req->rq_flags & RQF_QUIET;
933 trace_block_rq_complete(req, error, nr_bytes);
938 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
940 blk_integrity_complete(req, nr_bytes);
943 * Upper layers may call blk_crypto_evict_key() anytime after the last
944 * bio_endio(). Therefore, the keyslot must be released before that.
946 if (blk_crypto_rq_has_keyslot(req) && nr_bytes >= blk_rq_bytes(req))
947 __blk_crypto_rq_put_keyslot(req);
949 if (unlikely(error && !blk_rq_is_passthrough(req) && !quiet) &&
950 !test_bit(GD_DEAD, &req->q->disk->state)) {
951 blk_print_req_error(req, error);
952 trace_block_rq_error(req, error, nr_bytes);
955 blk_account_io_completion(req, nr_bytes);
959 struct bio *bio = req->bio;
960 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
963 bio->bi_status = error;
965 if (bio_bytes == bio->bi_iter.bi_size) {
966 req->bio = bio->bi_next;
967 } else if (bio_is_zone_append(bio) && error == BLK_STS_OK) {
969 * Partial zone append completions cannot be supported
970 * as the BIO fragments may end up not being written
973 bio->bi_status = BLK_STS_IOERR;
976 /* Completion has already been traced */
977 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
979 bio_set_flag(bio, BIO_QUIET);
981 bio_advance(bio, bio_bytes);
983 /* Don't actually finish bio if it's part of flush sequence */
984 if (!bio->bi_iter.bi_size) {
985 blk_zone_update_request_bio(req, bio);
990 total_bytes += bio_bytes;
991 nr_bytes -= bio_bytes;
1002 * Reset counters so that the request stacking driver
1003 * can find how many bytes remain in the request
1006 req->__data_len = 0;
1010 req->__data_len -= total_bytes;
1012 /* update sector only for requests with clear definition of sector */
1013 if (!blk_rq_is_passthrough(req))
1014 req->__sector += total_bytes >> 9;
1016 /* mixed attributes always follow the first bio */
1017 if (req->rq_flags & RQF_MIXED_MERGE) {
1018 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1019 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1022 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1024 * If total number of sectors is less than the first segment
1025 * size, something has gone terribly wrong.
1027 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1028 blk_dump_rq_flags(req, "request botched");
1029 req->__data_len = blk_rq_cur_bytes(req);
1032 /* recalculate the number of segments */
1033 req->nr_phys_segments = blk_recalc_rq_segments(req);
1038 EXPORT_SYMBOL_GPL(blk_update_request);
1040 static inline void blk_account_io_done(struct request *req, u64 now)
1042 trace_block_io_done(req);
1045 * Account IO completion. flush_rq isn't accounted as a
1046 * normal IO on queueing nor completion. Accounting the
1047 * containing request is enough.
1049 if ((req->rq_flags & (RQF_IO_STAT|RQF_FLUSH_SEQ)) == RQF_IO_STAT) {
1050 const int sgrp = op_stat_group(req_op(req));
1053 update_io_ticks(req->part, jiffies, true);
1054 part_stat_inc(req->part, ios[sgrp]);
1055 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1056 part_stat_local_dec(req->part,
1057 in_flight[op_is_write(req_op(req))]);
1062 static inline bool blk_rq_passthrough_stats(struct request *req)
1064 struct bio *bio = req->bio;
1066 if (!blk_queue_passthrough_stat(req->q))
1069 /* Requests without a bio do not transfer data. */
1074 * Stats are accumulated in the bdev, so must have one attached to a
1075 * bio to track stats. Most drivers do not set the bdev for passthrough
1076 * requests, but nvme is one that will set it.
1082 * We don't know what a passthrough command does, but we know the
1083 * payload size and data direction. Ensuring the size is aligned to the
1084 * block size filters out most commands with payloads that don't
1085 * represent sector access.
1087 if (blk_rq_bytes(req) & (bdev_logical_block_size(bio->bi_bdev) - 1))
1092 static inline void blk_account_io_start(struct request *req)
1094 trace_block_io_start(req);
1096 if (!blk_queue_io_stat(req->q))
1098 if (blk_rq_is_passthrough(req) && !blk_rq_passthrough_stats(req))
1101 req->rq_flags |= RQF_IO_STAT;
1102 req->start_time_ns = blk_time_get_ns();
1105 * All non-passthrough requests are created from a bio with one
1106 * exception: when a flush command that is part of a flush sequence
1107 * generated by the state machine in blk-flush.c is cloned onto the
1108 * lower device by dm-multipath we can get here without a bio.
1111 req->part = req->bio->bi_bdev;
1113 req->part = req->q->disk->part0;
1116 update_io_ticks(req->part, jiffies, false);
1117 part_stat_local_inc(req->part, in_flight[op_is_write(req_op(req))]);
1121 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
1123 if (rq->rq_flags & RQF_STATS)
1124 blk_stat_add(rq, now);
1126 blk_mq_sched_completed_request(rq, now);
1127 blk_account_io_done(rq, now);
1130 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
1132 if (blk_mq_need_time_stamp(rq))
1133 __blk_mq_end_request_acct(rq, blk_time_get_ns());
1135 blk_mq_finish_request(rq);
1138 rq_qos_done(rq->q, rq);
1139 if (rq->end_io(rq, error) == RQ_END_IO_FREE)
1140 blk_mq_free_request(rq);
1142 blk_mq_free_request(rq);
1145 EXPORT_SYMBOL(__blk_mq_end_request);
1147 void blk_mq_end_request(struct request *rq, blk_status_t error)
1149 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
1151 __blk_mq_end_request(rq, error);
1153 EXPORT_SYMBOL(blk_mq_end_request);
1155 #define TAG_COMP_BATCH 32
1157 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
1158 int *tag_array, int nr_tags)
1160 struct request_queue *q = hctx->queue;
1162 blk_mq_sub_active_requests(hctx, nr_tags);
1164 blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
1165 percpu_ref_put_many(&q->q_usage_counter, nr_tags);
1168 void blk_mq_end_request_batch(struct io_comp_batch *iob)
1170 int tags[TAG_COMP_BATCH], nr_tags = 0;
1171 struct blk_mq_hw_ctx *cur_hctx = NULL;
1176 now = blk_time_get_ns();
1178 while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
1180 prefetch(rq->rq_next);
1182 blk_complete_request(rq);
1184 __blk_mq_end_request_acct(rq, now);
1186 blk_mq_finish_request(rq);
1188 rq_qos_done(rq->q, rq);
1191 * If end_io handler returns NONE, then it still has
1192 * ownership of the request.
1194 if (rq->end_io && rq->end_io(rq, 0) == RQ_END_IO_NONE)
1197 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1198 if (!req_ref_put_and_test(rq))
1201 blk_crypto_free_request(rq);
1202 blk_pm_mark_last_busy(rq);
1204 if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
1206 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1208 cur_hctx = rq->mq_hctx;
1210 tags[nr_tags++] = rq->tag;
1214 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1216 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
1218 static void blk_complete_reqs(struct llist_head *list)
1220 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
1221 struct request *rq, *next;
1223 llist_for_each_entry_safe(rq, next, entry, ipi_list)
1224 rq->q->mq_ops->complete(rq);
1227 static __latent_entropy void blk_done_softirq(void)
1229 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
1232 static int blk_softirq_cpu_dead(unsigned int cpu)
1234 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
1238 static void __blk_mq_complete_request_remote(void *data)
1240 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
1243 static inline bool blk_mq_complete_need_ipi(struct request *rq)
1245 int cpu = raw_smp_processor_id();
1247 if (!IS_ENABLED(CONFIG_SMP) ||
1248 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
1251 * With force threaded interrupts enabled, raising softirq from an SMP
1252 * function call will always result in waking the ksoftirqd thread.
1253 * This is probably worse than completing the request on a different
1256 if (force_irqthreads())
1259 /* same CPU or cache domain and capacity? Complete locally */
1260 if (cpu == rq->mq_ctx->cpu ||
1261 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1262 cpus_share_cache(cpu, rq->mq_ctx->cpu) &&
1263 cpus_equal_capacity(cpu, rq->mq_ctx->cpu)))
1266 /* don't try to IPI to an offline CPU */
1267 return cpu_online(rq->mq_ctx->cpu);
1270 static void blk_mq_complete_send_ipi(struct request *rq)
1274 cpu = rq->mq_ctx->cpu;
1275 if (llist_add(&rq->ipi_list, &per_cpu(blk_cpu_done, cpu)))
1276 smp_call_function_single_async(cpu, &per_cpu(blk_cpu_csd, cpu));
1279 static void blk_mq_raise_softirq(struct request *rq)
1281 struct llist_head *list;
1284 list = this_cpu_ptr(&blk_cpu_done);
1285 if (llist_add(&rq->ipi_list, list))
1286 raise_softirq(BLOCK_SOFTIRQ);
1290 bool blk_mq_complete_request_remote(struct request *rq)
1292 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1295 * For request which hctx has only one ctx mapping,
1296 * or a polled request, always complete locally,
1297 * it's pointless to redirect the completion.
1299 if ((rq->mq_hctx->nr_ctx == 1 &&
1300 rq->mq_ctx->cpu == raw_smp_processor_id()) ||
1301 rq->cmd_flags & REQ_POLLED)
1304 if (blk_mq_complete_need_ipi(rq)) {
1305 blk_mq_complete_send_ipi(rq);
1309 if (rq->q->nr_hw_queues == 1) {
1310 blk_mq_raise_softirq(rq);
1315 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1318 * blk_mq_complete_request - end I/O on a request
1319 * @rq: the request being processed
1322 * Complete a request by scheduling the ->complete_rq operation.
1324 void blk_mq_complete_request(struct request *rq)
1326 if (!blk_mq_complete_request_remote(rq))
1327 rq->q->mq_ops->complete(rq);
1329 EXPORT_SYMBOL(blk_mq_complete_request);
1332 * blk_mq_start_request - Start processing a request
1333 * @rq: Pointer to request to be started
1335 * Function used by device drivers to notify the block layer that a request
1336 * is going to be processed now, so blk layer can do proper initializations
1337 * such as starting the timeout timer.
1339 void blk_mq_start_request(struct request *rq)
1341 struct request_queue *q = rq->q;
1343 trace_block_rq_issue(rq);
1345 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags) &&
1346 !blk_rq_is_passthrough(rq)) {
1347 rq->io_start_time_ns = blk_time_get_ns();
1348 rq->stats_sectors = blk_rq_sectors(rq);
1349 rq->rq_flags |= RQF_STATS;
1350 rq_qos_issue(q, rq);
1353 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1356 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1357 rq->mq_hctx->tags->rqs[rq->tag] = rq;
1359 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1360 blk_integrity_prepare(rq);
1362 if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1363 WRITE_ONCE(rq->bio->bi_cookie, rq->mq_hctx->queue_num);
1365 EXPORT_SYMBOL(blk_mq_start_request);
1368 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
1369 * queues. This is important for md arrays to benefit from merging
1372 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
1374 if (plug->multiple_queues)
1375 return BLK_MAX_REQUEST_COUNT * 2;
1376 return BLK_MAX_REQUEST_COUNT;
1379 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
1381 struct request *last = rq_list_peek(&plug->mq_list);
1383 if (!plug->rq_count) {
1384 trace_block_plug(rq->q);
1385 } else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
1386 (!blk_queue_nomerges(rq->q) &&
1387 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1388 blk_mq_flush_plug_list(plug, false);
1390 trace_block_plug(rq->q);
1393 if (!plug->multiple_queues && last && last->q != rq->q)
1394 plug->multiple_queues = true;
1396 * Any request allocated from sched tags can't be issued to
1397 * ->queue_rqs() directly
1399 if (!plug->has_elevator && (rq->rq_flags & RQF_SCHED_TAGS))
1400 plug->has_elevator = true;
1401 rq_list_add_tail(&plug->mq_list, rq);
1406 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1407 * @rq: request to insert
1408 * @at_head: insert request at head or tail of queue
1411 * Insert a fully prepared request at the back of the I/O scheduler queue
1412 * for execution. Don't wait for completion.
1415 * This function will invoke @done directly if the queue is dead.
1417 void blk_execute_rq_nowait(struct request *rq, bool at_head)
1419 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1421 WARN_ON(irqs_disabled());
1422 WARN_ON(!blk_rq_is_passthrough(rq));
1424 blk_account_io_start(rq);
1426 if (current->plug && !at_head) {
1427 blk_add_rq_to_plug(current->plug, rq);
1431 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1432 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
1434 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1436 struct blk_rq_wait {
1437 struct completion done;
1441 static enum rq_end_io_ret blk_end_sync_rq(struct request *rq, blk_status_t ret)
1443 struct blk_rq_wait *wait = rq->end_io_data;
1446 complete(&wait->done);
1447 return RQ_END_IO_NONE;
1450 bool blk_rq_is_poll(struct request *rq)
1454 if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1458 EXPORT_SYMBOL_GPL(blk_rq_is_poll);
1460 static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1463 blk_hctx_poll(rq->q, rq->mq_hctx, NULL, 0);
1465 } while (!completion_done(wait));
1469 * blk_execute_rq - insert a request into queue for execution
1470 * @rq: request to insert
1471 * @at_head: insert request at head or tail of queue
1474 * Insert a fully prepared request at the back of the I/O scheduler queue
1475 * for execution and wait for completion.
1476 * Return: The blk_status_t result provided to blk_mq_end_request().
1478 blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1480 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1481 struct blk_rq_wait wait = {
1482 .done = COMPLETION_INITIALIZER_ONSTACK(wait.done),
1485 WARN_ON(irqs_disabled());
1486 WARN_ON(!blk_rq_is_passthrough(rq));
1488 rq->end_io_data = &wait;
1489 rq->end_io = blk_end_sync_rq;
1491 blk_account_io_start(rq);
1492 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1493 blk_mq_run_hw_queue(hctx, false);
1495 if (blk_rq_is_poll(rq))
1496 blk_rq_poll_completion(rq, &wait.done);
1498 blk_wait_io(&wait.done);
1502 EXPORT_SYMBOL(blk_execute_rq);
1504 static void __blk_mq_requeue_request(struct request *rq)
1506 struct request_queue *q = rq->q;
1508 blk_mq_put_driver_tag(rq);
1510 trace_block_rq_requeue(rq);
1511 rq_qos_requeue(q, rq);
1513 if (blk_mq_request_started(rq)) {
1514 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1515 rq->rq_flags &= ~RQF_TIMED_OUT;
1519 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1521 struct request_queue *q = rq->q;
1522 unsigned long flags;
1524 __blk_mq_requeue_request(rq);
1526 /* this request will be re-inserted to io scheduler queue */
1527 blk_mq_sched_requeue_request(rq);
1529 spin_lock_irqsave(&q->requeue_lock, flags);
1530 list_add_tail(&rq->queuelist, &q->requeue_list);
1531 spin_unlock_irqrestore(&q->requeue_lock, flags);
1533 if (kick_requeue_list)
1534 blk_mq_kick_requeue_list(q);
1536 EXPORT_SYMBOL(blk_mq_requeue_request);
1538 static void blk_mq_requeue_work(struct work_struct *work)
1540 struct request_queue *q =
1541 container_of(work, struct request_queue, requeue_work.work);
1543 LIST_HEAD(flush_list);
1546 spin_lock_irq(&q->requeue_lock);
1547 list_splice_init(&q->requeue_list, &rq_list);
1548 list_splice_init(&q->flush_list, &flush_list);
1549 spin_unlock_irq(&q->requeue_lock);
1551 while (!list_empty(&rq_list)) {
1552 rq = list_entry(rq_list.next, struct request, queuelist);
1553 list_del_init(&rq->queuelist);
1555 * If RQF_DONTPREP is set, the request has been started by the
1556 * driver already and might have driver-specific data allocated
1557 * already. Insert it into the hctx dispatch list to avoid
1558 * block layer merges for the request.
1560 if (rq->rq_flags & RQF_DONTPREP)
1561 blk_mq_request_bypass_insert(rq, 0);
1563 blk_mq_insert_request(rq, BLK_MQ_INSERT_AT_HEAD);
1566 while (!list_empty(&flush_list)) {
1567 rq = list_entry(flush_list.next, struct request, queuelist);
1568 list_del_init(&rq->queuelist);
1569 blk_mq_insert_request(rq, 0);
1572 blk_mq_run_hw_queues(q, false);
1575 void blk_mq_kick_requeue_list(struct request_queue *q)
1577 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1579 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1581 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1582 unsigned long msecs)
1584 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1585 msecs_to_jiffies(msecs));
1587 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1589 static bool blk_is_flush_data_rq(struct request *rq)
1591 return (rq->rq_flags & RQF_FLUSH_SEQ) && !is_flush_rq(rq);
1594 static bool blk_mq_rq_inflight(struct request *rq, void *priv)
1597 * If we find a request that isn't idle we know the queue is busy
1598 * as it's checked in the iter.
1599 * Return false to stop the iteration.
1601 * In case of queue quiesce, if one flush data request is completed,
1602 * don't count it as inflight given the flush sequence is suspended,
1603 * and the original flush data request is invisible to driver, just
1604 * like other pending requests because of quiesce
1606 if (blk_mq_request_started(rq) && !(blk_queue_quiesced(rq->q) &&
1607 blk_is_flush_data_rq(rq) &&
1608 blk_mq_request_completed(rq))) {
1618 bool blk_mq_queue_inflight(struct request_queue *q)
1622 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1625 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1627 static void blk_mq_rq_timed_out(struct request *req)
1629 req->rq_flags |= RQF_TIMED_OUT;
1630 if (req->q->mq_ops->timeout) {
1631 enum blk_eh_timer_return ret;
1633 ret = req->q->mq_ops->timeout(req);
1634 if (ret == BLK_EH_DONE)
1636 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1642 struct blk_expired_data {
1643 bool has_timedout_rq;
1645 unsigned long timeout_start;
1648 static bool blk_mq_req_expired(struct request *rq, struct blk_expired_data *expired)
1650 unsigned long deadline;
1652 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1654 if (rq->rq_flags & RQF_TIMED_OUT)
1657 deadline = READ_ONCE(rq->deadline);
1658 if (time_after_eq(expired->timeout_start, deadline))
1661 if (expired->next == 0)
1662 expired->next = deadline;
1663 else if (time_after(expired->next, deadline))
1664 expired->next = deadline;
1668 void blk_mq_put_rq_ref(struct request *rq)
1670 if (is_flush_rq(rq)) {
1671 if (rq->end_io(rq, 0) == RQ_END_IO_FREE)
1672 blk_mq_free_request(rq);
1673 } else if (req_ref_put_and_test(rq)) {
1674 __blk_mq_free_request(rq);
1678 static bool blk_mq_check_expired(struct request *rq, void *priv)
1680 struct blk_expired_data *expired = priv;
1683 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1684 * be reallocated underneath the timeout handler's processing, then
1685 * the expire check is reliable. If the request is not expired, then
1686 * it was completed and reallocated as a new request after returning
1687 * from blk_mq_check_expired().
1689 if (blk_mq_req_expired(rq, expired)) {
1690 expired->has_timedout_rq = true;
1696 static bool blk_mq_handle_expired(struct request *rq, void *priv)
1698 struct blk_expired_data *expired = priv;
1700 if (blk_mq_req_expired(rq, expired))
1701 blk_mq_rq_timed_out(rq);
1705 static void blk_mq_timeout_work(struct work_struct *work)
1707 struct request_queue *q =
1708 container_of(work, struct request_queue, timeout_work);
1709 struct blk_expired_data expired = {
1710 .timeout_start = jiffies,
1712 struct blk_mq_hw_ctx *hctx;
1715 /* A deadlock might occur if a request is stuck requiring a
1716 * timeout at the same time a queue freeze is waiting
1717 * completion, since the timeout code would not be able to
1718 * acquire the queue reference here.
1720 * That's why we don't use blk_queue_enter here; instead, we use
1721 * percpu_ref_tryget directly, because we need to be able to
1722 * obtain a reference even in the short window between the queue
1723 * starting to freeze, by dropping the first reference in
1724 * blk_freeze_queue_start, and the moment the last request is
1725 * consumed, marked by the instant q_usage_counter reaches
1728 if (!percpu_ref_tryget(&q->q_usage_counter))
1731 /* check if there is any timed-out request */
1732 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &expired);
1733 if (expired.has_timedout_rq) {
1735 * Before walking tags, we must ensure any submit started
1736 * before the current time has finished. Since the submit
1737 * uses srcu or rcu, wait for a synchronization point to
1738 * ensure all running submits have finished
1740 blk_mq_wait_quiesce_done(q->tag_set);
1743 blk_mq_queue_tag_busy_iter(q, blk_mq_handle_expired, &expired);
1746 if (expired.next != 0) {
1747 mod_timer(&q->timeout, expired.next);
1750 * Request timeouts are handled as a forward rolling timer. If
1751 * we end up here it means that no requests are pending and
1752 * also that no request has been pending for a while. Mark
1753 * each hctx as idle.
1755 queue_for_each_hw_ctx(q, hctx, i) {
1756 /* the hctx may be unmapped, so check it here */
1757 if (blk_mq_hw_queue_mapped(hctx))
1758 blk_mq_tag_idle(hctx);
1764 struct flush_busy_ctx_data {
1765 struct blk_mq_hw_ctx *hctx;
1766 struct list_head *list;
1769 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1771 struct flush_busy_ctx_data *flush_data = data;
1772 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1773 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1774 enum hctx_type type = hctx->type;
1776 spin_lock(&ctx->lock);
1777 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1778 sbitmap_clear_bit(sb, bitnr);
1779 spin_unlock(&ctx->lock);
1784 * Process software queues that have been marked busy, splicing them
1785 * to the for-dispatch
1787 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1789 struct flush_busy_ctx_data data = {
1794 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1797 struct dispatch_rq_data {
1798 struct blk_mq_hw_ctx *hctx;
1802 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1805 struct dispatch_rq_data *dispatch_data = data;
1806 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1807 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1808 enum hctx_type type = hctx->type;
1810 spin_lock(&ctx->lock);
1811 if (!list_empty(&ctx->rq_lists[type])) {
1812 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1813 list_del_init(&dispatch_data->rq->queuelist);
1814 if (list_empty(&ctx->rq_lists[type]))
1815 sbitmap_clear_bit(sb, bitnr);
1817 spin_unlock(&ctx->lock);
1819 return !dispatch_data->rq;
1822 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1823 struct blk_mq_ctx *start)
1825 unsigned off = start ? start->index_hw[hctx->type] : 0;
1826 struct dispatch_rq_data data = {
1831 __sbitmap_for_each_set(&hctx->ctx_map, off,
1832 dispatch_rq_from_ctx, &data);
1837 bool __blk_mq_alloc_driver_tag(struct request *rq)
1839 struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1840 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1843 blk_mq_tag_busy(rq->mq_hctx);
1845 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1846 bt = &rq->mq_hctx->tags->breserved_tags;
1849 if (!hctx_may_queue(rq->mq_hctx, bt))
1853 tag = __sbitmap_queue_get(bt);
1854 if (tag == BLK_MQ_NO_TAG)
1857 rq->tag = tag + tag_offset;
1858 blk_mq_inc_active_requests(rq->mq_hctx);
1862 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1863 int flags, void *key)
1865 struct blk_mq_hw_ctx *hctx;
1867 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1869 spin_lock(&hctx->dispatch_wait_lock);
1870 if (!list_empty(&wait->entry)) {
1871 struct sbitmap_queue *sbq;
1873 list_del_init(&wait->entry);
1874 sbq = &hctx->tags->bitmap_tags;
1875 atomic_dec(&sbq->ws_active);
1877 spin_unlock(&hctx->dispatch_wait_lock);
1879 blk_mq_run_hw_queue(hctx, true);
1884 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1885 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1886 * restart. For both cases, take care to check the condition again after
1887 * marking us as waiting.
1889 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1892 struct sbitmap_queue *sbq;
1893 struct wait_queue_head *wq;
1894 wait_queue_entry_t *wait;
1897 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1898 !(blk_mq_is_shared_tags(hctx->flags))) {
1899 blk_mq_sched_mark_restart_hctx(hctx);
1902 * It's possible that a tag was freed in the window between the
1903 * allocation failure and adding the hardware queue to the wait
1906 * Don't clear RESTART here, someone else could have set it.
1907 * At most this will cost an extra queue run.
1909 return blk_mq_get_driver_tag(rq);
1912 wait = &hctx->dispatch_wait;
1913 if (!list_empty_careful(&wait->entry))
1916 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag))
1917 sbq = &hctx->tags->breserved_tags;
1919 sbq = &hctx->tags->bitmap_tags;
1920 wq = &bt_wait_ptr(sbq, hctx)->wait;
1922 spin_lock_irq(&wq->lock);
1923 spin_lock(&hctx->dispatch_wait_lock);
1924 if (!list_empty(&wait->entry)) {
1925 spin_unlock(&hctx->dispatch_wait_lock);
1926 spin_unlock_irq(&wq->lock);
1930 atomic_inc(&sbq->ws_active);
1931 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1932 __add_wait_queue(wq, wait);
1935 * Add one explicit barrier since blk_mq_get_driver_tag() may
1936 * not imply barrier in case of failure.
1938 * Order adding us to wait queue and allocating driver tag.
1940 * The pair is the one implied in sbitmap_queue_wake_up() which
1941 * orders clearing sbitmap tag bits and waitqueue_active() in
1942 * __sbitmap_queue_wake_up(), since waitqueue_active() is lockless
1944 * Otherwise, re-order of adding wait queue and getting driver tag
1945 * may cause __sbitmap_queue_wake_up() to wake up nothing because
1946 * the waitqueue_active() may not observe us in wait queue.
1951 * It's possible that a tag was freed in the window between the
1952 * allocation failure and adding the hardware queue to the wait
1955 ret = blk_mq_get_driver_tag(rq);
1957 spin_unlock(&hctx->dispatch_wait_lock);
1958 spin_unlock_irq(&wq->lock);
1963 * We got a tag, remove ourselves from the wait queue to ensure
1964 * someone else gets the wakeup.
1966 list_del_init(&wait->entry);
1967 atomic_dec(&sbq->ws_active);
1968 spin_unlock(&hctx->dispatch_wait_lock);
1969 spin_unlock_irq(&wq->lock);
1974 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1975 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1977 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1978 * - EWMA is one simple way to compute running average value
1979 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1980 * - take 4 as factor for avoiding to get too small(0) result, and this
1981 * factor doesn't matter because EWMA decreases exponentially
1983 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1987 ewma = hctx->dispatch_busy;
1992 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1994 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1995 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1997 hctx->dispatch_busy = ewma;
2000 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
2002 static void blk_mq_handle_dev_resource(struct request *rq,
2003 struct list_head *list)
2005 list_add(&rq->queuelist, list);
2006 __blk_mq_requeue_request(rq);
2009 enum prep_dispatch {
2011 PREP_DISPATCH_NO_TAG,
2012 PREP_DISPATCH_NO_BUDGET,
2015 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
2018 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2019 int budget_token = -1;
2022 budget_token = blk_mq_get_dispatch_budget(rq->q);
2023 if (budget_token < 0) {
2024 blk_mq_put_driver_tag(rq);
2025 return PREP_DISPATCH_NO_BUDGET;
2027 blk_mq_set_rq_budget_token(rq, budget_token);
2030 if (!blk_mq_get_driver_tag(rq)) {
2032 * The initial allocation attempt failed, so we need to
2033 * rerun the hardware queue when a tag is freed. The
2034 * waitqueue takes care of that. If the queue is run
2035 * before we add this entry back on the dispatch list,
2036 * we'll re-run it below.
2038 if (!blk_mq_mark_tag_wait(hctx, rq)) {
2040 * All budgets not got from this function will be put
2041 * together during handling partial dispatch
2044 blk_mq_put_dispatch_budget(rq->q, budget_token);
2045 return PREP_DISPATCH_NO_TAG;
2049 return PREP_DISPATCH_OK;
2052 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
2053 static void blk_mq_release_budgets(struct request_queue *q,
2054 struct list_head *list)
2058 list_for_each_entry(rq, list, queuelist) {
2059 int budget_token = blk_mq_get_rq_budget_token(rq);
2061 if (budget_token >= 0)
2062 blk_mq_put_dispatch_budget(q, budget_token);
2067 * blk_mq_commit_rqs will notify driver using bd->last that there is no
2068 * more requests. (See comment in struct blk_mq_ops for commit_rqs for
2070 * Attention, we should explicitly call this in unusual cases:
2071 * 1) did not queue everything initially scheduled to queue
2072 * 2) the last attempt to queue a request failed
2074 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int queued,
2077 if (hctx->queue->mq_ops->commit_rqs && queued) {
2078 trace_block_unplug(hctx->queue, queued, !from_schedule);
2079 hctx->queue->mq_ops->commit_rqs(hctx);
2084 * Returns true if we did some work AND can potentially do more.
2086 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
2089 enum prep_dispatch prep;
2090 struct request_queue *q = hctx->queue;
2093 blk_status_t ret = BLK_STS_OK;
2094 bool needs_resource = false;
2096 if (list_empty(list))
2100 * Now process all the entries, sending them to the driver.
2104 struct blk_mq_queue_data bd;
2106 rq = list_first_entry(list, struct request, queuelist);
2108 WARN_ON_ONCE(hctx != rq->mq_hctx);
2109 prep = blk_mq_prep_dispatch_rq(rq, get_budget);
2110 if (prep != PREP_DISPATCH_OK)
2113 list_del_init(&rq->queuelist);
2116 bd.last = list_empty(list);
2118 ret = q->mq_ops->queue_rq(hctx, &bd);
2123 case BLK_STS_RESOURCE:
2124 needs_resource = true;
2126 case BLK_STS_DEV_RESOURCE:
2127 blk_mq_handle_dev_resource(rq, list);
2130 blk_mq_end_request(rq, ret);
2132 } while (!list_empty(list));
2134 /* If we didn't flush the entire list, we could have told the driver
2135 * there was more coming, but that turned out to be a lie.
2137 if (!list_empty(list) || ret != BLK_STS_OK)
2138 blk_mq_commit_rqs(hctx, queued, false);
2141 * Any items that need requeuing? Stuff them into hctx->dispatch,
2142 * that is where we will continue on next queue run.
2144 if (!list_empty(list)) {
2146 /* For non-shared tags, the RESTART check will suffice */
2147 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
2148 ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) ||
2149 blk_mq_is_shared_tags(hctx->flags));
2152 * If the caller allocated budgets, free the budgets of the
2153 * requests that have not yet been passed to the block driver.
2156 blk_mq_release_budgets(q, list);
2158 spin_lock(&hctx->lock);
2159 list_splice_tail_init(list, &hctx->dispatch);
2160 spin_unlock(&hctx->lock);
2163 * Order adding requests to hctx->dispatch and checking
2164 * SCHED_RESTART flag. The pair of this smp_mb() is the one
2165 * in blk_mq_sched_restart(). Avoid restart code path to
2166 * miss the new added requests to hctx->dispatch, meantime
2167 * SCHED_RESTART is observed here.
2172 * If SCHED_RESTART was set by the caller of this function and
2173 * it is no longer set that means that it was cleared by another
2174 * thread and hence that a queue rerun is needed.
2176 * If 'no_tag' is set, that means that we failed getting
2177 * a driver tag with an I/O scheduler attached. If our dispatch
2178 * waitqueue is no longer active, ensure that we run the queue
2179 * AFTER adding our entries back to the list.
2181 * If no I/O scheduler has been configured it is possible that
2182 * the hardware queue got stopped and restarted before requests
2183 * were pushed back onto the dispatch list. Rerun the queue to
2184 * avoid starvation. Notes:
2185 * - blk_mq_run_hw_queue() checks whether or not a queue has
2186 * been stopped before rerunning a queue.
2187 * - Some but not all block drivers stop a queue before
2188 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
2191 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
2192 * bit is set, run queue after a delay to avoid IO stalls
2193 * that could otherwise occur if the queue is idle. We'll do
2194 * similar if we couldn't get budget or couldn't lock a zone
2195 * and SCHED_RESTART is set.
2197 needs_restart = blk_mq_sched_needs_restart(hctx);
2198 if (prep == PREP_DISPATCH_NO_BUDGET)
2199 needs_resource = true;
2200 if (!needs_restart ||
2201 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
2202 blk_mq_run_hw_queue(hctx, true);
2203 else if (needs_resource)
2204 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
2206 blk_mq_update_dispatch_busy(hctx, true);
2210 blk_mq_update_dispatch_busy(hctx, false);
2214 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
2216 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
2218 if (cpu >= nr_cpu_ids)
2219 cpu = cpumask_first(hctx->cpumask);
2224 * ->next_cpu is always calculated from hctx->cpumask, so simply use
2225 * it for speeding up the check
2227 static bool blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx *hctx)
2229 return hctx->next_cpu >= nr_cpu_ids;
2233 * It'd be great if the workqueue API had a way to pass
2234 * in a mask and had some smarts for more clever placement.
2235 * For now we just round-robin here, switching for every
2236 * BLK_MQ_CPU_WORK_BATCH queued items.
2238 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
2241 int next_cpu = hctx->next_cpu;
2243 /* Switch to unbound if no allowable CPUs in this hctx */
2244 if (hctx->queue->nr_hw_queues == 1 || blk_mq_hctx_empty_cpumask(hctx))
2245 return WORK_CPU_UNBOUND;
2247 if (--hctx->next_cpu_batch <= 0) {
2249 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
2251 if (next_cpu >= nr_cpu_ids)
2252 next_cpu = blk_mq_first_mapped_cpu(hctx);
2253 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2257 * Do unbound schedule if we can't find a online CPU for this hctx,
2258 * and it should only happen in the path of handling CPU DEAD.
2260 if (!cpu_online(next_cpu)) {
2267 * Make sure to re-select CPU next time once after CPUs
2268 * in hctx->cpumask become online again.
2270 hctx->next_cpu = next_cpu;
2271 hctx->next_cpu_batch = 1;
2272 return WORK_CPU_UNBOUND;
2275 hctx->next_cpu = next_cpu;
2280 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2281 * @hctx: Pointer to the hardware queue to run.
2282 * @msecs: Milliseconds of delay to wait before running the queue.
2284 * Run a hardware queue asynchronously with a delay of @msecs.
2286 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2288 if (unlikely(blk_mq_hctx_stopped(hctx)))
2290 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2291 msecs_to_jiffies(msecs));
2293 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2295 static inline bool blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx *hctx)
2300 * When queue is quiesced, we may be switching io scheduler, or
2301 * updating nr_hw_queues, or other things, and we can't run queue
2302 * any more, even blk_mq_hctx_has_pending() can't be called safely.
2304 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2307 __blk_mq_run_dispatch_ops(hctx->queue, false,
2308 need_run = !blk_queue_quiesced(hctx->queue) &&
2309 blk_mq_hctx_has_pending(hctx));
2314 * blk_mq_run_hw_queue - Start to run a hardware queue.
2315 * @hctx: Pointer to the hardware queue to run.
2316 * @async: If we want to run the queue asynchronously.
2318 * Check if the request queue is not in a quiesced state and if there are
2319 * pending requests to be sent. If this is true, run the queue to send requests
2322 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2327 * We can't run the queue inline with interrupts disabled.
2329 WARN_ON_ONCE(!async && in_interrupt());
2331 might_sleep_if(!async && hctx->flags & BLK_MQ_F_BLOCKING);
2333 need_run = blk_mq_hw_queue_need_run(hctx);
2335 unsigned long flags;
2338 * Synchronize with blk_mq_unquiesce_queue(), because we check
2339 * if hw queue is quiesced locklessly above, we need the use
2340 * ->queue_lock to make sure we see the up-to-date status to
2341 * not miss rerunning the hw queue.
2343 spin_lock_irqsave(&hctx->queue->queue_lock, flags);
2344 need_run = blk_mq_hw_queue_need_run(hctx);
2345 spin_unlock_irqrestore(&hctx->queue->queue_lock, flags);
2351 if (async || !cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask)) {
2352 blk_mq_delay_run_hw_queue(hctx, 0);
2356 blk_mq_run_dispatch_ops(hctx->queue,
2357 blk_mq_sched_dispatch_requests(hctx));
2359 EXPORT_SYMBOL(blk_mq_run_hw_queue);
2362 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2365 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2367 struct blk_mq_ctx *ctx = blk_mq_get_ctx(q);
2369 * If the IO scheduler does not respect hardware queues when
2370 * dispatching, we just don't bother with multiple HW queues and
2371 * dispatch from hctx for the current CPU since running multiple queues
2372 * just causes lock contention inside the scheduler and pointless cache
2375 struct blk_mq_hw_ctx *hctx = ctx->hctxs[HCTX_TYPE_DEFAULT];
2377 if (!blk_mq_hctx_stopped(hctx))
2383 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2384 * @q: Pointer to the request queue to run.
2385 * @async: If we want to run the queue asynchronously.
2387 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2389 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2393 if (blk_queue_sq_sched(q))
2394 sq_hctx = blk_mq_get_sq_hctx(q);
2395 queue_for_each_hw_ctx(q, hctx, i) {
2396 if (blk_mq_hctx_stopped(hctx))
2399 * Dispatch from this hctx either if there's no hctx preferred
2400 * by IO scheduler or if it has requests that bypass the
2403 if (!sq_hctx || sq_hctx == hctx ||
2404 !list_empty_careful(&hctx->dispatch))
2405 blk_mq_run_hw_queue(hctx, async);
2408 EXPORT_SYMBOL(blk_mq_run_hw_queues);
2411 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2412 * @q: Pointer to the request queue to run.
2413 * @msecs: Milliseconds of delay to wait before running the queues.
2415 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2417 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2421 if (blk_queue_sq_sched(q))
2422 sq_hctx = blk_mq_get_sq_hctx(q);
2423 queue_for_each_hw_ctx(q, hctx, i) {
2424 if (blk_mq_hctx_stopped(hctx))
2427 * If there is already a run_work pending, leave the
2428 * pending delay untouched. Otherwise, a hctx can stall
2429 * if another hctx is re-delaying the other's work
2430 * before the work executes.
2432 if (delayed_work_pending(&hctx->run_work))
2435 * Dispatch from this hctx either if there's no hctx preferred
2436 * by IO scheduler or if it has requests that bypass the
2439 if (!sq_hctx || sq_hctx == hctx ||
2440 !list_empty_careful(&hctx->dispatch))
2441 blk_mq_delay_run_hw_queue(hctx, msecs);
2444 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2447 * This function is often used for pausing .queue_rq() by driver when
2448 * there isn't enough resource or some conditions aren't satisfied, and
2449 * BLK_STS_RESOURCE is usually returned.
2451 * We do not guarantee that dispatch can be drained or blocked
2452 * after blk_mq_stop_hw_queue() returns. Please use
2453 * blk_mq_quiesce_queue() for that requirement.
2455 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2457 cancel_delayed_work(&hctx->run_work);
2459 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2461 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2464 * This function is often used for pausing .queue_rq() by driver when
2465 * there isn't enough resource or some conditions aren't satisfied, and
2466 * BLK_STS_RESOURCE is usually returned.
2468 * We do not guarantee that dispatch can be drained or blocked
2469 * after blk_mq_stop_hw_queues() returns. Please use
2470 * blk_mq_quiesce_queue() for that requirement.
2472 void blk_mq_stop_hw_queues(struct request_queue *q)
2474 struct blk_mq_hw_ctx *hctx;
2477 queue_for_each_hw_ctx(q, hctx, i)
2478 blk_mq_stop_hw_queue(hctx);
2480 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2482 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2484 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2486 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
2488 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2490 void blk_mq_start_hw_queues(struct request_queue *q)
2492 struct blk_mq_hw_ctx *hctx;
2495 queue_for_each_hw_ctx(q, hctx, i)
2496 blk_mq_start_hw_queue(hctx);
2498 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2500 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2502 if (!blk_mq_hctx_stopped(hctx))
2505 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2507 * Pairs with the smp_mb() in blk_mq_hctx_stopped() to order the
2508 * clearing of BLK_MQ_S_STOPPED above and the checking of dispatch
2509 * list in the subsequent routine.
2511 smp_mb__after_atomic();
2512 blk_mq_run_hw_queue(hctx, async);
2514 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2516 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2518 struct blk_mq_hw_ctx *hctx;
2521 queue_for_each_hw_ctx(q, hctx, i)
2522 blk_mq_start_stopped_hw_queue(hctx, async ||
2523 (hctx->flags & BLK_MQ_F_BLOCKING));
2525 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2527 static void blk_mq_run_work_fn(struct work_struct *work)
2529 struct blk_mq_hw_ctx *hctx =
2530 container_of(work, struct blk_mq_hw_ctx, run_work.work);
2532 blk_mq_run_dispatch_ops(hctx->queue,
2533 blk_mq_sched_dispatch_requests(hctx));
2537 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2538 * @rq: Pointer to request to be inserted.
2539 * @flags: BLK_MQ_INSERT_*
2541 * Should only be used carefully, when the caller knows we want to
2542 * bypass a potential IO scheduler on the target device.
2544 static void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
2546 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2548 spin_lock(&hctx->lock);
2549 if (flags & BLK_MQ_INSERT_AT_HEAD)
2550 list_add(&rq->queuelist, &hctx->dispatch);
2552 list_add_tail(&rq->queuelist, &hctx->dispatch);
2553 spin_unlock(&hctx->lock);
2556 static void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx,
2557 struct blk_mq_ctx *ctx, struct list_head *list,
2558 bool run_queue_async)
2561 enum hctx_type type = hctx->type;
2564 * Try to issue requests directly if the hw queue isn't busy to save an
2565 * extra enqueue & dequeue to the sw queue.
2567 if (!hctx->dispatch_busy && !run_queue_async) {
2568 blk_mq_run_dispatch_ops(hctx->queue,
2569 blk_mq_try_issue_list_directly(hctx, list));
2570 if (list_empty(list))
2575 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2578 list_for_each_entry(rq, list, queuelist) {
2579 BUG_ON(rq->mq_ctx != ctx);
2580 trace_block_rq_insert(rq);
2581 if (rq->cmd_flags & REQ_NOWAIT)
2582 run_queue_async = true;
2585 spin_lock(&ctx->lock);
2586 list_splice_tail_init(list, &ctx->rq_lists[type]);
2587 blk_mq_hctx_mark_pending(hctx, ctx);
2588 spin_unlock(&ctx->lock);
2590 blk_mq_run_hw_queue(hctx, run_queue_async);
2593 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags)
2595 struct request_queue *q = rq->q;
2596 struct blk_mq_ctx *ctx = rq->mq_ctx;
2597 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2599 if (blk_rq_is_passthrough(rq)) {
2601 * Passthrough request have to be added to hctx->dispatch
2602 * directly. The device may be in a situation where it can't
2603 * handle FS request, and always returns BLK_STS_RESOURCE for
2604 * them, which gets them added to hctx->dispatch.
2606 * If a passthrough request is required to unblock the queues,
2607 * and it is added to the scheduler queue, there is no chance to
2608 * dispatch it given we prioritize requests in hctx->dispatch.
2610 blk_mq_request_bypass_insert(rq, flags);
2611 } else if (req_op(rq) == REQ_OP_FLUSH) {
2613 * Firstly normal IO request is inserted to scheduler queue or
2614 * sw queue, meantime we add flush request to dispatch queue(
2615 * hctx->dispatch) directly and there is at most one in-flight
2616 * flush request for each hw queue, so it doesn't matter to add
2617 * flush request to tail or front of the dispatch queue.
2619 * Secondly in case of NCQ, flush request belongs to non-NCQ
2620 * command, and queueing it will fail when there is any
2621 * in-flight normal IO request(NCQ command). When adding flush
2622 * rq to the front of hctx->dispatch, it is easier to introduce
2623 * extra time to flush rq's latency because of S_SCHED_RESTART
2624 * compared with adding to the tail of dispatch queue, then
2625 * chance of flush merge is increased, and less flush requests
2626 * will be issued to controller. It is observed that ~10% time
2627 * is saved in blktests block/004 on disk attached to AHCI/NCQ
2628 * drive when adding flush rq to the front of hctx->dispatch.
2630 * Simply queue flush rq to the front of hctx->dispatch so that
2631 * intensive flush workloads can benefit in case of NCQ HW.
2633 blk_mq_request_bypass_insert(rq, BLK_MQ_INSERT_AT_HEAD);
2634 } else if (q->elevator) {
2637 WARN_ON_ONCE(rq->tag != BLK_MQ_NO_TAG);
2639 list_add(&rq->queuelist, &list);
2640 q->elevator->type->ops.insert_requests(hctx, &list, flags);
2642 trace_block_rq_insert(rq);
2644 spin_lock(&ctx->lock);
2645 if (flags & BLK_MQ_INSERT_AT_HEAD)
2646 list_add(&rq->queuelist, &ctx->rq_lists[hctx->type]);
2648 list_add_tail(&rq->queuelist,
2649 &ctx->rq_lists[hctx->type]);
2650 blk_mq_hctx_mark_pending(hctx, ctx);
2651 spin_unlock(&ctx->lock);
2655 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2656 unsigned int nr_segs)
2660 if (bio->bi_opf & REQ_RAHEAD)
2661 rq->cmd_flags |= REQ_FAILFAST_MASK;
2663 rq->bio = rq->biotail = bio;
2664 rq->__sector = bio->bi_iter.bi_sector;
2665 rq->__data_len = bio->bi_iter.bi_size;
2666 rq->nr_phys_segments = nr_segs;
2667 if (bio_integrity(bio))
2668 rq->nr_integrity_segments = blk_rq_count_integrity_sg(rq->q,
2671 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2672 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2675 blk_account_io_start(rq);
2678 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2679 struct request *rq, bool last)
2681 struct request_queue *q = rq->q;
2682 struct blk_mq_queue_data bd = {
2689 * For OK queue, we are done. For error, caller may kill it.
2690 * Any other error (busy), just add it to our list as we
2691 * previously would have done.
2693 ret = q->mq_ops->queue_rq(hctx, &bd);
2696 blk_mq_update_dispatch_busy(hctx, false);
2698 case BLK_STS_RESOURCE:
2699 case BLK_STS_DEV_RESOURCE:
2700 blk_mq_update_dispatch_busy(hctx, true);
2701 __blk_mq_requeue_request(rq);
2704 blk_mq_update_dispatch_busy(hctx, false);
2711 static bool blk_mq_get_budget_and_tag(struct request *rq)
2715 budget_token = blk_mq_get_dispatch_budget(rq->q);
2716 if (budget_token < 0)
2718 blk_mq_set_rq_budget_token(rq, budget_token);
2719 if (!blk_mq_get_driver_tag(rq)) {
2720 blk_mq_put_dispatch_budget(rq->q, budget_token);
2727 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2728 * @hctx: Pointer of the associated hardware queue.
2729 * @rq: Pointer to request to be sent.
2731 * If the device has enough resources to accept a new request now, send the
2732 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2733 * we can try send it another time in the future. Requests inserted at this
2734 * queue have higher priority.
2736 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2741 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2742 blk_mq_insert_request(rq, 0);
2743 blk_mq_run_hw_queue(hctx, false);
2747 if ((rq->rq_flags & RQF_USE_SCHED) || !blk_mq_get_budget_and_tag(rq)) {
2748 blk_mq_insert_request(rq, 0);
2749 blk_mq_run_hw_queue(hctx, rq->cmd_flags & REQ_NOWAIT);
2753 ret = __blk_mq_issue_directly(hctx, rq, true);
2757 case BLK_STS_RESOURCE:
2758 case BLK_STS_DEV_RESOURCE:
2759 blk_mq_request_bypass_insert(rq, 0);
2760 blk_mq_run_hw_queue(hctx, false);
2763 blk_mq_end_request(rq, ret);
2768 static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2770 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2772 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2773 blk_mq_insert_request(rq, 0);
2774 blk_mq_run_hw_queue(hctx, false);
2778 if (!blk_mq_get_budget_and_tag(rq))
2779 return BLK_STS_RESOURCE;
2780 return __blk_mq_issue_directly(hctx, rq, last);
2783 static void blk_mq_issue_direct(struct rq_list *rqs)
2785 struct blk_mq_hw_ctx *hctx = NULL;
2788 blk_status_t ret = BLK_STS_OK;
2790 while ((rq = rq_list_pop(rqs))) {
2791 bool last = rq_list_empty(rqs);
2793 if (hctx != rq->mq_hctx) {
2795 blk_mq_commit_rqs(hctx, queued, false);
2801 ret = blk_mq_request_issue_directly(rq, last);
2806 case BLK_STS_RESOURCE:
2807 case BLK_STS_DEV_RESOURCE:
2808 blk_mq_request_bypass_insert(rq, 0);
2809 blk_mq_run_hw_queue(hctx, false);
2812 blk_mq_end_request(rq, ret);
2818 if (ret != BLK_STS_OK)
2819 blk_mq_commit_rqs(hctx, queued, false);
2822 static void __blk_mq_flush_list(struct request_queue *q, struct rq_list *rqs)
2824 if (blk_queue_quiesced(q))
2826 q->mq_ops->queue_rqs(rqs);
2829 static unsigned blk_mq_extract_queue_requests(struct rq_list *rqs,
2830 struct rq_list *queue_rqs)
2832 struct request *rq = rq_list_pop(rqs);
2833 struct request_queue *this_q = rq->q;
2834 struct request **prev = &rqs->head;
2835 struct rq_list matched_rqs = {};
2836 struct request *last = NULL;
2839 rq_list_add_tail(&matched_rqs, rq);
2840 while ((rq = *prev)) {
2841 if (rq->q == this_q) {
2842 /* move rq from rqs to matched_rqs */
2843 *prev = rq->rq_next;
2844 rq_list_add_tail(&matched_rqs, rq);
2847 /* leave rq in rqs */
2848 prev = &rq->rq_next;
2854 *queue_rqs = matched_rqs;
2858 static void blk_mq_dispatch_queue_requests(struct rq_list *rqs, unsigned depth)
2860 struct request_queue *q = rq_list_peek(rqs)->q;
2862 trace_block_unplug(q, depth, true);
2865 * Peek first request and see if we have a ->queue_rqs() hook.
2866 * If we do, we can dispatch the whole list in one go.
2867 * We already know at this point that all requests belong to the
2868 * same queue, caller must ensure that's the case.
2870 if (q->mq_ops->queue_rqs) {
2871 blk_mq_run_dispatch_ops(q, __blk_mq_flush_list(q, rqs));
2872 if (rq_list_empty(rqs))
2876 blk_mq_run_dispatch_ops(q, blk_mq_issue_direct(rqs));
2879 static void blk_mq_dispatch_list(struct rq_list *rqs, bool from_sched)
2881 struct blk_mq_hw_ctx *this_hctx = NULL;
2882 struct blk_mq_ctx *this_ctx = NULL;
2883 struct rq_list requeue_list = {};
2884 unsigned int depth = 0;
2885 bool is_passthrough = false;
2889 struct request *rq = rq_list_pop(rqs);
2892 this_hctx = rq->mq_hctx;
2893 this_ctx = rq->mq_ctx;
2894 is_passthrough = blk_rq_is_passthrough(rq);
2895 } else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx ||
2896 is_passthrough != blk_rq_is_passthrough(rq)) {
2897 rq_list_add_tail(&requeue_list, rq);
2900 list_add_tail(&rq->queuelist, &list);
2902 } while (!rq_list_empty(rqs));
2904 *rqs = requeue_list;
2905 trace_block_unplug(this_hctx->queue, depth, !from_sched);
2907 percpu_ref_get(&this_hctx->queue->q_usage_counter);
2908 /* passthrough requests should never be issued to the I/O scheduler */
2909 if (is_passthrough) {
2910 spin_lock(&this_hctx->lock);
2911 list_splice_tail_init(&list, &this_hctx->dispatch);
2912 spin_unlock(&this_hctx->lock);
2913 blk_mq_run_hw_queue(this_hctx, from_sched);
2914 } else if (this_hctx->queue->elevator) {
2915 this_hctx->queue->elevator->type->ops.insert_requests(this_hctx,
2917 blk_mq_run_hw_queue(this_hctx, from_sched);
2919 blk_mq_insert_requests(this_hctx, this_ctx, &list, from_sched);
2921 percpu_ref_put(&this_hctx->queue->q_usage_counter);
2924 static void blk_mq_dispatch_multiple_queue_requests(struct rq_list *rqs)
2927 struct rq_list queue_rqs;
2930 depth = blk_mq_extract_queue_requests(rqs, &queue_rqs);
2931 blk_mq_dispatch_queue_requests(&queue_rqs, depth);
2932 while (!rq_list_empty(&queue_rqs))
2933 blk_mq_dispatch_list(&queue_rqs, false);
2934 } while (!rq_list_empty(rqs));
2937 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2942 * We may have been called recursively midway through handling
2943 * plug->mq_list via a schedule() in the driver's queue_rq() callback.
2944 * To avoid mq_list changing under our feet, clear rq_count early and
2945 * bail out specifically if rq_count is 0 rather than checking
2946 * whether the mq_list is empty.
2948 if (plug->rq_count == 0)
2950 depth = plug->rq_count;
2953 if (!plug->has_elevator && !from_schedule) {
2954 if (plug->multiple_queues) {
2955 blk_mq_dispatch_multiple_queue_requests(&plug->mq_list);
2959 blk_mq_dispatch_queue_requests(&plug->mq_list, depth);
2960 if (rq_list_empty(&plug->mq_list))
2965 blk_mq_dispatch_list(&plug->mq_list, from_schedule);
2966 } while (!rq_list_empty(&plug->mq_list));
2969 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2970 struct list_head *list)
2973 blk_status_t ret = BLK_STS_OK;
2975 while (!list_empty(list)) {
2976 struct request *rq = list_first_entry(list, struct request,
2979 list_del_init(&rq->queuelist);
2980 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2985 case BLK_STS_RESOURCE:
2986 case BLK_STS_DEV_RESOURCE:
2987 blk_mq_request_bypass_insert(rq, 0);
2988 if (list_empty(list))
2989 blk_mq_run_hw_queue(hctx, false);
2992 blk_mq_end_request(rq, ret);
2998 if (ret != BLK_STS_OK)
2999 blk_mq_commit_rqs(hctx, queued, false);
3002 static bool blk_mq_attempt_bio_merge(struct request_queue *q,
3003 struct bio *bio, unsigned int nr_segs)
3005 if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
3006 if (blk_attempt_plug_merge(q, bio, nr_segs))
3008 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
3014 static struct request *blk_mq_get_new_requests(struct request_queue *q,
3015 struct blk_plug *plug,
3018 struct blk_mq_alloc_data data = {
3022 .cmd_flags = bio->bi_opf,
3031 rq_qos_throttle(q, bio);
3034 data.nr_tags = plug->nr_ios;
3036 data.cached_rqs = &plug->cached_rqs;
3039 rq = __blk_mq_alloc_requests(&data);
3041 rq_qos_cleanup(q, bio);
3046 * Check if there is a suitable cached request and return it.
3048 static struct request *blk_mq_peek_cached_request(struct blk_plug *plug,
3049 struct request_queue *q, blk_opf_t opf)
3051 enum hctx_type type = blk_mq_get_hctx_type(opf);
3056 rq = rq_list_peek(&plug->cached_rqs);
3057 if (!rq || rq->q != q)
3059 if (type != rq->mq_hctx->type &&
3060 (type != HCTX_TYPE_READ || rq->mq_hctx->type != HCTX_TYPE_DEFAULT))
3062 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
3067 static void blk_mq_use_cached_rq(struct request *rq, struct blk_plug *plug,
3070 if (rq_list_pop(&plug->cached_rqs) != rq)
3074 * If any qos ->throttle() end up blocking, we will have flushed the
3075 * plug and hence killed the cached_rq list as well. Pop this entry
3076 * before we throttle.
3078 rq_qos_throttle(rq->q, bio);
3080 blk_mq_rq_time_init(rq, blk_time_get_ns());
3081 rq->cmd_flags = bio->bi_opf;
3082 INIT_LIST_HEAD(&rq->queuelist);
3085 static bool bio_unaligned(const struct bio *bio, struct request_queue *q)
3087 unsigned int bs_mask = queue_logical_block_size(q) - 1;
3089 /* .bi_sector of any zero sized bio need to be initialized */
3090 if ((bio->bi_iter.bi_size & bs_mask) ||
3091 ((bio->bi_iter.bi_sector << SECTOR_SHIFT) & bs_mask))
3097 * blk_mq_submit_bio - Create and send a request to block device.
3098 * @bio: Bio pointer.
3100 * Builds up a request structure from @q and @bio and send to the device. The
3101 * request may not be queued directly to hardware if:
3102 * * This request can be merged with another one
3103 * * We want to place request at plug queue for possible future merging
3104 * * There is an IO scheduler active at this queue
3106 * It will not queue the request if there is an error with the bio, or at the
3109 void blk_mq_submit_bio(struct bio *bio)
3111 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
3112 struct blk_plug *plug = current->plug;
3113 const int is_sync = op_is_sync(bio->bi_opf);
3114 struct blk_mq_hw_ctx *hctx;
3115 unsigned int nr_segs;
3120 * If the plug has a cached request for this queue, try to use it.
3122 rq = blk_mq_peek_cached_request(plug, q, bio->bi_opf);
3125 * A BIO that was released from a zone write plug has already been
3126 * through the preparation in this function, already holds a reference
3127 * on the queue usage counter, and is the only write BIO in-flight for
3128 * the target zone. Go straight to preparing a request for it.
3130 if (bio_zone_write_plugging(bio)) {
3131 nr_segs = bio->__bi_nr_segments;
3138 * The cached request already holds a q_usage_counter reference and we
3139 * don't have to acquire a new one if we use it.
3142 if (unlikely(bio_queue_enter(bio)))
3147 * Device reconfiguration may change logical block size or reduce the
3148 * number of poll queues, so the checks for alignment and poll support
3149 * have to be done with queue usage counter held.
3151 if (unlikely(bio_unaligned(bio, q))) {
3156 if ((bio->bi_opf & REQ_POLLED) && !blk_mq_can_poll(q)) {
3157 bio->bi_status = BLK_STS_NOTSUPP;
3162 bio = __bio_split_to_limits(bio, &q->limits, &nr_segs);
3166 if (!bio_integrity_prep(bio))
3169 if (blk_mq_attempt_bio_merge(q, bio, nr_segs))
3172 if (blk_queue_is_zoned(q) && blk_zone_plug_bio(bio, nr_segs))
3177 blk_mq_use_cached_rq(rq, plug, bio);
3179 rq = blk_mq_get_new_requests(q, plug, bio);
3180 if (unlikely(!rq)) {
3181 if (bio->bi_opf & REQ_NOWAIT)
3182 bio_wouldblock_error(bio);
3187 trace_block_getrq(bio);
3189 rq_qos_track(q, rq, bio);
3191 blk_mq_bio_to_request(rq, bio, nr_segs);
3193 ret = blk_crypto_rq_get_keyslot(rq);
3194 if (ret != BLK_STS_OK) {
3195 bio->bi_status = ret;
3197 blk_mq_free_request(rq);
3201 if (bio_zone_write_plugging(bio))
3202 blk_zone_write_plug_init_request(rq);
3204 if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
3208 blk_add_rq_to_plug(plug, rq);
3213 if ((rq->rq_flags & RQF_USE_SCHED) ||
3214 (hctx->dispatch_busy && (q->nr_hw_queues == 1 || !is_sync))) {
3215 blk_mq_insert_request(rq, 0);
3216 blk_mq_run_hw_queue(hctx, true);
3218 blk_mq_run_dispatch_ops(q, blk_mq_try_issue_directly(hctx, rq));
3224 * Don't drop the queue reference if we were trying to use a cached
3225 * request and thus didn't acquire one.
3231 #ifdef CONFIG_BLK_MQ_STACKING
3233 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
3234 * @rq: the request being queued
3236 blk_status_t blk_insert_cloned_request(struct request *rq)
3238 struct request_queue *q = rq->q;
3239 unsigned int max_sectors = blk_queue_get_max_sectors(rq);
3240 unsigned int max_segments = blk_rq_get_max_segments(rq);
3243 if (blk_rq_sectors(rq) > max_sectors) {
3245 * SCSI device does not have a good way to return if
3246 * Write Same/Zero is actually supported. If a device rejects
3247 * a non-read/write command (discard, write same,etc.) the
3248 * low-level device driver will set the relevant queue limit to
3249 * 0 to prevent blk-lib from issuing more of the offending
3250 * operations. Commands queued prior to the queue limit being
3251 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
3252 * errors being propagated to upper layers.
3254 if (max_sectors == 0)
3255 return BLK_STS_NOTSUPP;
3257 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
3258 __func__, blk_rq_sectors(rq), max_sectors);
3259 return BLK_STS_IOERR;
3263 * The queue settings related to segment counting may differ from the
3266 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
3267 if (rq->nr_phys_segments > max_segments) {
3268 printk(KERN_ERR "%s: over max segments limit. (%u > %u)\n",
3269 __func__, rq->nr_phys_segments, max_segments);
3270 return BLK_STS_IOERR;
3273 if (q->disk && should_fail_request(q->disk->part0, blk_rq_bytes(rq)))
3274 return BLK_STS_IOERR;
3276 ret = blk_crypto_rq_get_keyslot(rq);
3277 if (ret != BLK_STS_OK)
3280 blk_account_io_start(rq);
3283 * Since we have a scheduler attached on the top device,
3284 * bypass a potential scheduler on the bottom device for
3287 blk_mq_run_dispatch_ops(q,
3288 ret = blk_mq_request_issue_directly(rq, true));
3290 blk_account_io_done(rq, blk_time_get_ns());
3293 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
3296 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3297 * @rq: the clone request to be cleaned up
3300 * Free all bios in @rq for a cloned request.
3302 void blk_rq_unprep_clone(struct request *rq)
3306 while ((bio = rq->bio) != NULL) {
3307 rq->bio = bio->bi_next;
3312 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3315 * blk_rq_prep_clone - Helper function to setup clone request
3316 * @rq: the request to be setup
3317 * @rq_src: original request to be cloned
3318 * @bs: bio_set that bios for clone are allocated from
3319 * @gfp_mask: memory allocation mask for bio
3320 * @bio_ctr: setup function to be called for each clone bio.
3321 * Returns %0 for success, non %0 for failure.
3322 * @data: private data to be passed to @bio_ctr
3325 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3326 * Also, pages which the original bios are pointing to are not copied
3327 * and the cloned bios just point same pages.
3328 * So cloned bios must be completed before original bios, which means
3329 * the caller must complete @rq before @rq_src.
3331 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3332 struct bio_set *bs, gfp_t gfp_mask,
3333 int (*bio_ctr)(struct bio *, struct bio *, void *),
3336 struct bio *bio_src;
3341 __rq_for_each_bio(bio_src, rq_src) {
3342 struct bio *bio = bio_alloc_clone(rq->q->disk->part0, bio_src,
3347 if (bio_ctr && bio_ctr(bio, bio_src, data)) {
3353 rq->biotail->bi_next = bio;
3356 rq->bio = rq->biotail = bio;
3360 /* Copy attributes of the original request to the clone request. */
3361 rq->__sector = blk_rq_pos(rq_src);
3362 rq->__data_len = blk_rq_bytes(rq_src);
3363 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
3364 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
3365 rq->special_vec = rq_src->special_vec;
3367 rq->nr_phys_segments = rq_src->nr_phys_segments;
3368 rq->nr_integrity_segments = rq_src->nr_integrity_segments;
3370 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
3376 blk_rq_unprep_clone(rq);
3380 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3381 #endif /* CONFIG_BLK_MQ_STACKING */
3384 * Steal bios from a request and add them to a bio list.
3385 * The request must not have been partially completed before.
3387 void blk_steal_bios(struct bio_list *list, struct request *rq)
3391 list->tail->bi_next = rq->bio;
3393 list->head = rq->bio;
3394 list->tail = rq->biotail;
3402 EXPORT_SYMBOL_GPL(blk_steal_bios);
3404 static size_t order_to_size(unsigned int order)
3406 return (size_t)PAGE_SIZE << order;
3409 /* called before freeing request pool in @tags */
3410 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3411 struct blk_mq_tags *tags)
3414 unsigned long flags;
3417 * There is no need to clear mapping if driver tags is not initialized
3418 * or the mapping belongs to the driver tags.
3420 if (!drv_tags || drv_tags == tags)
3423 list_for_each_entry(page, &tags->page_list, lru) {
3424 unsigned long start = (unsigned long)page_address(page);
3425 unsigned long end = start + order_to_size(page->private);
3428 for (i = 0; i < drv_tags->nr_tags; i++) {
3429 struct request *rq = drv_tags->rqs[i];
3430 unsigned long rq_addr = (unsigned long)rq;
3432 if (rq_addr >= start && rq_addr < end) {
3433 WARN_ON_ONCE(req_ref_read(rq) != 0);
3434 cmpxchg(&drv_tags->rqs[i], rq, NULL);
3440 * Wait until all pending iteration is done.
3442 * Request reference is cleared and it is guaranteed to be observed
3443 * after the ->lock is released.
3445 spin_lock_irqsave(&drv_tags->lock, flags);
3446 spin_unlock_irqrestore(&drv_tags->lock, flags);
3449 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3450 unsigned int hctx_idx)
3452 struct blk_mq_tags *drv_tags;
3455 if (list_empty(&tags->page_list))
3458 if (blk_mq_is_shared_tags(set->flags))
3459 drv_tags = set->shared_tags;
3461 drv_tags = set->tags[hctx_idx];
3463 if (tags->static_rqs && set->ops->exit_request) {
3466 for (i = 0; i < tags->nr_tags; i++) {
3467 struct request *rq = tags->static_rqs[i];
3471 set->ops->exit_request(set, rq, hctx_idx);
3472 tags->static_rqs[i] = NULL;
3476 blk_mq_clear_rq_mapping(drv_tags, tags);
3478 while (!list_empty(&tags->page_list)) {
3479 page = list_first_entry(&tags->page_list, struct page, lru);
3480 list_del_init(&page->lru);
3482 * Remove kmemleak object previously allocated in
3483 * blk_mq_alloc_rqs().
3485 kmemleak_free(page_address(page));
3486 __free_pages(page, page->private);
3490 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
3494 kfree(tags->static_rqs);
3495 tags->static_rqs = NULL;
3497 blk_mq_free_tags(tags);
3500 static enum hctx_type hctx_idx_to_type(struct blk_mq_tag_set *set,
3501 unsigned int hctx_idx)
3505 for (i = 0; i < set->nr_maps; i++) {
3506 unsigned int start = set->map[i].queue_offset;
3507 unsigned int end = start + set->map[i].nr_queues;
3509 if (hctx_idx >= start && hctx_idx < end)
3513 if (i >= set->nr_maps)
3514 i = HCTX_TYPE_DEFAULT;
3519 static int blk_mq_get_hctx_node(struct blk_mq_tag_set *set,
3520 unsigned int hctx_idx)
3522 enum hctx_type type = hctx_idx_to_type(set, hctx_idx);
3524 return blk_mq_hw_queue_to_node(&set->map[type], hctx_idx);
3527 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3528 unsigned int hctx_idx,
3529 unsigned int nr_tags,
3530 unsigned int reserved_tags)
3532 int node = blk_mq_get_hctx_node(set, hctx_idx);
3533 struct blk_mq_tags *tags;
3535 if (node == NUMA_NO_NODE)
3536 node = set->numa_node;
3538 tags = blk_mq_init_tags(nr_tags, reserved_tags, set->flags, node);
3542 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3543 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3548 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3549 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3551 if (!tags->static_rqs)
3559 blk_mq_free_tags(tags);
3563 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3564 unsigned int hctx_idx, int node)
3568 if (set->ops->init_request) {
3569 ret = set->ops->init_request(set, rq, hctx_idx, node);
3574 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3578 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3579 struct blk_mq_tags *tags,
3580 unsigned int hctx_idx, unsigned int depth)
3582 unsigned int i, j, entries_per_page, max_order = 4;
3583 int node = blk_mq_get_hctx_node(set, hctx_idx);
3584 size_t rq_size, left;
3586 if (node == NUMA_NO_NODE)
3587 node = set->numa_node;
3589 INIT_LIST_HEAD(&tags->page_list);
3592 * rq_size is the size of the request plus driver payload, rounded
3593 * to the cacheline size
3595 rq_size = round_up(sizeof(struct request) + set->cmd_size,
3597 left = rq_size * depth;
3599 for (i = 0; i < depth; ) {
3600 int this_order = max_order;
3605 while (this_order && left < order_to_size(this_order - 1))
3609 page = alloc_pages_node(node,
3610 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3616 if (order_to_size(this_order) < rq_size)
3623 page->private = this_order;
3624 list_add_tail(&page->lru, &tags->page_list);
3626 p = page_address(page);
3628 * Allow kmemleak to scan these pages as they contain pointers
3629 * to additional allocations like via ops->init_request().
3631 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3632 entries_per_page = order_to_size(this_order) / rq_size;
3633 to_do = min(entries_per_page, depth - i);
3634 left -= to_do * rq_size;
3635 for (j = 0; j < to_do; j++) {
3636 struct request *rq = p;
3638 tags->static_rqs[i] = rq;
3639 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3640 tags->static_rqs[i] = NULL;
3651 blk_mq_free_rqs(set, tags, hctx_idx);
3655 struct rq_iter_data {
3656 struct blk_mq_hw_ctx *hctx;
3660 static bool blk_mq_has_request(struct request *rq, void *data)
3662 struct rq_iter_data *iter_data = data;
3664 if (rq->mq_hctx != iter_data->hctx)
3666 iter_data->has_rq = true;
3670 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3672 struct blk_mq_tags *tags = hctx->sched_tags ?
3673 hctx->sched_tags : hctx->tags;
3674 struct rq_iter_data data = {
3678 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3682 static bool blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx *hctx,
3683 unsigned int this_cpu)
3685 enum hctx_type type = hctx->type;
3689 * hctx->cpumask has to rule out isolated CPUs, but userspace still
3690 * might submit IOs on these isolated CPUs, so use the queue map to
3691 * check if all CPUs mapped to this hctx are offline
3693 for_each_online_cpu(cpu) {
3694 struct blk_mq_hw_ctx *h = blk_mq_map_queue_type(hctx->queue,
3700 /* this hctx has at least one online CPU */
3701 if (this_cpu != cpu)
3708 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3710 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3711 struct blk_mq_hw_ctx, cpuhp_online);
3713 if (blk_mq_hctx_has_online_cpu(hctx, cpu))
3717 * Prevent new request from being allocated on the current hctx.
3719 * The smp_mb__after_atomic() Pairs with the implied barrier in
3720 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
3721 * seen once we return from the tag allocator.
3723 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3724 smp_mb__after_atomic();
3727 * Try to grab a reference to the queue and wait for any outstanding
3728 * requests. If we could not grab a reference the queue has been
3729 * frozen and there are no requests.
3731 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3732 while (blk_mq_hctx_has_requests(hctx))
3734 percpu_ref_put(&hctx->queue->q_usage_counter);
3741 * Check if one CPU is mapped to the specified hctx
3743 * Isolated CPUs have been ruled out from hctx->cpumask, which is supposed
3744 * to be used for scheduling kworker only. For other usage, please call this
3745 * helper for checking if one CPU belongs to the specified hctx
3747 static bool blk_mq_cpu_mapped_to_hctx(unsigned int cpu,
3748 const struct blk_mq_hw_ctx *hctx)
3750 struct blk_mq_hw_ctx *mapped_hctx = blk_mq_map_queue_type(hctx->queue,
3753 return mapped_hctx == hctx;
3756 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3758 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3759 struct blk_mq_hw_ctx, cpuhp_online);
3761 if (blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3762 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3767 * 'cpu' is going away. splice any existing rq_list entries from this
3768 * software queue to the hw queue dispatch list, and ensure that it
3771 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3773 struct blk_mq_hw_ctx *hctx;
3774 struct blk_mq_ctx *ctx;
3776 enum hctx_type type;
3778 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3779 if (!blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3782 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3785 spin_lock(&ctx->lock);
3786 if (!list_empty(&ctx->rq_lists[type])) {
3787 list_splice_init(&ctx->rq_lists[type], &tmp);
3788 blk_mq_hctx_clear_pending(hctx, ctx);
3790 spin_unlock(&ctx->lock);
3792 if (list_empty(&tmp))
3795 spin_lock(&hctx->lock);
3796 list_splice_tail_init(&tmp, &hctx->dispatch);
3797 spin_unlock(&hctx->lock);
3799 blk_mq_run_hw_queue(hctx, true);
3803 static void __blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3805 lockdep_assert_held(&blk_mq_cpuhp_lock);
3807 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3808 !hlist_unhashed(&hctx->cpuhp_online)) {
3809 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3810 &hctx->cpuhp_online);
3811 INIT_HLIST_NODE(&hctx->cpuhp_online);
3814 if (!hlist_unhashed(&hctx->cpuhp_dead)) {
3815 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3817 INIT_HLIST_NODE(&hctx->cpuhp_dead);
3821 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3823 mutex_lock(&blk_mq_cpuhp_lock);
3824 __blk_mq_remove_cpuhp(hctx);
3825 mutex_unlock(&blk_mq_cpuhp_lock);
3828 static void __blk_mq_add_cpuhp(struct blk_mq_hw_ctx *hctx)
3830 lockdep_assert_held(&blk_mq_cpuhp_lock);
3832 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3833 hlist_unhashed(&hctx->cpuhp_online))
3834 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3835 &hctx->cpuhp_online);
3837 if (hlist_unhashed(&hctx->cpuhp_dead))
3838 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3842 static void __blk_mq_remove_cpuhp_list(struct list_head *head)
3844 struct blk_mq_hw_ctx *hctx;
3846 lockdep_assert_held(&blk_mq_cpuhp_lock);
3848 list_for_each_entry(hctx, head, hctx_list)
3849 __blk_mq_remove_cpuhp(hctx);
3853 * Unregister cpuhp callbacks from exited hw queues
3855 * Safe to call if this `request_queue` is live
3857 static void blk_mq_remove_hw_queues_cpuhp(struct request_queue *q)
3859 LIST_HEAD(hctx_list);
3861 spin_lock(&q->unused_hctx_lock);
3862 list_splice_init(&q->unused_hctx_list, &hctx_list);
3863 spin_unlock(&q->unused_hctx_lock);
3865 mutex_lock(&blk_mq_cpuhp_lock);
3866 __blk_mq_remove_cpuhp_list(&hctx_list);
3867 mutex_unlock(&blk_mq_cpuhp_lock);
3869 spin_lock(&q->unused_hctx_lock);
3870 list_splice(&hctx_list, &q->unused_hctx_list);
3871 spin_unlock(&q->unused_hctx_lock);
3875 * Register cpuhp callbacks from all hw queues
3877 * Safe to call if this `request_queue` is live
3879 static void blk_mq_add_hw_queues_cpuhp(struct request_queue *q)
3881 struct blk_mq_hw_ctx *hctx;
3884 mutex_lock(&blk_mq_cpuhp_lock);
3885 queue_for_each_hw_ctx(q, hctx, i)
3886 __blk_mq_add_cpuhp(hctx);
3887 mutex_unlock(&blk_mq_cpuhp_lock);
3891 * Before freeing hw queue, clearing the flush request reference in
3892 * tags->rqs[] for avoiding potential UAF.
3894 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3895 unsigned int queue_depth, struct request *flush_rq)
3898 unsigned long flags;
3900 /* The hw queue may not be mapped yet */
3904 WARN_ON_ONCE(req_ref_read(flush_rq) != 0);
3906 for (i = 0; i < queue_depth; i++)
3907 cmpxchg(&tags->rqs[i], flush_rq, NULL);
3910 * Wait until all pending iteration is done.
3912 * Request reference is cleared and it is guaranteed to be observed
3913 * after the ->lock is released.
3915 spin_lock_irqsave(&tags->lock, flags);
3916 spin_unlock_irqrestore(&tags->lock, flags);
3919 /* hctx->ctxs will be freed in queue's release handler */
3920 static void blk_mq_exit_hctx(struct request_queue *q,
3921 struct blk_mq_tag_set *set,
3922 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3924 struct request *flush_rq = hctx->fq->flush_rq;
3926 if (blk_mq_hw_queue_mapped(hctx))
3927 blk_mq_tag_idle(hctx);
3929 if (blk_queue_init_done(q))
3930 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3931 set->queue_depth, flush_rq);
3932 if (set->ops->exit_request)
3933 set->ops->exit_request(set, flush_rq, hctx_idx);
3935 if (set->ops->exit_hctx)
3936 set->ops->exit_hctx(hctx, hctx_idx);
3938 xa_erase(&q->hctx_table, hctx_idx);
3940 spin_lock(&q->unused_hctx_lock);
3941 list_add(&hctx->hctx_list, &q->unused_hctx_list);
3942 spin_unlock(&q->unused_hctx_lock);
3945 static void blk_mq_exit_hw_queues(struct request_queue *q,
3946 struct blk_mq_tag_set *set, int nr_queue)
3948 struct blk_mq_hw_ctx *hctx;
3951 queue_for_each_hw_ctx(q, hctx, i) {
3954 blk_mq_remove_cpuhp(hctx);
3955 blk_mq_exit_hctx(q, set, hctx, i);
3959 static int blk_mq_init_hctx(struct request_queue *q,
3960 struct blk_mq_tag_set *set,
3961 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3963 hctx->queue_num = hctx_idx;
3965 hctx->tags = set->tags[hctx_idx];
3967 if (set->ops->init_hctx &&
3968 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3971 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3975 if (xa_insert(&q->hctx_table, hctx_idx, hctx, GFP_KERNEL))
3981 if (set->ops->exit_request)
3982 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
3984 if (set->ops->exit_hctx)
3985 set->ops->exit_hctx(hctx, hctx_idx);
3990 static struct blk_mq_hw_ctx *
3991 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3994 struct blk_mq_hw_ctx *hctx;
3995 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3997 hctx = kzalloc_node(sizeof(struct blk_mq_hw_ctx), gfp, node);
3999 goto fail_alloc_hctx;
4001 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
4004 atomic_set(&hctx->nr_active, 0);
4005 if (node == NUMA_NO_NODE)
4006 node = set->numa_node;
4007 hctx->numa_node = node;
4009 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
4010 spin_lock_init(&hctx->lock);
4011 INIT_LIST_HEAD(&hctx->dispatch);
4012 INIT_HLIST_NODE(&hctx->cpuhp_dead);
4013 INIT_HLIST_NODE(&hctx->cpuhp_online);
4015 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
4017 INIT_LIST_HEAD(&hctx->hctx_list);
4020 * Allocate space for all possible cpus to avoid allocation at
4023 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
4028 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
4029 gfp, node, false, false))
4033 spin_lock_init(&hctx->dispatch_wait_lock);
4034 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
4035 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
4037 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
4041 blk_mq_hctx_kobj_init(hctx);
4046 sbitmap_free(&hctx->ctx_map);
4050 free_cpumask_var(hctx->cpumask);
4057 static void blk_mq_init_cpu_queues(struct request_queue *q,
4058 unsigned int nr_hw_queues)
4060 struct blk_mq_tag_set *set = q->tag_set;
4063 for_each_possible_cpu(i) {
4064 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
4065 struct blk_mq_hw_ctx *hctx;
4069 spin_lock_init(&__ctx->lock);
4070 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
4071 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
4076 * Set local node, IFF we have more than one hw queue. If
4077 * not, we remain on the home node of the device
4079 for (j = 0; j < set->nr_maps; j++) {
4080 hctx = blk_mq_map_queue_type(q, j, i);
4081 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
4082 hctx->numa_node = cpu_to_node(i);
4087 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4088 unsigned int hctx_idx,
4091 struct blk_mq_tags *tags;
4094 tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
4098 ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
4100 blk_mq_free_rq_map(tags);
4107 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4110 if (blk_mq_is_shared_tags(set->flags)) {
4111 set->tags[hctx_idx] = set->shared_tags;
4116 set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
4119 return set->tags[hctx_idx];
4122 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4123 struct blk_mq_tags *tags,
4124 unsigned int hctx_idx)
4127 blk_mq_free_rqs(set, tags, hctx_idx);
4128 blk_mq_free_rq_map(tags);
4132 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4133 unsigned int hctx_idx)
4135 if (!blk_mq_is_shared_tags(set->flags))
4136 blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
4138 set->tags[hctx_idx] = NULL;
4141 static void blk_mq_map_swqueue(struct request_queue *q)
4143 unsigned int j, hctx_idx;
4145 struct blk_mq_hw_ctx *hctx;
4146 struct blk_mq_ctx *ctx;
4147 struct blk_mq_tag_set *set = q->tag_set;
4149 queue_for_each_hw_ctx(q, hctx, i) {
4150 cpumask_clear(hctx->cpumask);
4152 hctx->dispatch_from = NULL;
4156 * Map software to hardware queues.
4158 * If the cpu isn't present, the cpu is mapped to first hctx.
4160 for_each_possible_cpu(i) {
4162 ctx = per_cpu_ptr(q->queue_ctx, i);
4163 for (j = 0; j < set->nr_maps; j++) {
4164 if (!set->map[j].nr_queues) {
4165 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4166 HCTX_TYPE_DEFAULT, i);
4169 hctx_idx = set->map[j].mq_map[i];
4170 /* unmapped hw queue can be remapped after CPU topo changed */
4171 if (!set->tags[hctx_idx] &&
4172 !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4174 * If tags initialization fail for some hctx,
4175 * that hctx won't be brought online. In this
4176 * case, remap the current ctx to hctx[0] which
4177 * is guaranteed to always have tags allocated
4179 set->map[j].mq_map[i] = 0;
4182 hctx = blk_mq_map_queue_type(q, j, i);
4183 ctx->hctxs[j] = hctx;
4185 * If the CPU is already set in the mask, then we've
4186 * mapped this one already. This can happen if
4187 * devices share queues across queue maps.
4189 if (cpumask_test_cpu(i, hctx->cpumask))
4192 cpumask_set_cpu(i, hctx->cpumask);
4194 ctx->index_hw[hctx->type] = hctx->nr_ctx;
4195 hctx->ctxs[hctx->nr_ctx++] = ctx;
4198 * If the nr_ctx type overflows, we have exceeded the
4199 * amount of sw queues we can support.
4201 BUG_ON(!hctx->nr_ctx);
4204 for (; j < HCTX_MAX_TYPES; j++)
4205 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4206 HCTX_TYPE_DEFAULT, i);
4209 queue_for_each_hw_ctx(q, hctx, i) {
4213 * If no software queues are mapped to this hardware queue,
4214 * disable it and free the request entries.
4216 if (!hctx->nr_ctx) {
4217 /* Never unmap queue 0. We need it as a
4218 * fallback in case of a new remap fails
4222 __blk_mq_free_map_and_rqs(set, i);
4228 hctx->tags = set->tags[i];
4229 WARN_ON(!hctx->tags);
4232 * Set the map size to the number of mapped software queues.
4233 * This is more accurate and more efficient than looping
4234 * over all possibly mapped software queues.
4236 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4239 * Rule out isolated CPUs from hctx->cpumask to avoid
4240 * running block kworker on isolated CPUs
4242 for_each_cpu(cpu, hctx->cpumask) {
4243 if (cpu_is_isolated(cpu))
4244 cpumask_clear_cpu(cpu, hctx->cpumask);
4248 * Initialize batch roundrobin counts
4250 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4251 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4256 * Caller needs to ensure that we're either frozen/quiesced, or that
4257 * the queue isn't live yet.
4259 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
4261 struct blk_mq_hw_ctx *hctx;
4264 queue_for_each_hw_ctx(q, hctx, i) {
4266 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4268 blk_mq_tag_idle(hctx);
4269 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4274 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
4277 struct request_queue *q;
4278 unsigned int memflags;
4280 lockdep_assert_held(&set->tag_list_lock);
4282 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4283 memflags = blk_mq_freeze_queue(q);
4284 queue_set_hctx_shared(q, shared);
4285 blk_mq_unfreeze_queue(q, memflags);
4289 static void blk_mq_del_queue_tag_set(struct request_queue *q)
4291 struct blk_mq_tag_set *set = q->tag_set;
4293 mutex_lock(&set->tag_list_lock);
4294 list_del(&q->tag_set_list);
4295 if (list_is_singular(&set->tag_list)) {
4296 /* just transitioned to unshared */
4297 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4298 /* update existing queue */
4299 blk_mq_update_tag_set_shared(set, false);
4301 mutex_unlock(&set->tag_list_lock);
4302 INIT_LIST_HEAD(&q->tag_set_list);
4305 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4306 struct request_queue *q)
4308 mutex_lock(&set->tag_list_lock);
4311 * Check to see if we're transitioning to shared (from 1 to 2 queues).
4313 if (!list_empty(&set->tag_list) &&
4314 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4315 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4316 /* update existing queue */
4317 blk_mq_update_tag_set_shared(set, true);
4319 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4320 queue_set_hctx_shared(q, true);
4321 list_add_tail(&q->tag_set_list, &set->tag_list);
4323 mutex_unlock(&set->tag_list_lock);
4326 /* All allocations will be freed in release handler of q->mq_kobj */
4327 static int blk_mq_alloc_ctxs(struct request_queue *q)
4329 struct blk_mq_ctxs *ctxs;
4332 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
4336 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
4337 if (!ctxs->queue_ctx)
4340 for_each_possible_cpu(cpu) {
4341 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
4345 q->mq_kobj = &ctxs->kobj;
4346 q->queue_ctx = ctxs->queue_ctx;
4355 * It is the actual release handler for mq, but we do it from
4356 * request queue's release handler for avoiding use-after-free
4357 * and headache because q->mq_kobj shouldn't have been introduced,
4358 * but we can't group ctx/kctx kobj without it.
4360 void blk_mq_release(struct request_queue *q)
4362 struct blk_mq_hw_ctx *hctx, *next;
4365 queue_for_each_hw_ctx(q, hctx, i)
4366 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
4368 /* all hctx are in .unused_hctx_list now */
4369 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
4370 list_del_init(&hctx->hctx_list);
4371 kobject_put(&hctx->kobj);
4374 xa_destroy(&q->hctx_table);
4377 * release .mq_kobj and sw queue's kobject now because
4378 * both share lifetime with request queue.
4380 blk_mq_sysfs_deinit(q);
4383 struct request_queue *blk_mq_alloc_queue(struct blk_mq_tag_set *set,
4384 struct queue_limits *lim, void *queuedata)
4386 struct queue_limits default_lim = { };
4387 struct request_queue *q;
4392 lim->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT;
4393 if (set->nr_maps > HCTX_TYPE_POLL)
4394 lim->features |= BLK_FEAT_POLL;
4396 q = blk_alloc_queue(lim, set->numa_node);
4399 q->queuedata = queuedata;
4400 ret = blk_mq_init_allocated_queue(set, q);
4403 return ERR_PTR(ret);
4407 EXPORT_SYMBOL(blk_mq_alloc_queue);
4410 * blk_mq_destroy_queue - shutdown a request queue
4411 * @q: request queue to shutdown
4413 * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4414 * requests will be failed with -ENODEV. The caller is responsible for dropping
4415 * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4417 * Context: can sleep
4419 void blk_mq_destroy_queue(struct request_queue *q)
4421 WARN_ON_ONCE(!queue_is_mq(q));
4422 WARN_ON_ONCE(blk_queue_registered(q));
4426 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4427 blk_queue_start_drain(q);
4428 blk_mq_freeze_queue_wait(q);
4431 blk_mq_cancel_work_sync(q);
4432 blk_mq_exit_queue(q);
4434 EXPORT_SYMBOL(blk_mq_destroy_queue);
4436 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4437 struct queue_limits *lim, void *queuedata,
4438 struct lock_class_key *lkclass)
4440 struct request_queue *q;
4441 struct gendisk *disk;
4443 q = blk_mq_alloc_queue(set, lim, queuedata);
4447 disk = __alloc_disk_node(q, set->numa_node, lkclass);
4449 blk_mq_destroy_queue(q);
4451 return ERR_PTR(-ENOMEM);
4453 set_bit(GD_OWNS_QUEUE, &disk->state);
4456 EXPORT_SYMBOL(__blk_mq_alloc_disk);
4458 struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
4459 struct lock_class_key *lkclass)
4461 struct gendisk *disk;
4463 if (!blk_get_queue(q))
4465 disk = __alloc_disk_node(q, NUMA_NO_NODE, lkclass);
4470 EXPORT_SYMBOL(blk_mq_alloc_disk_for_queue);
4473 * Only hctx removed from cpuhp list can be reused
4475 static bool blk_mq_hctx_is_reusable(struct blk_mq_hw_ctx *hctx)
4477 return hlist_unhashed(&hctx->cpuhp_online) &&
4478 hlist_unhashed(&hctx->cpuhp_dead);
4481 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
4482 struct blk_mq_tag_set *set, struct request_queue *q,
4483 int hctx_idx, int node)
4485 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
4487 /* reuse dead hctx first */
4488 spin_lock(&q->unused_hctx_lock);
4489 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
4490 if (tmp->numa_node == node && blk_mq_hctx_is_reusable(tmp)) {
4496 list_del_init(&hctx->hctx_list);
4497 spin_unlock(&q->unused_hctx_lock);
4500 hctx = blk_mq_alloc_hctx(q, set, node);
4504 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
4510 kobject_put(&hctx->kobj);
4515 static void __blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4516 struct request_queue *q)
4518 struct blk_mq_hw_ctx *hctx;
4521 for (i = 0; i < set->nr_hw_queues; i++) {
4523 int node = blk_mq_get_hctx_node(set, i);
4524 struct blk_mq_hw_ctx *old_hctx = xa_load(&q->hctx_table, i);
4527 old_node = old_hctx->numa_node;
4528 blk_mq_exit_hctx(q, set, old_hctx, i);
4531 if (!blk_mq_alloc_and_init_hctx(set, q, i, node)) {
4534 pr_warn("Allocate new hctx on node %d fails, fallback to previous one on node %d\n",
4536 hctx = blk_mq_alloc_and_init_hctx(set, q, i, old_node);
4537 WARN_ON_ONCE(!hctx);
4541 * Increasing nr_hw_queues fails. Free the newly allocated
4542 * hctxs and keep the previous q->nr_hw_queues.
4544 if (i != set->nr_hw_queues) {
4545 j = q->nr_hw_queues;
4548 q->nr_hw_queues = set->nr_hw_queues;
4551 xa_for_each_start(&q->hctx_table, j, hctx, j)
4552 blk_mq_exit_hctx(q, set, hctx, j);
4555 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4556 struct request_queue *q)
4558 __blk_mq_realloc_hw_ctxs(set, q);
4560 /* unregister cpuhp callbacks for exited hctxs */
4561 blk_mq_remove_hw_queues_cpuhp(q);
4563 /* register cpuhp for new initialized hctxs */
4564 blk_mq_add_hw_queues_cpuhp(q);
4567 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4568 struct request_queue *q)
4570 /* mark the queue as mq asap */
4571 q->mq_ops = set->ops;
4574 * ->tag_set has to be setup before initialize hctx, which cpuphp
4575 * handler needs it for checking queue mapping
4579 if (blk_mq_alloc_ctxs(q))
4582 /* init q->mq_kobj and sw queues' kobjects */
4583 blk_mq_sysfs_init(q);
4585 INIT_LIST_HEAD(&q->unused_hctx_list);
4586 spin_lock_init(&q->unused_hctx_lock);
4588 xa_init(&q->hctx_table);
4590 blk_mq_realloc_hw_ctxs(set, q);
4591 if (!q->nr_hw_queues)
4594 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4595 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4597 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4599 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4600 INIT_LIST_HEAD(&q->flush_list);
4601 INIT_LIST_HEAD(&q->requeue_list);
4602 spin_lock_init(&q->requeue_lock);
4604 q->nr_requests = set->queue_depth;
4606 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4607 blk_mq_map_swqueue(q);
4608 blk_mq_add_queue_tag_set(set, q);
4617 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4619 /* tags can _not_ be used after returning from blk_mq_exit_queue */
4620 void blk_mq_exit_queue(struct request_queue *q)
4622 struct blk_mq_tag_set *set = q->tag_set;
4624 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4625 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4626 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4627 blk_mq_del_queue_tag_set(q);
4630 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4634 if (blk_mq_is_shared_tags(set->flags)) {
4635 set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4638 if (!set->shared_tags)
4642 for (i = 0; i < set->nr_hw_queues; i++) {
4643 if (!__blk_mq_alloc_map_and_rqs(set, i))
4652 __blk_mq_free_map_and_rqs(set, i);
4654 if (blk_mq_is_shared_tags(set->flags)) {
4655 blk_mq_free_map_and_rqs(set, set->shared_tags,
4656 BLK_MQ_NO_HCTX_IDX);
4663 * Allocate the request maps associated with this tag_set. Note that this
4664 * may reduce the depth asked for, if memory is tight. set->queue_depth
4665 * will be updated to reflect the allocated depth.
4667 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4672 depth = set->queue_depth;
4674 err = __blk_mq_alloc_rq_maps(set);
4678 set->queue_depth >>= 1;
4679 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4683 } while (set->queue_depth);
4685 if (!set->queue_depth || err) {
4686 pr_err("blk-mq: failed to allocate request map\n");
4690 if (depth != set->queue_depth)
4691 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4692 depth, set->queue_depth);
4697 static void blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4700 * blk_mq_map_queues() and multiple .map_queues() implementations
4701 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4702 * number of hardware queues.
4704 if (set->nr_maps == 1)
4705 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4707 if (set->ops->map_queues) {
4711 * transport .map_queues is usually done in the following
4714 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4715 * mask = get_cpu_mask(queue)
4716 * for_each_cpu(cpu, mask)
4717 * set->map[x].mq_map[cpu] = queue;
4720 * When we need to remap, the table has to be cleared for
4721 * killing stale mapping since one CPU may not be mapped
4724 for (i = 0; i < set->nr_maps; i++)
4725 blk_mq_clear_mq_map(&set->map[i]);
4727 set->ops->map_queues(set);
4729 BUG_ON(set->nr_maps > 1);
4730 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4734 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
4735 int new_nr_hw_queues)
4737 struct blk_mq_tags **new_tags;
4740 if (set->nr_hw_queues >= new_nr_hw_queues)
4743 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4744 GFP_KERNEL, set->numa_node);
4749 memcpy(new_tags, set->tags, set->nr_hw_queues *
4750 sizeof(*set->tags));
4752 set->tags = new_tags;
4754 for (i = set->nr_hw_queues; i < new_nr_hw_queues; i++) {
4755 if (!__blk_mq_alloc_map_and_rqs(set, i)) {
4756 while (--i >= set->nr_hw_queues)
4757 __blk_mq_free_map_and_rqs(set, i);
4764 set->nr_hw_queues = new_nr_hw_queues;
4769 * Alloc a tag set to be associated with one or more request queues.
4770 * May fail with EINVAL for various error conditions. May adjust the
4771 * requested depth down, if it's too large. In that case, the set
4772 * value will be stored in set->queue_depth.
4774 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4778 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4780 if (!set->nr_hw_queues)
4782 if (!set->queue_depth)
4784 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4787 if (!set->ops->queue_rq)
4790 if (!set->ops->get_budget ^ !set->ops->put_budget)
4793 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4794 pr_info("blk-mq: reduced tag depth to %u\n",
4796 set->queue_depth = BLK_MQ_MAX_DEPTH;
4801 else if (set->nr_maps > HCTX_MAX_TYPES)
4805 * If a crashdump is active, then we are potentially in a very
4806 * memory constrained environment. Limit us to 64 tags to prevent
4807 * using too much memory.
4809 if (is_kdump_kernel())
4810 set->queue_depth = min(64U, set->queue_depth);
4813 * There is no use for more h/w queues than cpus if we just have
4816 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4817 set->nr_hw_queues = nr_cpu_ids;
4819 if (set->flags & BLK_MQ_F_BLOCKING) {
4820 set->srcu = kmalloc(sizeof(*set->srcu), GFP_KERNEL);
4823 ret = init_srcu_struct(set->srcu);
4828 init_rwsem(&set->update_nr_hwq_lock);
4831 set->tags = kcalloc_node(set->nr_hw_queues,
4832 sizeof(struct blk_mq_tags *), GFP_KERNEL,
4835 goto out_cleanup_srcu;
4837 for (i = 0; i < set->nr_maps; i++) {
4838 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4839 sizeof(set->map[i].mq_map[0]),
4840 GFP_KERNEL, set->numa_node);
4841 if (!set->map[i].mq_map)
4842 goto out_free_mq_map;
4843 set->map[i].nr_queues = set->nr_hw_queues;
4846 blk_mq_update_queue_map(set);
4848 ret = blk_mq_alloc_set_map_and_rqs(set);
4850 goto out_free_mq_map;
4852 mutex_init(&set->tag_list_lock);
4853 INIT_LIST_HEAD(&set->tag_list);
4858 for (i = 0; i < set->nr_maps; i++) {
4859 kfree(set->map[i].mq_map);
4860 set->map[i].mq_map = NULL;
4865 if (set->flags & BLK_MQ_F_BLOCKING)
4866 cleanup_srcu_struct(set->srcu);
4868 if (set->flags & BLK_MQ_F_BLOCKING)
4872 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4874 /* allocate and initialize a tagset for a simple single-queue device */
4875 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4876 const struct blk_mq_ops *ops, unsigned int queue_depth,
4877 unsigned int set_flags)
4879 memset(set, 0, sizeof(*set));
4881 set->nr_hw_queues = 1;
4883 set->queue_depth = queue_depth;
4884 set->numa_node = NUMA_NO_NODE;
4885 set->flags = set_flags;
4886 return blk_mq_alloc_tag_set(set);
4888 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4890 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4894 for (i = 0; i < set->nr_hw_queues; i++)
4895 __blk_mq_free_map_and_rqs(set, i);
4897 if (blk_mq_is_shared_tags(set->flags)) {
4898 blk_mq_free_map_and_rqs(set, set->shared_tags,
4899 BLK_MQ_NO_HCTX_IDX);
4902 for (j = 0; j < set->nr_maps; j++) {
4903 kfree(set->map[j].mq_map);
4904 set->map[j].mq_map = NULL;
4909 if (set->flags & BLK_MQ_F_BLOCKING) {
4910 cleanup_srcu_struct(set->srcu);
4914 EXPORT_SYMBOL(blk_mq_free_tag_set);
4916 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
4918 struct blk_mq_tag_set *set = q->tag_set;
4919 struct blk_mq_hw_ctx *hctx;
4923 if (WARN_ON_ONCE(!q->mq_freeze_depth))
4929 if (q->nr_requests == nr)
4932 blk_mq_quiesce_queue(q);
4935 queue_for_each_hw_ctx(q, hctx, i) {
4939 * If we're using an MQ scheduler, just update the scheduler
4940 * queue depth. This is similar to what the old code would do.
4942 if (hctx->sched_tags) {
4943 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
4946 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
4951 if (q->elevator && q->elevator->type->ops.depth_updated)
4952 q->elevator->type->ops.depth_updated(hctx);
4955 q->nr_requests = nr;
4956 if (blk_mq_is_shared_tags(set->flags)) {
4958 blk_mq_tag_update_sched_shared_tags(q);
4960 blk_mq_tag_resize_shared_tags(set, nr);
4964 blk_mq_unquiesce_queue(q);
4969 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
4972 struct request_queue *q;
4973 int prev_nr_hw_queues = set->nr_hw_queues;
4974 unsigned int memflags;
4977 lockdep_assert_held(&set->tag_list_lock);
4979 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
4980 nr_hw_queues = nr_cpu_ids;
4981 if (nr_hw_queues < 1)
4983 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
4986 memflags = memalloc_noio_save();
4987 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4988 blk_mq_debugfs_unregister_hctxs(q);
4989 blk_mq_sysfs_unregister_hctxs(q);
4992 list_for_each_entry(q, &set->tag_list, tag_set_list)
4993 blk_mq_freeze_queue_nomemsave(q);
4995 if (blk_mq_realloc_tag_set_tags(set, nr_hw_queues) < 0) {
4996 list_for_each_entry(q, &set->tag_list, tag_set_list)
4997 blk_mq_unfreeze_queue_nomemrestore(q);
5002 blk_mq_update_queue_map(set);
5003 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5004 __blk_mq_realloc_hw_ctxs(set, q);
5006 if (q->nr_hw_queues != set->nr_hw_queues) {
5007 int i = prev_nr_hw_queues;
5009 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
5010 nr_hw_queues, prev_nr_hw_queues);
5011 for (; i < set->nr_hw_queues; i++)
5012 __blk_mq_free_map_and_rqs(set, i);
5014 set->nr_hw_queues = prev_nr_hw_queues;
5017 blk_mq_map_swqueue(q);
5020 /* elv_update_nr_hw_queues() unfreeze queue for us */
5021 list_for_each_entry(q, &set->tag_list, tag_set_list)
5022 elv_update_nr_hw_queues(q);
5025 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5026 blk_mq_sysfs_register_hctxs(q);
5027 blk_mq_debugfs_register_hctxs(q);
5029 blk_mq_remove_hw_queues_cpuhp(q);
5030 blk_mq_add_hw_queues_cpuhp(q);
5032 memalloc_noio_restore(memflags);
5034 /* Free the excess tags when nr_hw_queues shrink. */
5035 for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
5036 __blk_mq_free_map_and_rqs(set, i);
5039 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
5041 down_write(&set->update_nr_hwq_lock);
5042 mutex_lock(&set->tag_list_lock);
5043 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
5044 mutex_unlock(&set->tag_list_lock);
5045 up_write(&set->update_nr_hwq_lock);
5047 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
5049 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
5050 struct io_comp_batch *iob, unsigned int flags)
5052 long state = get_current_state();
5056 ret = q->mq_ops->poll(hctx, iob);
5058 __set_current_state(TASK_RUNNING);
5062 if (signal_pending_state(state, current))
5063 __set_current_state(TASK_RUNNING);
5064 if (task_is_running(current))
5067 if (ret < 0 || (flags & BLK_POLL_ONESHOT))
5070 } while (!need_resched());
5072 __set_current_state(TASK_RUNNING);
5076 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
5077 struct io_comp_batch *iob, unsigned int flags)
5079 if (!blk_mq_can_poll(q))
5081 return blk_hctx_poll(q, xa_load(&q->hctx_table, cookie), iob, flags);
5084 int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
5085 unsigned int poll_flags)
5087 struct request_queue *q = rq->q;
5090 if (!blk_rq_is_poll(rq))
5092 if (!percpu_ref_tryget(&q->q_usage_counter))
5095 ret = blk_hctx_poll(q, rq->mq_hctx, iob, poll_flags);
5100 EXPORT_SYMBOL_GPL(blk_rq_poll);
5102 unsigned int blk_mq_rq_cpu(struct request *rq)
5104 return rq->mq_ctx->cpu;
5106 EXPORT_SYMBOL(blk_mq_rq_cpu);
5108 void blk_mq_cancel_work_sync(struct request_queue *q)
5110 struct blk_mq_hw_ctx *hctx;
5113 cancel_delayed_work_sync(&q->requeue_work);
5115 queue_for_each_hw_ctx(q, hctx, i)
5116 cancel_delayed_work_sync(&hctx->run_work);
5119 static int __init blk_mq_init(void)
5123 for_each_possible_cpu(i)
5124 init_llist_head(&per_cpu(blk_cpu_done, i));
5125 for_each_possible_cpu(i)
5126 INIT_CSD(&per_cpu(blk_cpu_csd, i),
5127 __blk_mq_complete_request_remote, NULL);
5128 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
5130 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
5131 "block/softirq:dead", NULL,
5132 blk_softirq_cpu_dead);
5133 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
5134 blk_mq_hctx_notify_dead);
5135 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
5136 blk_mq_hctx_notify_online,
5137 blk_mq_hctx_notify_offline);
5140 subsys_initcall(blk_mq_init);