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/sysctl.h>
25 #include <linux/sched/topology.h>
26 #include <linux/sched/signal.h>
27 #include <linux/delay.h>
28 #include <linux/crash_dump.h>
29 #include <linux/prefetch.h>
30 #include <linux/blk-crypto.h>
31 #include <linux/part_stat.h>
33 #include <trace/events/block.h>
35 #include <linux/blk-mq.h>
36 #include <linux/t10-pi.h>
39 #include "blk-mq-debugfs.h"
40 #include "blk-mq-tag.h"
43 #include "blk-mq-sched.h"
44 #include "blk-rq-qos.h"
46 static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
48 static void blk_mq_poll_stats_start(struct request_queue *q);
49 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
51 static int blk_mq_poll_stats_bkt(const struct request *rq)
53 int ddir, sectors, bucket;
55 ddir = rq_data_dir(rq);
56 sectors = blk_rq_stats_sectors(rq);
58 bucket = ddir + 2 * ilog2(sectors);
62 else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
63 return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
68 #define BLK_QC_T_SHIFT 16
69 #define BLK_QC_T_INTERNAL (1U << 31)
71 static inline struct blk_mq_hw_ctx *blk_qc_to_hctx(struct request_queue *q,
74 return q->queue_hw_ctx[(qc & ~BLK_QC_T_INTERNAL) >> BLK_QC_T_SHIFT];
77 static inline struct request *blk_qc_to_rq(struct blk_mq_hw_ctx *hctx,
80 unsigned int tag = qc & ((1U << BLK_QC_T_SHIFT) - 1);
82 if (qc & BLK_QC_T_INTERNAL)
83 return blk_mq_tag_to_rq(hctx->sched_tags, tag);
84 return blk_mq_tag_to_rq(hctx->tags, tag);
87 static inline blk_qc_t blk_rq_to_qc(struct request *rq)
89 return (rq->mq_hctx->queue_num << BLK_QC_T_SHIFT) |
91 rq->tag : (rq->internal_tag | BLK_QC_T_INTERNAL));
95 * Check if any of the ctx, dispatch list or elevator
96 * have pending work in this hardware queue.
98 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
100 return !list_empty_careful(&hctx->dispatch) ||
101 sbitmap_any_bit_set(&hctx->ctx_map) ||
102 blk_mq_sched_has_work(hctx);
106 * Mark this ctx as having pending work in this hardware queue
108 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
109 struct blk_mq_ctx *ctx)
111 const int bit = ctx->index_hw[hctx->type];
113 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
114 sbitmap_set_bit(&hctx->ctx_map, bit);
117 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
118 struct blk_mq_ctx *ctx)
120 const int bit = ctx->index_hw[hctx->type];
122 sbitmap_clear_bit(&hctx->ctx_map, bit);
126 struct block_device *part;
127 unsigned int inflight[2];
130 static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
131 struct request *rq, void *priv,
134 struct mq_inflight *mi = priv;
136 if ((!mi->part->bd_partno || rq->part == mi->part) &&
137 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
138 mi->inflight[rq_data_dir(rq)]++;
143 unsigned int blk_mq_in_flight(struct request_queue *q,
144 struct block_device *part)
146 struct mq_inflight mi = { .part = part };
148 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
150 return mi.inflight[0] + mi.inflight[1];
153 void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
154 unsigned int inflight[2])
156 struct mq_inflight mi = { .part = part };
158 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
159 inflight[0] = mi.inflight[0];
160 inflight[1] = mi.inflight[1];
163 void blk_freeze_queue_start(struct request_queue *q)
165 mutex_lock(&q->mq_freeze_lock);
166 if (++q->mq_freeze_depth == 1) {
167 percpu_ref_kill(&q->q_usage_counter);
168 mutex_unlock(&q->mq_freeze_lock);
170 blk_mq_run_hw_queues(q, false);
172 mutex_unlock(&q->mq_freeze_lock);
175 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
177 void blk_mq_freeze_queue_wait(struct request_queue *q)
179 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
181 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
183 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
184 unsigned long timeout)
186 return wait_event_timeout(q->mq_freeze_wq,
187 percpu_ref_is_zero(&q->q_usage_counter),
190 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
193 * Guarantee no request is in use, so we can change any data structure of
194 * the queue afterward.
196 void blk_freeze_queue(struct request_queue *q)
199 * In the !blk_mq case we are only calling this to kill the
200 * q_usage_counter, otherwise this increases the freeze depth
201 * and waits for it to return to zero. For this reason there is
202 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
203 * exported to drivers as the only user for unfreeze is blk_mq.
205 blk_freeze_queue_start(q);
206 blk_mq_freeze_queue_wait(q);
209 void blk_mq_freeze_queue(struct request_queue *q)
212 * ...just an alias to keep freeze and unfreeze actions balanced
213 * in the blk_mq_* namespace
217 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
219 void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
221 mutex_lock(&q->mq_freeze_lock);
223 q->q_usage_counter.data->force_atomic = true;
224 q->mq_freeze_depth--;
225 WARN_ON_ONCE(q->mq_freeze_depth < 0);
226 if (!q->mq_freeze_depth) {
227 percpu_ref_resurrect(&q->q_usage_counter);
228 wake_up_all(&q->mq_freeze_wq);
230 mutex_unlock(&q->mq_freeze_lock);
233 void blk_mq_unfreeze_queue(struct request_queue *q)
235 __blk_mq_unfreeze_queue(q, false);
237 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
240 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
241 * mpt3sas driver such that this function can be removed.
243 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
247 spin_lock_irqsave(&q->queue_lock, flags);
248 if (!q->quiesce_depth++)
249 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
250 spin_unlock_irqrestore(&q->queue_lock, flags);
252 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
255 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
258 * Note: it is driver's responsibility for making sure that quiesce has
261 void blk_mq_wait_quiesce_done(struct request_queue *q)
263 struct blk_mq_hw_ctx *hctx;
267 queue_for_each_hw_ctx(q, hctx, i) {
268 if (hctx->flags & BLK_MQ_F_BLOCKING)
269 synchronize_srcu(hctx->srcu);
276 EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
279 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
282 * Note: this function does not prevent that the struct request end_io()
283 * callback function is invoked. Once this function is returned, we make
284 * sure no dispatch can happen until the queue is unquiesced via
285 * blk_mq_unquiesce_queue().
287 void blk_mq_quiesce_queue(struct request_queue *q)
289 blk_mq_quiesce_queue_nowait(q);
290 blk_mq_wait_quiesce_done(q);
292 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
295 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
298 * This function recovers queue into the state before quiescing
299 * which is done by blk_mq_quiesce_queue.
301 void blk_mq_unquiesce_queue(struct request_queue *q)
304 bool run_queue = false;
306 spin_lock_irqsave(&q->queue_lock, flags);
307 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
309 } else if (!--q->quiesce_depth) {
310 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
313 spin_unlock_irqrestore(&q->queue_lock, flags);
315 /* dispatch requests which are inserted during quiescing */
317 blk_mq_run_hw_queues(q, true);
319 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
321 void blk_mq_wake_waiters(struct request_queue *q)
323 struct blk_mq_hw_ctx *hctx;
326 queue_for_each_hw_ctx(q, hctx, i)
327 if (blk_mq_hw_queue_mapped(hctx))
328 blk_mq_tag_wakeup_all(hctx->tags, true);
331 void blk_rq_init(struct request_queue *q, struct request *rq)
333 memset(rq, 0, sizeof(*rq));
335 INIT_LIST_HEAD(&rq->queuelist);
337 rq->__sector = (sector_t) -1;
338 INIT_HLIST_NODE(&rq->hash);
339 RB_CLEAR_NODE(&rq->rb_node);
340 rq->tag = BLK_MQ_NO_TAG;
341 rq->internal_tag = BLK_MQ_NO_TAG;
342 rq->start_time_ns = ktime_get_ns();
344 blk_crypto_rq_set_defaults(rq);
346 EXPORT_SYMBOL(blk_rq_init);
348 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
349 struct blk_mq_tags *tags, unsigned int tag, u64 alloc_time_ns)
351 struct blk_mq_ctx *ctx = data->ctx;
352 struct blk_mq_hw_ctx *hctx = data->hctx;
353 struct request_queue *q = data->q;
354 struct request *rq = tags->static_rqs[tag];
359 rq->cmd_flags = data->cmd_flags;
361 if (data->flags & BLK_MQ_REQ_PM)
362 data->rq_flags |= RQF_PM;
363 if (blk_queue_io_stat(q))
364 data->rq_flags |= RQF_IO_STAT;
365 rq->rq_flags = data->rq_flags;
367 if (!(data->rq_flags & RQF_ELV)) {
369 rq->internal_tag = BLK_MQ_NO_TAG;
371 rq->tag = BLK_MQ_NO_TAG;
372 rq->internal_tag = tag;
376 if (blk_mq_need_time_stamp(rq))
377 rq->start_time_ns = ktime_get_ns();
379 rq->start_time_ns = 0;
381 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
382 rq->alloc_time_ns = alloc_time_ns;
384 rq->io_start_time_ns = 0;
385 rq->stats_sectors = 0;
386 rq->nr_phys_segments = 0;
387 #if defined(CONFIG_BLK_DEV_INTEGRITY)
388 rq->nr_integrity_segments = 0;
391 rq->end_io_data = NULL;
393 blk_crypto_rq_set_defaults(rq);
394 INIT_LIST_HEAD(&rq->queuelist);
395 /* tag was already set */
396 WRITE_ONCE(rq->deadline, 0);
397 refcount_set(&rq->ref, 1);
399 if (rq->rq_flags & RQF_ELV) {
400 struct elevator_queue *e = data->q->elevator;
402 INIT_HLIST_NODE(&rq->hash);
403 RB_CLEAR_NODE(&rq->rb_node);
405 if (!op_is_flush(data->cmd_flags) &&
406 e->type->ops.prepare_request) {
407 e->type->ops.prepare_request(rq);
408 rq->rq_flags |= RQF_ELVPRIV;
415 static inline struct request *
416 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data,
419 unsigned int tag, tag_offset;
420 struct blk_mq_tags *tags;
422 unsigned long tag_mask;
425 tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
426 if (unlikely(!tag_mask))
429 tags = blk_mq_tags_from_data(data);
430 for (i = 0; tag_mask; i++) {
431 if (!(tag_mask & (1UL << i)))
433 tag = tag_offset + i;
434 prefetch(tags->static_rqs[tag]);
435 tag_mask &= ~(1UL << i);
436 rq = blk_mq_rq_ctx_init(data, tags, tag, alloc_time_ns);
437 rq_list_add(data->cached_rq, rq);
440 /* caller already holds a reference, add for remainder */
441 percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
444 return rq_list_pop(data->cached_rq);
447 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
449 struct request_queue *q = data->q;
450 u64 alloc_time_ns = 0;
454 /* alloc_time includes depth and tag waits */
455 if (blk_queue_rq_alloc_time(q))
456 alloc_time_ns = ktime_get_ns();
458 if (data->cmd_flags & REQ_NOWAIT)
459 data->flags |= BLK_MQ_REQ_NOWAIT;
462 struct elevator_queue *e = q->elevator;
464 data->rq_flags |= RQF_ELV;
467 * Flush/passthrough requests are special and go directly to the
468 * dispatch list. Don't include reserved tags in the
469 * limiting, as it isn't useful.
471 if (!op_is_flush(data->cmd_flags) &&
472 !blk_op_is_passthrough(data->cmd_flags) &&
473 e->type->ops.limit_depth &&
474 !(data->flags & BLK_MQ_REQ_RESERVED))
475 e->type->ops.limit_depth(data->cmd_flags, data);
479 data->ctx = blk_mq_get_ctx(q);
480 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
481 if (!(data->rq_flags & RQF_ELV))
482 blk_mq_tag_busy(data->hctx);
485 * Try batched alloc if we want more than 1 tag.
487 if (data->nr_tags > 1) {
488 rq = __blk_mq_alloc_requests_batch(data, alloc_time_ns);
495 * Waiting allocations only fail because of an inactive hctx. In that
496 * case just retry the hctx assignment and tag allocation as CPU hotplug
497 * should have migrated us to an online CPU by now.
499 tag = blk_mq_get_tag(data);
500 if (tag == BLK_MQ_NO_TAG) {
501 if (data->flags & BLK_MQ_REQ_NOWAIT)
504 * Give up the CPU and sleep for a random short time to
505 * ensure that thread using a realtime scheduling class
506 * are migrated off the CPU, and thus off the hctx that
513 return blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag,
517 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
518 blk_mq_req_flags_t flags)
520 struct blk_mq_alloc_data data = {
529 ret = blk_queue_enter(q, flags);
533 rq = __blk_mq_alloc_requests(&data);
537 rq->__sector = (sector_t) -1;
538 rq->bio = rq->biotail = NULL;
542 return ERR_PTR(-EWOULDBLOCK);
544 EXPORT_SYMBOL(blk_mq_alloc_request);
546 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
547 unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
549 struct blk_mq_alloc_data data = {
555 u64 alloc_time_ns = 0;
560 /* alloc_time includes depth and tag waits */
561 if (blk_queue_rq_alloc_time(q))
562 alloc_time_ns = ktime_get_ns();
565 * If the tag allocator sleeps we could get an allocation for a
566 * different hardware context. No need to complicate the low level
567 * allocator for this for the rare use case of a command tied to
570 if (WARN_ON_ONCE(!(flags & (BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED))))
571 return ERR_PTR(-EINVAL);
573 if (hctx_idx >= q->nr_hw_queues)
574 return ERR_PTR(-EIO);
576 ret = blk_queue_enter(q, flags);
581 * Check if the hardware context is actually mapped to anything.
582 * If not tell the caller that it should skip this queue.
585 data.hctx = q->queue_hw_ctx[hctx_idx];
586 if (!blk_mq_hw_queue_mapped(data.hctx))
588 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
589 data.ctx = __blk_mq_get_ctx(q, cpu);
592 blk_mq_tag_busy(data.hctx);
594 data.rq_flags |= RQF_ELV;
597 tag = blk_mq_get_tag(&data);
598 if (tag == BLK_MQ_NO_TAG)
600 return blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag,
607 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
609 static void __blk_mq_free_request(struct request *rq)
611 struct request_queue *q = rq->q;
612 struct blk_mq_ctx *ctx = rq->mq_ctx;
613 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
614 const int sched_tag = rq->internal_tag;
616 blk_crypto_free_request(rq);
617 blk_pm_mark_last_busy(rq);
619 if (rq->tag != BLK_MQ_NO_TAG)
620 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
621 if (sched_tag != BLK_MQ_NO_TAG)
622 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
623 blk_mq_sched_restart(hctx);
627 void blk_mq_free_request(struct request *rq)
629 struct request_queue *q = rq->q;
630 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
632 if ((rq->rq_flags & RQF_ELVPRIV) &&
633 q->elevator->type->ops.finish_request)
634 q->elevator->type->ops.finish_request(rq);
636 if (rq->rq_flags & RQF_MQ_INFLIGHT)
637 __blk_mq_dec_active_requests(hctx);
639 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
640 laptop_io_completion(q->disk->bdi);
644 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
645 if (refcount_dec_and_test(&rq->ref))
646 __blk_mq_free_request(rq);
648 EXPORT_SYMBOL_GPL(blk_mq_free_request);
650 void blk_mq_free_plug_rqs(struct blk_plug *plug)
654 while ((rq = rq_list_pop(&plug->cached_rq)) != NULL)
655 blk_mq_free_request(rq);
658 void blk_dump_rq_flags(struct request *rq, char *msg)
660 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
661 rq->q->disk ? rq->q->disk->disk_name : "?",
662 (unsigned long long) rq->cmd_flags);
664 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
665 (unsigned long long)blk_rq_pos(rq),
666 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
667 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
668 rq->bio, rq->biotail, blk_rq_bytes(rq));
670 EXPORT_SYMBOL(blk_dump_rq_flags);
672 static void req_bio_endio(struct request *rq, struct bio *bio,
673 unsigned int nbytes, blk_status_t error)
675 if (unlikely(error)) {
676 bio->bi_status = error;
677 } else if (req_op(rq) == REQ_OP_ZONE_APPEND) {
679 * Partial zone append completions cannot be supported as the
680 * BIO fragments may end up not being written sequentially.
682 if (bio->bi_iter.bi_size != nbytes)
683 bio->bi_status = BLK_STS_IOERR;
685 bio->bi_iter.bi_sector = rq->__sector;
688 bio_advance(bio, nbytes);
690 if (unlikely(rq->rq_flags & RQF_QUIET))
691 bio_set_flag(bio, BIO_QUIET);
692 /* don't actually finish bio if it's part of flush sequence */
693 if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
697 static void blk_account_io_completion(struct request *req, unsigned int bytes)
699 if (req->part && blk_do_io_stat(req)) {
700 const int sgrp = op_stat_group(req_op(req));
703 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
708 static void blk_print_req_error(struct request *req, blk_status_t status)
710 printk_ratelimited(KERN_ERR
711 "%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
712 "phys_seg %u prio class %u\n",
713 blk_status_to_str(status),
714 req->q->disk ? req->q->disk->disk_name : "?",
715 blk_rq_pos(req), req_op(req), blk_op_str(req_op(req)),
716 req->cmd_flags & ~REQ_OP_MASK,
717 req->nr_phys_segments,
718 IOPRIO_PRIO_CLASS(req->ioprio));
722 * blk_update_request - Complete multiple bytes without completing the request
723 * @req: the request being processed
724 * @error: block status code
725 * @nr_bytes: number of bytes to complete for @req
728 * Ends I/O on a number of bytes attached to @req, but doesn't complete
729 * the request structure even if @req doesn't have leftover.
730 * If @req has leftover, sets it up for the next range of segments.
732 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
733 * %false return from this function.
736 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
737 * except in the consistency check at the end of this function.
740 * %false - this request doesn't have any more data
741 * %true - this request has more data
743 bool blk_update_request(struct request *req, blk_status_t error,
744 unsigned int nr_bytes)
748 trace_block_rq_complete(req, error, nr_bytes);
753 #ifdef CONFIG_BLK_DEV_INTEGRITY
754 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
756 req->q->integrity.profile->complete_fn(req, nr_bytes);
759 if (unlikely(error && !blk_rq_is_passthrough(req) &&
760 !(req->rq_flags & RQF_QUIET)))
761 blk_print_req_error(req, error);
763 blk_account_io_completion(req, nr_bytes);
767 struct bio *bio = req->bio;
768 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
770 if (bio_bytes == bio->bi_iter.bi_size)
771 req->bio = bio->bi_next;
773 /* Completion has already been traced */
774 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
775 req_bio_endio(req, bio, bio_bytes, error);
777 total_bytes += bio_bytes;
778 nr_bytes -= bio_bytes;
789 * Reset counters so that the request stacking driver
790 * can find how many bytes remain in the request
797 req->__data_len -= total_bytes;
799 /* update sector only for requests with clear definition of sector */
800 if (!blk_rq_is_passthrough(req))
801 req->__sector += total_bytes >> 9;
803 /* mixed attributes always follow the first bio */
804 if (req->rq_flags & RQF_MIXED_MERGE) {
805 req->cmd_flags &= ~REQ_FAILFAST_MASK;
806 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
809 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
811 * If total number of sectors is less than the first segment
812 * size, something has gone terribly wrong.
814 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
815 blk_dump_rq_flags(req, "request botched");
816 req->__data_len = blk_rq_cur_bytes(req);
819 /* recalculate the number of segments */
820 req->nr_phys_segments = blk_recalc_rq_segments(req);
825 EXPORT_SYMBOL_GPL(blk_update_request);
827 static void __blk_account_io_done(struct request *req, u64 now)
829 const int sgrp = op_stat_group(req_op(req));
832 update_io_ticks(req->part, jiffies, true);
833 part_stat_inc(req->part, ios[sgrp]);
834 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
838 static inline void blk_account_io_done(struct request *req, u64 now)
841 * Account IO completion. flush_rq isn't accounted as a
842 * normal IO on queueing nor completion. Accounting the
843 * containing request is enough.
845 if (blk_do_io_stat(req) && req->part &&
846 !(req->rq_flags & RQF_FLUSH_SEQ))
847 __blk_account_io_done(req, now);
850 static void __blk_account_io_start(struct request *rq)
852 /* passthrough requests can hold bios that do not have ->bi_bdev set */
853 if (rq->bio && rq->bio->bi_bdev)
854 rq->part = rq->bio->bi_bdev;
855 else if (rq->q->disk)
856 rq->part = rq->q->disk->part0;
859 update_io_ticks(rq->part, jiffies, false);
863 static inline void blk_account_io_start(struct request *req)
865 if (blk_do_io_stat(req))
866 __blk_account_io_start(req);
869 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
871 if (rq->rq_flags & RQF_STATS) {
872 blk_mq_poll_stats_start(rq->q);
873 blk_stat_add(rq, now);
876 blk_mq_sched_completed_request(rq, now);
877 blk_account_io_done(rq, now);
880 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
882 if (blk_mq_need_time_stamp(rq))
883 __blk_mq_end_request_acct(rq, ktime_get_ns());
886 rq_qos_done(rq->q, rq);
887 rq->end_io(rq, error);
889 blk_mq_free_request(rq);
892 EXPORT_SYMBOL(__blk_mq_end_request);
894 void blk_mq_end_request(struct request *rq, blk_status_t error)
896 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
898 __blk_mq_end_request(rq, error);
900 EXPORT_SYMBOL(blk_mq_end_request);
902 #define TAG_COMP_BATCH 32
904 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
905 int *tag_array, int nr_tags)
907 struct request_queue *q = hctx->queue;
910 * All requests should have been marked as RQF_MQ_INFLIGHT, so
911 * update hctx->nr_active in batch
913 if (hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
914 __blk_mq_sub_active_requests(hctx, nr_tags);
916 blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
917 percpu_ref_put_many(&q->q_usage_counter, nr_tags);
920 void blk_mq_end_request_batch(struct io_comp_batch *iob)
922 int tags[TAG_COMP_BATCH], nr_tags = 0;
923 struct blk_mq_hw_ctx *cur_hctx = NULL;
928 now = ktime_get_ns();
930 while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
932 prefetch(rq->rq_next);
934 blk_update_request(rq, BLK_STS_OK, blk_rq_bytes(rq));
936 __blk_mq_end_request_acct(rq, now);
938 rq_qos_done(rq->q, rq);
940 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
941 if (!refcount_dec_and_test(&rq->ref))
944 blk_crypto_free_request(rq);
945 blk_pm_mark_last_busy(rq);
947 if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
949 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
951 cur_hctx = rq->mq_hctx;
953 tags[nr_tags++] = rq->tag;
957 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
959 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
961 static void blk_complete_reqs(struct llist_head *list)
963 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
964 struct request *rq, *next;
966 llist_for_each_entry_safe(rq, next, entry, ipi_list)
967 rq->q->mq_ops->complete(rq);
970 static __latent_entropy void blk_done_softirq(struct softirq_action *h)
972 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
975 static int blk_softirq_cpu_dead(unsigned int cpu)
977 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
981 static void __blk_mq_complete_request_remote(void *data)
983 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
986 static inline bool blk_mq_complete_need_ipi(struct request *rq)
988 int cpu = raw_smp_processor_id();
990 if (!IS_ENABLED(CONFIG_SMP) ||
991 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
994 * With force threaded interrupts enabled, raising softirq from an SMP
995 * function call will always result in waking the ksoftirqd thread.
996 * This is probably worse than completing the request on a different
999 if (force_irqthreads())
1002 /* same CPU or cache domain? Complete locally */
1003 if (cpu == rq->mq_ctx->cpu ||
1004 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1005 cpus_share_cache(cpu, rq->mq_ctx->cpu)))
1008 /* don't try to IPI to an offline CPU */
1009 return cpu_online(rq->mq_ctx->cpu);
1012 static void blk_mq_complete_send_ipi(struct request *rq)
1014 struct llist_head *list;
1017 cpu = rq->mq_ctx->cpu;
1018 list = &per_cpu(blk_cpu_done, cpu);
1019 if (llist_add(&rq->ipi_list, list)) {
1020 INIT_CSD(&rq->csd, __blk_mq_complete_request_remote, rq);
1021 smp_call_function_single_async(cpu, &rq->csd);
1025 static void blk_mq_raise_softirq(struct request *rq)
1027 struct llist_head *list;
1030 list = this_cpu_ptr(&blk_cpu_done);
1031 if (llist_add(&rq->ipi_list, list))
1032 raise_softirq(BLOCK_SOFTIRQ);
1036 bool blk_mq_complete_request_remote(struct request *rq)
1038 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1041 * For a polled request, always complete locallly, it's pointless
1042 * to redirect the completion.
1044 if (rq->cmd_flags & REQ_POLLED)
1047 if (blk_mq_complete_need_ipi(rq)) {
1048 blk_mq_complete_send_ipi(rq);
1052 if (rq->q->nr_hw_queues == 1) {
1053 blk_mq_raise_softirq(rq);
1058 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1061 * blk_mq_complete_request - end I/O on a request
1062 * @rq: the request being processed
1065 * Complete a request by scheduling the ->complete_rq operation.
1067 void blk_mq_complete_request(struct request *rq)
1069 if (!blk_mq_complete_request_remote(rq))
1070 rq->q->mq_ops->complete(rq);
1072 EXPORT_SYMBOL(blk_mq_complete_request);
1074 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
1075 __releases(hctx->srcu)
1077 if (!(hctx->flags & BLK_MQ_F_BLOCKING))
1080 srcu_read_unlock(hctx->srcu, srcu_idx);
1083 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
1084 __acquires(hctx->srcu)
1086 if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
1087 /* shut up gcc false positive */
1091 *srcu_idx = srcu_read_lock(hctx->srcu);
1095 * blk_mq_start_request - Start processing a request
1096 * @rq: Pointer to request to be started
1098 * Function used by device drivers to notify the block layer that a request
1099 * is going to be processed now, so blk layer can do proper initializations
1100 * such as starting the timeout timer.
1102 void blk_mq_start_request(struct request *rq)
1104 struct request_queue *q = rq->q;
1106 trace_block_rq_issue(rq);
1108 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
1110 #ifdef CONFIG_BLK_CGROUP
1112 start_time = bio_issue_time(&rq->bio->bi_issue);
1115 start_time = ktime_get_ns();
1116 rq->io_start_time_ns = start_time;
1117 rq->stats_sectors = blk_rq_sectors(rq);
1118 rq->rq_flags |= RQF_STATS;
1119 rq_qos_issue(q, rq);
1122 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1125 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1127 #ifdef CONFIG_BLK_DEV_INTEGRITY
1128 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1129 q->integrity.profile->prepare_fn(rq);
1131 if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1132 WRITE_ONCE(rq->bio->bi_cookie, blk_rq_to_qc(rq));
1134 EXPORT_SYMBOL(blk_mq_start_request);
1137 * blk_end_sync_rq - executes a completion event on a request
1138 * @rq: request to complete
1139 * @error: end I/O status of the request
1141 static void blk_end_sync_rq(struct request *rq, blk_status_t error)
1143 struct completion *waiting = rq->end_io_data;
1145 rq->end_io_data = (void *)(uintptr_t)error;
1148 * complete last, if this is a stack request the process (and thus
1149 * the rq pointer) could be invalid right after this complete()
1155 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1156 * @rq: request to insert
1157 * @at_head: insert request at head or tail of queue
1158 * @done: I/O completion handler
1161 * Insert a fully prepared request at the back of the I/O scheduler queue
1162 * for execution. Don't wait for completion.
1165 * This function will invoke @done directly if the queue is dead.
1167 void blk_execute_rq_nowait(struct request *rq, bool at_head, rq_end_io_fn *done)
1169 WARN_ON(irqs_disabled());
1170 WARN_ON(!blk_rq_is_passthrough(rq));
1174 blk_account_io_start(rq);
1177 * don't check dying flag for MQ because the request won't
1178 * be reused after dying flag is set
1180 blk_mq_sched_insert_request(rq, at_head, true, false);
1182 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1184 static bool blk_rq_is_poll(struct request *rq)
1188 if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1190 if (WARN_ON_ONCE(!rq->bio))
1195 static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1198 bio_poll(rq->bio, NULL, 0);
1200 } while (!completion_done(wait));
1204 * blk_execute_rq - insert a request into queue for execution
1205 * @rq: request to insert
1206 * @at_head: insert request at head or tail of queue
1209 * Insert a fully prepared request at the back of the I/O scheduler queue
1210 * for execution and wait for completion.
1211 * Return: The blk_status_t result provided to blk_mq_end_request().
1213 blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1215 DECLARE_COMPLETION_ONSTACK(wait);
1216 unsigned long hang_check;
1218 rq->end_io_data = &wait;
1219 blk_execute_rq_nowait(rq, at_head, blk_end_sync_rq);
1221 /* Prevent hang_check timer from firing at us during very long I/O */
1222 hang_check = sysctl_hung_task_timeout_secs;
1224 if (blk_rq_is_poll(rq))
1225 blk_rq_poll_completion(rq, &wait);
1226 else if (hang_check)
1227 while (!wait_for_completion_io_timeout(&wait,
1228 hang_check * (HZ/2)))
1231 wait_for_completion_io(&wait);
1233 return (blk_status_t)(uintptr_t)rq->end_io_data;
1235 EXPORT_SYMBOL(blk_execute_rq);
1237 static void __blk_mq_requeue_request(struct request *rq)
1239 struct request_queue *q = rq->q;
1241 blk_mq_put_driver_tag(rq);
1243 trace_block_rq_requeue(rq);
1244 rq_qos_requeue(q, rq);
1246 if (blk_mq_request_started(rq)) {
1247 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1248 rq->rq_flags &= ~RQF_TIMED_OUT;
1252 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1254 __blk_mq_requeue_request(rq);
1256 /* this request will be re-inserted to io scheduler queue */
1257 blk_mq_sched_requeue_request(rq);
1259 blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
1261 EXPORT_SYMBOL(blk_mq_requeue_request);
1263 static void blk_mq_requeue_work(struct work_struct *work)
1265 struct request_queue *q =
1266 container_of(work, struct request_queue, requeue_work.work);
1268 struct request *rq, *next;
1270 spin_lock_irq(&q->requeue_lock);
1271 list_splice_init(&q->requeue_list, &rq_list);
1272 spin_unlock_irq(&q->requeue_lock);
1274 list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
1275 if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
1278 rq->rq_flags &= ~RQF_SOFTBARRIER;
1279 list_del_init(&rq->queuelist);
1281 * If RQF_DONTPREP, rq has contained some driver specific
1282 * data, so insert it to hctx dispatch list to avoid any
1285 if (rq->rq_flags & RQF_DONTPREP)
1286 blk_mq_request_bypass_insert(rq, false, false);
1288 blk_mq_sched_insert_request(rq, true, false, false);
1291 while (!list_empty(&rq_list)) {
1292 rq = list_entry(rq_list.next, struct request, queuelist);
1293 list_del_init(&rq->queuelist);
1294 blk_mq_sched_insert_request(rq, false, false, false);
1297 blk_mq_run_hw_queues(q, false);
1300 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
1301 bool kick_requeue_list)
1303 struct request_queue *q = rq->q;
1304 unsigned long flags;
1307 * We abuse this flag that is otherwise used by the I/O scheduler to
1308 * request head insertion from the workqueue.
1310 BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
1312 spin_lock_irqsave(&q->requeue_lock, flags);
1314 rq->rq_flags |= RQF_SOFTBARRIER;
1315 list_add(&rq->queuelist, &q->requeue_list);
1317 list_add_tail(&rq->queuelist, &q->requeue_list);
1319 spin_unlock_irqrestore(&q->requeue_lock, flags);
1321 if (kick_requeue_list)
1322 blk_mq_kick_requeue_list(q);
1325 void blk_mq_kick_requeue_list(struct request_queue *q)
1327 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1329 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1331 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1332 unsigned long msecs)
1334 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1335 msecs_to_jiffies(msecs));
1337 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1339 static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
1340 void *priv, bool reserved)
1343 * If we find a request that isn't idle and the queue matches,
1344 * we know the queue is busy. Return false to stop the iteration.
1346 if (blk_mq_request_started(rq) && rq->q == hctx->queue) {
1356 bool blk_mq_queue_inflight(struct request_queue *q)
1360 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1363 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1365 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
1367 req->rq_flags |= RQF_TIMED_OUT;
1368 if (req->q->mq_ops->timeout) {
1369 enum blk_eh_timer_return ret;
1371 ret = req->q->mq_ops->timeout(req, reserved);
1372 if (ret == BLK_EH_DONE)
1374 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1380 static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
1382 unsigned long deadline;
1384 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1386 if (rq->rq_flags & RQF_TIMED_OUT)
1389 deadline = READ_ONCE(rq->deadline);
1390 if (time_after_eq(jiffies, deadline))
1395 else if (time_after(*next, deadline))
1400 void blk_mq_put_rq_ref(struct request *rq)
1402 if (is_flush_rq(rq))
1404 else if (refcount_dec_and_test(&rq->ref))
1405 __blk_mq_free_request(rq);
1408 static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
1409 struct request *rq, void *priv, bool reserved)
1411 unsigned long *next = priv;
1414 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1415 * be reallocated underneath the timeout handler's processing, then
1416 * the expire check is reliable. If the request is not expired, then
1417 * it was completed and reallocated as a new request after returning
1418 * from blk_mq_check_expired().
1420 if (blk_mq_req_expired(rq, next))
1421 blk_mq_rq_timed_out(rq, reserved);
1425 static void blk_mq_timeout_work(struct work_struct *work)
1427 struct request_queue *q =
1428 container_of(work, struct request_queue, timeout_work);
1429 unsigned long next = 0;
1430 struct blk_mq_hw_ctx *hctx;
1433 /* A deadlock might occur if a request is stuck requiring a
1434 * timeout at the same time a queue freeze is waiting
1435 * completion, since the timeout code would not be able to
1436 * acquire the queue reference here.
1438 * That's why we don't use blk_queue_enter here; instead, we use
1439 * percpu_ref_tryget directly, because we need to be able to
1440 * obtain a reference even in the short window between the queue
1441 * starting to freeze, by dropping the first reference in
1442 * blk_freeze_queue_start, and the moment the last request is
1443 * consumed, marked by the instant q_usage_counter reaches
1446 if (!percpu_ref_tryget(&q->q_usage_counter))
1449 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
1452 mod_timer(&q->timeout, next);
1455 * Request timeouts are handled as a forward rolling timer. If
1456 * we end up here it means that no requests are pending and
1457 * also that no request has been pending for a while. Mark
1458 * each hctx as idle.
1460 queue_for_each_hw_ctx(q, hctx, i) {
1461 /* the hctx may be unmapped, so check it here */
1462 if (blk_mq_hw_queue_mapped(hctx))
1463 blk_mq_tag_idle(hctx);
1469 struct flush_busy_ctx_data {
1470 struct blk_mq_hw_ctx *hctx;
1471 struct list_head *list;
1474 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1476 struct flush_busy_ctx_data *flush_data = data;
1477 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1478 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1479 enum hctx_type type = hctx->type;
1481 spin_lock(&ctx->lock);
1482 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1483 sbitmap_clear_bit(sb, bitnr);
1484 spin_unlock(&ctx->lock);
1489 * Process software queues that have been marked busy, splicing them
1490 * to the for-dispatch
1492 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1494 struct flush_busy_ctx_data data = {
1499 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1501 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1503 struct dispatch_rq_data {
1504 struct blk_mq_hw_ctx *hctx;
1508 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1511 struct dispatch_rq_data *dispatch_data = data;
1512 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1513 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1514 enum hctx_type type = hctx->type;
1516 spin_lock(&ctx->lock);
1517 if (!list_empty(&ctx->rq_lists[type])) {
1518 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1519 list_del_init(&dispatch_data->rq->queuelist);
1520 if (list_empty(&ctx->rq_lists[type]))
1521 sbitmap_clear_bit(sb, bitnr);
1523 spin_unlock(&ctx->lock);
1525 return !dispatch_data->rq;
1528 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1529 struct blk_mq_ctx *start)
1531 unsigned off = start ? start->index_hw[hctx->type] : 0;
1532 struct dispatch_rq_data data = {
1537 __sbitmap_for_each_set(&hctx->ctx_map, off,
1538 dispatch_rq_from_ctx, &data);
1543 static bool __blk_mq_alloc_driver_tag(struct request *rq)
1545 struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1546 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1549 blk_mq_tag_busy(rq->mq_hctx);
1551 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1552 bt = &rq->mq_hctx->tags->breserved_tags;
1555 if (!hctx_may_queue(rq->mq_hctx, bt))
1559 tag = __sbitmap_queue_get(bt);
1560 if (tag == BLK_MQ_NO_TAG)
1563 rq->tag = tag + tag_offset;
1567 bool __blk_mq_get_driver_tag(struct blk_mq_hw_ctx *hctx, struct request *rq)
1569 if (rq->tag == BLK_MQ_NO_TAG && !__blk_mq_alloc_driver_tag(rq))
1572 if ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1573 !(rq->rq_flags & RQF_MQ_INFLIGHT)) {
1574 rq->rq_flags |= RQF_MQ_INFLIGHT;
1575 __blk_mq_inc_active_requests(hctx);
1577 hctx->tags->rqs[rq->tag] = rq;
1581 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1582 int flags, void *key)
1584 struct blk_mq_hw_ctx *hctx;
1586 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1588 spin_lock(&hctx->dispatch_wait_lock);
1589 if (!list_empty(&wait->entry)) {
1590 struct sbitmap_queue *sbq;
1592 list_del_init(&wait->entry);
1593 sbq = &hctx->tags->bitmap_tags;
1594 atomic_dec(&sbq->ws_active);
1596 spin_unlock(&hctx->dispatch_wait_lock);
1598 blk_mq_run_hw_queue(hctx, true);
1603 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1604 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1605 * restart. For both cases, take care to check the condition again after
1606 * marking us as waiting.
1608 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1611 struct sbitmap_queue *sbq = &hctx->tags->bitmap_tags;
1612 struct wait_queue_head *wq;
1613 wait_queue_entry_t *wait;
1616 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
1617 blk_mq_sched_mark_restart_hctx(hctx);
1620 * It's possible that a tag was freed in the window between the
1621 * allocation failure and adding the hardware queue to the wait
1624 * Don't clear RESTART here, someone else could have set it.
1625 * At most this will cost an extra queue run.
1627 return blk_mq_get_driver_tag(rq);
1630 wait = &hctx->dispatch_wait;
1631 if (!list_empty_careful(&wait->entry))
1634 wq = &bt_wait_ptr(sbq, hctx)->wait;
1636 spin_lock_irq(&wq->lock);
1637 spin_lock(&hctx->dispatch_wait_lock);
1638 if (!list_empty(&wait->entry)) {
1639 spin_unlock(&hctx->dispatch_wait_lock);
1640 spin_unlock_irq(&wq->lock);
1644 atomic_inc(&sbq->ws_active);
1645 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1646 __add_wait_queue(wq, wait);
1649 * It's possible that a tag was freed in the window between the
1650 * allocation failure and adding the hardware queue to the wait
1653 ret = blk_mq_get_driver_tag(rq);
1655 spin_unlock(&hctx->dispatch_wait_lock);
1656 spin_unlock_irq(&wq->lock);
1661 * We got a tag, remove ourselves from the wait queue to ensure
1662 * someone else gets the wakeup.
1664 list_del_init(&wait->entry);
1665 atomic_dec(&sbq->ws_active);
1666 spin_unlock(&hctx->dispatch_wait_lock);
1667 spin_unlock_irq(&wq->lock);
1672 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1673 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1675 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1676 * - EWMA is one simple way to compute running average value
1677 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1678 * - take 4 as factor for avoiding to get too small(0) result, and this
1679 * factor doesn't matter because EWMA decreases exponentially
1681 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1685 ewma = hctx->dispatch_busy;
1690 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1692 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1693 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1695 hctx->dispatch_busy = ewma;
1698 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1700 static void blk_mq_handle_dev_resource(struct request *rq,
1701 struct list_head *list)
1703 struct request *next =
1704 list_first_entry_or_null(list, struct request, queuelist);
1707 * If an I/O scheduler has been configured and we got a driver tag for
1708 * the next request already, free it.
1711 blk_mq_put_driver_tag(next);
1713 list_add(&rq->queuelist, list);
1714 __blk_mq_requeue_request(rq);
1717 static void blk_mq_handle_zone_resource(struct request *rq,
1718 struct list_head *zone_list)
1721 * If we end up here it is because we cannot dispatch a request to a
1722 * specific zone due to LLD level zone-write locking or other zone
1723 * related resource not being available. In this case, set the request
1724 * aside in zone_list for retrying it later.
1726 list_add(&rq->queuelist, zone_list);
1727 __blk_mq_requeue_request(rq);
1730 enum prep_dispatch {
1732 PREP_DISPATCH_NO_TAG,
1733 PREP_DISPATCH_NO_BUDGET,
1736 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
1739 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1740 int budget_token = -1;
1743 budget_token = blk_mq_get_dispatch_budget(rq->q);
1744 if (budget_token < 0) {
1745 blk_mq_put_driver_tag(rq);
1746 return PREP_DISPATCH_NO_BUDGET;
1748 blk_mq_set_rq_budget_token(rq, budget_token);
1751 if (!blk_mq_get_driver_tag(rq)) {
1753 * The initial allocation attempt failed, so we need to
1754 * rerun the hardware queue when a tag is freed. The
1755 * waitqueue takes care of that. If the queue is run
1756 * before we add this entry back on the dispatch list,
1757 * we'll re-run it below.
1759 if (!blk_mq_mark_tag_wait(hctx, rq)) {
1761 * All budgets not got from this function will be put
1762 * together during handling partial dispatch
1765 blk_mq_put_dispatch_budget(rq->q, budget_token);
1766 return PREP_DISPATCH_NO_TAG;
1770 return PREP_DISPATCH_OK;
1773 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
1774 static void blk_mq_release_budgets(struct request_queue *q,
1775 struct list_head *list)
1779 list_for_each_entry(rq, list, queuelist) {
1780 int budget_token = blk_mq_get_rq_budget_token(rq);
1782 if (budget_token >= 0)
1783 blk_mq_put_dispatch_budget(q, budget_token);
1788 * Returns true if we did some work AND can potentially do more.
1790 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
1791 unsigned int nr_budgets)
1793 enum prep_dispatch prep;
1794 struct request_queue *q = hctx->queue;
1795 struct request *rq, *nxt;
1797 blk_status_t ret = BLK_STS_OK;
1798 LIST_HEAD(zone_list);
1799 bool needs_resource = false;
1801 if (list_empty(list))
1805 * Now process all the entries, sending them to the driver.
1807 errors = queued = 0;
1809 struct blk_mq_queue_data bd;
1811 rq = list_first_entry(list, struct request, queuelist);
1813 WARN_ON_ONCE(hctx != rq->mq_hctx);
1814 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
1815 if (prep != PREP_DISPATCH_OK)
1818 list_del_init(&rq->queuelist);
1823 * Flag last if we have no more requests, or if we have more
1824 * but can't assign a driver tag to it.
1826 if (list_empty(list))
1829 nxt = list_first_entry(list, struct request, queuelist);
1830 bd.last = !blk_mq_get_driver_tag(nxt);
1834 * once the request is queued to lld, no need to cover the
1839 ret = q->mq_ops->queue_rq(hctx, &bd);
1844 case BLK_STS_RESOURCE:
1845 needs_resource = true;
1847 case BLK_STS_DEV_RESOURCE:
1848 blk_mq_handle_dev_resource(rq, list);
1850 case BLK_STS_ZONE_RESOURCE:
1852 * Move the request to zone_list and keep going through
1853 * the dispatch list to find more requests the drive can
1856 blk_mq_handle_zone_resource(rq, &zone_list);
1857 needs_resource = true;
1861 blk_mq_end_request(rq, ret);
1863 } while (!list_empty(list));
1865 if (!list_empty(&zone_list))
1866 list_splice_tail_init(&zone_list, list);
1868 /* If we didn't flush the entire list, we could have told the driver
1869 * there was more coming, but that turned out to be a lie.
1871 if ((!list_empty(list) || errors) && q->mq_ops->commit_rqs && queued)
1872 q->mq_ops->commit_rqs(hctx);
1874 * Any items that need requeuing? Stuff them into hctx->dispatch,
1875 * that is where we will continue on next queue run.
1877 if (!list_empty(list)) {
1879 /* For non-shared tags, the RESTART check will suffice */
1880 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
1881 (hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED);
1884 blk_mq_release_budgets(q, list);
1886 spin_lock(&hctx->lock);
1887 list_splice_tail_init(list, &hctx->dispatch);
1888 spin_unlock(&hctx->lock);
1891 * Order adding requests to hctx->dispatch and checking
1892 * SCHED_RESTART flag. The pair of this smp_mb() is the one
1893 * in blk_mq_sched_restart(). Avoid restart code path to
1894 * miss the new added requests to hctx->dispatch, meantime
1895 * SCHED_RESTART is observed here.
1900 * If SCHED_RESTART was set by the caller of this function and
1901 * it is no longer set that means that it was cleared by another
1902 * thread and hence that a queue rerun is needed.
1904 * If 'no_tag' is set, that means that we failed getting
1905 * a driver tag with an I/O scheduler attached. If our dispatch
1906 * waitqueue is no longer active, ensure that we run the queue
1907 * AFTER adding our entries back to the list.
1909 * If no I/O scheduler has been configured it is possible that
1910 * the hardware queue got stopped and restarted before requests
1911 * were pushed back onto the dispatch list. Rerun the queue to
1912 * avoid starvation. Notes:
1913 * - blk_mq_run_hw_queue() checks whether or not a queue has
1914 * been stopped before rerunning a queue.
1915 * - Some but not all block drivers stop a queue before
1916 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1919 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1920 * bit is set, run queue after a delay to avoid IO stalls
1921 * that could otherwise occur if the queue is idle. We'll do
1922 * similar if we couldn't get budget or couldn't lock a zone
1923 * and SCHED_RESTART is set.
1925 needs_restart = blk_mq_sched_needs_restart(hctx);
1926 if (prep == PREP_DISPATCH_NO_BUDGET)
1927 needs_resource = true;
1928 if (!needs_restart ||
1929 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1930 blk_mq_run_hw_queue(hctx, true);
1931 else if (needs_restart && needs_resource)
1932 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1934 blk_mq_update_dispatch_busy(hctx, true);
1937 blk_mq_update_dispatch_busy(hctx, false);
1939 return (queued + errors) != 0;
1943 * __blk_mq_run_hw_queue - Run a hardware queue.
1944 * @hctx: Pointer to the hardware queue to run.
1946 * Send pending requests to the hardware.
1948 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1953 * We can't run the queue inline with ints disabled. Ensure that
1954 * we catch bad users of this early.
1956 WARN_ON_ONCE(in_interrupt());
1958 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1960 hctx_lock(hctx, &srcu_idx);
1961 blk_mq_sched_dispatch_requests(hctx);
1962 hctx_unlock(hctx, srcu_idx);
1965 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1967 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1969 if (cpu >= nr_cpu_ids)
1970 cpu = cpumask_first(hctx->cpumask);
1975 * It'd be great if the workqueue API had a way to pass
1976 * in a mask and had some smarts for more clever placement.
1977 * For now we just round-robin here, switching for every
1978 * BLK_MQ_CPU_WORK_BATCH queued items.
1980 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1983 int next_cpu = hctx->next_cpu;
1985 if (hctx->queue->nr_hw_queues == 1)
1986 return WORK_CPU_UNBOUND;
1988 if (--hctx->next_cpu_batch <= 0) {
1990 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
1992 if (next_cpu >= nr_cpu_ids)
1993 next_cpu = blk_mq_first_mapped_cpu(hctx);
1994 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1998 * Do unbound schedule if we can't find a online CPU for this hctx,
1999 * and it should only happen in the path of handling CPU DEAD.
2001 if (!cpu_online(next_cpu)) {
2008 * Make sure to re-select CPU next time once after CPUs
2009 * in hctx->cpumask become online again.
2011 hctx->next_cpu = next_cpu;
2012 hctx->next_cpu_batch = 1;
2013 return WORK_CPU_UNBOUND;
2016 hctx->next_cpu = next_cpu;
2021 * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
2022 * @hctx: Pointer to the hardware queue to run.
2023 * @async: If we want to run the queue asynchronously.
2024 * @msecs: Milliseconds of delay to wait before running the queue.
2026 * If !@async, try to run the queue now. Else, run the queue asynchronously and
2027 * with a delay of @msecs.
2029 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
2030 unsigned long msecs)
2032 if (unlikely(blk_mq_hctx_stopped(hctx)))
2035 if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
2036 int cpu = get_cpu();
2037 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
2038 __blk_mq_run_hw_queue(hctx);
2046 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2047 msecs_to_jiffies(msecs));
2051 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2052 * @hctx: Pointer to the hardware queue to run.
2053 * @msecs: Milliseconds of delay to wait before running the queue.
2055 * Run a hardware queue asynchronously with a delay of @msecs.
2057 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2059 __blk_mq_delay_run_hw_queue(hctx, true, msecs);
2061 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2064 * blk_mq_run_hw_queue - Start to run a hardware queue.
2065 * @hctx: Pointer to the hardware queue to run.
2066 * @async: If we want to run the queue asynchronously.
2068 * Check if the request queue is not in a quiesced state and if there are
2069 * pending requests to be sent. If this is true, run the queue to send requests
2072 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2078 * When queue is quiesced, we may be switching io scheduler, or
2079 * updating nr_hw_queues, or other things, and we can't run queue
2080 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
2082 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2085 hctx_lock(hctx, &srcu_idx);
2086 need_run = !blk_queue_quiesced(hctx->queue) &&
2087 blk_mq_hctx_has_pending(hctx);
2088 hctx_unlock(hctx, srcu_idx);
2091 __blk_mq_delay_run_hw_queue(hctx, async, 0);
2093 EXPORT_SYMBOL(blk_mq_run_hw_queue);
2096 * Is the request queue handled by an IO scheduler that does not respect
2097 * hardware queues when dispatching?
2099 static bool blk_mq_has_sqsched(struct request_queue *q)
2101 struct elevator_queue *e = q->elevator;
2103 if (e && e->type->ops.dispatch_request &&
2104 !(e->type->elevator_features & ELEVATOR_F_MQ_AWARE))
2110 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2113 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2115 struct blk_mq_hw_ctx *hctx;
2118 * If the IO scheduler does not respect hardware queues when
2119 * dispatching, we just don't bother with multiple HW queues and
2120 * dispatch from hctx for the current CPU since running multiple queues
2121 * just causes lock contention inside the scheduler and pointless cache
2124 hctx = blk_mq_map_queue_type(q, HCTX_TYPE_DEFAULT,
2125 raw_smp_processor_id());
2126 if (!blk_mq_hctx_stopped(hctx))
2132 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2133 * @q: Pointer to the request queue to run.
2134 * @async: If we want to run the queue asynchronously.
2136 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2138 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2142 if (blk_mq_has_sqsched(q))
2143 sq_hctx = blk_mq_get_sq_hctx(q);
2144 queue_for_each_hw_ctx(q, hctx, i) {
2145 if (blk_mq_hctx_stopped(hctx))
2148 * Dispatch from this hctx either if there's no hctx preferred
2149 * by IO scheduler or if it has requests that bypass the
2152 if (!sq_hctx || sq_hctx == hctx ||
2153 !list_empty_careful(&hctx->dispatch))
2154 blk_mq_run_hw_queue(hctx, async);
2157 EXPORT_SYMBOL(blk_mq_run_hw_queues);
2160 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2161 * @q: Pointer to the request queue to run.
2162 * @msecs: Milliseconds of delay to wait before running the queues.
2164 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2166 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2170 if (blk_mq_has_sqsched(q))
2171 sq_hctx = blk_mq_get_sq_hctx(q);
2172 queue_for_each_hw_ctx(q, hctx, i) {
2173 if (blk_mq_hctx_stopped(hctx))
2176 * Dispatch from this hctx either if there's no hctx preferred
2177 * by IO scheduler or if it has requests that bypass the
2180 if (!sq_hctx || sq_hctx == hctx ||
2181 !list_empty_careful(&hctx->dispatch))
2182 blk_mq_delay_run_hw_queue(hctx, msecs);
2185 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2188 * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
2189 * @q: request queue.
2191 * The caller is responsible for serializing this function against
2192 * blk_mq_{start,stop}_hw_queue().
2194 bool blk_mq_queue_stopped(struct request_queue *q)
2196 struct blk_mq_hw_ctx *hctx;
2199 queue_for_each_hw_ctx(q, hctx, i)
2200 if (blk_mq_hctx_stopped(hctx))
2205 EXPORT_SYMBOL(blk_mq_queue_stopped);
2208 * This function is often used for pausing .queue_rq() by driver when
2209 * there isn't enough resource or some conditions aren't satisfied, and
2210 * BLK_STS_RESOURCE is usually returned.
2212 * We do not guarantee that dispatch can be drained or blocked
2213 * after blk_mq_stop_hw_queue() returns. Please use
2214 * blk_mq_quiesce_queue() for that requirement.
2216 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2218 cancel_delayed_work(&hctx->run_work);
2220 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2222 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2225 * This function is often used for pausing .queue_rq() by driver when
2226 * there isn't enough resource or some conditions aren't satisfied, and
2227 * BLK_STS_RESOURCE is usually returned.
2229 * We do not guarantee that dispatch can be drained or blocked
2230 * after blk_mq_stop_hw_queues() returns. Please use
2231 * blk_mq_quiesce_queue() for that requirement.
2233 void blk_mq_stop_hw_queues(struct request_queue *q)
2235 struct blk_mq_hw_ctx *hctx;
2238 queue_for_each_hw_ctx(q, hctx, i)
2239 blk_mq_stop_hw_queue(hctx);
2241 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2243 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2245 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2247 blk_mq_run_hw_queue(hctx, false);
2249 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2251 void blk_mq_start_hw_queues(struct request_queue *q)
2253 struct blk_mq_hw_ctx *hctx;
2256 queue_for_each_hw_ctx(q, hctx, i)
2257 blk_mq_start_hw_queue(hctx);
2259 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2261 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2263 if (!blk_mq_hctx_stopped(hctx))
2266 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2267 blk_mq_run_hw_queue(hctx, async);
2269 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2271 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2273 struct blk_mq_hw_ctx *hctx;
2276 queue_for_each_hw_ctx(q, hctx, i)
2277 blk_mq_start_stopped_hw_queue(hctx, async);
2279 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2281 static void blk_mq_run_work_fn(struct work_struct *work)
2283 struct blk_mq_hw_ctx *hctx;
2285 hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
2288 * If we are stopped, don't run the queue.
2290 if (blk_mq_hctx_stopped(hctx))
2293 __blk_mq_run_hw_queue(hctx);
2296 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
2300 struct blk_mq_ctx *ctx = rq->mq_ctx;
2301 enum hctx_type type = hctx->type;
2303 lockdep_assert_held(&ctx->lock);
2305 trace_block_rq_insert(rq);
2308 list_add(&rq->queuelist, &ctx->rq_lists[type]);
2310 list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
2313 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
2316 struct blk_mq_ctx *ctx = rq->mq_ctx;
2318 lockdep_assert_held(&ctx->lock);
2320 __blk_mq_insert_req_list(hctx, rq, at_head);
2321 blk_mq_hctx_mark_pending(hctx, ctx);
2325 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2326 * @rq: Pointer to request to be inserted.
2327 * @at_head: true if the request should be inserted at the head of the list.
2328 * @run_queue: If we should run the hardware queue after inserting the request.
2330 * Should only be used carefully, when the caller knows we want to
2331 * bypass a potential IO scheduler on the target device.
2333 void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
2336 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2338 spin_lock(&hctx->lock);
2340 list_add(&rq->queuelist, &hctx->dispatch);
2342 list_add_tail(&rq->queuelist, &hctx->dispatch);
2343 spin_unlock(&hctx->lock);
2346 blk_mq_run_hw_queue(hctx, false);
2349 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
2350 struct list_head *list)
2354 enum hctx_type type = hctx->type;
2357 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2360 list_for_each_entry(rq, list, queuelist) {
2361 BUG_ON(rq->mq_ctx != ctx);
2362 trace_block_rq_insert(rq);
2365 spin_lock(&ctx->lock);
2366 list_splice_tail_init(list, &ctx->rq_lists[type]);
2367 blk_mq_hctx_mark_pending(hctx, ctx);
2368 spin_unlock(&ctx->lock);
2371 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int *queued,
2374 if (hctx->queue->mq_ops->commit_rqs) {
2375 trace_block_unplug(hctx->queue, *queued, !from_schedule);
2376 hctx->queue->mq_ops->commit_rqs(hctx);
2381 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2382 unsigned int nr_segs)
2386 if (bio->bi_opf & REQ_RAHEAD)
2387 rq->cmd_flags |= REQ_FAILFAST_MASK;
2389 rq->__sector = bio->bi_iter.bi_sector;
2390 rq->write_hint = bio->bi_write_hint;
2391 blk_rq_bio_prep(rq, bio, nr_segs);
2393 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2394 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2397 blk_account_io_start(rq);
2400 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2401 struct request *rq, bool last)
2403 struct request_queue *q = rq->q;
2404 struct blk_mq_queue_data bd = {
2411 * For OK queue, we are done. For error, caller may kill it.
2412 * Any other error (busy), just add it to our list as we
2413 * previously would have done.
2415 ret = q->mq_ops->queue_rq(hctx, &bd);
2418 blk_mq_update_dispatch_busy(hctx, false);
2420 case BLK_STS_RESOURCE:
2421 case BLK_STS_DEV_RESOURCE:
2422 blk_mq_update_dispatch_busy(hctx, true);
2423 __blk_mq_requeue_request(rq);
2426 blk_mq_update_dispatch_busy(hctx, false);
2433 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2435 bool bypass_insert, bool last)
2437 struct request_queue *q = rq->q;
2438 bool run_queue = true;
2442 * RCU or SRCU read lock is needed before checking quiesced flag.
2444 * When queue is stopped or quiesced, ignore 'bypass_insert' from
2445 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
2446 * and avoid driver to try to dispatch again.
2448 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
2450 bypass_insert = false;
2454 if ((rq->rq_flags & RQF_ELV) && !bypass_insert)
2457 budget_token = blk_mq_get_dispatch_budget(q);
2458 if (budget_token < 0)
2461 blk_mq_set_rq_budget_token(rq, budget_token);
2463 if (!blk_mq_get_driver_tag(rq)) {
2464 blk_mq_put_dispatch_budget(q, budget_token);
2468 return __blk_mq_issue_directly(hctx, rq, last);
2471 return BLK_STS_RESOURCE;
2473 blk_mq_sched_insert_request(rq, false, run_queue, false);
2479 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2480 * @hctx: Pointer of the associated hardware queue.
2481 * @rq: Pointer to request to be sent.
2483 * If the device has enough resources to accept a new request now, send the
2484 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2485 * we can try send it another time in the future. Requests inserted at this
2486 * queue have higher priority.
2488 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2494 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
2496 hctx_lock(hctx, &srcu_idx);
2498 ret = __blk_mq_try_issue_directly(hctx, rq, false, true);
2499 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
2500 blk_mq_request_bypass_insert(rq, false, true);
2501 else if (ret != BLK_STS_OK)
2502 blk_mq_end_request(rq, ret);
2504 hctx_unlock(hctx, srcu_idx);
2507 static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2511 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2513 hctx_lock(hctx, &srcu_idx);
2514 ret = __blk_mq_try_issue_directly(hctx, rq, true, last);
2515 hctx_unlock(hctx, srcu_idx);
2520 static void blk_mq_plug_issue_direct(struct blk_plug *plug, bool from_schedule)
2522 struct blk_mq_hw_ctx *hctx = NULL;
2527 while ((rq = rq_list_pop(&plug->mq_list))) {
2528 bool last = rq_list_empty(plug->mq_list);
2531 if (hctx != rq->mq_hctx) {
2533 blk_mq_commit_rqs(hctx, &queued, from_schedule);
2537 ret = blk_mq_request_issue_directly(rq, last);
2542 case BLK_STS_RESOURCE:
2543 case BLK_STS_DEV_RESOURCE:
2544 blk_mq_request_bypass_insert(rq, false, last);
2545 blk_mq_commit_rqs(hctx, &queued, from_schedule);
2548 blk_mq_end_request(rq, ret);
2555 * If we didn't flush the entire list, we could have told the driver
2556 * there was more coming, but that turned out to be a lie.
2559 blk_mq_commit_rqs(hctx, &queued, from_schedule);
2562 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2564 struct blk_mq_hw_ctx *this_hctx;
2565 struct blk_mq_ctx *this_ctx;
2569 if (rq_list_empty(plug->mq_list))
2573 if (!plug->multiple_queues && !plug->has_elevator && !from_schedule) {
2574 blk_mq_plug_issue_direct(plug, false);
2575 if (rq_list_empty(plug->mq_list))
2585 rq = rq_list_pop(&plug->mq_list);
2588 this_hctx = rq->mq_hctx;
2589 this_ctx = rq->mq_ctx;
2590 } else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx) {
2591 trace_block_unplug(this_hctx->queue, depth,
2593 blk_mq_sched_insert_requests(this_hctx, this_ctx,
2594 &list, from_schedule);
2596 this_hctx = rq->mq_hctx;
2597 this_ctx = rq->mq_ctx;
2601 list_add(&rq->queuelist, &list);
2603 } while (!rq_list_empty(plug->mq_list));
2605 if (!list_empty(&list)) {
2606 trace_block_unplug(this_hctx->queue, depth, !from_schedule);
2607 blk_mq_sched_insert_requests(this_hctx, this_ctx, &list,
2612 void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2613 struct list_head *list)
2618 while (!list_empty(list)) {
2620 struct request *rq = list_first_entry(list, struct request,
2623 list_del_init(&rq->queuelist);
2624 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2625 if (ret != BLK_STS_OK) {
2626 if (ret == BLK_STS_RESOURCE ||
2627 ret == BLK_STS_DEV_RESOURCE) {
2628 blk_mq_request_bypass_insert(rq, false,
2632 blk_mq_end_request(rq, ret);
2639 * If we didn't flush the entire list, we could have told
2640 * the driver there was more coming, but that turned out to
2643 if ((!list_empty(list) || errors) &&
2644 hctx->queue->mq_ops->commit_rqs && queued)
2645 hctx->queue->mq_ops->commit_rqs(hctx);
2649 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
2650 * queues. This is important for md arrays to benefit from merging
2653 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
2655 if (plug->multiple_queues)
2656 return BLK_MAX_REQUEST_COUNT * 2;
2657 return BLK_MAX_REQUEST_COUNT;
2660 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2662 struct request *last = rq_list_peek(&plug->mq_list);
2664 if (!plug->rq_count) {
2665 trace_block_plug(rq->q);
2666 } else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
2667 (!blk_queue_nomerges(rq->q) &&
2668 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
2669 blk_mq_flush_plug_list(plug, false);
2670 trace_block_plug(rq->q);
2673 if (!plug->multiple_queues && last && last->q != rq->q)
2674 plug->multiple_queues = true;
2675 if (!plug->has_elevator && (rq->rq_flags & RQF_ELV))
2676 plug->has_elevator = true;
2678 rq_list_add(&plug->mq_list, rq);
2682 static bool blk_mq_attempt_bio_merge(struct request_queue *q,
2683 struct bio *bio, unsigned int nr_segs)
2685 if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
2686 if (blk_attempt_plug_merge(q, bio, nr_segs))
2688 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2694 static struct request *blk_mq_get_new_requests(struct request_queue *q,
2695 struct blk_plug *plug,
2699 struct blk_mq_alloc_data data = {
2705 if (unlikely(bio_queue_enter(bio)))
2707 if (unlikely(!submit_bio_checks(bio)))
2709 if (blk_mq_attempt_bio_merge(q, bio, nsegs))
2712 rq_qos_throttle(q, bio);
2714 /* ->bi_opf is finalized after submit_bio_checks() returns */
2715 data.cmd_flags = bio->bi_opf;
2717 data.nr_tags = plug->nr_ios;
2719 data.cached_rq = &plug->cached_rq;
2722 rq = __blk_mq_alloc_requests(&data);
2725 rq_qos_cleanup(q, bio);
2726 if (bio->bi_opf & REQ_NOWAIT)
2727 bio_wouldblock_error(bio);
2733 static inline struct request *blk_mq_get_cached_request(struct request_queue *q,
2734 struct blk_plug *plug, struct bio **bio, unsigned int nsegs)
2740 rq = rq_list_peek(&plug->cached_rq);
2741 if (!rq || rq->q != q)
2744 if (unlikely(!submit_bio_checks(*bio)))
2746 if (blk_mq_attempt_bio_merge(q, *bio, nsegs)) {
2750 if (blk_mq_get_hctx_type((*bio)->bi_opf) != rq->mq_hctx->type)
2752 if (op_is_flush(rq->cmd_flags) != op_is_flush((*bio)->bi_opf))
2755 rq->cmd_flags = (*bio)->bi_opf;
2756 plug->cached_rq = rq_list_next(rq);
2757 INIT_LIST_HEAD(&rq->queuelist);
2758 rq_qos_throttle(q, *bio);
2763 * blk_mq_submit_bio - Create and send a request to block device.
2764 * @bio: Bio pointer.
2766 * Builds up a request structure from @q and @bio and send to the device. The
2767 * request may not be queued directly to hardware if:
2768 * * This request can be merged with another one
2769 * * We want to place request at plug queue for possible future merging
2770 * * There is an IO scheduler active at this queue
2772 * It will not queue the request if there is an error with the bio, or at the
2775 void blk_mq_submit_bio(struct bio *bio)
2777 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2778 struct blk_plug *plug = blk_mq_plug(q, bio);
2779 const int is_sync = op_is_sync(bio->bi_opf);
2781 unsigned int nr_segs = 1;
2784 if (unlikely(!blk_crypto_bio_prep(&bio)))
2787 blk_queue_bounce(q, &bio);
2788 if (blk_may_split(q, bio))
2789 __blk_queue_split(q, &bio, &nr_segs);
2791 if (!bio_integrity_prep(bio))
2794 rq = blk_mq_get_cached_request(q, plug, &bio, nr_segs);
2798 rq = blk_mq_get_new_requests(q, plug, bio, nr_segs);
2803 trace_block_getrq(bio);
2805 rq_qos_track(q, rq, bio);
2807 blk_mq_bio_to_request(rq, bio, nr_segs);
2809 ret = blk_crypto_init_request(rq);
2810 if (ret != BLK_STS_OK) {
2811 bio->bi_status = ret;
2813 blk_mq_free_request(rq);
2817 if (op_is_flush(bio->bi_opf)) {
2818 blk_insert_flush(rq);
2823 blk_add_rq_to_plug(plug, rq);
2824 else if ((rq->rq_flags & RQF_ELV) ||
2825 (rq->mq_hctx->dispatch_busy &&
2826 (q->nr_hw_queues == 1 || !is_sync)))
2827 blk_mq_sched_insert_request(rq, false, true, true);
2829 blk_mq_try_issue_directly(rq->mq_hctx, rq);
2833 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2834 * for the new queue limits
2836 * @rq: the request being checked
2839 * @rq may have been made based on weaker limitations of upper-level queues
2840 * in request stacking drivers, and it may violate the limitation of @q.
2841 * Since the block layer and the underlying device driver trust @rq
2842 * after it is inserted to @q, it should be checked against @q before
2843 * the insertion using this generic function.
2845 * Request stacking drivers like request-based dm may change the queue
2846 * limits when retrying requests on other queues. Those requests need
2847 * to be checked against the new queue limits again during dispatch.
2849 static blk_status_t blk_cloned_rq_check_limits(struct request_queue *q,
2852 unsigned int max_sectors = blk_queue_get_max_sectors(q, req_op(rq));
2854 if (blk_rq_sectors(rq) > max_sectors) {
2856 * SCSI device does not have a good way to return if
2857 * Write Same/Zero is actually supported. If a device rejects
2858 * a non-read/write command (discard, write same,etc.) the
2859 * low-level device driver will set the relevant queue limit to
2860 * 0 to prevent blk-lib from issuing more of the offending
2861 * operations. Commands queued prior to the queue limit being
2862 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
2863 * errors being propagated to upper layers.
2865 if (max_sectors == 0)
2866 return BLK_STS_NOTSUPP;
2868 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
2869 __func__, blk_rq_sectors(rq), max_sectors);
2870 return BLK_STS_IOERR;
2874 * The queue settings related to segment counting may differ from the
2877 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
2878 if (rq->nr_phys_segments > queue_max_segments(q)) {
2879 printk(KERN_ERR "%s: over max segments limit. (%hu > %hu)\n",
2880 __func__, rq->nr_phys_segments, queue_max_segments(q));
2881 return BLK_STS_IOERR;
2888 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2889 * @q: the queue to submit the request
2890 * @rq: the request being queued
2892 blk_status_t blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2896 ret = blk_cloned_rq_check_limits(q, rq);
2897 if (ret != BLK_STS_OK)
2901 should_fail_request(rq->q->disk->part0, blk_rq_bytes(rq)))
2902 return BLK_STS_IOERR;
2904 if (blk_crypto_insert_cloned_request(rq))
2905 return BLK_STS_IOERR;
2907 blk_account_io_start(rq);
2910 * Since we have a scheduler attached on the top device,
2911 * bypass a potential scheduler on the bottom device for
2914 return blk_mq_request_issue_directly(rq, true);
2916 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2919 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2920 * @rq: the clone request to be cleaned up
2923 * Free all bios in @rq for a cloned request.
2925 void blk_rq_unprep_clone(struct request *rq)
2929 while ((bio = rq->bio) != NULL) {
2930 rq->bio = bio->bi_next;
2935 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2938 * blk_rq_prep_clone - Helper function to setup clone request
2939 * @rq: the request to be setup
2940 * @rq_src: original request to be cloned
2941 * @bs: bio_set that bios for clone are allocated from
2942 * @gfp_mask: memory allocation mask for bio
2943 * @bio_ctr: setup function to be called for each clone bio.
2944 * Returns %0 for success, non %0 for failure.
2945 * @data: private data to be passed to @bio_ctr
2948 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2949 * Also, pages which the original bios are pointing to are not copied
2950 * and the cloned bios just point same pages.
2951 * So cloned bios must be completed before original bios, which means
2952 * the caller must complete @rq before @rq_src.
2954 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2955 struct bio_set *bs, gfp_t gfp_mask,
2956 int (*bio_ctr)(struct bio *, struct bio *, void *),
2959 struct bio *bio, *bio_src;
2964 __rq_for_each_bio(bio_src, rq_src) {
2965 bio = bio_clone_fast(bio_src, gfp_mask, bs);
2969 if (bio_ctr && bio_ctr(bio, bio_src, data))
2973 rq->biotail->bi_next = bio;
2976 rq->bio = rq->biotail = bio;
2981 /* Copy attributes of the original request to the clone request. */
2982 rq->__sector = blk_rq_pos(rq_src);
2983 rq->__data_len = blk_rq_bytes(rq_src);
2984 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
2985 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
2986 rq->special_vec = rq_src->special_vec;
2988 rq->nr_phys_segments = rq_src->nr_phys_segments;
2989 rq->ioprio = rq_src->ioprio;
2991 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
2999 blk_rq_unprep_clone(rq);
3003 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3006 * Steal bios from a request and add them to a bio list.
3007 * The request must not have been partially completed before.
3009 void blk_steal_bios(struct bio_list *list, struct request *rq)
3013 list->tail->bi_next = rq->bio;
3015 list->head = rq->bio;
3016 list->tail = rq->biotail;
3024 EXPORT_SYMBOL_GPL(blk_steal_bios);
3026 static size_t order_to_size(unsigned int order)
3028 return (size_t)PAGE_SIZE << order;
3031 /* called before freeing request pool in @tags */
3032 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3033 struct blk_mq_tags *tags)
3036 unsigned long flags;
3038 /* There is no need to clear a driver tags own mapping */
3039 if (drv_tags == tags)
3042 list_for_each_entry(page, &tags->page_list, lru) {
3043 unsigned long start = (unsigned long)page_address(page);
3044 unsigned long end = start + order_to_size(page->private);
3047 for (i = 0; i < drv_tags->nr_tags; i++) {
3048 struct request *rq = drv_tags->rqs[i];
3049 unsigned long rq_addr = (unsigned long)rq;
3051 if (rq_addr >= start && rq_addr < end) {
3052 WARN_ON_ONCE(refcount_read(&rq->ref) != 0);
3053 cmpxchg(&drv_tags->rqs[i], rq, NULL);
3059 * Wait until all pending iteration is done.
3061 * Request reference is cleared and it is guaranteed to be observed
3062 * after the ->lock is released.
3064 spin_lock_irqsave(&drv_tags->lock, flags);
3065 spin_unlock_irqrestore(&drv_tags->lock, flags);
3068 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3069 unsigned int hctx_idx)
3071 struct blk_mq_tags *drv_tags;
3074 if (blk_mq_is_shared_tags(set->flags))
3075 drv_tags = set->shared_tags;
3077 drv_tags = set->tags[hctx_idx];
3079 if (tags->static_rqs && set->ops->exit_request) {
3082 for (i = 0; i < tags->nr_tags; i++) {
3083 struct request *rq = tags->static_rqs[i];
3087 set->ops->exit_request(set, rq, hctx_idx);
3088 tags->static_rqs[i] = NULL;
3092 blk_mq_clear_rq_mapping(drv_tags, tags);
3094 while (!list_empty(&tags->page_list)) {
3095 page = list_first_entry(&tags->page_list, struct page, lru);
3096 list_del_init(&page->lru);
3098 * Remove kmemleak object previously allocated in
3099 * blk_mq_alloc_rqs().
3101 kmemleak_free(page_address(page));
3102 __free_pages(page, page->private);
3106 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
3110 kfree(tags->static_rqs);
3111 tags->static_rqs = NULL;
3113 blk_mq_free_tags(tags);
3116 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3117 unsigned int hctx_idx,
3118 unsigned int nr_tags,
3119 unsigned int reserved_tags)
3121 struct blk_mq_tags *tags;
3124 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
3125 if (node == NUMA_NO_NODE)
3126 node = set->numa_node;
3128 tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
3129 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
3133 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3134 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3137 blk_mq_free_tags(tags);
3141 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3142 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3144 if (!tags->static_rqs) {
3146 blk_mq_free_tags(tags);
3153 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3154 unsigned int hctx_idx, int node)
3158 if (set->ops->init_request) {
3159 ret = set->ops->init_request(set, rq, hctx_idx, node);
3164 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3168 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3169 struct blk_mq_tags *tags,
3170 unsigned int hctx_idx, unsigned int depth)
3172 unsigned int i, j, entries_per_page, max_order = 4;
3173 size_t rq_size, left;
3176 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
3177 if (node == NUMA_NO_NODE)
3178 node = set->numa_node;
3180 INIT_LIST_HEAD(&tags->page_list);
3183 * rq_size is the size of the request plus driver payload, rounded
3184 * to the cacheline size
3186 rq_size = round_up(sizeof(struct request) + set->cmd_size,
3188 left = rq_size * depth;
3190 for (i = 0; i < depth; ) {
3191 int this_order = max_order;
3196 while (this_order && left < order_to_size(this_order - 1))
3200 page = alloc_pages_node(node,
3201 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3207 if (order_to_size(this_order) < rq_size)
3214 page->private = this_order;
3215 list_add_tail(&page->lru, &tags->page_list);
3217 p = page_address(page);
3219 * Allow kmemleak to scan these pages as they contain pointers
3220 * to additional allocations like via ops->init_request().
3222 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3223 entries_per_page = order_to_size(this_order) / rq_size;
3224 to_do = min(entries_per_page, depth - i);
3225 left -= to_do * rq_size;
3226 for (j = 0; j < to_do; j++) {
3227 struct request *rq = p;
3229 tags->static_rqs[i] = rq;
3230 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3231 tags->static_rqs[i] = NULL;
3242 blk_mq_free_rqs(set, tags, hctx_idx);
3246 struct rq_iter_data {
3247 struct blk_mq_hw_ctx *hctx;
3251 static bool blk_mq_has_request(struct request *rq, void *data, bool reserved)
3253 struct rq_iter_data *iter_data = data;
3255 if (rq->mq_hctx != iter_data->hctx)
3257 iter_data->has_rq = true;
3261 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3263 struct blk_mq_tags *tags = hctx->sched_tags ?
3264 hctx->sched_tags : hctx->tags;
3265 struct rq_iter_data data = {
3269 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3273 static inline bool blk_mq_last_cpu_in_hctx(unsigned int cpu,
3274 struct blk_mq_hw_ctx *hctx)
3276 if (cpumask_next_and(-1, hctx->cpumask, cpu_online_mask) != cpu)
3278 if (cpumask_next_and(cpu, hctx->cpumask, cpu_online_mask) < nr_cpu_ids)
3283 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3285 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3286 struct blk_mq_hw_ctx, cpuhp_online);
3288 if (!cpumask_test_cpu(cpu, hctx->cpumask) ||
3289 !blk_mq_last_cpu_in_hctx(cpu, hctx))
3293 * Prevent new request from being allocated on the current hctx.
3295 * The smp_mb__after_atomic() Pairs with the implied barrier in
3296 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
3297 * seen once we return from the tag allocator.
3299 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3300 smp_mb__after_atomic();
3303 * Try to grab a reference to the queue and wait for any outstanding
3304 * requests. If we could not grab a reference the queue has been
3305 * frozen and there are no requests.
3307 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3308 while (blk_mq_hctx_has_requests(hctx))
3310 percpu_ref_put(&hctx->queue->q_usage_counter);
3316 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3318 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3319 struct blk_mq_hw_ctx, cpuhp_online);
3321 if (cpumask_test_cpu(cpu, hctx->cpumask))
3322 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3327 * 'cpu' is going away. splice any existing rq_list entries from this
3328 * software queue to the hw queue dispatch list, and ensure that it
3331 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3333 struct blk_mq_hw_ctx *hctx;
3334 struct blk_mq_ctx *ctx;
3336 enum hctx_type type;
3338 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3339 if (!cpumask_test_cpu(cpu, hctx->cpumask))
3342 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3345 spin_lock(&ctx->lock);
3346 if (!list_empty(&ctx->rq_lists[type])) {
3347 list_splice_init(&ctx->rq_lists[type], &tmp);
3348 blk_mq_hctx_clear_pending(hctx, ctx);
3350 spin_unlock(&ctx->lock);
3352 if (list_empty(&tmp))
3355 spin_lock(&hctx->lock);
3356 list_splice_tail_init(&tmp, &hctx->dispatch);
3357 spin_unlock(&hctx->lock);
3359 blk_mq_run_hw_queue(hctx, true);
3363 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3365 if (!(hctx->flags & BLK_MQ_F_STACKING))
3366 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3367 &hctx->cpuhp_online);
3368 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3373 * Before freeing hw queue, clearing the flush request reference in
3374 * tags->rqs[] for avoiding potential UAF.
3376 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3377 unsigned int queue_depth, struct request *flush_rq)
3380 unsigned long flags;
3382 /* The hw queue may not be mapped yet */
3386 WARN_ON_ONCE(refcount_read(&flush_rq->ref) != 0);
3388 for (i = 0; i < queue_depth; i++)
3389 cmpxchg(&tags->rqs[i], flush_rq, NULL);
3392 * Wait until all pending iteration is done.
3394 * Request reference is cleared and it is guaranteed to be observed
3395 * after the ->lock is released.
3397 spin_lock_irqsave(&tags->lock, flags);
3398 spin_unlock_irqrestore(&tags->lock, flags);
3401 /* hctx->ctxs will be freed in queue's release handler */
3402 static void blk_mq_exit_hctx(struct request_queue *q,
3403 struct blk_mq_tag_set *set,
3404 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3406 struct request *flush_rq = hctx->fq->flush_rq;
3408 if (blk_mq_hw_queue_mapped(hctx))
3409 blk_mq_tag_idle(hctx);
3411 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3412 set->queue_depth, flush_rq);
3413 if (set->ops->exit_request)
3414 set->ops->exit_request(set, flush_rq, hctx_idx);
3416 if (set->ops->exit_hctx)
3417 set->ops->exit_hctx(hctx, hctx_idx);
3419 blk_mq_remove_cpuhp(hctx);
3421 spin_lock(&q->unused_hctx_lock);
3422 list_add(&hctx->hctx_list, &q->unused_hctx_list);
3423 spin_unlock(&q->unused_hctx_lock);
3426 static void blk_mq_exit_hw_queues(struct request_queue *q,
3427 struct blk_mq_tag_set *set, int nr_queue)
3429 struct blk_mq_hw_ctx *hctx;
3432 queue_for_each_hw_ctx(q, hctx, i) {
3435 blk_mq_debugfs_unregister_hctx(hctx);
3436 blk_mq_exit_hctx(q, set, hctx, i);
3440 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
3442 int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
3444 BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
3445 __alignof__(struct blk_mq_hw_ctx)) !=
3446 sizeof(struct blk_mq_hw_ctx));
3448 if (tag_set->flags & BLK_MQ_F_BLOCKING)
3449 hw_ctx_size += sizeof(struct srcu_struct);
3454 static int blk_mq_init_hctx(struct request_queue *q,
3455 struct blk_mq_tag_set *set,
3456 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3458 hctx->queue_num = hctx_idx;
3460 if (!(hctx->flags & BLK_MQ_F_STACKING))
3461 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3462 &hctx->cpuhp_online);
3463 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
3465 hctx->tags = set->tags[hctx_idx];
3467 if (set->ops->init_hctx &&
3468 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3469 goto unregister_cpu_notifier;
3471 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3477 if (set->ops->exit_hctx)
3478 set->ops->exit_hctx(hctx, hctx_idx);
3479 unregister_cpu_notifier:
3480 blk_mq_remove_cpuhp(hctx);
3484 static struct blk_mq_hw_ctx *
3485 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3488 struct blk_mq_hw_ctx *hctx;
3489 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3491 hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
3493 goto fail_alloc_hctx;
3495 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
3498 atomic_set(&hctx->nr_active, 0);
3499 if (node == NUMA_NO_NODE)
3500 node = set->numa_node;
3501 hctx->numa_node = node;
3503 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
3504 spin_lock_init(&hctx->lock);
3505 INIT_LIST_HEAD(&hctx->dispatch);
3507 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
3509 INIT_LIST_HEAD(&hctx->hctx_list);
3512 * Allocate space for all possible cpus to avoid allocation at
3515 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
3520 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
3521 gfp, node, false, false))
3525 spin_lock_init(&hctx->dispatch_wait_lock);
3526 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
3527 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
3529 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
3533 if (hctx->flags & BLK_MQ_F_BLOCKING)
3534 init_srcu_struct(hctx->srcu);
3535 blk_mq_hctx_kobj_init(hctx);
3540 sbitmap_free(&hctx->ctx_map);
3544 free_cpumask_var(hctx->cpumask);
3551 static void blk_mq_init_cpu_queues(struct request_queue *q,
3552 unsigned int nr_hw_queues)
3554 struct blk_mq_tag_set *set = q->tag_set;
3557 for_each_possible_cpu(i) {
3558 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
3559 struct blk_mq_hw_ctx *hctx;
3563 spin_lock_init(&__ctx->lock);
3564 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
3565 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
3570 * Set local node, IFF we have more than one hw queue. If
3571 * not, we remain on the home node of the device
3573 for (j = 0; j < set->nr_maps; j++) {
3574 hctx = blk_mq_map_queue_type(q, j, i);
3575 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
3576 hctx->numa_node = cpu_to_node(i);
3581 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3582 unsigned int hctx_idx,
3585 struct blk_mq_tags *tags;
3588 tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
3592 ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
3594 blk_mq_free_rq_map(tags);
3601 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3604 if (blk_mq_is_shared_tags(set->flags)) {
3605 set->tags[hctx_idx] = set->shared_tags;
3610 set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
3613 return set->tags[hctx_idx];
3616 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3617 struct blk_mq_tags *tags,
3618 unsigned int hctx_idx)
3621 blk_mq_free_rqs(set, tags, hctx_idx);
3622 blk_mq_free_rq_map(tags);
3626 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3627 unsigned int hctx_idx)
3629 if (!blk_mq_is_shared_tags(set->flags))
3630 blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
3632 set->tags[hctx_idx] = NULL;
3635 static void blk_mq_map_swqueue(struct request_queue *q)
3637 unsigned int i, j, hctx_idx;
3638 struct blk_mq_hw_ctx *hctx;
3639 struct blk_mq_ctx *ctx;
3640 struct blk_mq_tag_set *set = q->tag_set;
3642 queue_for_each_hw_ctx(q, hctx, i) {
3643 cpumask_clear(hctx->cpumask);
3645 hctx->dispatch_from = NULL;
3649 * Map software to hardware queues.
3651 * If the cpu isn't present, the cpu is mapped to first hctx.
3653 for_each_possible_cpu(i) {
3655 ctx = per_cpu_ptr(q->queue_ctx, i);
3656 for (j = 0; j < set->nr_maps; j++) {
3657 if (!set->map[j].nr_queues) {
3658 ctx->hctxs[j] = blk_mq_map_queue_type(q,
3659 HCTX_TYPE_DEFAULT, i);
3662 hctx_idx = set->map[j].mq_map[i];
3663 /* unmapped hw queue can be remapped after CPU topo changed */
3664 if (!set->tags[hctx_idx] &&
3665 !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
3667 * If tags initialization fail for some hctx,
3668 * that hctx won't be brought online. In this
3669 * case, remap the current ctx to hctx[0] which
3670 * is guaranteed to always have tags allocated
3672 set->map[j].mq_map[i] = 0;
3675 hctx = blk_mq_map_queue_type(q, j, i);
3676 ctx->hctxs[j] = hctx;
3678 * If the CPU is already set in the mask, then we've
3679 * mapped this one already. This can happen if
3680 * devices share queues across queue maps.
3682 if (cpumask_test_cpu(i, hctx->cpumask))
3685 cpumask_set_cpu(i, hctx->cpumask);
3687 ctx->index_hw[hctx->type] = hctx->nr_ctx;
3688 hctx->ctxs[hctx->nr_ctx++] = ctx;
3691 * If the nr_ctx type overflows, we have exceeded the
3692 * amount of sw queues we can support.
3694 BUG_ON(!hctx->nr_ctx);
3697 for (; j < HCTX_MAX_TYPES; j++)
3698 ctx->hctxs[j] = blk_mq_map_queue_type(q,
3699 HCTX_TYPE_DEFAULT, i);
3702 queue_for_each_hw_ctx(q, hctx, i) {
3704 * If no software queues are mapped to this hardware queue,
3705 * disable it and free the request entries.
3707 if (!hctx->nr_ctx) {
3708 /* Never unmap queue 0. We need it as a
3709 * fallback in case of a new remap fails
3713 __blk_mq_free_map_and_rqs(set, i);
3719 hctx->tags = set->tags[i];
3720 WARN_ON(!hctx->tags);
3723 * Set the map size to the number of mapped software queues.
3724 * This is more accurate and more efficient than looping
3725 * over all possibly mapped software queues.
3727 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
3730 * Initialize batch roundrobin counts
3732 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
3733 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
3738 * Caller needs to ensure that we're either frozen/quiesced, or that
3739 * the queue isn't live yet.
3741 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
3743 struct blk_mq_hw_ctx *hctx;
3746 queue_for_each_hw_ctx(q, hctx, i) {
3748 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3750 blk_mq_tag_idle(hctx);
3751 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3756 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
3759 struct request_queue *q;
3761 lockdep_assert_held(&set->tag_list_lock);
3763 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3764 blk_mq_freeze_queue(q);
3765 queue_set_hctx_shared(q, shared);
3766 blk_mq_unfreeze_queue(q);
3770 static void blk_mq_del_queue_tag_set(struct request_queue *q)
3772 struct blk_mq_tag_set *set = q->tag_set;
3774 mutex_lock(&set->tag_list_lock);
3775 list_del(&q->tag_set_list);
3776 if (list_is_singular(&set->tag_list)) {
3777 /* just transitioned to unshared */
3778 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3779 /* update existing queue */
3780 blk_mq_update_tag_set_shared(set, false);
3782 mutex_unlock(&set->tag_list_lock);
3783 INIT_LIST_HEAD(&q->tag_set_list);
3786 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
3787 struct request_queue *q)
3789 mutex_lock(&set->tag_list_lock);
3792 * Check to see if we're transitioning to shared (from 1 to 2 queues).
3794 if (!list_empty(&set->tag_list) &&
3795 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
3796 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3797 /* update existing queue */
3798 blk_mq_update_tag_set_shared(set, true);
3800 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
3801 queue_set_hctx_shared(q, true);
3802 list_add_tail(&q->tag_set_list, &set->tag_list);
3804 mutex_unlock(&set->tag_list_lock);
3807 /* All allocations will be freed in release handler of q->mq_kobj */
3808 static int blk_mq_alloc_ctxs(struct request_queue *q)
3810 struct blk_mq_ctxs *ctxs;
3813 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
3817 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
3818 if (!ctxs->queue_ctx)
3821 for_each_possible_cpu(cpu) {
3822 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
3826 q->mq_kobj = &ctxs->kobj;
3827 q->queue_ctx = ctxs->queue_ctx;
3836 * It is the actual release handler for mq, but we do it from
3837 * request queue's release handler for avoiding use-after-free
3838 * and headache because q->mq_kobj shouldn't have been introduced,
3839 * but we can't group ctx/kctx kobj without it.
3841 void blk_mq_release(struct request_queue *q)
3843 struct blk_mq_hw_ctx *hctx, *next;
3846 queue_for_each_hw_ctx(q, hctx, i)
3847 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
3849 /* all hctx are in .unused_hctx_list now */
3850 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
3851 list_del_init(&hctx->hctx_list);
3852 kobject_put(&hctx->kobj);
3855 kfree(q->queue_hw_ctx);
3858 * release .mq_kobj and sw queue's kobject now because
3859 * both share lifetime with request queue.
3861 blk_mq_sysfs_deinit(q);
3864 static struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
3867 struct request_queue *q;
3870 q = blk_alloc_queue(set->numa_node);
3872 return ERR_PTR(-ENOMEM);
3873 q->queuedata = queuedata;
3874 ret = blk_mq_init_allocated_queue(set, q);
3876 blk_cleanup_queue(q);
3877 return ERR_PTR(ret);
3882 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
3884 return blk_mq_init_queue_data(set, NULL);
3886 EXPORT_SYMBOL(blk_mq_init_queue);
3888 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set, void *queuedata,
3889 struct lock_class_key *lkclass)
3891 struct request_queue *q;
3892 struct gendisk *disk;
3894 q = blk_mq_init_queue_data(set, queuedata);
3898 disk = __alloc_disk_node(q, set->numa_node, lkclass);
3900 blk_cleanup_queue(q);
3901 return ERR_PTR(-ENOMEM);
3905 EXPORT_SYMBOL(__blk_mq_alloc_disk);
3907 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
3908 struct blk_mq_tag_set *set, struct request_queue *q,
3909 int hctx_idx, int node)
3911 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
3913 /* reuse dead hctx first */
3914 spin_lock(&q->unused_hctx_lock);
3915 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
3916 if (tmp->numa_node == node) {
3922 list_del_init(&hctx->hctx_list);
3923 spin_unlock(&q->unused_hctx_lock);
3926 hctx = blk_mq_alloc_hctx(q, set, node);
3930 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
3936 kobject_put(&hctx->kobj);
3941 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
3942 struct request_queue *q)
3945 struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
3947 if (q->nr_hw_queues < set->nr_hw_queues) {
3948 struct blk_mq_hw_ctx **new_hctxs;
3950 new_hctxs = kcalloc_node(set->nr_hw_queues,
3951 sizeof(*new_hctxs), GFP_KERNEL,
3956 memcpy(new_hctxs, hctxs, q->nr_hw_queues *
3958 q->queue_hw_ctx = new_hctxs;
3963 /* protect against switching io scheduler */
3964 mutex_lock(&q->sysfs_lock);
3965 for (i = 0; i < set->nr_hw_queues; i++) {
3967 struct blk_mq_hw_ctx *hctx;
3969 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
3971 * If the hw queue has been mapped to another numa node,
3972 * we need to realloc the hctx. If allocation fails, fallback
3973 * to use the previous one.
3975 if (hctxs[i] && (hctxs[i]->numa_node == node))
3978 hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
3981 blk_mq_exit_hctx(q, set, hctxs[i], i);
3985 pr_warn("Allocate new hctx on node %d fails,\
3986 fallback to previous one on node %d\n",
3987 node, hctxs[i]->numa_node);
3993 * Increasing nr_hw_queues fails. Free the newly allocated
3994 * hctxs and keep the previous q->nr_hw_queues.
3996 if (i != set->nr_hw_queues) {
3997 j = q->nr_hw_queues;
4001 end = q->nr_hw_queues;
4002 q->nr_hw_queues = set->nr_hw_queues;
4005 for (; j < end; j++) {
4006 struct blk_mq_hw_ctx *hctx = hctxs[j];
4009 blk_mq_exit_hctx(q, set, hctx, j);
4013 mutex_unlock(&q->sysfs_lock);
4016 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4017 struct request_queue *q)
4019 /* mark the queue as mq asap */
4020 q->mq_ops = set->ops;
4022 q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
4023 blk_mq_poll_stats_bkt,
4024 BLK_MQ_POLL_STATS_BKTS, q);
4028 if (blk_mq_alloc_ctxs(q))
4031 /* init q->mq_kobj and sw queues' kobjects */
4032 blk_mq_sysfs_init(q);
4034 INIT_LIST_HEAD(&q->unused_hctx_list);
4035 spin_lock_init(&q->unused_hctx_lock);
4037 blk_mq_realloc_hw_ctxs(set, q);
4038 if (!q->nr_hw_queues)
4041 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4042 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4046 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4047 if (set->nr_maps > HCTX_TYPE_POLL &&
4048 set->map[HCTX_TYPE_POLL].nr_queues)
4049 blk_queue_flag_set(QUEUE_FLAG_POLL, q);
4051 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4052 INIT_LIST_HEAD(&q->requeue_list);
4053 spin_lock_init(&q->requeue_lock);
4055 q->nr_requests = set->queue_depth;
4058 * Default to classic polling
4060 q->poll_nsec = BLK_MQ_POLL_CLASSIC;
4062 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4063 blk_mq_add_queue_tag_set(set, q);
4064 blk_mq_map_swqueue(q);
4068 kfree(q->queue_hw_ctx);
4069 q->nr_hw_queues = 0;
4070 blk_mq_sysfs_deinit(q);
4072 blk_stat_free_callback(q->poll_cb);
4078 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4080 /* tags can _not_ be used after returning from blk_mq_exit_queue */
4081 void blk_mq_exit_queue(struct request_queue *q)
4083 struct blk_mq_tag_set *set = q->tag_set;
4085 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4086 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4087 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4088 blk_mq_del_queue_tag_set(q);
4091 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4095 if (blk_mq_is_shared_tags(set->flags)) {
4096 set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4099 if (!set->shared_tags)
4103 for (i = 0; i < set->nr_hw_queues; i++) {
4104 if (!__blk_mq_alloc_map_and_rqs(set, i))
4113 __blk_mq_free_map_and_rqs(set, i);
4115 if (blk_mq_is_shared_tags(set->flags)) {
4116 blk_mq_free_map_and_rqs(set, set->shared_tags,
4117 BLK_MQ_NO_HCTX_IDX);
4124 * Allocate the request maps associated with this tag_set. Note that this
4125 * may reduce the depth asked for, if memory is tight. set->queue_depth
4126 * will be updated to reflect the allocated depth.
4128 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4133 depth = set->queue_depth;
4135 err = __blk_mq_alloc_rq_maps(set);
4139 set->queue_depth >>= 1;
4140 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4144 } while (set->queue_depth);
4146 if (!set->queue_depth || err) {
4147 pr_err("blk-mq: failed to allocate request map\n");
4151 if (depth != set->queue_depth)
4152 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4153 depth, set->queue_depth);
4158 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4161 * blk_mq_map_queues() and multiple .map_queues() implementations
4162 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4163 * number of hardware queues.
4165 if (set->nr_maps == 1)
4166 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4168 if (set->ops->map_queues && !is_kdump_kernel()) {
4172 * transport .map_queues is usually done in the following
4175 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4176 * mask = get_cpu_mask(queue)
4177 * for_each_cpu(cpu, mask)
4178 * set->map[x].mq_map[cpu] = queue;
4181 * When we need to remap, the table has to be cleared for
4182 * killing stale mapping since one CPU may not be mapped
4185 for (i = 0; i < set->nr_maps; i++)
4186 blk_mq_clear_mq_map(&set->map[i]);
4188 return set->ops->map_queues(set);
4190 BUG_ON(set->nr_maps > 1);
4191 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4195 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
4196 int cur_nr_hw_queues, int new_nr_hw_queues)
4198 struct blk_mq_tags **new_tags;
4200 if (cur_nr_hw_queues >= new_nr_hw_queues)
4203 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4204 GFP_KERNEL, set->numa_node);
4209 memcpy(new_tags, set->tags, cur_nr_hw_queues *
4210 sizeof(*set->tags));
4212 set->tags = new_tags;
4213 set->nr_hw_queues = new_nr_hw_queues;
4218 static int blk_mq_alloc_tag_set_tags(struct blk_mq_tag_set *set,
4219 int new_nr_hw_queues)
4221 return blk_mq_realloc_tag_set_tags(set, 0, new_nr_hw_queues);
4225 * Alloc a tag set to be associated with one or more request queues.
4226 * May fail with EINVAL for various error conditions. May adjust the
4227 * requested depth down, if it's too large. In that case, the set
4228 * value will be stored in set->queue_depth.
4230 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4234 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4236 if (!set->nr_hw_queues)
4238 if (!set->queue_depth)
4240 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4243 if (!set->ops->queue_rq)
4246 if (!set->ops->get_budget ^ !set->ops->put_budget)
4249 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4250 pr_info("blk-mq: reduced tag depth to %u\n",
4252 set->queue_depth = BLK_MQ_MAX_DEPTH;
4257 else if (set->nr_maps > HCTX_MAX_TYPES)
4261 * If a crashdump is active, then we are potentially in a very
4262 * memory constrained environment. Limit us to 1 queue and
4263 * 64 tags to prevent using too much memory.
4265 if (is_kdump_kernel()) {
4266 set->nr_hw_queues = 1;
4268 set->queue_depth = min(64U, set->queue_depth);
4271 * There is no use for more h/w queues than cpus if we just have
4274 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4275 set->nr_hw_queues = nr_cpu_ids;
4277 if (blk_mq_alloc_tag_set_tags(set, set->nr_hw_queues) < 0)
4281 for (i = 0; i < set->nr_maps; i++) {
4282 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4283 sizeof(set->map[i].mq_map[0]),
4284 GFP_KERNEL, set->numa_node);
4285 if (!set->map[i].mq_map)
4286 goto out_free_mq_map;
4287 set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
4290 ret = blk_mq_update_queue_map(set);
4292 goto out_free_mq_map;
4294 ret = blk_mq_alloc_set_map_and_rqs(set);
4296 goto out_free_mq_map;
4298 mutex_init(&set->tag_list_lock);
4299 INIT_LIST_HEAD(&set->tag_list);
4304 for (i = 0; i < set->nr_maps; i++) {
4305 kfree(set->map[i].mq_map);
4306 set->map[i].mq_map = NULL;
4312 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4314 /* allocate and initialize a tagset for a simple single-queue device */
4315 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4316 const struct blk_mq_ops *ops, unsigned int queue_depth,
4317 unsigned int set_flags)
4319 memset(set, 0, sizeof(*set));
4321 set->nr_hw_queues = 1;
4323 set->queue_depth = queue_depth;
4324 set->numa_node = NUMA_NO_NODE;
4325 set->flags = set_flags;
4326 return blk_mq_alloc_tag_set(set);
4328 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4330 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4334 for (i = 0; i < set->nr_hw_queues; i++)
4335 __blk_mq_free_map_and_rqs(set, i);
4337 if (blk_mq_is_shared_tags(set->flags)) {
4338 blk_mq_free_map_and_rqs(set, set->shared_tags,
4339 BLK_MQ_NO_HCTX_IDX);
4342 for (j = 0; j < set->nr_maps; j++) {
4343 kfree(set->map[j].mq_map);
4344 set->map[j].mq_map = NULL;
4350 EXPORT_SYMBOL(blk_mq_free_tag_set);
4352 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
4354 struct blk_mq_tag_set *set = q->tag_set;
4355 struct blk_mq_hw_ctx *hctx;
4361 if (q->nr_requests == nr)
4364 blk_mq_freeze_queue(q);
4365 blk_mq_quiesce_queue(q);
4368 queue_for_each_hw_ctx(q, hctx, i) {
4372 * If we're using an MQ scheduler, just update the scheduler
4373 * queue depth. This is similar to what the old code would do.
4375 if (hctx->sched_tags) {
4376 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
4379 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
4384 if (q->elevator && q->elevator->type->ops.depth_updated)
4385 q->elevator->type->ops.depth_updated(hctx);
4388 q->nr_requests = nr;
4389 if (blk_mq_is_shared_tags(set->flags)) {
4391 blk_mq_tag_update_sched_shared_tags(q);
4393 blk_mq_tag_resize_shared_tags(set, nr);
4397 blk_mq_unquiesce_queue(q);
4398 blk_mq_unfreeze_queue(q);
4404 * request_queue and elevator_type pair.
4405 * It is just used by __blk_mq_update_nr_hw_queues to cache
4406 * the elevator_type associated with a request_queue.
4408 struct blk_mq_qe_pair {
4409 struct list_head node;
4410 struct request_queue *q;
4411 struct elevator_type *type;
4415 * Cache the elevator_type in qe pair list and switch the
4416 * io scheduler to 'none'
4418 static bool blk_mq_elv_switch_none(struct list_head *head,
4419 struct request_queue *q)
4421 struct blk_mq_qe_pair *qe;
4426 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
4430 INIT_LIST_HEAD(&qe->node);
4432 qe->type = q->elevator->type;
4433 list_add(&qe->node, head);
4435 mutex_lock(&q->sysfs_lock);
4437 * After elevator_switch_mq, the previous elevator_queue will be
4438 * released by elevator_release. The reference of the io scheduler
4439 * module get by elevator_get will also be put. So we need to get
4440 * a reference of the io scheduler module here to prevent it to be
4443 __module_get(qe->type->elevator_owner);
4444 elevator_switch_mq(q, NULL);
4445 mutex_unlock(&q->sysfs_lock);
4450 static void blk_mq_elv_switch_back(struct list_head *head,
4451 struct request_queue *q)
4453 struct blk_mq_qe_pair *qe;
4454 struct elevator_type *t = NULL;
4456 list_for_each_entry(qe, head, node)
4465 list_del(&qe->node);
4468 mutex_lock(&q->sysfs_lock);
4469 elevator_switch_mq(q, t);
4470 mutex_unlock(&q->sysfs_lock);
4473 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
4476 struct request_queue *q;
4478 int prev_nr_hw_queues;
4480 lockdep_assert_held(&set->tag_list_lock);
4482 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
4483 nr_hw_queues = nr_cpu_ids;
4484 if (nr_hw_queues < 1)
4486 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
4489 list_for_each_entry(q, &set->tag_list, tag_set_list)
4490 blk_mq_freeze_queue(q);
4492 * Switch IO scheduler to 'none', cleaning up the data associated
4493 * with the previous scheduler. We will switch back once we are done
4494 * updating the new sw to hw queue mappings.
4496 list_for_each_entry(q, &set->tag_list, tag_set_list)
4497 if (!blk_mq_elv_switch_none(&head, q))
4500 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4501 blk_mq_debugfs_unregister_hctxs(q);
4502 blk_mq_sysfs_unregister(q);
4505 prev_nr_hw_queues = set->nr_hw_queues;
4506 if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
4510 set->nr_hw_queues = nr_hw_queues;
4512 blk_mq_update_queue_map(set);
4513 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4514 blk_mq_realloc_hw_ctxs(set, q);
4515 if (q->nr_hw_queues != set->nr_hw_queues) {
4516 int i = prev_nr_hw_queues;
4518 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
4519 nr_hw_queues, prev_nr_hw_queues);
4520 for (; i < set->nr_hw_queues; i++)
4521 __blk_mq_free_map_and_rqs(set, i);
4523 set->nr_hw_queues = prev_nr_hw_queues;
4524 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4527 blk_mq_map_swqueue(q);
4531 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4532 blk_mq_sysfs_register(q);
4533 blk_mq_debugfs_register_hctxs(q);
4537 list_for_each_entry(q, &set->tag_list, tag_set_list)
4538 blk_mq_elv_switch_back(&head, q);
4540 list_for_each_entry(q, &set->tag_list, tag_set_list)
4541 blk_mq_unfreeze_queue(q);
4544 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
4546 mutex_lock(&set->tag_list_lock);
4547 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
4548 mutex_unlock(&set->tag_list_lock);
4550 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
4552 /* Enable polling stats and return whether they were already enabled. */
4553 static bool blk_poll_stats_enable(struct request_queue *q)
4558 return blk_stats_alloc_enable(q);
4561 static void blk_mq_poll_stats_start(struct request_queue *q)
4564 * We don't arm the callback if polling stats are not enabled or the
4565 * callback is already active.
4567 if (!q->poll_stat || blk_stat_is_active(q->poll_cb))
4570 blk_stat_activate_msecs(q->poll_cb, 100);
4573 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
4575 struct request_queue *q = cb->data;
4578 for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
4579 if (cb->stat[bucket].nr_samples)
4580 q->poll_stat[bucket] = cb->stat[bucket];
4584 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
4587 unsigned long ret = 0;
4591 * If stats collection isn't on, don't sleep but turn it on for
4594 if (!blk_poll_stats_enable(q))
4598 * As an optimistic guess, use half of the mean service time
4599 * for this type of request. We can (and should) make this smarter.
4600 * For instance, if the completion latencies are tight, we can
4601 * get closer than just half the mean. This is especially
4602 * important on devices where the completion latencies are longer
4603 * than ~10 usec. We do use the stats for the relevant IO size
4604 * if available which does lead to better estimates.
4606 bucket = blk_mq_poll_stats_bkt(rq);
4610 if (q->poll_stat[bucket].nr_samples)
4611 ret = (q->poll_stat[bucket].mean + 1) / 2;
4616 static bool blk_mq_poll_hybrid(struct request_queue *q, blk_qc_t qc)
4618 struct blk_mq_hw_ctx *hctx = blk_qc_to_hctx(q, qc);
4619 struct request *rq = blk_qc_to_rq(hctx, qc);
4620 struct hrtimer_sleeper hs;
4621 enum hrtimer_mode mode;
4626 * If a request has completed on queue that uses an I/O scheduler, we
4627 * won't get back a request from blk_qc_to_rq.
4629 if (!rq || (rq->rq_flags & RQF_MQ_POLL_SLEPT))
4633 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
4635 * 0: use half of prev avg
4636 * >0: use this specific value
4638 if (q->poll_nsec > 0)
4639 nsecs = q->poll_nsec;
4641 nsecs = blk_mq_poll_nsecs(q, rq);
4646 rq->rq_flags |= RQF_MQ_POLL_SLEPT;
4649 * This will be replaced with the stats tracking code, using
4650 * 'avg_completion_time / 2' as the pre-sleep target.
4654 mode = HRTIMER_MODE_REL;
4655 hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
4656 hrtimer_set_expires(&hs.timer, kt);
4659 if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
4661 set_current_state(TASK_UNINTERRUPTIBLE);
4662 hrtimer_sleeper_start_expires(&hs, mode);
4665 hrtimer_cancel(&hs.timer);
4666 mode = HRTIMER_MODE_ABS;
4667 } while (hs.task && !signal_pending(current));
4669 __set_current_state(TASK_RUNNING);
4670 destroy_hrtimer_on_stack(&hs.timer);
4673 * If we sleep, have the caller restart the poll loop to reset the
4674 * state. Like for the other success return cases, the caller is
4675 * responsible for checking if the IO completed. If the IO isn't
4676 * complete, we'll get called again and will go straight to the busy
4682 static int blk_mq_poll_classic(struct request_queue *q, blk_qc_t cookie,
4683 struct io_comp_batch *iob, unsigned int flags)
4685 struct blk_mq_hw_ctx *hctx = blk_qc_to_hctx(q, cookie);
4686 long state = get_current_state();
4690 ret = q->mq_ops->poll(hctx, iob);
4692 __set_current_state(TASK_RUNNING);
4696 if (signal_pending_state(state, current))
4697 __set_current_state(TASK_RUNNING);
4698 if (task_is_running(current))
4701 if (ret < 0 || (flags & BLK_POLL_ONESHOT))
4704 } while (!need_resched());
4706 __set_current_state(TASK_RUNNING);
4710 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie, struct io_comp_batch *iob,
4713 if (!(flags & BLK_POLL_NOSLEEP) &&
4714 q->poll_nsec != BLK_MQ_POLL_CLASSIC) {
4715 if (blk_mq_poll_hybrid(q, cookie))
4718 return blk_mq_poll_classic(q, cookie, iob, flags);
4721 unsigned int blk_mq_rq_cpu(struct request *rq)
4723 return rq->mq_ctx->cpu;
4725 EXPORT_SYMBOL(blk_mq_rq_cpu);
4727 void blk_mq_cancel_work_sync(struct request_queue *q)
4729 if (queue_is_mq(q)) {
4730 struct blk_mq_hw_ctx *hctx;
4733 cancel_delayed_work_sync(&q->requeue_work);
4735 queue_for_each_hw_ctx(q, hctx, i)
4736 cancel_delayed_work_sync(&hctx->run_work);
4740 static int __init blk_mq_init(void)
4744 for_each_possible_cpu(i)
4745 init_llist_head(&per_cpu(blk_cpu_done, i));
4746 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
4748 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
4749 "block/softirq:dead", NULL,
4750 blk_softirq_cpu_dead);
4751 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
4752 blk_mq_hctx_notify_dead);
4753 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
4754 blk_mq_hctx_notify_online,
4755 blk_mq_hctx_notify_offline);
4758 subsys_initcall(blk_mq_init);