File Index
Files and directories
Sign in
FILE

blk-mq.c

File preview with syntax highlighting.

linux-6.19.14/block/blk-mq.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Block multiqueue core code
   4 *
   5 * Copyright (C) 2013-2014 Jens Axboe
   6 * Copyright (C) 2013-2014 Christoph Hellwig
   7 */
   8#include <linux/kernel.h>
   9#include <linux/module.h>
  10#include <linux/backing-dev.h>
  11#include <linux/bio.h>
  12#include <linux/blkdev.h>
  13#include <linux/blk-integrity.h>
  14#include <linux/kmemleak.h>
  15#include <linux/mm.h>
  16#include <linux/init.h>
  17#include <linux/slab.h>
  18#include <linux/workqueue.h>
  19#include <linux/smp.h>
  20#include <linux/interrupt.h>
  21#include <linux/llist.h>
  22#include <linux/cpu.h>
  23#include <linux/cache.h>
  24#include <linux/sched/topology.h>
  25#include <linux/sched/signal.h>
  26#include <linux/suspend.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>
  32#include <linux/sched/isolation.h>
  33
  34#include <trace/events/block.h>
  35
  36#include <linux/t10-pi.h>
  37#include "blk.h"
  38#include "blk-mq.h"
  39#include "blk-mq-debugfs.h"
  40#include "blk-pm.h"
  41#include "blk-stat.h"
  42#include "blk-mq-sched.h"
  43#include "blk-rq-qos.h"
  44
  45static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
  46static DEFINE_PER_CPU(call_single_data_t, blk_cpu_csd);
  47static DEFINE_MUTEX(blk_mq_cpuhp_lock);
  48
  49static void blk_mq_insert_request(struct request *rq, blk_insert_t flags);
  50static void blk_mq_request_bypass_insert(struct request *rq,
  51		blk_insert_t flags);
  52static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
  53		struct list_head *list);
  54static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
  55			 struct io_comp_batch *iob, unsigned int flags);
  56
  57/*
  58 * Check if any of the ctx, dispatch list or elevator
  59 * have pending work in this hardware queue.
  60 */
  61static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
  62{
  63	return !list_empty_careful(&hctx->dispatch) ||
  64		sbitmap_any_bit_set(&hctx->ctx_map) ||
  65			blk_mq_sched_has_work(hctx);
  66}
  67
  68/*
  69 * Mark this ctx as having pending work in this hardware queue
  70 */
  71static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
  72				     struct blk_mq_ctx *ctx)
  73{
  74	const int bit = ctx->index_hw[hctx->type];
  75
  76	if (!sbitmap_test_bit(&hctx->ctx_map, bit))
  77		sbitmap_set_bit(&hctx->ctx_map, bit);
  78}
  79
  80static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
  81				      struct blk_mq_ctx *ctx)
  82{
  83	const int bit = ctx->index_hw[hctx->type];
  84
  85	sbitmap_clear_bit(&hctx->ctx_map, bit);
  86}
  87
  88struct mq_inflight {
  89	struct block_device *part;
  90	unsigned int inflight[2];
  91};
  92
  93static bool blk_mq_check_in_driver(struct request *rq, void *priv)
  94{
  95	struct mq_inflight *mi = priv;
  96
  97	if (rq->rq_flags & RQF_IO_STAT &&
  98	    (!bdev_is_partition(mi->part) || rq->part == mi->part) &&
  99	    blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
 100		mi->inflight[rq_data_dir(rq)]++;
 101
 102	return true;
 103}
 104
 105void blk_mq_in_driver_rw(struct block_device *part, unsigned int inflight[2])
 106{
 107	struct mq_inflight mi = { .part = part };
 108
 109	blk_mq_queue_tag_busy_iter(bdev_get_queue(part), blk_mq_check_in_driver,
 110				   &mi);
 111	inflight[READ] = mi.inflight[READ];
 112	inflight[WRITE] = mi.inflight[WRITE];
 113}
 114
 115#ifdef CONFIG_LOCKDEP
 116static bool blk_freeze_set_owner(struct request_queue *q,
 117				 struct task_struct *owner)
 118{
 119	if (!owner)
 120		return false;
 121
 122	if (!q->mq_freeze_depth) {
 123		q->mq_freeze_owner = owner;
 124		q->mq_freeze_owner_depth = 1;
 125		q->mq_freeze_disk_dead = !q->disk ||
 126			test_bit(GD_DEAD, &q->disk->state) ||
 127			!blk_queue_registered(q);
 128		q->mq_freeze_queue_dying = blk_queue_dying(q);
 129		return true;
 130	}
 131
 132	if (owner == q->mq_freeze_owner)
 133		q->mq_freeze_owner_depth += 1;
 134	return false;
 135}
 136
 137/* verify the last unfreeze in owner context */
 138static bool blk_unfreeze_check_owner(struct request_queue *q)
 139{
 140	if (q->mq_freeze_owner != current)
 141		return false;
 142	if (--q->mq_freeze_owner_depth == 0) {
 143		q->mq_freeze_owner = NULL;
 144		return true;
 145	}
 146	return false;
 147}
 148
 149#else
 150
 151static bool blk_freeze_set_owner(struct request_queue *q,
 152				 struct task_struct *owner)
 153{
 154	return false;
 155}
 156
 157static bool blk_unfreeze_check_owner(struct request_queue *q)
 158{
 159	return false;
 160}
 161#endif
 162
 163bool __blk_freeze_queue_start(struct request_queue *q,
 164			      struct task_struct *owner)
 165{
 166	bool freeze;
 167
 168	mutex_lock(&q->mq_freeze_lock);
 169	freeze = blk_freeze_set_owner(q, owner);
 170	if (++q->mq_freeze_depth == 1) {
 171		percpu_ref_kill(&q->q_usage_counter);
 172		mutex_unlock(&q->mq_freeze_lock);
 173		if (queue_is_mq(q))
 174			blk_mq_run_hw_queues(q, false);
 175	} else {
 176		mutex_unlock(&q->mq_freeze_lock);
 177	}
 178
 179	return freeze;
 180}
 181
 182void blk_freeze_queue_start(struct request_queue *q)
 183{
 184	if (__blk_freeze_queue_start(q, current))
 185		blk_freeze_acquire_lock(q);
 186}
 187EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
 188
 189void blk_mq_freeze_queue_wait(struct request_queue *q)
 190{
 191	wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
 192}
 193EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
 194
 195int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
 196				     unsigned long timeout)
 197{
 198	return wait_event_timeout(q->mq_freeze_wq,
 199					percpu_ref_is_zero(&q->q_usage_counter),
 200					timeout);
 201}
 202EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
 203
 204void blk_mq_freeze_queue_nomemsave(struct request_queue *q)
 205{
 206	blk_freeze_queue_start(q);
 207	blk_mq_freeze_queue_wait(q);
 208}
 209EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_nomemsave);
 210
 211bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
 212{
 213	bool unfreeze;
 214
 215	mutex_lock(&q->mq_freeze_lock);
 216	if (force_atomic)
 217		q->q_usage_counter.data->force_atomic = true;
 218	q->mq_freeze_depth--;
 219	WARN_ON_ONCE(q->mq_freeze_depth < 0);
 220	if (!q->mq_freeze_depth) {
 221		percpu_ref_resurrect(&q->q_usage_counter);
 222		wake_up_all(&q->mq_freeze_wq);
 223	}
 224	unfreeze = blk_unfreeze_check_owner(q);
 225	mutex_unlock(&q->mq_freeze_lock);
 226
 227	return unfreeze;
 228}
 229
 230void blk_mq_unfreeze_queue_nomemrestore(struct request_queue *q)
 231{
 232	if (__blk_mq_unfreeze_queue(q, false))
 233		blk_unfreeze_release_lock(q);
 234}
 235EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_nomemrestore);
 236
 237/*
 238 * non_owner variant of blk_freeze_queue_start
 239 *
 240 * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
 241 * by the same task.  This is fragile and should not be used if at all
 242 * possible.
 243 */
 244void blk_freeze_queue_start_non_owner(struct request_queue *q)
 245{
 246	__blk_freeze_queue_start(q, NULL);
 247}
 248EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
 249
 250/* non_owner variant of blk_mq_unfreeze_queue */
 251void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
 252{
 253	__blk_mq_unfreeze_queue(q, false);
 254}
 255EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
 256
 257/*
 258 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
 259 * mpt3sas driver such that this function can be removed.
 260 */
 261void blk_mq_quiesce_queue_nowait(struct request_queue *q)
 262{
 263	unsigned long flags;
 264
 265	spin_lock_irqsave(&q->queue_lock, flags);
 266	if (!q->quiesce_depth++)
 267		blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
 268	spin_unlock_irqrestore(&q->queue_lock, flags);
 269}
 270EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
 271
 272/**
 273 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
 274 * @set: tag_set to wait on
 275 *
 276 * Note: it is driver's responsibility for making sure that quiesce has
 277 * been started on or more of the request_queues of the tag_set.  This
 278 * function only waits for the quiesce on those request_queues that had
 279 * the quiesce flag set using blk_mq_quiesce_queue_nowait.
 280 */
 281void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
 282{
 283	if (set->flags & BLK_MQ_F_BLOCKING)
 284		synchronize_srcu(set->srcu);
 285	else
 286		synchronize_rcu();
 287}
 288EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
 289
 290/**
 291 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
 292 * @q: request queue.
 293 *
 294 * Note: this function does not prevent that the struct request end_io()
 295 * callback function is invoked. Once this function is returned, we make
 296 * sure no dispatch can happen until the queue is unquiesced via
 297 * blk_mq_unquiesce_queue().
 298 */
 299void blk_mq_quiesce_queue(struct request_queue *q)
 300{
 301	blk_mq_quiesce_queue_nowait(q);
 302	/* nothing to wait for non-mq queues */
 303	if (queue_is_mq(q))
 304		blk_mq_wait_quiesce_done(q->tag_set);
 305}
 306EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
 307
 308/*
 309 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
 310 * @q: request queue.
 311 *
 312 * This function recovers queue into the state before quiescing
 313 * which is done by blk_mq_quiesce_queue.
 314 */
 315void blk_mq_unquiesce_queue(struct request_queue *q)
 316{
 317	unsigned long flags;
 318	bool run_queue = false;
 319
 320	spin_lock_irqsave(&q->queue_lock, flags);
 321	if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
 322		;
 323	} else if (!--q->quiesce_depth) {
 324		blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
 325		run_queue = true;
 326	}
 327	spin_unlock_irqrestore(&q->queue_lock, flags);
 328
 329	/* dispatch requests which are inserted during quiescing */
 330	if (run_queue)
 331		blk_mq_run_hw_queues(q, true);
 332}
 333EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
 334
 335void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
 336{
 337	struct request_queue *q;
 338
 339	rcu_read_lock();
 340	list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) {
 341		if (!blk_queue_skip_tagset_quiesce(q))
 342			blk_mq_quiesce_queue_nowait(q);
 343	}
 344	rcu_read_unlock();
 345
 346	blk_mq_wait_quiesce_done(set);
 347}
 348EXPORT_SYMBOL_GPL(blk_mq_quiesce_tagset);
 349
 350void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
 351{
 352	struct request_queue *q;
 353
 354	rcu_read_lock();
 355	list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) {
 356		if (!blk_queue_skip_tagset_quiesce(q))
 357			blk_mq_unquiesce_queue(q);
 358	}
 359	rcu_read_unlock();
 360}
 361EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
 362
 363void blk_mq_wake_waiters(struct request_queue *q)
 364{
 365	struct blk_mq_hw_ctx *hctx;
 366	unsigned long i;
 367
 368	queue_for_each_hw_ctx(q, hctx, i)
 369		if (blk_mq_hw_queue_mapped(hctx))
 370			blk_mq_tag_wakeup_all(hctx->tags, true);
 371}
 372
 373void blk_rq_init(struct request_queue *q, struct request *rq)
 374{
 375	memset(rq, 0, sizeof(*rq));
 376
 377	INIT_LIST_HEAD(&rq->queuelist);
 378	rq->q = q;
 379	rq->__sector = (sector_t) -1;
 380	rq->phys_gap_bit = 0;
 381	INIT_HLIST_NODE(&rq->hash);
 382	RB_CLEAR_NODE(&rq->rb_node);
 383	rq->tag = BLK_MQ_NO_TAG;
 384	rq->internal_tag = BLK_MQ_NO_TAG;
 385	rq->start_time_ns = blk_time_get_ns();
 386	blk_crypto_rq_set_defaults(rq);
 387}
 388EXPORT_SYMBOL(blk_rq_init);
 389
 390/* Set start and alloc time when the allocated request is actually used */
 391static inline void blk_mq_rq_time_init(struct request *rq, u64 alloc_time_ns)
 392{
 393#ifdef CONFIG_BLK_RQ_ALLOC_TIME
 394	if (blk_queue_rq_alloc_time(rq->q))
 395		rq->alloc_time_ns = alloc_time_ns;
 396	else
 397		rq->alloc_time_ns = 0;
 398#endif
 399}
 400
 401static inline void blk_mq_bio_issue_init(struct request_queue *q,
 402					 struct bio *bio)
 403{
 404#ifdef CONFIG_BLK_CGROUP
 405	if (test_bit(QUEUE_FLAG_BIO_ISSUE_TIME, &q->queue_flags))
 406		bio->issue_time_ns = blk_time_get_ns();
 407#endif
 408}
 409
 410static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
 411		struct blk_mq_tags *tags, unsigned int tag)
 412{
 413	struct blk_mq_ctx *ctx = data->ctx;
 414	struct blk_mq_hw_ctx *hctx = data->hctx;
 415	struct request_queue *q = data->q;
 416	struct request *rq = tags->static_rqs[tag];
 417
 418	rq->q = q;
 419	rq->mq_ctx = ctx;
 420	rq->mq_hctx = hctx;
 421	rq->cmd_flags = data->cmd_flags;
 422
 423	if (data->flags & BLK_MQ_REQ_PM)
 424		data->rq_flags |= RQF_PM;
 425	rq->rq_flags = data->rq_flags;
 426
 427	if (data->rq_flags & RQF_SCHED_TAGS) {
 428		rq->tag = BLK_MQ_NO_TAG;
 429		rq->internal_tag = tag;
 430	} else {
 431		rq->tag = tag;
 432		rq->internal_tag = BLK_MQ_NO_TAG;
 433	}
 434	rq->timeout = 0;
 435
 436	rq->part = NULL;
 437	rq->io_start_time_ns = 0;
 438	rq->stats_sectors = 0;
 439	rq->nr_phys_segments = 0;
 440	rq->nr_integrity_segments = 0;
 441	rq->end_io = NULL;
 442	rq->end_io_data = NULL;
 443
 444	blk_crypto_rq_set_defaults(rq);
 445	INIT_LIST_HEAD(&rq->queuelist);
 446	/* tag was already set */
 447	WRITE_ONCE(rq->deadline, 0);
 448	req_ref_set(rq, 1);
 449
 450	if (rq->rq_flags & RQF_USE_SCHED) {
 451		struct elevator_queue *e = data->q->elevator;
 452
 453		INIT_HLIST_NODE(&rq->hash);
 454		RB_CLEAR_NODE(&rq->rb_node);
 455
 456		if (e->type->ops.prepare_request)
 457			e->type->ops.prepare_request(rq);
 458	}
 459
 460	return rq;
 461}
 462
 463static inline struct request *
 464__blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data)
 465{
 466	unsigned int tag, tag_offset;
 467	struct blk_mq_tags *tags;
 468	struct request *rq;
 469	unsigned long tag_mask;
 470	int i, nr = 0;
 471
 472	do {
 473		tag_mask = blk_mq_get_tags(data, data->nr_tags - nr, &tag_offset);
 474		if (unlikely(!tag_mask)) {
 475			if (nr == 0)
 476				return NULL;
 477			break;
 478		}
 479		tags = blk_mq_tags_from_data(data);
 480		for (i = 0; tag_mask; i++) {
 481			if (!(tag_mask & (1UL << i)))
 482				continue;
 483			tag = tag_offset + i;
 484			prefetch(tags->static_rqs[tag]);
 485			tag_mask &= ~(1UL << i);
 486			rq = blk_mq_rq_ctx_init(data, tags, tag);
 487			rq_list_add_head(data->cached_rqs, rq);
 488			nr++;
 489		}
 490	} while (data->nr_tags > nr);
 491
 492	if (!(data->rq_flags & RQF_SCHED_TAGS))
 493		blk_mq_add_active_requests(data->hctx, nr);
 494	/* caller already holds a reference, add for remainder */
 495	percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
 496	data->nr_tags -= nr;
 497
 498	return rq_list_pop(data->cached_rqs);
 499}
 500
 501static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
 502{
 503	struct request_queue *q = data->q;
 504	u64 alloc_time_ns = 0;
 505	struct request *rq;
 506	unsigned int tag;
 507
 508	/* alloc_time includes depth and tag waits */
 509	if (blk_queue_rq_alloc_time(q))
 510		alloc_time_ns = blk_time_get_ns();
 511
 512	if (data->cmd_flags & REQ_NOWAIT)
 513		data->flags |= BLK_MQ_REQ_NOWAIT;
 514
 515retry:
 516	data->ctx = blk_mq_get_ctx(q);
 517	data->hctx = blk_mq_map_queue(data->cmd_flags, data->ctx);
 518
 519	if (q->elevator) {
 520		/*
 521		 * All requests use scheduler tags when an I/O scheduler is
 522		 * enabled for the queue.
 523		 */
 524		data->rq_flags |= RQF_SCHED_TAGS;
 525
 526		/*
 527		 * Flush/passthrough requests are special and go directly to the
 528		 * dispatch list.
 529		 */
 530		if ((data->cmd_flags & REQ_OP_MASK) != REQ_OP_FLUSH &&
 531		    !blk_op_is_passthrough(data->cmd_flags)) {
 532			struct elevator_mq_ops *ops = &q->elevator->type->ops;
 533
 534			WARN_ON_ONCE(data->flags & BLK_MQ_REQ_RESERVED);
 535
 536			data->rq_flags |= RQF_USE_SCHED;
 537			if (ops->limit_depth)
 538				ops->limit_depth(data->cmd_flags, data);
 539		}
 540	} else {
 541		blk_mq_tag_busy(data->hctx);
 542	}
 543
 544	if (data->flags & BLK_MQ_REQ_RESERVED)
 545		data->rq_flags |= RQF_RESV;
 546
 547	/*
 548	 * Try batched alloc if we want more than 1 tag.
 549	 */
 550	if (data->nr_tags > 1) {
 551		rq = __blk_mq_alloc_requests_batch(data);
 552		if (rq) {
 553			blk_mq_rq_time_init(rq, alloc_time_ns);
 554			return rq;
 555		}
 556		data->nr_tags = 1;
 557	}
 558
 559	/*
 560	 * Waiting allocations only fail because of an inactive hctx.  In that
 561	 * case just retry the hctx assignment and tag allocation as CPU hotplug
 562	 * should have migrated us to an online CPU by now.
 563	 */
 564	tag = blk_mq_get_tag(data);
 565	if (tag == BLK_MQ_NO_TAG) {
 566		if (data->flags & BLK_MQ_REQ_NOWAIT)
 567			return NULL;
 568		/*
 569		 * Give up the CPU and sleep for a random short time to
 570		 * ensure that thread using a realtime scheduling class
 571		 * are migrated off the CPU, and thus off the hctx that
 572		 * is going away.
 573		 */
 574		msleep(3);
 575		goto retry;
 576	}
 577
 578	if (!(data->rq_flags & RQF_SCHED_TAGS))
 579		blk_mq_inc_active_requests(data->hctx);
 580	rq = blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag);
 581	blk_mq_rq_time_init(rq, alloc_time_ns);
 582	return rq;
 583}
 584
 585static struct request *blk_mq_rq_cache_fill(struct request_queue *q,
 586					    struct blk_plug *plug,
 587					    blk_opf_t opf,
 588					    blk_mq_req_flags_t flags)
 589{
 590	struct blk_mq_alloc_data data = {
 591		.q		= q,
 592		.flags		= flags,
 593		.shallow_depth	= 0,
 594		.cmd_flags	= opf,
 595		.rq_flags	= 0,
 596		.nr_tags	= plug->nr_ios,
 597		.cached_rqs	= &plug->cached_rqs,
 598		.ctx		= NULL,
 599		.hctx		= NULL
 600	};
 601	struct request *rq;
 602
 603	if (blk_queue_enter(q, flags))
 604		return NULL;
 605
 606	plug->nr_ios = 1;
 607
 608	rq = __blk_mq_alloc_requests(&data);
 609	if (unlikely(!rq))
 610		blk_queue_exit(q);
 611	return rq;
 612}
 613
 614static struct request *blk_mq_alloc_cached_request(struct request_queue *q,
 615						   blk_opf_t opf,
 616						   blk_mq_req_flags_t flags)
 617{
 618	struct blk_plug *plug = current->plug;
 619	struct request *rq;
 620
 621	if (!plug)
 622		return NULL;
 623
 624	if (rq_list_empty(&plug->cached_rqs)) {
 625		if (plug->nr_ios == 1)
 626			return NULL;
 627		rq = blk_mq_rq_cache_fill(q, plug, opf, flags);
 628		if (!rq)
 629			return NULL;
 630	} else {
 631		rq = rq_list_peek(&plug->cached_rqs);
 632		if (!rq || rq->q != q)
 633			return NULL;
 634
 635		if (blk_mq_get_hctx_type(opf) != rq->mq_hctx->type)
 636			return NULL;
 637		if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
 638			return NULL;
 639
 640		rq_list_pop(&plug->cached_rqs);
 641		blk_mq_rq_time_init(rq, blk_time_get_ns());
 642	}
 643
 644	rq->cmd_flags = opf;
 645	INIT_LIST_HEAD(&rq->queuelist);
 646	return rq;
 647}
 648
 649struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
 650		blk_mq_req_flags_t flags)
 651{
 652	struct request *rq;
 653
 654	rq = blk_mq_alloc_cached_request(q, opf, flags);
 655	if (!rq) {
 656		struct blk_mq_alloc_data data = {
 657			.q		= q,
 658			.flags		= flags,
 659			.shallow_depth	= 0,
 660			.cmd_flags	= opf,
 661			.rq_flags	= 0,
 662			.nr_tags	= 1,
 663			.cached_rqs	= NULL,
 664			.ctx		= NULL,
 665			.hctx		= NULL
 666		};
 667		int ret;
 668
 669		ret = blk_queue_enter(q, flags);
 670		if (ret)
 671			return ERR_PTR(ret);
 672
 673		rq = __blk_mq_alloc_requests(&data);
 674		if (!rq)
 675			goto out_queue_exit;
 676	}
 677	rq->__data_len = 0;
 678	rq->phys_gap_bit = 0;
 679	rq->__sector = (sector_t) -1;
 680	rq->bio = rq->biotail = NULL;
 681	return rq;
 682out_queue_exit:
 683	blk_queue_exit(q);
 684	return ERR_PTR(-EWOULDBLOCK);
 685}
 686EXPORT_SYMBOL(blk_mq_alloc_request);
 687
 688struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
 689	blk_opf_t opf, blk_mq_req_flags_t flags, unsigned int hctx_idx)
 690{
 691	struct blk_mq_alloc_data data = {
 692		.q		= q,
 693		.flags		= flags,
 694		.shallow_depth	= 0,
 695		.cmd_flags	= opf,
 696		.rq_flags	= 0,
 697		.nr_tags	= 1,
 698		.cached_rqs	= NULL,
 699		.ctx		= NULL,
 700		.hctx		= NULL
 701	};
 702	u64 alloc_time_ns = 0;
 703	struct request *rq;
 704	unsigned int cpu;
 705	unsigned int tag;
 706	int ret;
 707
 708	/* alloc_time includes depth and tag waits */
 709	if (blk_queue_rq_alloc_time(q))
 710		alloc_time_ns = blk_time_get_ns();
 711
 712	/*
 713	 * If the tag allocator sleeps we could get an allocation for a
 714	 * different hardware context.  No need to complicate the low level
 715	 * allocator for this for the rare use case of a command tied to
 716	 * a specific queue.
 717	 */
 718	if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)) ||
 719	    WARN_ON_ONCE(!(flags & BLK_MQ_REQ_RESERVED)))
 720		return ERR_PTR(-EINVAL);
 721
 722	if (hctx_idx >= q->nr_hw_queues)
 723		return ERR_PTR(-EIO);
 724
 725	ret = blk_queue_enter(q, flags);
 726	if (ret)
 727		return ERR_PTR(ret);
 728
 729	/*
 730	 * Check if the hardware context is actually mapped to anything.
 731	 * If not tell the caller that it should skip this queue.
 732	 */
 733	ret = -EXDEV;
 734	data.hctx = q->queue_hw_ctx[hctx_idx];
 735	if (!blk_mq_hw_queue_mapped(data.hctx))
 736		goto out_queue_exit;
 737	cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
 738	if (cpu >= nr_cpu_ids)
 739		goto out_queue_exit;
 740	data.ctx = __blk_mq_get_ctx(q, cpu);
 741
 742	if (q->elevator)
 743		data.rq_flags |= RQF_SCHED_TAGS;
 744	else
 745		blk_mq_tag_busy(data.hctx);
 746
 747	if (flags & BLK_MQ_REQ_RESERVED)
 748		data.rq_flags |= RQF_RESV;
 749
 750	ret = -EWOULDBLOCK;
 751	tag = blk_mq_get_tag(&data);
 752	if (tag == BLK_MQ_NO_TAG)
 753		goto out_queue_exit;
 754	if (!(data.rq_flags & RQF_SCHED_TAGS))
 755		blk_mq_inc_active_requests(data.hctx);
 756	rq = blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag);
 757	blk_mq_rq_time_init(rq, alloc_time_ns);
 758	rq->__data_len = 0;
 759	rq->phys_gap_bit = 0;
 760	rq->__sector = (sector_t) -1;
 761	rq->bio = rq->biotail = NULL;
 762	return rq;
 763
 764out_queue_exit:
 765	blk_queue_exit(q);
 766	return ERR_PTR(ret);
 767}
 768EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
 769
 770static void blk_mq_finish_request(struct request *rq)
 771{
 772	struct request_queue *q = rq->q;
 773
 774	blk_zone_finish_request(rq);
 775
 776	if (rq->rq_flags & RQF_USE_SCHED) {
 777		q->elevator->type->ops.finish_request(rq);
 778		/*
 779		 * For postflush request that may need to be
 780		 * completed twice, we should clear this flag
 781		 * to avoid double finish_request() on the rq.
 782		 */
 783		rq->rq_flags &= ~RQF_USE_SCHED;
 784	}
 785}
 786
 787static void __blk_mq_free_request(struct request *rq)
 788{
 789	struct request_queue *q = rq->q;
 790	struct blk_mq_ctx *ctx = rq->mq_ctx;
 791	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
 792	const int sched_tag = rq->internal_tag;
 793
 794	blk_crypto_free_request(rq);
 795	blk_pm_mark_last_busy(rq);
 796	rq->mq_hctx = NULL;
 797
 798	if (rq->tag != BLK_MQ_NO_TAG) {
 799		blk_mq_dec_active_requests(hctx);
 800		blk_mq_put_tag(hctx->tags, ctx, rq->tag);
 801	}
 802	if (sched_tag != BLK_MQ_NO_TAG)
 803		blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
 804	blk_mq_sched_restart(hctx);
 805	blk_queue_exit(q);
 806}
 807
 808void blk_mq_free_request(struct request *rq)
 809{
 810	struct request_queue *q = rq->q;
 811
 812	blk_mq_finish_request(rq);
 813
 814	if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
 815		laptop_io_completion(q->disk->bdi);
 816
 817	rq_qos_done(q, rq);
 818
 819	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
 820	if (req_ref_put_and_test(rq))
 821		__blk_mq_free_request(rq);
 822}
 823EXPORT_SYMBOL_GPL(blk_mq_free_request);
 824
 825void blk_mq_free_plug_rqs(struct blk_plug *plug)
 826{
 827	struct request *rq;
 828
 829	while ((rq = rq_list_pop(&plug->cached_rqs)) != NULL)
 830		blk_mq_free_request(rq);
 831}
 832
 833void blk_dump_rq_flags(struct request *rq, char *msg)
 834{
 835	printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
 836		rq->q->disk ? rq->q->disk->disk_name : "?",
 837		(__force unsigned long long) rq->cmd_flags);
 838
 839	printk(KERN_INFO "  sector %llu, nr/cnr %u/%u\n",
 840	       (unsigned long long)blk_rq_pos(rq),
 841	       blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
 842	printk(KERN_INFO "  bio %p, biotail %p, len %u\n",
 843	       rq->bio, rq->biotail, blk_rq_bytes(rq));
 844}
 845EXPORT_SYMBOL(blk_dump_rq_flags);
 846
 847static void blk_account_io_completion(struct request *req, unsigned int bytes)
 848{
 849	if (req->rq_flags & RQF_IO_STAT) {
 850		const int sgrp = op_stat_group(req_op(req));
 851
 852		part_stat_lock();
 853		part_stat_add(req->part, sectors[sgrp], bytes >> 9);
 854		part_stat_unlock();
 855	}
 856}
 857
 858static void blk_print_req_error(struct request *req, blk_status_t status)
 859{
 860	printk_ratelimited(KERN_ERR
 861		"%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
 862		"phys_seg %u prio class %u\n",
 863		blk_status_to_str(status),
 864		req->q->disk ? req->q->disk->disk_name : "?",
 865		blk_rq_pos(req), (__force u32)req_op(req),
 866		blk_op_str(req_op(req)),
 867		(__force u32)(req->cmd_flags & ~REQ_OP_MASK),
 868		req->nr_phys_segments,
 869		IOPRIO_PRIO_CLASS(req_get_ioprio(req)));
 870}
 871
 872/*
 873 * Fully end IO on a request. Does not support partial completions, or
 874 * errors.
 875 */
 876static void blk_complete_request(struct request *req)
 877{
 878	const bool is_flush = (req->rq_flags & RQF_FLUSH_SEQ) != 0;
 879	int total_bytes = blk_rq_bytes(req);
 880	struct bio *bio = req->bio;
 881
 882	trace_block_rq_complete(req, BLK_STS_OK, total_bytes);
 883
 884	if (!bio)
 885		return;
 886
 887	if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ)
 888		blk_integrity_complete(req, total_bytes);
 889
 890	/*
 891	 * Upper layers may call blk_crypto_evict_key() anytime after the last
 892	 * bio_endio().  Therefore, the keyslot must be released before that.
 893	 */
 894	blk_crypto_rq_put_keyslot(req);
 895
 896	blk_account_io_completion(req, total_bytes);
 897
 898	do {
 899		struct bio *next = bio->bi_next;
 900
 901		/* Completion has already been traced */
 902		bio_clear_flag(bio, BIO_TRACE_COMPLETION);
 903
 904		if (blk_req_bio_is_zone_append(req, bio))
 905			blk_zone_append_update_request_bio(req, bio);
 906
 907		if (!is_flush)
 908			bio_endio(bio);
 909		bio = next;
 910	} while (bio);
 911
 912	/*
 913	 * Reset counters so that the request stacking driver
 914	 * can find how many bytes remain in the request
 915	 * later.
 916	 */
 917	if (!req->end_io) {
 918		req->bio = NULL;
 919		req->__data_len = 0;
 920	}
 921}
 922
 923/**
 924 * blk_update_request - Complete multiple bytes without completing the request
 925 * @req:      the request being processed
 926 * @error:    block status code
 927 * @nr_bytes: number of bytes to complete for @req
 928 *
 929 * Description:
 930 *     Ends I/O on a number of bytes attached to @req, but doesn't complete
 931 *     the request structure even if @req doesn't have leftover.
 932 *     If @req has leftover, sets it up for the next range of segments.
 933 *
 934 *     Passing the result of blk_rq_bytes() as @nr_bytes guarantees
 935 *     %false return from this function.
 936 *
 937 * Note:
 938 *	The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
 939 *      except in the consistency check at the end of this function.
 940 *
 941 * Return:
 942 *     %false - this request doesn't have any more data
 943 *     %true  - this request has more data
 944 **/
 945bool blk_update_request(struct request *req, blk_status_t error,
 946		unsigned int nr_bytes)
 947{
 948	bool is_flush = req->rq_flags & RQF_FLUSH_SEQ;
 949	bool quiet = req->rq_flags & RQF_QUIET;
 950	int total_bytes;
 951
 952	trace_block_rq_complete(req, error, nr_bytes);
 953
 954	if (!req->bio)
 955		return false;
 956
 957	if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
 958	    error == BLK_STS_OK)
 959		blk_integrity_complete(req, nr_bytes);
 960
 961	/*
 962	 * Upper layers may call blk_crypto_evict_key() anytime after the last
 963	 * bio_endio().  Therefore, the keyslot must be released before that.
 964	 */
 965	if (blk_crypto_rq_has_keyslot(req) && nr_bytes >= blk_rq_bytes(req))
 966		__blk_crypto_rq_put_keyslot(req);
 967
 968	if (unlikely(error && !blk_rq_is_passthrough(req) && !quiet) &&
 969	    !test_bit(GD_DEAD, &req->q->disk->state)) {
 970		blk_print_req_error(req, error);
 971		trace_block_rq_error(req, error, nr_bytes);
 972	}
 973
 974	blk_account_io_completion(req, nr_bytes);
 975
 976	total_bytes = 0;
 977	while (req->bio) {
 978		struct bio *bio = req->bio;
 979		unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
 980
 981		if (unlikely(error))
 982			bio->bi_status = error;
 983
 984		if (bio_bytes == bio->bi_iter.bi_size) {
 985			req->bio = bio->bi_next;
 986		} else if (bio_is_zone_append(bio) && error == BLK_STS_OK) {
 987			/*
 988			 * Partial zone append completions cannot be supported
 989			 * as the BIO fragments may end up not being written
 990			 * sequentially.
 991			 */
 992			bio->bi_status = BLK_STS_IOERR;
 993		}
 994
 995		/* Completion has already been traced */
 996		bio_clear_flag(bio, BIO_TRACE_COMPLETION);
 997		if (unlikely(quiet))
 998			bio_set_flag(bio, BIO_QUIET);
 999
1000		bio_advance(bio, bio_bytes);
1001
1002		/* Don't actually finish bio if it's part of flush sequence */
1003		if (!bio->bi_iter.bi_size) {
1004			if (blk_req_bio_is_zone_append(req, bio))
1005				blk_zone_append_update_request_bio(req, bio);
1006			if (!is_flush)
1007				bio_endio(bio);
1008		}
1009
1010		total_bytes += bio_bytes;
1011		nr_bytes -= bio_bytes;
1012
1013		if (!nr_bytes)
1014			break;
1015	}
1016
1017	/*
1018	 * completely done
1019	 */
1020	if (!req->bio) {
1021		/*
1022		 * Reset counters so that the request stacking driver
1023		 * can find how many bytes remain in the request
1024		 * later.
1025		 */
1026		req->__data_len = 0;
1027		return false;
1028	}
1029
1030	req->__data_len -= total_bytes;
1031
1032	/* update sector only for requests with clear definition of sector */
1033	if (!blk_rq_is_passthrough(req))
1034		req->__sector += total_bytes >> 9;
1035
1036	/* mixed attributes always follow the first bio */
1037	if (req->rq_flags & RQF_MIXED_MERGE) {
1038		req->cmd_flags &= ~REQ_FAILFAST_MASK;
1039		req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1040	}
1041
1042	if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1043		/*
1044		 * If total number of sectors is less than the first segment
1045		 * size, something has gone terribly wrong.
1046		 */
1047		if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1048			blk_dump_rq_flags(req, "request botched");
1049			req->__data_len = blk_rq_cur_bytes(req);
1050		}
1051
1052		/* recalculate the number of segments */
1053		req->nr_phys_segments = blk_recalc_rq_segments(req);
1054	}
1055
1056	return true;
1057}
1058EXPORT_SYMBOL_GPL(blk_update_request);
1059
1060static inline void blk_account_io_done(struct request *req, u64 now)
1061{
1062	trace_block_io_done(req);
1063
1064	/*
1065	 * Account IO completion.  flush_rq isn't accounted as a
1066	 * normal IO on queueing nor completion.  Accounting the
1067	 * containing request is enough.
1068	 */
1069	if ((req->rq_flags & (RQF_IO_STAT|RQF_FLUSH_SEQ)) == RQF_IO_STAT) {
1070		const int sgrp = op_stat_group(req_op(req));
1071
1072		part_stat_lock();
1073		update_io_ticks(req->part, jiffies, true);
1074		part_stat_inc(req->part, ios[sgrp]);
1075		part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1076		part_stat_local_dec(req->part,
1077				    in_flight[op_is_write(req_op(req))]);
1078		part_stat_unlock();
1079	}
1080}
1081
1082static inline bool blk_rq_passthrough_stats(struct request *req)
1083{
1084	struct bio *bio = req->bio;
1085
1086	if (!blk_queue_passthrough_stat(req->q))
1087		return false;
1088
1089	/* Requests without a bio do not transfer data. */
1090	if (!bio)
1091		return false;
1092
1093	/*
1094	 * Stats are accumulated in the bdev, so must have one attached to a
1095	 * bio to track stats. Most drivers do not set the bdev for passthrough
1096	 * requests, but nvme is one that will set it.
1097	 */
1098	if (!bio->bi_bdev)
1099		return false;
1100
1101	/*
1102	 * We don't know what a passthrough command does, but we know the
1103	 * payload size and data direction. Ensuring the size is aligned to the
1104	 * block size filters out most commands with payloads that don't
1105	 * represent sector access.
1106	 */
1107	if (blk_rq_bytes(req) & (bdev_logical_block_size(bio->bi_bdev) - 1))
1108		return false;
1109	return true;
1110}
1111
1112static inline void blk_account_io_start(struct request *req)
1113{
1114	trace_block_io_start(req);
1115
1116	if (!blk_queue_io_stat(req->q))
1117		return;
1118	if (blk_rq_is_passthrough(req) && !blk_rq_passthrough_stats(req))
1119		return;
1120
1121	req->rq_flags |= RQF_IO_STAT;
1122	req->start_time_ns = blk_time_get_ns();
1123
1124	/*
1125	 * All non-passthrough requests are created from a bio with one
1126	 * exception: when a flush command that is part of a flush sequence
1127	 * generated by the state machine in blk-flush.c is cloned onto the
1128	 * lower device by dm-multipath we can get here without a bio.
1129	 */
1130	if (req->bio)
1131		req->part = req->bio->bi_bdev;
1132	else
1133		req->part = req->q->disk->part0;
1134
1135	part_stat_lock();
1136	update_io_ticks(req->part, jiffies, false);
1137	part_stat_local_inc(req->part, in_flight[op_is_write(req_op(req))]);
1138	part_stat_unlock();
1139}
1140
1141static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
1142{
1143	if (rq->rq_flags & RQF_STATS)
1144		blk_stat_add(rq, now);
1145
1146	blk_mq_sched_completed_request(rq, now);
1147	blk_account_io_done(rq, now);
1148}
1149
1150inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
1151{
1152	if (blk_mq_need_time_stamp(rq))
1153		__blk_mq_end_request_acct(rq, blk_time_get_ns());
1154
1155	blk_mq_finish_request(rq);
1156
1157	if (rq->end_io) {
1158		rq_qos_done(rq->q, rq);
1159		if (rq->end_io(rq, error) == RQ_END_IO_FREE)
1160			blk_mq_free_request(rq);
1161	} else {
1162		blk_mq_free_request(rq);
1163	}
1164}
1165EXPORT_SYMBOL(__blk_mq_end_request);
1166
1167void blk_mq_end_request(struct request *rq, blk_status_t error)
1168{
1169	if (blk_update_request(rq, error, blk_rq_bytes(rq)))
1170		BUG();
1171	__blk_mq_end_request(rq, error);
1172}
1173EXPORT_SYMBOL(blk_mq_end_request);
1174
1175#define TAG_COMP_BATCH		32
1176
1177static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
1178					  int *tag_array, int nr_tags)
1179{
1180	struct request_queue *q = hctx->queue;
1181
1182	blk_mq_sub_active_requests(hctx, nr_tags);
1183
1184	blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
1185	percpu_ref_put_many(&q->q_usage_counter, nr_tags);
1186}
1187
1188void blk_mq_end_request_batch(struct io_comp_batch *iob)
1189{
1190	int tags[TAG_COMP_BATCH], nr_tags = 0;
1191	struct blk_mq_hw_ctx *cur_hctx = NULL;
1192	struct request *rq;
1193	u64 now = 0;
1194
1195	if (iob->need_ts)
1196		now = blk_time_get_ns();
1197
1198	while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
1199		prefetch(rq->bio);
1200		prefetch(rq->rq_next);
1201
1202		blk_complete_request(rq);
1203		if (iob->need_ts)
1204			__blk_mq_end_request_acct(rq, now);
1205
1206		blk_mq_finish_request(rq);
1207
1208		rq_qos_done(rq->q, rq);
1209
1210		/*
1211		 * If end_io handler returns NONE, then it still has
1212		 * ownership of the request.
1213		 */
1214		if (rq->end_io && rq->end_io(rq, 0) == RQ_END_IO_NONE)
1215			continue;
1216
1217		WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1218		if (!req_ref_put_and_test(rq))
1219			continue;
1220
1221		blk_crypto_free_request(rq);
1222		blk_pm_mark_last_busy(rq);
1223
1224		if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
1225			if (cur_hctx)
1226				blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1227			nr_tags = 0;
1228			cur_hctx = rq->mq_hctx;
1229		}
1230		tags[nr_tags++] = rq->tag;
1231	}
1232
1233	if (nr_tags)
1234		blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1235}
1236EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
1237
1238static void blk_complete_reqs(struct llist_head *list)
1239{
1240	struct llist_node *entry = llist_reverse_order(llist_del_all(list));
1241	struct request *rq, *next;
1242
1243	llist_for_each_entry_safe(rq, next, entry, ipi_list)
1244		rq->q->mq_ops->complete(rq);
1245}
1246
1247static __latent_entropy void blk_done_softirq(void)
1248{
1249	blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
1250}
1251
1252static int blk_softirq_cpu_dead(unsigned int cpu)
1253{
1254	blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
1255	return 0;
1256}
1257
1258static void __blk_mq_complete_request_remote(void *data)
1259{
1260	__raise_softirq_irqoff(BLOCK_SOFTIRQ);
1261}
1262
1263static inline bool blk_mq_complete_need_ipi(struct request *rq)
1264{
1265	int cpu = raw_smp_processor_id();
1266
1267	if (!IS_ENABLED(CONFIG_SMP) ||
1268	    !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
1269		return false;
1270	/*
1271	 * With force threaded interrupts enabled, raising softirq from an SMP
1272	 * function call will always result in waking the ksoftirqd thread.
1273	 * This is probably worse than completing the request on a different
1274	 * cache domain.
1275	 */
1276	if (force_irqthreads())
1277		return false;
1278
1279	/* same CPU or cache domain and capacity?  Complete locally */
1280	if (cpu == rq->mq_ctx->cpu ||
1281	    (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1282	     cpus_share_cache(cpu, rq->mq_ctx->cpu) &&
1283	     cpus_equal_capacity(cpu, rq->mq_ctx->cpu)))
1284		return false;
1285
1286	/* don't try to IPI to an offline CPU */
1287	return cpu_online(rq->mq_ctx->cpu);
1288}
1289
1290static void blk_mq_complete_send_ipi(struct request *rq)
1291{
1292	unsigned int cpu;
1293
1294	cpu = rq->mq_ctx->cpu;
1295	if (llist_add(&rq->ipi_list, &per_cpu(blk_cpu_done, cpu)))
1296		smp_call_function_single_async(cpu, &per_cpu(blk_cpu_csd, cpu));
1297}
1298
1299static void blk_mq_raise_softirq(struct request *rq)
1300{
1301	struct llist_head *list;
1302
1303	preempt_disable();
1304	list = this_cpu_ptr(&blk_cpu_done);
1305	if (llist_add(&rq->ipi_list, list))
1306		raise_softirq(BLOCK_SOFTIRQ);
1307	preempt_enable();
1308}
1309
1310bool blk_mq_complete_request_remote(struct request *rq)
1311{
1312	WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1313
1314	/*
1315	 * For request which hctx has only one ctx mapping,
1316	 * or a polled request, always complete locally,
1317	 * it's pointless to redirect the completion.
1318	 */
1319	if ((rq->mq_hctx->nr_ctx == 1 &&
1320	     rq->mq_ctx->cpu == raw_smp_processor_id()) ||
1321	     rq->cmd_flags & REQ_POLLED)
1322		return false;
1323
1324	if (blk_mq_complete_need_ipi(rq)) {
1325		blk_mq_complete_send_ipi(rq);
1326		return true;
1327	}
1328
1329	if (rq->q->nr_hw_queues == 1) {
1330		blk_mq_raise_softirq(rq);
1331		return true;
1332	}
1333	return false;
1334}
1335EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1336
1337/**
1338 * blk_mq_complete_request - end I/O on a request
1339 * @rq:		the request being processed
1340 *
1341 * Description:
1342 *	Complete a request by scheduling the ->complete_rq operation.
1343 **/
1344void blk_mq_complete_request(struct request *rq)
1345{
1346	if (!blk_mq_complete_request_remote(rq))
1347		rq->q->mq_ops->complete(rq);
1348}
1349EXPORT_SYMBOL(blk_mq_complete_request);
1350
1351/**
1352 * blk_mq_start_request - Start processing a request
1353 * @rq: Pointer to request to be started
1354 *
1355 * Function used by device drivers to notify the block layer that a request
1356 * is going to be processed now, so blk layer can do proper initializations
1357 * such as starting the timeout timer.
1358 */
1359void blk_mq_start_request(struct request *rq)
1360{
1361	struct request_queue *q = rq->q;
1362
1363	trace_block_rq_issue(rq);
1364
1365	if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags) &&
1366	    !blk_rq_is_passthrough(rq)) {
1367		rq->io_start_time_ns = blk_time_get_ns();
1368		rq->stats_sectors = blk_rq_sectors(rq);
1369		rq->rq_flags |= RQF_STATS;
1370		rq_qos_issue(q, rq);
1371	}
1372
1373	WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1374
1375	blk_add_timer(rq);
1376	WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1377	rq->mq_hctx->tags->rqs[rq->tag] = rq;
1378
1379	if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1380		blk_integrity_prepare(rq);
1381
1382	if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1383	        WRITE_ONCE(rq->bio->bi_cookie, rq->mq_hctx->queue_num);
1384}
1385EXPORT_SYMBOL(blk_mq_start_request);
1386
1387/*
1388 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
1389 * queues. This is important for md arrays to benefit from merging
1390 * requests.
1391 */
1392static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
1393{
1394	if (plug->multiple_queues)
1395		return BLK_MAX_REQUEST_COUNT * 2;
1396	return BLK_MAX_REQUEST_COUNT;
1397}
1398
1399static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
1400{
1401	struct request *last = rq_list_peek(&plug->mq_list);
1402
1403	if (!plug->rq_count) {
1404		trace_block_plug(rq->q);
1405	} else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
1406		   (!blk_queue_nomerges(rq->q) &&
1407		    blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1408		blk_mq_flush_plug_list(plug, false);
1409		last = NULL;
1410		trace_block_plug(rq->q);
1411	}
1412
1413	if (!plug->multiple_queues && last && last->q != rq->q)
1414		plug->multiple_queues = true;
1415	/*
1416	 * Any request allocated from sched tags can't be issued to
1417	 * ->queue_rqs() directly
1418	 */
1419	if (!plug->has_elevator && (rq->rq_flags & RQF_SCHED_TAGS))
1420		plug->has_elevator = true;
1421	rq_list_add_tail(&plug->mq_list, rq);
1422	plug->rq_count++;
1423}
1424
1425/**
1426 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1427 * @rq:		request to insert
1428 * @at_head:    insert request at head or tail of queue
1429 *
1430 * Description:
1431 *    Insert a fully prepared request at the back of the I/O scheduler queue
1432 *    for execution.  Don't wait for completion.
1433 *
1434 * Note:
1435 *    This function will invoke @done directly if the queue is dead.
1436 */
1437void blk_execute_rq_nowait(struct request *rq, bool at_head)
1438{
1439	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1440
1441	WARN_ON(irqs_disabled());
1442	WARN_ON(!blk_rq_is_passthrough(rq));
1443
1444	blk_account_io_start(rq);
1445
1446	if (current->plug && !at_head) {
1447		blk_add_rq_to_plug(current->plug, rq);
1448		return;
1449	}
1450
1451	blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1452	blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
1453}
1454EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1455
1456struct blk_rq_wait {
1457	struct completion done;
1458	blk_status_t ret;
1459};
1460
1461static enum rq_end_io_ret blk_end_sync_rq(struct request *rq, blk_status_t ret)
1462{
1463	struct blk_rq_wait *wait = rq->end_io_data;
1464
1465	wait->ret = ret;
1466	complete(&wait->done);
1467	return RQ_END_IO_NONE;
1468}
1469
1470bool blk_rq_is_poll(struct request *rq)
1471{
1472	if (!rq->mq_hctx)
1473		return false;
1474	if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1475		return false;
1476	return true;
1477}
1478EXPORT_SYMBOL_GPL(blk_rq_is_poll);
1479
1480static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1481{
1482	do {
1483		blk_hctx_poll(rq->q, rq->mq_hctx, NULL, BLK_POLL_ONESHOT);
1484		cond_resched();
1485	} while (!completion_done(wait));
1486}
1487
1488/**
1489 * blk_execute_rq - insert a request into queue for execution
1490 * @rq:		request to insert
1491 * @at_head:    insert request at head or tail of queue
1492 *
1493 * Description:
1494 *    Insert a fully prepared request at the back of the I/O scheduler queue
1495 *    for execution and wait for completion.
1496 * Return: The blk_status_t result provided to blk_mq_end_request().
1497 */
1498blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1499{
1500	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1501	struct blk_rq_wait wait = {
1502		.done = COMPLETION_INITIALIZER_ONSTACK(wait.done),
1503	};
1504
1505	WARN_ON(irqs_disabled());
1506	WARN_ON(!blk_rq_is_passthrough(rq));
1507
1508	rq->end_io_data = &wait;
1509	rq->end_io = blk_end_sync_rq;
1510
1511	blk_account_io_start(rq);
1512	blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1513	blk_mq_run_hw_queue(hctx, false);
1514
1515	if (blk_rq_is_poll(rq))
1516		blk_rq_poll_completion(rq, &wait.done);
1517	else
1518		blk_wait_io(&wait.done);
1519
1520	return wait.ret;
1521}
1522EXPORT_SYMBOL(blk_execute_rq);
1523
1524static void __blk_mq_requeue_request(struct request *rq)
1525{
1526	struct request_queue *q = rq->q;
1527
1528	blk_mq_put_driver_tag(rq);
1529
1530	trace_block_rq_requeue(rq);
1531	rq_qos_requeue(q, rq);
1532
1533	if (blk_mq_request_started(rq)) {
1534		WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1535		rq->rq_flags &= ~RQF_TIMED_OUT;
1536	}
1537}
1538
1539void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1540{
1541	struct request_queue *q = rq->q;
1542	unsigned long flags;
1543
1544	__blk_mq_requeue_request(rq);
1545
1546	/* this request will be re-inserted to io scheduler queue */
1547	blk_mq_sched_requeue_request(rq);
1548
1549	spin_lock_irqsave(&q->requeue_lock, flags);
1550	list_add_tail(&rq->queuelist, &q->requeue_list);
1551	spin_unlock_irqrestore(&q->requeue_lock, flags);
1552
1553	if (kick_requeue_list)
1554		blk_mq_kick_requeue_list(q);
1555}
1556EXPORT_SYMBOL(blk_mq_requeue_request);
1557
1558static void blk_mq_requeue_work(struct work_struct *work)
1559{
1560	struct request_queue *q =
1561		container_of(work, struct request_queue, requeue_work.work);
1562	LIST_HEAD(rq_list);
1563	LIST_HEAD(flush_list);
1564	struct request *rq;
1565
1566	spin_lock_irq(&q->requeue_lock);
1567	list_splice_init(&q->requeue_list, &rq_list);
1568	list_splice_init(&q->flush_list, &flush_list);
1569	spin_unlock_irq(&q->requeue_lock);
1570
1571	while (!list_empty(&rq_list)) {
1572		rq = list_entry(rq_list.next, struct request, queuelist);
1573		list_del_init(&rq->queuelist);
1574		/*
1575		 * If RQF_DONTPREP is set, the request has been started by the
1576		 * driver already and might have driver-specific data allocated
1577		 * already.  Insert it into the hctx dispatch list to avoid
1578		 * block layer merges for the request.
1579		 */
1580		if (rq->rq_flags & RQF_DONTPREP)
1581			blk_mq_request_bypass_insert(rq, 0);
1582		else
1583			blk_mq_insert_request(rq, BLK_MQ_INSERT_AT_HEAD);
1584	}
1585
1586	while (!list_empty(&flush_list)) {
1587		rq = list_entry(flush_list.next, struct request, queuelist);
1588		list_del_init(&rq->queuelist);
1589		blk_mq_insert_request(rq, 0);
1590	}
1591
1592	blk_mq_run_hw_queues(q, false);
1593}
1594
1595void blk_mq_kick_requeue_list(struct request_queue *q)
1596{
1597	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1598}
1599EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1600
1601void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1602				    unsigned long msecs)
1603{
1604	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1605				    msecs_to_jiffies(msecs));
1606}
1607EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1608
1609static bool blk_is_flush_data_rq(struct request *rq)
1610{
1611	return (rq->rq_flags & RQF_FLUSH_SEQ) && !is_flush_rq(rq);
1612}
1613
1614static bool blk_mq_rq_inflight(struct request *rq, void *priv)
1615{
1616	/*
1617	 * If we find a request that isn't idle we know the queue is busy
1618	 * as it's checked in the iter.
1619	 * Return false to stop the iteration.
1620	 *
1621	 * In case of queue quiesce, if one flush data request is completed,
1622	 * don't count it as inflight given the flush sequence is suspended,
1623	 * and the original flush data request is invisible to driver, just
1624	 * like other pending requests because of quiesce
1625	 */
1626	if (blk_mq_request_started(rq) && !(blk_queue_quiesced(rq->q) &&
1627				blk_is_flush_data_rq(rq) &&
1628				blk_mq_request_completed(rq))) {
1629		bool *busy = priv;
1630
1631		*busy = true;
1632		return false;
1633	}
1634
1635	return true;
1636}
1637
1638bool blk_mq_queue_inflight(struct request_queue *q)
1639{
1640	bool busy = false;
1641
1642	blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1643	return busy;
1644}
1645EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1646
1647static void blk_mq_rq_timed_out(struct request *req)
1648{
1649	req->rq_flags |= RQF_TIMED_OUT;
1650	if (req->q->mq_ops->timeout) {
1651		enum blk_eh_timer_return ret;
1652
1653		ret = req->q->mq_ops->timeout(req);
1654		if (ret == BLK_EH_DONE)
1655			return;
1656		WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1657	}
1658
1659	blk_add_timer(req);
1660}
1661
1662struct blk_expired_data {
1663	bool has_timedout_rq;
1664	unsigned long next;
1665	unsigned long timeout_start;
1666};
1667
1668static bool blk_mq_req_expired(struct request *rq, struct blk_expired_data *expired)
1669{
1670	unsigned long deadline;
1671
1672	if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1673		return false;
1674	if (rq->rq_flags & RQF_TIMED_OUT)
1675		return false;
1676
1677	deadline = READ_ONCE(rq->deadline);
1678	if (time_after_eq(expired->timeout_start, deadline))
1679		return true;
1680
1681	if (expired->next == 0)
1682		expired->next = deadline;
1683	else if (time_after(expired->next, deadline))
1684		expired->next = deadline;
1685	return false;
1686}
1687
1688void blk_mq_put_rq_ref(struct request *rq)
1689{
1690	if (is_flush_rq(rq)) {
1691		if (rq->end_io(rq, 0) == RQ_END_IO_FREE)
1692			blk_mq_free_request(rq);
1693	} else if (req_ref_put_and_test(rq)) {
1694		__blk_mq_free_request(rq);
1695	}
1696}
1697
1698static bool blk_mq_check_expired(struct request *rq, void *priv)
1699{
1700	struct blk_expired_data *expired = priv;
1701
1702	/*
1703	 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1704	 * be reallocated underneath the timeout handler's processing, then
1705	 * the expire check is reliable. If the request is not expired, then
1706	 * it was completed and reallocated as a new request after returning
1707	 * from blk_mq_check_expired().
1708	 */
1709	if (blk_mq_req_expired(rq, expired)) {
1710		expired->has_timedout_rq = true;
1711		return false;
1712	}
1713	return true;
1714}
1715
1716static bool blk_mq_handle_expired(struct request *rq, void *priv)
1717{
1718	struct blk_expired_data *expired = priv;
1719
1720	if (blk_mq_req_expired(rq, expired))
1721		blk_mq_rq_timed_out(rq);
1722	return true;
1723}
1724
1725static void blk_mq_timeout_work(struct work_struct *work)
1726{
1727	struct request_queue *q =
1728		container_of(work, struct request_queue, timeout_work);
1729	struct blk_expired_data expired = {
1730		.timeout_start = jiffies,
1731	};
1732	struct blk_mq_hw_ctx *hctx;
1733	unsigned long i;
1734
1735	/* A deadlock might occur if a request is stuck requiring a
1736	 * timeout at the same time a queue freeze is waiting
1737	 * completion, since the timeout code would not be able to
1738	 * acquire the queue reference here.
1739	 *
1740	 * That's why we don't use blk_queue_enter here; instead, we use
1741	 * percpu_ref_tryget directly, because we need to be able to
1742	 * obtain a reference even in the short window between the queue
1743	 * starting to freeze, by dropping the first reference in
1744	 * blk_freeze_queue_start, and the moment the last request is
1745	 * consumed, marked by the instant q_usage_counter reaches
1746	 * zero.
1747	 */
1748	if (!percpu_ref_tryget(&q->q_usage_counter))
1749		return;
1750
1751	/* check if there is any timed-out request */
1752	blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &expired);
1753	if (expired.has_timedout_rq) {
1754		/*
1755		 * Before walking tags, we must ensure any submit started
1756		 * before the current time has finished. Since the submit
1757		 * uses srcu or rcu, wait for a synchronization point to
1758		 * ensure all running submits have finished
1759		 */
1760		blk_mq_wait_quiesce_done(q->tag_set);
1761
1762		expired.next = 0;
1763		blk_mq_queue_tag_busy_iter(q, blk_mq_handle_expired, &expired);
1764	}
1765
1766	if (expired.next != 0) {
1767		mod_timer(&q->timeout, expired.next);
1768	} else {
1769		/*
1770		 * Request timeouts are handled as a forward rolling timer. If
1771		 * we end up here it means that no requests are pending and
1772		 * also that no request has been pending for a while. Mark
1773		 * each hctx as idle.
1774		 */
1775		queue_for_each_hw_ctx(q, hctx, i) {
1776			/* the hctx may be unmapped, so check it here */
1777			if (blk_mq_hw_queue_mapped(hctx))
1778				blk_mq_tag_idle(hctx);
1779		}
1780	}
1781	blk_queue_exit(q);
1782}
1783
1784struct flush_busy_ctx_data {
1785	struct blk_mq_hw_ctx *hctx;
1786	struct list_head *list;
1787};
1788
1789static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1790{
1791	struct flush_busy_ctx_data *flush_data = data;
1792	struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1793	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1794	enum hctx_type type = hctx->type;
1795
1796	spin_lock(&ctx->lock);
1797	list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1798	sbitmap_clear_bit(sb, bitnr);
1799	spin_unlock(&ctx->lock);
1800	return true;
1801}
1802
1803/*
1804 * Process software queues that have been marked busy, splicing them
1805 * to the for-dispatch
1806 */
1807void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1808{
1809	struct flush_busy_ctx_data data = {
1810		.hctx = hctx,
1811		.list = list,
1812	};
1813
1814	sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1815}
1816
1817struct dispatch_rq_data {
1818	struct blk_mq_hw_ctx *hctx;
1819	struct request *rq;
1820};
1821
1822static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1823		void *data)
1824{
1825	struct dispatch_rq_data *dispatch_data = data;
1826	struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1827	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1828	enum hctx_type type = hctx->type;
1829
1830	spin_lock(&ctx->lock);
1831	if (!list_empty(&ctx->rq_lists[type])) {
1832		dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1833		list_del_init(&dispatch_data->rq->queuelist);
1834		if (list_empty(&ctx->rq_lists[type]))
1835			sbitmap_clear_bit(sb, bitnr);
1836	}
1837	spin_unlock(&ctx->lock);
1838
1839	return !dispatch_data->rq;
1840}
1841
1842struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1843					struct blk_mq_ctx *start)
1844{
1845	unsigned off = start ? start->index_hw[hctx->type] : 0;
1846	struct dispatch_rq_data data = {
1847		.hctx = hctx,
1848		.rq   = NULL,
1849	};
1850
1851	__sbitmap_for_each_set(&hctx->ctx_map, off,
1852			       dispatch_rq_from_ctx, &data);
1853
1854	return data.rq;
1855}
1856
1857bool __blk_mq_alloc_driver_tag(struct request *rq)
1858{
1859	struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1860	unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1861	int tag;
1862
1863	blk_mq_tag_busy(rq->mq_hctx);
1864
1865	if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1866		bt = &rq->mq_hctx->tags->breserved_tags;
1867		tag_offset = 0;
1868	} else {
1869		if (!hctx_may_queue(rq->mq_hctx, bt))
1870			return false;
1871	}
1872
1873	tag = __sbitmap_queue_get(bt);
1874	if (tag == BLK_MQ_NO_TAG)
1875		return false;
1876
1877	rq->tag = tag + tag_offset;
1878	blk_mq_inc_active_requests(rq->mq_hctx);
1879	return true;
1880}
1881
1882static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1883				int flags, void *key)
1884{
1885	struct blk_mq_hw_ctx *hctx;
1886
1887	hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1888
1889	spin_lock(&hctx->dispatch_wait_lock);
1890	if (!list_empty(&wait->entry)) {
1891		struct sbitmap_queue *sbq;
1892
1893		list_del_init(&wait->entry);
1894		sbq = &hctx->tags->bitmap_tags;
1895		atomic_dec(&sbq->ws_active);
1896	}
1897	spin_unlock(&hctx->dispatch_wait_lock);
1898
1899	blk_mq_run_hw_queue(hctx, true);
1900	return 1;
1901}
1902
1903/*
1904 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1905 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1906 * restart. For both cases, take care to check the condition again after
1907 * marking us as waiting.
1908 */
1909static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1910				 struct request *rq)
1911{
1912	struct sbitmap_queue *sbq;
1913	struct wait_queue_head *wq;
1914	wait_queue_entry_t *wait;
1915	bool ret;
1916
1917	if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1918	    !(blk_mq_is_shared_tags(hctx->flags))) {
1919		blk_mq_sched_mark_restart_hctx(hctx);
1920
1921		/*
1922		 * It's possible that a tag was freed in the window between the
1923		 * allocation failure and adding the hardware queue to the wait
1924		 * queue.
1925		 *
1926		 * Don't clear RESTART here, someone else could have set it.
1927		 * At most this will cost an extra queue run.
1928		 */
1929		return blk_mq_get_driver_tag(rq);
1930	}
1931
1932	wait = &hctx->dispatch_wait;
1933	if (!list_empty_careful(&wait->entry))
1934		return false;
1935
1936	if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag))
1937		sbq = &hctx->tags->breserved_tags;
1938	else
1939		sbq = &hctx->tags->bitmap_tags;
1940	wq = &bt_wait_ptr(sbq, hctx)->wait;
1941
1942	spin_lock_irq(&wq->lock);
1943	spin_lock(&hctx->dispatch_wait_lock);
1944	if (!list_empty(&wait->entry)) {
1945		spin_unlock(&hctx->dispatch_wait_lock);
1946		spin_unlock_irq(&wq->lock);
1947		return false;
1948	}
1949
1950	atomic_inc(&sbq->ws_active);
1951	wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1952	__add_wait_queue(wq, wait);
1953
1954	/*
1955	 * Add one explicit barrier since blk_mq_get_driver_tag() may
1956	 * not imply barrier in case of failure.
1957	 *
1958	 * Order adding us to wait queue and allocating driver tag.
1959	 *
1960	 * The pair is the one implied in sbitmap_queue_wake_up() which
1961	 * orders clearing sbitmap tag bits and waitqueue_active() in
1962	 * __sbitmap_queue_wake_up(), since waitqueue_active() is lockless
1963	 *
1964	 * Otherwise, re-order of adding wait queue and getting driver tag
1965	 * may cause __sbitmap_queue_wake_up() to wake up nothing because
1966	 * the waitqueue_active() may not observe us in wait queue.
1967	 */
1968	smp_mb();
1969
1970	/*
1971	 * It's possible that a tag was freed in the window between the
1972	 * allocation failure and adding the hardware queue to the wait
1973	 * queue.
1974	 */
1975	ret = blk_mq_get_driver_tag(rq);
1976	if (!ret) {
1977		spin_unlock(&hctx->dispatch_wait_lock);
1978		spin_unlock_irq(&wq->lock);
1979		return false;
1980	}
1981
1982	/*
1983	 * We got a tag, remove ourselves from the wait queue to ensure
1984	 * someone else gets the wakeup.
1985	 */
1986	list_del_init(&wait->entry);
1987	atomic_dec(&sbq->ws_active);
1988	spin_unlock(&hctx->dispatch_wait_lock);
1989	spin_unlock_irq(&wq->lock);
1990
1991	return true;
1992}
1993
1994#define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT  8
1995#define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR  4
1996/*
1997 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1998 * - EWMA is one simple way to compute running average value
1999 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
2000 * - take 4 as factor for avoiding to get too small(0) result, and this
2001 *   factor doesn't matter because EWMA decreases exponentially
2002 */
2003static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
2004{
2005	unsigned int ewma;
2006
2007	ewma = hctx->dispatch_busy;
2008
2009	if (!ewma && !busy)
2010		return;
2011
2012	ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
2013	if (busy)
2014		ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
2015	ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
2016
2017	hctx->dispatch_busy = ewma;
2018}
2019
2020#define BLK_MQ_RESOURCE_DELAY	3		/* ms units */
2021
2022static void blk_mq_handle_dev_resource(struct request *rq,
2023				       struct list_head *list)
2024{
2025	list_add(&rq->queuelist, list);
2026	__blk_mq_requeue_request(rq);
2027}
2028
2029enum prep_dispatch {
2030	PREP_DISPATCH_OK,
2031	PREP_DISPATCH_NO_TAG,
2032	PREP_DISPATCH_NO_BUDGET,
2033};
2034
2035static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
2036						  bool need_budget)
2037{
2038	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2039	int budget_token = -1;
2040
2041	if (need_budget) {
2042		budget_token = blk_mq_get_dispatch_budget(rq->q);
2043		if (budget_token < 0) {
2044			blk_mq_put_driver_tag(rq);
2045			return PREP_DISPATCH_NO_BUDGET;
2046		}
2047		blk_mq_set_rq_budget_token(rq, budget_token);
2048	}
2049
2050	if (!blk_mq_get_driver_tag(rq)) {
2051		/*
2052		 * The initial allocation attempt failed, so we need to
2053		 * rerun the hardware queue when a tag is freed. The
2054		 * waitqueue takes care of that. If the queue is run
2055		 * before we add this entry back on the dispatch list,
2056		 * we'll re-run it below.
2057		 */
2058		if (!blk_mq_mark_tag_wait(hctx, rq)) {
2059			/*
2060			 * All budgets not got from this function will be put
2061			 * together during handling partial dispatch
2062			 */
2063			if (need_budget)
2064				blk_mq_put_dispatch_budget(rq->q, budget_token);
2065			return PREP_DISPATCH_NO_TAG;
2066		}
2067	}
2068
2069	return PREP_DISPATCH_OK;
2070}
2071
2072/* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
2073static void blk_mq_release_budgets(struct request_queue *q,
2074		struct list_head *list)
2075{
2076	struct request *rq;
2077
2078	list_for_each_entry(rq, list, queuelist) {
2079		int budget_token = blk_mq_get_rq_budget_token(rq);
2080
2081		if (budget_token >= 0)
2082			blk_mq_put_dispatch_budget(q, budget_token);
2083	}
2084}
2085
2086/*
2087 * blk_mq_commit_rqs will notify driver using bd->last that there is no
2088 * more requests. (See comment in struct blk_mq_ops for commit_rqs for
2089 * details)
2090 * Attention, we should explicitly call this in unusual cases:
2091 *  1) did not queue everything initially scheduled to queue
2092 *  2) the last attempt to queue a request failed
2093 */
2094static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int queued,
2095			      bool from_schedule)
2096{
2097	if (hctx->queue->mq_ops->commit_rqs && queued) {
2098		trace_block_unplug(hctx->queue, queued, !from_schedule);
2099		hctx->queue->mq_ops->commit_rqs(hctx);
2100	}
2101}
2102
2103/*
2104 * Returns true if we did some work AND can potentially do more.
2105 */
2106bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
2107			     bool get_budget)
2108{
2109	enum prep_dispatch prep;
2110	struct request_queue *q = hctx->queue;
2111	struct request *rq;
2112	int queued;
2113	blk_status_t ret = BLK_STS_OK;
2114	bool needs_resource = false;
2115
2116	if (list_empty(list))
2117		return false;
2118
2119	/*
2120	 * Now process all the entries, sending them to the driver.
2121	 */
2122	queued = 0;
2123	do {
2124		struct blk_mq_queue_data bd;
2125
2126		rq = list_first_entry(list, struct request, queuelist);
2127
2128		WARN_ON_ONCE(hctx != rq->mq_hctx);
2129		prep = blk_mq_prep_dispatch_rq(rq, get_budget);
2130		if (prep != PREP_DISPATCH_OK)
2131			break;
2132
2133		list_del_init(&rq->queuelist);
2134
2135		bd.rq = rq;
2136		bd.last = list_empty(list);
2137
2138		ret = q->mq_ops->queue_rq(hctx, &bd);
2139		switch (ret) {
2140		case BLK_STS_OK:
2141			queued++;
2142			break;
2143		case BLK_STS_RESOURCE:
2144			needs_resource = true;
2145			fallthrough;
2146		case BLK_STS_DEV_RESOURCE:
2147			blk_mq_handle_dev_resource(rq, list);
2148			goto out;
2149		default:
2150			blk_mq_end_request(rq, ret);
2151		}
2152	} while (!list_empty(list));
2153out:
2154	/* If we didn't flush the entire list, we could have told the driver
2155	 * there was more coming, but that turned out to be a lie.
2156	 */
2157	if (!list_empty(list) || ret != BLK_STS_OK)
2158		blk_mq_commit_rqs(hctx, queued, false);
2159
2160	/*
2161	 * Any items that need requeuing? Stuff them into hctx->dispatch,
2162	 * that is where we will continue on next queue run.
2163	 */
2164	if (!list_empty(list)) {
2165		bool needs_restart;
2166		/* For non-shared tags, the RESTART check will suffice */
2167		bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
2168			((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) ||
2169			blk_mq_is_shared_tags(hctx->flags));
2170
2171		/*
2172		 * If the caller allocated budgets, free the budgets of the
2173		 * requests that have not yet been passed to the block driver.
2174		 */
2175		if (!get_budget)
2176			blk_mq_release_budgets(q, list);
2177
2178		spin_lock(&hctx->lock);
2179		list_splice_tail_init(list, &hctx->dispatch);
2180		spin_unlock(&hctx->lock);
2181
2182		/*
2183		 * Order adding requests to hctx->dispatch and checking
2184		 * SCHED_RESTART flag. The pair of this smp_mb() is the one
2185		 * in blk_mq_sched_restart(). Avoid restart code path to
2186		 * miss the new added requests to hctx->dispatch, meantime
2187		 * SCHED_RESTART is observed here.
2188		 */
2189		smp_mb();
2190
2191		/*
2192		 * If SCHED_RESTART was set by the caller of this function and
2193		 * it is no longer set that means that it was cleared by another
2194		 * thread and hence that a queue rerun is needed.
2195		 *
2196		 * If 'no_tag' is set, that means that we failed getting
2197		 * a driver tag with an I/O scheduler attached. If our dispatch
2198		 * waitqueue is no longer active, ensure that we run the queue
2199		 * AFTER adding our entries back to the list.
2200		 *
2201		 * If no I/O scheduler has been configured it is possible that
2202		 * the hardware queue got stopped and restarted before requests
2203		 * were pushed back onto the dispatch list. Rerun the queue to
2204		 * avoid starvation. Notes:
2205		 * - blk_mq_run_hw_queue() checks whether or not a queue has
2206		 *   been stopped before rerunning a queue.
2207		 * - Some but not all block drivers stop a queue before
2208		 *   returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
2209		 *   and dm-rq.
2210		 *
2211		 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
2212		 * bit is set, run queue after a delay to avoid IO stalls
2213		 * that could otherwise occur if the queue is idle.  We'll do
2214		 * similar if we couldn't get budget or couldn't lock a zone
2215		 * and SCHED_RESTART is set.
2216		 */
2217		needs_restart = blk_mq_sched_needs_restart(hctx);
2218		if (prep == PREP_DISPATCH_NO_BUDGET)
2219			needs_resource = true;
2220		if (!needs_restart ||
2221		    (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
2222			blk_mq_run_hw_queue(hctx, true);
2223		else if (needs_resource)
2224			blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
2225
2226		blk_mq_update_dispatch_busy(hctx, true);
2227		return false;
2228	}
2229
2230	blk_mq_update_dispatch_busy(hctx, false);
2231	return true;
2232}
2233
2234static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
2235{
2236	int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
2237
2238	if (cpu >= nr_cpu_ids)
2239		cpu = cpumask_first(hctx->cpumask);
2240	return cpu;
2241}
2242
2243/*
2244 * ->next_cpu is always calculated from hctx->cpumask, so simply use
2245 * it for speeding up the check
2246 */
2247static bool blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx *hctx)
2248{
2249        return hctx->next_cpu >= nr_cpu_ids;
2250}
2251
2252/*
2253 * It'd be great if the workqueue API had a way to pass
2254 * in a mask and had some smarts for more clever placement.
2255 * For now we just round-robin here, switching for every
2256 * BLK_MQ_CPU_WORK_BATCH queued items.
2257 */
2258static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
2259{
2260	bool tried = false;
2261	int next_cpu = hctx->next_cpu;
2262
2263	/* Switch to unbound if no allowable CPUs in this hctx */
2264	if (hctx->queue->nr_hw_queues == 1 || blk_mq_hctx_empty_cpumask(hctx))
2265		return WORK_CPU_UNBOUND;
2266
2267	if (--hctx->next_cpu_batch <= 0) {
2268select_cpu:
2269		next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
2270				cpu_online_mask);
2271		if (next_cpu >= nr_cpu_ids)
2272			next_cpu = blk_mq_first_mapped_cpu(hctx);
2273		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2274	}
2275
2276	/*
2277	 * Do unbound schedule if we can't find a online CPU for this hctx,
2278	 * and it should only happen in the path of handling CPU DEAD.
2279	 */
2280	if (!cpu_online(next_cpu)) {
2281		if (!tried) {
2282			tried = true;
2283			goto select_cpu;
2284		}
2285
2286		/*
2287		 * Make sure to re-select CPU next time once after CPUs
2288		 * in hctx->cpumask become online again.
2289		 */
2290		hctx->next_cpu = next_cpu;
2291		hctx->next_cpu_batch = 1;
2292		return WORK_CPU_UNBOUND;
2293	}
2294
2295	hctx->next_cpu = next_cpu;
2296	return next_cpu;
2297}
2298
2299/**
2300 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2301 * @hctx: Pointer to the hardware queue to run.
2302 * @msecs: Milliseconds of delay to wait before running the queue.
2303 *
2304 * Run a hardware queue asynchronously with a delay of @msecs.
2305 */
2306void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2307{
2308	if (unlikely(blk_mq_hctx_stopped(hctx)))
2309		return;
2310	kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2311				    msecs_to_jiffies(msecs));
2312}
2313EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2314
2315static inline bool blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx *hctx)
2316{
2317	bool need_run;
2318
2319	/*
2320	 * When queue is quiesced, we may be switching io scheduler, or
2321	 * updating nr_hw_queues, or other things, and we can't run queue
2322	 * any more, even blk_mq_hctx_has_pending() can't be called safely.
2323	 *
2324	 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2325	 * quiesced.
2326	 */
2327	__blk_mq_run_dispatch_ops(hctx->queue, false,
2328		need_run = !blk_queue_quiesced(hctx->queue) &&
2329		blk_mq_hctx_has_pending(hctx));
2330	return need_run;
2331}
2332
2333/**
2334 * blk_mq_run_hw_queue - Start to run a hardware queue.
2335 * @hctx: Pointer to the hardware queue to run.
2336 * @async: If we want to run the queue asynchronously.
2337 *
2338 * Check if the request queue is not in a quiesced state and if there are
2339 * pending requests to be sent. If this is true, run the queue to send requests
2340 * to hardware.
2341 */
2342void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2343{
2344	bool need_run;
2345
2346	/*
2347	 * We can't run the queue inline with interrupts disabled.
2348	 */
2349	WARN_ON_ONCE(!async && in_interrupt());
2350
2351	might_sleep_if(!async && hctx->flags & BLK_MQ_F_BLOCKING);
2352
2353	need_run = blk_mq_hw_queue_need_run(hctx);
2354	if (!need_run) {
2355		unsigned long flags;
2356
2357		/*
2358		 * Synchronize with blk_mq_unquiesce_queue(), because we check
2359		 * if hw queue is quiesced locklessly above, we need the use
2360		 * ->queue_lock to make sure we see the up-to-date status to
2361		 * not miss rerunning the hw queue.
2362		 */
2363		spin_lock_irqsave(&hctx->queue->queue_lock, flags);
2364		need_run = blk_mq_hw_queue_need_run(hctx);
2365		spin_unlock_irqrestore(&hctx->queue->queue_lock, flags);
2366
2367		if (!need_run)
2368			return;
2369	}
2370
2371	if (async || !cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask)) {
2372		blk_mq_delay_run_hw_queue(hctx, 0);
2373		return;
2374	}
2375
2376	blk_mq_run_dispatch_ops(hctx->queue,
2377				blk_mq_sched_dispatch_requests(hctx));
2378}
2379EXPORT_SYMBOL(blk_mq_run_hw_queue);
2380
2381/*
2382 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2383 * scheduler.
2384 */
2385static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2386{
2387	struct blk_mq_ctx *ctx = blk_mq_get_ctx(q);
2388	/*
2389	 * If the IO scheduler does not respect hardware queues when
2390	 * dispatching, we just don't bother with multiple HW queues and
2391	 * dispatch from hctx for the current CPU since running multiple queues
2392	 * just causes lock contention inside the scheduler and pointless cache
2393	 * bouncing.
2394	 */
2395	struct blk_mq_hw_ctx *hctx = ctx->hctxs[HCTX_TYPE_DEFAULT];
2396
2397	if (!blk_mq_hctx_stopped(hctx))
2398		return hctx;
2399	return NULL;
2400}
2401
2402/**
2403 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2404 * @q: Pointer to the request queue to run.
2405 * @async: If we want to run the queue asynchronously.
2406 */
2407void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2408{
2409	struct blk_mq_hw_ctx *hctx, *sq_hctx;
2410	unsigned long i;
2411
2412	sq_hctx = NULL;
2413	if (blk_queue_sq_sched(q))
2414		sq_hctx = blk_mq_get_sq_hctx(q);
2415	queue_for_each_hw_ctx(q, hctx, i) {
2416		if (blk_mq_hctx_stopped(hctx))
2417			continue;
2418		/*
2419		 * Dispatch from this hctx either if there's no hctx preferred
2420		 * by IO scheduler or if it has requests that bypass the
2421		 * scheduler.
2422		 */
2423		if (!sq_hctx || sq_hctx == hctx ||
2424		    !list_empty_careful(&hctx->dispatch))
2425			blk_mq_run_hw_queue(hctx, async);
2426	}
2427}
2428EXPORT_SYMBOL(blk_mq_run_hw_queues);
2429
2430/**
2431 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2432 * @q: Pointer to the request queue to run.
2433 * @msecs: Milliseconds of delay to wait before running the queues.
2434 */
2435void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2436{
2437	struct blk_mq_hw_ctx *hctx, *sq_hctx;
2438	unsigned long i;
2439
2440	sq_hctx = NULL;
2441	if (blk_queue_sq_sched(q))
2442		sq_hctx = blk_mq_get_sq_hctx(q);
2443	queue_for_each_hw_ctx(q, hctx, i) {
2444		if (blk_mq_hctx_stopped(hctx))
2445			continue;
2446		/*
2447		 * If there is already a run_work pending, leave the
2448		 * pending delay untouched. Otherwise, a hctx can stall
2449		 * if another hctx is re-delaying the other's work
2450		 * before the work executes.
2451		 */
2452		if (delayed_work_pending(&hctx->run_work))
2453			continue;
2454		/*
2455		 * Dispatch from this hctx either if there's no hctx preferred
2456		 * by IO scheduler or if it has requests that bypass the
2457		 * scheduler.
2458		 */
2459		if (!sq_hctx || sq_hctx == hctx ||
2460		    !list_empty_careful(&hctx->dispatch))
2461			blk_mq_delay_run_hw_queue(hctx, msecs);
2462	}
2463}
2464EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2465
2466/*
2467 * This function is often used for pausing .queue_rq() by driver when
2468 * there isn't enough resource or some conditions aren't satisfied, and
2469 * BLK_STS_RESOURCE is usually returned.
2470 *
2471 * We do not guarantee that dispatch can be drained or blocked
2472 * after blk_mq_stop_hw_queue() returns. Please use
2473 * blk_mq_quiesce_queue() for that requirement.
2474 */
2475void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2476{
2477	cancel_delayed_work(&hctx->run_work);
2478
2479	set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2480}
2481EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2482
2483/*
2484 * This function is often used for pausing .queue_rq() by driver when
2485 * there isn't enough resource or some conditions aren't satisfied, and
2486 * BLK_STS_RESOURCE is usually returned.
2487 *
2488 * We do not guarantee that dispatch can be drained or blocked
2489 * after blk_mq_stop_hw_queues() returns. Please use
2490 * blk_mq_quiesce_queue() for that requirement.
2491 */
2492void blk_mq_stop_hw_queues(struct request_queue *q)
2493{
2494	struct blk_mq_hw_ctx *hctx;
2495	unsigned long i;
2496
2497	queue_for_each_hw_ctx(q, hctx, i)
2498		blk_mq_stop_hw_queue(hctx);
2499}
2500EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2501
2502void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2503{
2504	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2505
2506	blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
2507}
2508EXPORT_SYMBOL(blk_mq_start_hw_queue);
2509
2510void blk_mq_start_hw_queues(struct request_queue *q)
2511{
2512	struct blk_mq_hw_ctx *hctx;
2513	unsigned long i;
2514
2515	queue_for_each_hw_ctx(q, hctx, i)
2516		blk_mq_start_hw_queue(hctx);
2517}
2518EXPORT_SYMBOL(blk_mq_start_hw_queues);
2519
2520void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2521{
2522	if (!blk_mq_hctx_stopped(hctx))
2523		return;
2524
2525	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2526	/*
2527	 * Pairs with the smp_mb() in blk_mq_hctx_stopped() to order the
2528	 * clearing of BLK_MQ_S_STOPPED above and the checking of dispatch
2529	 * list in the subsequent routine.
2530	 */
2531	smp_mb__after_atomic();
2532	blk_mq_run_hw_queue(hctx, async);
2533}
2534EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2535
2536void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2537{
2538	struct blk_mq_hw_ctx *hctx;
2539	unsigned long i;
2540
2541	queue_for_each_hw_ctx(q, hctx, i)
2542		blk_mq_start_stopped_hw_queue(hctx, async ||
2543					(hctx->flags & BLK_MQ_F_BLOCKING));
2544}
2545EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2546
2547static void blk_mq_run_work_fn(struct work_struct *work)
2548{
2549	struct blk_mq_hw_ctx *hctx =
2550		container_of(work, struct blk_mq_hw_ctx, run_work.work);
2551
2552	blk_mq_run_dispatch_ops(hctx->queue,
2553				blk_mq_sched_dispatch_requests(hctx));
2554}
2555
2556/**
2557 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2558 * @rq: Pointer to request to be inserted.
2559 * @flags: BLK_MQ_INSERT_*
2560 *
2561 * Should only be used carefully, when the caller knows we want to
2562 * bypass a potential IO scheduler on the target device.
2563 */
2564static void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
2565{
2566	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2567
2568	spin_lock(&hctx->lock);
2569	if (flags & BLK_MQ_INSERT_AT_HEAD)
2570		list_add(&rq->queuelist, &hctx->dispatch);
2571	else
2572		list_add_tail(&rq->queuelist, &hctx->dispatch);
2573	spin_unlock(&hctx->lock);
2574}
2575
2576static void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx,
2577		struct blk_mq_ctx *ctx, struct list_head *list,
2578		bool run_queue_async)
2579{
2580	struct request *rq;
2581	enum hctx_type type = hctx->type;
2582
2583	/*
2584	 * Try to issue requests directly if the hw queue isn't busy to save an
2585	 * extra enqueue & dequeue to the sw queue.
2586	 */
2587	if (!hctx->dispatch_busy && !run_queue_async) {
2588		blk_mq_run_dispatch_ops(hctx->queue,
2589			blk_mq_try_issue_list_directly(hctx, list));
2590		if (list_empty(list))
2591			goto out;
2592	}
2593
2594	/*
2595	 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2596	 * offline now
2597	 */
2598	list_for_each_entry(rq, list, queuelist) {
2599		BUG_ON(rq->mq_ctx != ctx);
2600		trace_block_rq_insert(rq);
2601		if (rq->cmd_flags & REQ_NOWAIT)
2602			run_queue_async = true;
2603	}
2604
2605	spin_lock(&ctx->lock);
2606	list_splice_tail_init(list, &ctx->rq_lists[type]);
2607	blk_mq_hctx_mark_pending(hctx, ctx);
2608	spin_unlock(&ctx->lock);
2609out:
2610	blk_mq_run_hw_queue(hctx, run_queue_async);
2611}
2612
2613static void blk_mq_insert_request(struct request *rq, blk_insert_t flags)
2614{
2615	struct request_queue *q = rq->q;
2616	struct blk_mq_ctx *ctx = rq->mq_ctx;
2617	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2618
2619	if (blk_rq_is_passthrough(rq)) {
2620		/*
2621		 * Passthrough request have to be added to hctx->dispatch
2622		 * directly.  The device may be in a situation where it can't
2623		 * handle FS request, and always returns BLK_STS_RESOURCE for
2624		 * them, which gets them added to hctx->dispatch.
2625		 *
2626		 * If a passthrough request is required to unblock the queues,
2627		 * and it is added to the scheduler queue, there is no chance to
2628		 * dispatch it given we prioritize requests in hctx->dispatch.
2629		 */
2630		blk_mq_request_bypass_insert(rq, flags);
2631	} else if (req_op(rq) == REQ_OP_FLUSH) {
2632		/*
2633		 * Firstly normal IO request is inserted to scheduler queue or
2634		 * sw queue, meantime we add flush request to dispatch queue(
2635		 * hctx->dispatch) directly and there is at most one in-flight
2636		 * flush request for each hw queue, so it doesn't matter to add
2637		 * flush request to tail or front of the dispatch queue.
2638		 *
2639		 * Secondly in case of NCQ, flush request belongs to non-NCQ
2640		 * command, and queueing it will fail when there is any
2641		 * in-flight normal IO request(NCQ command). When adding flush
2642		 * rq to the front of hctx->dispatch, it is easier to introduce
2643		 * extra time to flush rq's latency because of S_SCHED_RESTART
2644		 * compared with adding to the tail of dispatch queue, then
2645		 * chance of flush merge is increased, and less flush requests
2646		 * will be issued to controller. It is observed that ~10% time
2647		 * is saved in blktests block/004 on disk attached to AHCI/NCQ
2648		 * drive when adding flush rq to the front of hctx->dispatch.
2649		 *
2650		 * Simply queue flush rq to the front of hctx->dispatch so that
2651		 * intensive flush workloads can benefit in case of NCQ HW.
2652		 */
2653		blk_mq_request_bypass_insert(rq, BLK_MQ_INSERT_AT_HEAD);
2654	} else if (q->elevator) {
2655		LIST_HEAD(list);
2656
2657		WARN_ON_ONCE(rq->tag != BLK_MQ_NO_TAG);
2658
2659		list_add(&rq->queuelist, &list);
2660		q->elevator->type->ops.insert_requests(hctx, &list, flags);
2661	} else {
2662		trace_block_rq_insert(rq);
2663
2664		spin_lock(&ctx->lock);
2665		if (flags & BLK_MQ_INSERT_AT_HEAD)
2666			list_add(&rq->queuelist, &ctx->rq_lists[hctx->type]);
2667		else
2668			list_add_tail(&rq->queuelist,
2669				      &ctx->rq_lists[hctx->type]);
2670		blk_mq_hctx_mark_pending(hctx, ctx);
2671		spin_unlock(&ctx->lock);
2672	}
2673}
2674
2675static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2676		unsigned int nr_segs)
2677{
2678	int err;
2679
2680	if (bio->bi_opf & REQ_RAHEAD)
2681		rq->cmd_flags |= REQ_FAILFAST_MASK;
2682
2683	rq->bio = rq->biotail = bio;
2684	rq->__sector = bio->bi_iter.bi_sector;
2685	rq->__data_len = bio->bi_iter.bi_size;
2686	rq->phys_gap_bit = bio->bi_bvec_gap_bit;
2687
2688	rq->nr_phys_segments = nr_segs;
2689	if (bio_integrity(bio))
2690		rq->nr_integrity_segments = blk_rq_count_integrity_sg(rq->q,
2691								      bio);
2692
2693	/* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2694	err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2695	WARN_ON_ONCE(err);
2696
2697	blk_account_io_start(rq);
2698}
2699
2700static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2701					    struct request *rq, bool last)
2702{
2703	struct request_queue *q = rq->q;
2704	struct blk_mq_queue_data bd = {
2705		.rq = rq,
2706		.last = last,
2707	};
2708	blk_status_t ret;
2709
2710	/*
2711	 * For OK queue, we are done. For error, caller may kill it.
2712	 * Any other error (busy), just add it to our list as we
2713	 * previously would have done.
2714	 */
2715	ret = q->mq_ops->queue_rq(hctx, &bd);
2716	switch (ret) {
2717	case BLK_STS_OK:
2718		blk_mq_update_dispatch_busy(hctx, false);
2719		break;
2720	case BLK_STS_RESOURCE:
2721	case BLK_STS_DEV_RESOURCE:
2722		blk_mq_update_dispatch_busy(hctx, true);
2723		__blk_mq_requeue_request(rq);
2724		break;
2725	default:
2726		blk_mq_update_dispatch_busy(hctx, false);
2727		break;
2728	}
2729
2730	return ret;
2731}
2732
2733static bool blk_mq_get_budget_and_tag(struct request *rq)
2734{
2735	int budget_token;
2736
2737	budget_token = blk_mq_get_dispatch_budget(rq->q);
2738	if (budget_token < 0)
2739		return false;
2740	blk_mq_set_rq_budget_token(rq, budget_token);
2741	if (!blk_mq_get_driver_tag(rq)) {
2742		blk_mq_put_dispatch_budget(rq->q, budget_token);
2743		return false;
2744	}
2745	return true;
2746}
2747
2748/**
2749 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2750 * @hctx: Pointer of the associated hardware queue.
2751 * @rq: Pointer to request to be sent.
2752 *
2753 * If the device has enough resources to accept a new request now, send the
2754 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2755 * we can try send it another time in the future. Requests inserted at this
2756 * queue have higher priority.
2757 */
2758static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2759		struct request *rq)
2760{
2761	blk_status_t ret;
2762
2763	if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2764		blk_mq_insert_request(rq, 0);
2765		blk_mq_run_hw_queue(hctx, false);
2766		return;
2767	}
2768
2769	if ((rq->rq_flags & RQF_USE_SCHED) || !blk_mq_get_budget_and_tag(rq)) {
2770		blk_mq_insert_request(rq, 0);
2771		blk_mq_run_hw_queue(hctx, rq->cmd_flags & REQ_NOWAIT);
2772		return;
2773	}
2774
2775	ret = __blk_mq_issue_directly(hctx, rq, true);
2776	switch (ret) {
2777	case BLK_STS_OK:
2778		break;
2779	case BLK_STS_RESOURCE:
2780	case BLK_STS_DEV_RESOURCE:
2781		blk_mq_request_bypass_insert(rq, 0);
2782		blk_mq_run_hw_queue(hctx, false);
2783		break;
2784	default:
2785		blk_mq_end_request(rq, ret);
2786		break;
2787	}
2788}
2789
2790static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2791{
2792	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2793
2794	if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2795		blk_mq_insert_request(rq, 0);
2796		blk_mq_run_hw_queue(hctx, false);
2797		return BLK_STS_OK;
2798	}
2799
2800	if (!blk_mq_get_budget_and_tag(rq))
2801		return BLK_STS_RESOURCE;
2802	return __blk_mq_issue_directly(hctx, rq, last);
2803}
2804
2805static void blk_mq_issue_direct(struct rq_list *rqs)
2806{
2807	struct blk_mq_hw_ctx *hctx = NULL;
2808	struct request *rq;
2809	int queued = 0;
2810	blk_status_t ret = BLK_STS_OK;
2811
2812	while ((rq = rq_list_pop(rqs))) {
2813		bool last = rq_list_empty(rqs);
2814
2815		if (hctx != rq->mq_hctx) {
2816			if (hctx) {
2817				blk_mq_commit_rqs(hctx, queued, false);
2818				queued = 0;
2819			}
2820			hctx = rq->mq_hctx;
2821		}
2822
2823		ret = blk_mq_request_issue_directly(rq, last);
2824		switch (ret) {
2825		case BLK_STS_OK:
2826			queued++;
2827			break;
2828		case BLK_STS_RESOURCE:
2829		case BLK_STS_DEV_RESOURCE:
2830			blk_mq_request_bypass_insert(rq, 0);
2831			blk_mq_run_hw_queue(hctx, false);
2832			goto out;
2833		default:
2834			blk_mq_end_request(rq, ret);
2835			break;
2836		}
2837	}
2838
2839out:
2840	if (ret != BLK_STS_OK)
2841		blk_mq_commit_rqs(hctx, queued, false);
2842}
2843
2844static void __blk_mq_flush_list(struct request_queue *q, struct rq_list *rqs)
2845{
2846	if (blk_queue_quiesced(q))
2847		return;
2848	q->mq_ops->queue_rqs(rqs);
2849}
2850
2851static unsigned blk_mq_extract_queue_requests(struct rq_list *rqs,
2852					      struct rq_list *queue_rqs)
2853{
2854	struct request *rq = rq_list_pop(rqs);
2855	struct request_queue *this_q = rq->q;
2856	struct request **prev = &rqs->head;
2857	struct rq_list matched_rqs = {};
2858	struct request *last = NULL;
2859	unsigned depth = 1;
2860
2861	rq_list_add_tail(&matched_rqs, rq);
2862	while ((rq = *prev)) {
2863		if (rq->q == this_q) {
2864			/* move rq from rqs to matched_rqs */
2865			*prev = rq->rq_next;
2866			rq_list_add_tail(&matched_rqs, rq);
2867			depth++;
2868		} else {
2869			/* leave rq in rqs */
2870			prev = &rq->rq_next;
2871			last = rq;
2872		}
2873	}
2874
2875	rqs->tail = last;
2876	*queue_rqs = matched_rqs;
2877	return depth;
2878}
2879
2880static void blk_mq_dispatch_queue_requests(struct rq_list *rqs, unsigned depth)
2881{
2882	struct request_queue *q = rq_list_peek(rqs)->q;
2883
2884	trace_block_unplug(q, depth, true);
2885
2886	/*
2887	 * Peek first request and see if we have a ->queue_rqs() hook.
2888	 * If we do, we can dispatch the whole list in one go.
2889	 * We already know at this point that all requests belong to the
2890	 * same queue, caller must ensure that's the case.
2891	 */
2892	if (q->mq_ops->queue_rqs) {
2893		blk_mq_run_dispatch_ops(q, __blk_mq_flush_list(q, rqs));
2894		if (rq_list_empty(rqs))
2895			return;
2896	}
2897
2898	blk_mq_run_dispatch_ops(q, blk_mq_issue_direct(rqs));
2899}
2900
2901static void blk_mq_dispatch_list(struct rq_list *rqs, bool from_sched)
2902{
2903	struct blk_mq_hw_ctx *this_hctx = NULL;
2904	struct blk_mq_ctx *this_ctx = NULL;
2905	struct rq_list requeue_list = {};
2906	unsigned int depth = 0;
2907	bool is_passthrough = false;
2908	LIST_HEAD(list);
2909
2910	do {
2911		struct request *rq = rq_list_pop(rqs);
2912
2913		if (!this_hctx) {
2914			this_hctx = rq->mq_hctx;
2915			this_ctx = rq->mq_ctx;
2916			is_passthrough = blk_rq_is_passthrough(rq);
2917		} else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx ||
2918			   is_passthrough != blk_rq_is_passthrough(rq)) {
2919			rq_list_add_tail(&requeue_list, rq);
2920			continue;
2921		}
2922		list_add_tail(&rq->queuelist, &list);
2923		depth++;
2924	} while (!rq_list_empty(rqs));
2925
2926	*rqs = requeue_list;
2927	trace_block_unplug(this_hctx->queue, depth, !from_sched);
2928
2929	percpu_ref_get(&this_hctx->queue->q_usage_counter);
2930	/* passthrough requests should never be issued to the I/O scheduler */
2931	if (is_passthrough) {
2932		spin_lock(&this_hctx->lock);
2933		list_splice_tail_init(&list, &this_hctx->dispatch);
2934		spin_unlock(&this_hctx->lock);
2935		blk_mq_run_hw_queue(this_hctx, from_sched);
2936	} else if (this_hctx->queue->elevator) {
2937		this_hctx->queue->elevator->type->ops.insert_requests(this_hctx,
2938				&list, 0);
2939		blk_mq_run_hw_queue(this_hctx, from_sched);
2940	} else {
2941		blk_mq_insert_requests(this_hctx, this_ctx, &list, from_sched);
2942	}
2943	percpu_ref_put(&this_hctx->queue->q_usage_counter);
2944}
2945
2946static void blk_mq_dispatch_multiple_queue_requests(struct rq_list *rqs)
2947{
2948	do {
2949		struct rq_list queue_rqs;
2950		unsigned depth;
2951
2952		depth = blk_mq_extract_queue_requests(rqs, &queue_rqs);
2953		blk_mq_dispatch_queue_requests(&queue_rqs, depth);
2954		while (!rq_list_empty(&queue_rqs))
2955			blk_mq_dispatch_list(&queue_rqs, false);
2956	} while (!rq_list_empty(rqs));
2957}
2958
2959void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2960{
2961	unsigned int depth;
2962
2963	/*
2964	 * We may have been called recursively midway through handling
2965	 * plug->mq_list via a schedule() in the driver's queue_rq() callback.
2966	 * To avoid mq_list changing under our feet, clear rq_count early and
2967	 * bail out specifically if rq_count is 0 rather than checking
2968	 * whether the mq_list is empty.
2969	 */
2970	if (plug->rq_count == 0)
2971		return;
2972	depth = plug->rq_count;
2973	plug->rq_count = 0;
2974
2975	if (!plug->has_elevator && !from_schedule) {
2976		if (plug->multiple_queues) {
2977			blk_mq_dispatch_multiple_queue_requests(&plug->mq_list);
2978			return;
2979		}
2980
2981		blk_mq_dispatch_queue_requests(&plug->mq_list, depth);
2982		if (rq_list_empty(&plug->mq_list))
2983			return;
2984	}
2985
2986	do {
2987		blk_mq_dispatch_list(&plug->mq_list, from_schedule);
2988	} while (!rq_list_empty(&plug->mq_list));
2989}
2990
2991static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2992		struct list_head *list)
2993{
2994	int queued = 0;
2995	blk_status_t ret = BLK_STS_OK;
2996
2997	while (!list_empty(list)) {
2998		struct request *rq = list_first_entry(list, struct request,
2999				queuelist);
3000
3001		list_del_init(&rq->queuelist);
3002		ret = blk_mq_request_issue_directly(rq, list_empty(list));
3003		switch (ret) {
3004		case BLK_STS_OK:
3005			queued++;
3006			break;
3007		case BLK_STS_RESOURCE:
3008		case BLK_STS_DEV_RESOURCE:
3009			blk_mq_request_bypass_insert(rq, 0);
3010			if (list_empty(list))
3011				blk_mq_run_hw_queue(hctx, false);
3012			goto out;
3013		default:
3014			blk_mq_end_request(rq, ret);
3015			break;
3016		}
3017	}
3018
3019out:
3020	if (ret != BLK_STS_OK)
3021		blk_mq_commit_rqs(hctx, queued, false);
3022}
3023
3024static bool blk_mq_attempt_bio_merge(struct request_queue *q,
3025				     struct bio *bio, unsigned int nr_segs)
3026{
3027	if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
3028		if (blk_attempt_plug_merge(q, bio, nr_segs))
3029			return true;
3030		if (blk_mq_sched_bio_merge(q, bio, nr_segs))
3031			return true;
3032	}
3033	return false;
3034}
3035
3036static struct request *blk_mq_get_new_requests(struct request_queue *q,
3037					       struct blk_plug *plug,
3038					       struct bio *bio)
3039{
3040	struct blk_mq_alloc_data data = {
3041		.q		= q,
3042		.flags		= 0,
3043		.shallow_depth	= 0,
3044		.cmd_flags	= bio->bi_opf,
3045		.rq_flags	= 0,
3046		.nr_tags	= 1,
3047		.cached_rqs	= NULL,
3048		.ctx		= NULL,
3049		.hctx		= NULL
3050	};
3051	struct request *rq;
3052
3053	rq_qos_throttle(q, bio);
3054
3055	if (plug) {
3056		data.nr_tags = plug->nr_ios;
3057		plug->nr_ios = 1;
3058		data.cached_rqs = &plug->cached_rqs;
3059	}
3060
3061	rq = __blk_mq_alloc_requests(&data);
3062	if (unlikely(!rq))
3063		rq_qos_cleanup(q, bio);
3064	return rq;
3065}
3066
3067/*
3068 * Check if there is a suitable cached request and return it.
3069 */
3070static struct request *blk_mq_peek_cached_request(struct blk_plug *plug,
3071		struct request_queue *q, blk_opf_t opf)
3072{
3073	enum hctx_type type = blk_mq_get_hctx_type(opf);
3074	struct request *rq;
3075
3076	if (!plug)
3077		return NULL;
3078	rq = rq_list_peek(&plug->cached_rqs);
3079	if (!rq || rq->q != q)
3080		return NULL;
3081	if (type != rq->mq_hctx->type &&
3082	    (type != HCTX_TYPE_READ || rq->mq_hctx->type != HCTX_TYPE_DEFAULT))
3083		return NULL;
3084	if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
3085		return NULL;
3086	return rq;
3087}
3088
3089static void blk_mq_use_cached_rq(struct request *rq, struct blk_plug *plug,
3090		struct bio *bio)
3091{
3092	if (rq_list_pop(&plug->cached_rqs) != rq)
3093		WARN_ON_ONCE(1);
3094
3095	/*
3096	 * If any qos ->throttle() end up blocking, we will have flushed the
3097	 * plug and hence killed the cached_rq list as well. Pop this entry
3098	 * before we throttle.
3099	 */
3100	rq_qos_throttle(rq->q, bio);
3101
3102	blk_mq_rq_time_init(rq, blk_time_get_ns());
3103	rq->cmd_flags = bio->bi_opf;
3104	INIT_LIST_HEAD(&rq->queuelist);
3105}
3106
3107static bool bio_unaligned(const struct bio *bio, struct request_queue *q)
3108{
3109	unsigned int bs_mask = queue_logical_block_size(q) - 1;
3110
3111	/* .bi_sector of any zero sized bio need to be initialized */
3112	if ((bio->bi_iter.bi_size & bs_mask) ||
3113	    ((bio->bi_iter.bi_sector << SECTOR_SHIFT) & bs_mask))
3114		return true;
3115	return false;
3116}
3117
3118/**
3119 * blk_mq_submit_bio - Create and send a request to block device.
3120 * @bio: Bio pointer.
3121 *
3122 * Builds up a request structure from @q and @bio and send to the device. The
3123 * request may not be queued directly to hardware if:
3124 * * This request can be merged with another one
3125 * * We want to place request at plug queue for possible future merging
3126 * * There is an IO scheduler active at this queue
3127 *
3128 * It will not queue the request if there is an error with the bio, or at the
3129 * request creation.
3130 */
3131void blk_mq_submit_bio(struct bio *bio)
3132{
3133	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
3134	struct blk_plug *plug = current->plug;
3135	const int is_sync = op_is_sync(bio->bi_opf);
3136	struct blk_mq_hw_ctx *hctx;
3137	unsigned int nr_segs;
3138	struct request *rq;
3139	blk_status_t ret;
3140
3141	/*
3142	 * If the plug has a cached request for this queue, try to use it.
3143	 */
3144	rq = blk_mq_peek_cached_request(plug, q, bio->bi_opf);
3145
3146	/*
3147	 * A BIO that was released from a zone write plug has already been
3148	 * through the preparation in this function, already holds a reference
3149	 * on the queue usage counter, and is the only write BIO in-flight for
3150	 * the target zone. Go straight to preparing a request for it.
3151	 */
3152	if (bio_zone_write_plugging(bio)) {
3153		nr_segs = bio->__bi_nr_segments;
3154		if (rq)
3155			blk_queue_exit(q);
3156		goto new_request;
3157	}
3158
3159	/*
3160	 * The cached request already holds a q_usage_counter reference and we
3161	 * don't have to acquire a new one if we use it.
3162	 */
3163	if (!rq) {
3164		if (unlikely(bio_queue_enter(bio)))
3165			return;
3166	}
3167
3168	/*
3169	 * Device reconfiguration may change logical block size or reduce the
3170	 * number of poll queues, so the checks for alignment and poll support
3171	 * have to be done with queue usage counter held.
3172	 */
3173	if (unlikely(bio_unaligned(bio, q))) {
3174		bio_io_error(bio);
3175		goto queue_exit;
3176	}
3177
3178	if ((bio->bi_opf & REQ_POLLED) && !blk_mq_can_poll(q)) {
3179		bio->bi_status = BLK_STS_NOTSUPP;
3180		bio_endio(bio);
3181		goto queue_exit;
3182	}
3183
3184	bio = __bio_split_to_limits(bio, &q->limits, &nr_segs);
3185	if (!bio)
3186		goto queue_exit;
3187
3188	if (!bio_integrity_prep(bio))
3189		goto queue_exit;
3190
3191	blk_mq_bio_issue_init(q, bio);
3192	if (blk_mq_attempt_bio_merge(q, bio, nr_segs))
3193		goto queue_exit;
3194
3195	if (bio_needs_zone_write_plugging(bio)) {
3196		if (blk_zone_plug_bio(bio, nr_segs))
3197			goto queue_exit;
3198	}
3199
3200new_request:
3201	if (rq) {
3202		blk_mq_use_cached_rq(rq, plug, bio);
3203	} else {
3204		rq = blk_mq_get_new_requests(q, plug, bio);
3205		if (unlikely(!rq)) {
3206			if (bio->bi_opf & REQ_NOWAIT)
3207				bio_wouldblock_error(bio);
3208			goto queue_exit;
3209		}
3210	}
3211
3212	trace_block_getrq(bio);
3213
3214	rq_qos_track(q, rq, bio);
3215
3216	blk_mq_bio_to_request(rq, bio, nr_segs);
3217
3218	ret = blk_crypto_rq_get_keyslot(rq);
3219	if (ret != BLK_STS_OK) {
3220		bio->bi_status = ret;
3221		bio_endio(bio);
3222		blk_mq_free_request(rq);
3223		return;
3224	}
3225
3226	if (bio_zone_write_plugging(bio))
3227		blk_zone_write_plug_init_request(rq);
3228
3229	if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
3230		return;
3231
3232	if (plug) {
3233		blk_add_rq_to_plug(plug, rq);
3234		return;
3235	}
3236
3237	hctx = rq->mq_hctx;
3238	if ((rq->rq_flags & RQF_USE_SCHED) ||
3239	    (hctx->dispatch_busy && (q->nr_hw_queues == 1 || !is_sync))) {
3240		blk_mq_insert_request(rq, 0);
3241		blk_mq_run_hw_queue(hctx, true);
3242	} else {
3243		blk_mq_run_dispatch_ops(q, blk_mq_try_issue_directly(hctx, rq));
3244	}
3245	return;
3246
3247queue_exit:
3248	/*
3249	 * Don't drop the queue reference if we were trying to use a cached
3250	 * request and thus didn't acquire one.
3251	 */
3252	if (!rq)
3253		blk_queue_exit(q);
3254}
3255
3256#ifdef CONFIG_BLK_MQ_STACKING
3257/**
3258 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
3259 * @rq: the request being queued
3260 */
3261blk_status_t blk_insert_cloned_request(struct request *rq)
3262{
3263	struct request_queue *q = rq->q;
3264	unsigned int max_sectors = blk_queue_get_max_sectors(rq);
3265	unsigned int max_segments = blk_rq_get_max_segments(rq);
3266	blk_status_t ret;
3267
3268	if (blk_rq_sectors(rq) > max_sectors) {
3269		/*
3270		 * SCSI device does not have a good way to return if
3271		 * Write Same/Zero is actually supported. If a device rejects
3272		 * a non-read/write command (discard, write same,etc.) the
3273		 * low-level device driver will set the relevant queue limit to
3274		 * 0 to prevent blk-lib from issuing more of the offending
3275		 * operations. Commands queued prior to the queue limit being
3276		 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
3277		 * errors being propagated to upper layers.
3278		 */
3279		if (max_sectors == 0)
3280			return BLK_STS_NOTSUPP;
3281
3282		printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
3283			__func__, blk_rq_sectors(rq), max_sectors);
3284		return BLK_STS_IOERR;
3285	}
3286
3287	/*
3288	 * The queue settings related to segment counting may differ from the
3289	 * original queue.
3290	 */
3291	rq->nr_phys_segments = blk_recalc_rq_segments(rq);
3292	if (rq->nr_phys_segments > max_segments) {
3293		printk(KERN_ERR "%s: over max segments limit. (%u > %u)\n",
3294			__func__, rq->nr_phys_segments, max_segments);
3295		return BLK_STS_IOERR;
3296	}
3297
3298	if (q->disk && should_fail_request(q->disk->part0, blk_rq_bytes(rq)))
3299		return BLK_STS_IOERR;
3300
3301	ret = blk_crypto_rq_get_keyslot(rq);
3302	if (ret != BLK_STS_OK)
3303		return ret;
3304
3305	blk_account_io_start(rq);
3306
3307	/*
3308	 * Since we have a scheduler attached on the top device,
3309	 * bypass a potential scheduler on the bottom device for
3310	 * insert.
3311	 */
3312	blk_mq_run_dispatch_ops(q,
3313			ret = blk_mq_request_issue_directly(rq, true));
3314	if (ret)
3315		blk_account_io_done(rq, blk_time_get_ns());
3316	return ret;
3317}
3318EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
3319
3320/**
3321 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3322 * @rq: the clone request to be cleaned up
3323 *
3324 * Description:
3325 *     Free all bios in @rq for a cloned request.
3326 */
3327void blk_rq_unprep_clone(struct request *rq)
3328{
3329	struct bio *bio;
3330
3331	while ((bio = rq->bio) != NULL) {
3332		rq->bio = bio->bi_next;
3333
3334		bio_put(bio);
3335	}
3336}
3337EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3338
3339/**
3340 * blk_rq_prep_clone - Helper function to setup clone request
3341 * @rq: the request to be setup
3342 * @rq_src: original request to be cloned
3343 * @bs: bio_set that bios for clone are allocated from
3344 * @gfp_mask: memory allocation mask for bio
3345 * @bio_ctr: setup function to be called for each clone bio.
3346 *           Returns %0 for success, non %0 for failure.
3347 * @data: private data to be passed to @bio_ctr
3348 *
3349 * Description:
3350 *     Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3351 *     Also, pages which the original bios are pointing to are not copied
3352 *     and the cloned bios just point same pages.
3353 *     So cloned bios must be completed before original bios, which means
3354 *     the caller must complete @rq before @rq_src.
3355 */
3356int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3357		      struct bio_set *bs, gfp_t gfp_mask,
3358		      int (*bio_ctr)(struct bio *, struct bio *, void *),
3359		      void *data)
3360{
3361	struct bio *bio_src;
3362
3363	if (!bs)
3364		bs = &fs_bio_set;
3365
3366	__rq_for_each_bio(bio_src, rq_src) {
3367		struct bio *bio	 = bio_alloc_clone(rq->q->disk->part0, bio_src,
3368					gfp_mask, bs);
3369		if (!bio)
3370			goto free_and_out;
3371
3372		if (bio_ctr && bio_ctr(bio, bio_src, data)) {
3373			bio_put(bio);
3374			goto free_and_out;
3375		}
3376
3377		if (rq->bio) {
3378			rq->biotail->bi_next = bio;
3379			rq->biotail = bio;
3380		} else {
3381			rq->bio = rq->biotail = bio;
3382		}
3383	}
3384
3385	/* Copy attributes of the original request to the clone request. */
3386	rq->__sector = blk_rq_pos(rq_src);
3387	rq->__data_len = blk_rq_bytes(rq_src);
3388	if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
3389		rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
3390		rq->special_vec = rq_src->special_vec;
3391	}
3392	rq->nr_phys_segments = rq_src->nr_phys_segments;
3393	rq->nr_integrity_segments = rq_src->nr_integrity_segments;
3394	rq->phys_gap_bit = rq_src->phys_gap_bit;
3395
3396	if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
3397		goto free_and_out;
3398
3399	return 0;
3400
3401free_and_out:
3402	blk_rq_unprep_clone(rq);
3403
3404	return -ENOMEM;
3405}
3406EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3407#endif /* CONFIG_BLK_MQ_STACKING */
3408
3409/*
3410 * Steal bios from a request and add them to a bio list.
3411 * The request must not have been partially completed before.
3412 */
3413void blk_steal_bios(struct bio_list *list, struct request *rq)
3414{
3415	if (rq->bio) {
3416		if (list->tail)
3417			list->tail->bi_next = rq->bio;
3418		else
3419			list->head = rq->bio;
3420		list->tail = rq->biotail;
3421
3422		rq->bio = NULL;
3423		rq->biotail = NULL;
3424	}
3425
3426	rq->__data_len = 0;
3427}
3428EXPORT_SYMBOL_GPL(blk_steal_bios);
3429
3430static size_t order_to_size(unsigned int order)
3431{
3432	return (size_t)PAGE_SIZE << order;
3433}
3434
3435/* called before freeing request pool in @tags */
3436static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3437				    struct blk_mq_tags *tags)
3438{
3439	struct page *page;
3440
3441	/*
3442	 * There is no need to clear mapping if driver tags is not initialized
3443	 * or the mapping belongs to the driver tags.
3444	 */
3445	if (!drv_tags || drv_tags == tags)
3446		return;
3447
3448	list_for_each_entry(page, &tags->page_list, lru) {
3449		unsigned long start = (unsigned long)page_address(page);
3450		unsigned long end = start + order_to_size(page->private);
3451		int i;
3452
3453		for (i = 0; i < drv_tags->nr_tags; i++) {
3454			struct request *rq = drv_tags->rqs[i];
3455			unsigned long rq_addr = (unsigned long)rq;
3456
3457			if (rq_addr >= start && rq_addr < end) {
3458				WARN_ON_ONCE(req_ref_read(rq) != 0);
3459				cmpxchg(&drv_tags->rqs[i], rq, NULL);
3460			}
3461		}
3462	}
3463}
3464
3465void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3466		     unsigned int hctx_idx)
3467{
3468	struct blk_mq_tags *drv_tags;
3469
3470	if (list_empty(&tags->page_list))
3471		return;
3472
3473	if (blk_mq_is_shared_tags(set->flags))
3474		drv_tags = set->shared_tags;
3475	else
3476		drv_tags = set->tags[hctx_idx];
3477
3478	if (tags->static_rqs && set->ops->exit_request) {
3479		int i;
3480
3481		for (i = 0; i < tags->nr_tags; i++) {
3482			struct request *rq = tags->static_rqs[i];
3483
3484			if (!rq)
3485				continue;
3486			set->ops->exit_request(set, rq, hctx_idx);
3487			tags->static_rqs[i] = NULL;
3488		}
3489	}
3490
3491	blk_mq_clear_rq_mapping(drv_tags, tags);
3492	/*
3493	 * Free request pages in SRCU callback, which is called from
3494	 * blk_mq_free_tags().
3495	 */
3496}
3497
3498void blk_mq_free_rq_map(struct blk_mq_tag_set *set, struct blk_mq_tags *tags)
3499{
3500	kfree(tags->rqs);
3501	tags->rqs = NULL;
3502	kfree(tags->static_rqs);
3503	tags->static_rqs = NULL;
3504
3505	blk_mq_free_tags(set, tags);
3506}
3507
3508static enum hctx_type hctx_idx_to_type(struct blk_mq_tag_set *set,
3509		unsigned int hctx_idx)
3510{
3511	int i;
3512
3513	for (i = 0; i < set->nr_maps; i++) {
3514		unsigned int start = set->map[i].queue_offset;
3515		unsigned int end = start + set->map[i].nr_queues;
3516
3517		if (hctx_idx >= start && hctx_idx < end)
3518			break;
3519	}
3520
3521	if (i >= set->nr_maps)
3522		i = HCTX_TYPE_DEFAULT;
3523
3524	return i;
3525}
3526
3527static int blk_mq_get_hctx_node(struct blk_mq_tag_set *set,
3528		unsigned int hctx_idx)
3529{
3530	enum hctx_type type = hctx_idx_to_type(set, hctx_idx);
3531
3532	return blk_mq_hw_queue_to_node(&set->map[type], hctx_idx);
3533}
3534
3535static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3536					       unsigned int hctx_idx,
3537					       unsigned int nr_tags,
3538					       unsigned int reserved_tags)
3539{
3540	int node = blk_mq_get_hctx_node(set, hctx_idx);
3541	struct blk_mq_tags *tags;
3542
3543	if (node == NUMA_NO_NODE)
3544		node = set->numa_node;
3545
3546	tags = blk_mq_init_tags(nr_tags, reserved_tags, set->flags, node);
3547	if (!tags)
3548		return NULL;
3549
3550	tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3551				 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3552				 node);
3553	if (!tags->rqs)
3554		goto err_free_tags;
3555
3556	tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3557					GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3558					node);
3559	if (!tags->static_rqs)
3560		goto err_free_rqs;
3561
3562	return tags;
3563
3564err_free_rqs:
3565	kfree(tags->rqs);
3566err_free_tags:
3567	blk_mq_free_tags(set, tags);
3568	return NULL;
3569}
3570
3571static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3572			       unsigned int hctx_idx, int node)
3573{
3574	int ret;
3575
3576	if (set->ops->init_request) {
3577		ret = set->ops->init_request(set, rq, hctx_idx, node);
3578		if (ret)
3579			return ret;
3580	}
3581
3582	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3583	return 0;
3584}
3585
3586static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3587			    struct blk_mq_tags *tags,
3588			    unsigned int hctx_idx, unsigned int depth)
3589{
3590	unsigned int i, j, entries_per_page, max_order = 4;
3591	int node = blk_mq_get_hctx_node(set, hctx_idx);
3592	size_t rq_size, left;
3593
3594	if (node == NUMA_NO_NODE)
3595		node = set->numa_node;
3596
3597	/*
3598	 * rq_size is the size of the request plus driver payload, rounded
3599	 * to the cacheline size
3600	 */
3601	rq_size = round_up(sizeof(struct request) + set->cmd_size,
3602				cache_line_size());
3603	left = rq_size * depth;
3604
3605	for (i = 0; i < depth; ) {
3606		int this_order = max_order;
3607		struct page *page;
3608		int to_do;
3609		void *p;
3610
3611		while (this_order && left < order_to_size(this_order - 1))
3612			this_order--;
3613
3614		do {
3615			page = alloc_pages_node(node,
3616				GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3617				this_order);
3618			if (page)
3619				break;
3620			if (!this_order--)
3621				break;
3622			if (order_to_size(this_order) < rq_size)
3623				break;
3624		} while (1);
3625
3626		if (!page)
3627			goto fail;
3628
3629		page->private = this_order;
3630		list_add_tail(&page->lru, &tags->page_list);
3631
3632		p = page_address(page);
3633		/*
3634		 * Allow kmemleak to scan these pages as they contain pointers
3635		 * to additional allocations like via ops->init_request().
3636		 */
3637		kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3638		entries_per_page = order_to_size(this_order) / rq_size;
3639		to_do = min(entries_per_page, depth - i);
3640		left -= to_do * rq_size;
3641		for (j = 0; j < to_do; j++) {
3642			struct request *rq = p;
3643
3644			tags->static_rqs[i] = rq;
3645			if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3646				tags->static_rqs[i] = NULL;
3647				goto fail;
3648			}
3649
3650			p += rq_size;
3651			i++;
3652		}
3653	}
3654	return 0;
3655
3656fail:
3657	blk_mq_free_rqs(set, tags, hctx_idx);
3658	return -ENOMEM;
3659}
3660
3661struct rq_iter_data {
3662	struct blk_mq_hw_ctx *hctx;
3663	bool has_rq;
3664};
3665
3666static bool blk_mq_has_request(struct request *rq, void *data)
3667{
3668	struct rq_iter_data *iter_data = data;
3669
3670	if (rq->mq_hctx != iter_data->hctx)
3671		return true;
3672	iter_data->has_rq = true;
3673	return false;
3674}
3675
3676static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3677{
3678	struct blk_mq_tags *tags = hctx->sched_tags ?
3679			hctx->sched_tags : hctx->tags;
3680	struct rq_iter_data data = {
3681		.hctx	= hctx,
3682	};
3683	int srcu_idx;
3684
3685	srcu_idx = srcu_read_lock(&hctx->queue->tag_set->tags_srcu);
3686	blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3687	srcu_read_unlock(&hctx->queue->tag_set->tags_srcu, srcu_idx);
3688
3689	return data.has_rq;
3690}
3691
3692static bool blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx *hctx,
3693		unsigned int this_cpu)
3694{
3695	enum hctx_type type = hctx->type;
3696	int cpu;
3697
3698	/*
3699	 * hctx->cpumask has to rule out isolated CPUs, but userspace still
3700	 * might submit IOs on these isolated CPUs, so use the queue map to
3701	 * check if all CPUs mapped to this hctx are offline
3702	 */
3703	for_each_online_cpu(cpu) {
3704		struct blk_mq_hw_ctx *h = blk_mq_map_queue_type(hctx->queue,
3705				type, cpu);
3706
3707		if (h != hctx)
3708			continue;
3709
3710		/* this hctx has at least one online CPU */
3711		if (this_cpu != cpu)
3712			return true;
3713	}
3714
3715	return false;
3716}
3717
3718static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3719{
3720	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3721			struct blk_mq_hw_ctx, cpuhp_online);
3722	int ret = 0;
3723
3724	if (!hctx->nr_ctx || blk_mq_hctx_has_online_cpu(hctx, cpu))
3725		return 0;
3726
3727	/*
3728	 * Prevent new request from being allocated on the current hctx.
3729	 *
3730	 * The smp_mb__after_atomic() Pairs with the implied barrier in
3731	 * test_and_set_bit_lock in sbitmap_get().  Ensures the inactive flag is
3732	 * seen once we return from the tag allocator.
3733	 */
3734	set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3735	smp_mb__after_atomic();
3736
3737	/*
3738	 * Try to grab a reference to the queue and wait for any outstanding
3739	 * requests.  If we could not grab a reference the queue has been
3740	 * frozen and there are no requests.
3741	 */
3742	if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3743		while (blk_mq_hctx_has_requests(hctx)) {
3744			/*
3745			 * The wakeup capable IRQ handler of block device is
3746			 * not called during suspend. Skip the loop by checking
3747			 * pm_wakeup_pending to prevent the deadlock and improve
3748			 * suspend latency.
3749			 */
3750			if (pm_wakeup_pending()) {
3751				clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3752				ret = -EBUSY;
3753				break;
3754			}
3755			msleep(5);
3756		}
3757		percpu_ref_put(&hctx->queue->q_usage_counter);
3758	}
3759
3760	return ret;
3761}
3762
3763/*
3764 * Check if one CPU is mapped to the specified hctx
3765 *
3766 * Isolated CPUs have been ruled out from hctx->cpumask, which is supposed
3767 * to be used for scheduling kworker only. For other usage, please call this
3768 * helper for checking if one CPU belongs to the specified hctx
3769 */
3770static bool blk_mq_cpu_mapped_to_hctx(unsigned int cpu,
3771		const struct blk_mq_hw_ctx *hctx)
3772{
3773	struct blk_mq_hw_ctx *mapped_hctx = blk_mq_map_queue_type(hctx->queue,
3774			hctx->type, cpu);
3775
3776	return mapped_hctx == hctx;
3777}
3778
3779static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3780{
3781	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3782			struct blk_mq_hw_ctx, cpuhp_online);
3783
3784	if (blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3785		clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3786	return 0;
3787}
3788
3789/*
3790 * 'cpu' is going away. splice any existing rq_list entries from this
3791 * software queue to the hw queue dispatch list, and ensure that it
3792 * gets run.
3793 */
3794static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3795{
3796	struct blk_mq_hw_ctx *hctx;
3797	struct blk_mq_ctx *ctx;
3798	LIST_HEAD(tmp);
3799	enum hctx_type type;
3800
3801	hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3802	if (!blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3803		return 0;
3804
3805	ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3806	type = hctx->type;
3807
3808	spin_lock(&ctx->lock);
3809	if (!list_empty(&ctx->rq_lists[type])) {
3810		list_splice_init(&ctx->rq_lists[type], &tmp);
3811		blk_mq_hctx_clear_pending(hctx, ctx);
3812	}
3813	spin_unlock(&ctx->lock);
3814
3815	if (list_empty(&tmp))
3816		return 0;
3817
3818	spin_lock(&hctx->lock);
3819	list_splice_tail_init(&tmp, &hctx->dispatch);
3820	spin_unlock(&hctx->lock);
3821
3822	blk_mq_run_hw_queue(hctx, true);
3823	return 0;
3824}
3825
3826static void __blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3827{
3828	lockdep_assert_held(&blk_mq_cpuhp_lock);
3829
3830	if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3831	    !hlist_unhashed(&hctx->cpuhp_online)) {
3832		cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3833						    &hctx->cpuhp_online);
3834		INIT_HLIST_NODE(&hctx->cpuhp_online);
3835	}
3836
3837	if (!hlist_unhashed(&hctx->cpuhp_dead)) {
3838		cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3839						    &hctx->cpuhp_dead);
3840		INIT_HLIST_NODE(&hctx->cpuhp_dead);
3841	}
3842}
3843
3844static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3845{
3846	mutex_lock(&blk_mq_cpuhp_lock);
3847	__blk_mq_remove_cpuhp(hctx);
3848	mutex_unlock(&blk_mq_cpuhp_lock);
3849}
3850
3851static void __blk_mq_add_cpuhp(struct blk_mq_hw_ctx *hctx)
3852{
3853	lockdep_assert_held(&blk_mq_cpuhp_lock);
3854
3855	if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3856	    hlist_unhashed(&hctx->cpuhp_online))
3857		cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3858				&hctx->cpuhp_online);
3859
3860	if (hlist_unhashed(&hctx->cpuhp_dead))
3861		cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3862				&hctx->cpuhp_dead);
3863}
3864
3865static void __blk_mq_remove_cpuhp_list(struct list_head *head)
3866{
3867	struct blk_mq_hw_ctx *hctx;
3868
3869	lockdep_assert_held(&blk_mq_cpuhp_lock);
3870
3871	list_for_each_entry(hctx, head, hctx_list)
3872		__blk_mq_remove_cpuhp(hctx);
3873}
3874
3875/*
3876 * Unregister cpuhp callbacks from exited hw queues
3877 *
3878 * Safe to call if this `request_queue` is live
3879 */
3880static void blk_mq_remove_hw_queues_cpuhp(struct request_queue *q)
3881{
3882	LIST_HEAD(hctx_list);
3883
3884	spin_lock(&q->unused_hctx_lock);
3885	list_splice_init(&q->unused_hctx_list, &hctx_list);
3886	spin_unlock(&q->unused_hctx_lock);
3887
3888	mutex_lock(&blk_mq_cpuhp_lock);
3889	__blk_mq_remove_cpuhp_list(&hctx_list);
3890	mutex_unlock(&blk_mq_cpuhp_lock);
3891
3892	spin_lock(&q->unused_hctx_lock);
3893	list_splice(&hctx_list, &q->unused_hctx_list);
3894	spin_unlock(&q->unused_hctx_lock);
3895}
3896
3897/*
3898 * Register cpuhp callbacks from all hw queues
3899 *
3900 * Safe to call if this `request_queue` is live
3901 */
3902static void blk_mq_add_hw_queues_cpuhp(struct request_queue *q)
3903{
3904	struct blk_mq_hw_ctx *hctx;
3905	unsigned long i;
3906
3907	mutex_lock(&blk_mq_cpuhp_lock);
3908	queue_for_each_hw_ctx(q, hctx, i)
3909		__blk_mq_add_cpuhp(hctx);
3910	mutex_unlock(&blk_mq_cpuhp_lock);
3911}
3912
3913/*
3914 * Before freeing hw queue, clearing the flush request reference in
3915 * tags->rqs[] for avoiding potential UAF.
3916 */
3917static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3918		unsigned int queue_depth, struct request *flush_rq)
3919{
3920	int i;
3921
3922	/* The hw queue may not be mapped yet */
3923	if (!tags)
3924		return;
3925
3926	WARN_ON_ONCE(req_ref_read(flush_rq) != 0);
3927
3928	for (i = 0; i < queue_depth; i++)
3929		cmpxchg(&tags->rqs[i], flush_rq, NULL);
3930}
3931
3932static void blk_free_flush_queue_callback(struct rcu_head *head)
3933{
3934	struct blk_flush_queue *fq =
3935		container_of(head, struct blk_flush_queue, rcu_head);
3936
3937	blk_free_flush_queue(fq);
3938}
3939
3940/* hctx->ctxs will be freed in queue's release handler */
3941static void blk_mq_exit_hctx(struct request_queue *q,
3942		struct blk_mq_tag_set *set,
3943		struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3944{
3945	struct request *flush_rq = hctx->fq->flush_rq;
3946
3947	if (blk_mq_hw_queue_mapped(hctx))
3948		blk_mq_tag_idle(hctx);
3949
3950	if (blk_queue_init_done(q))
3951		blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3952				set->queue_depth, flush_rq);
3953	if (set->ops->exit_request)
3954		set->ops->exit_request(set, flush_rq, hctx_idx);
3955
3956	if (set->ops->exit_hctx)
3957		set->ops->exit_hctx(hctx, hctx_idx);
3958
3959	call_srcu(&set->tags_srcu, &hctx->fq->rcu_head,
3960			blk_free_flush_queue_callback);
3961	hctx->fq = NULL;
3962
3963	spin_lock(&q->unused_hctx_lock);
3964	list_add(&hctx->hctx_list, &q->unused_hctx_list);
3965	spin_unlock(&q->unused_hctx_lock);
3966}
3967
3968static void blk_mq_exit_hw_queues(struct request_queue *q,
3969		struct blk_mq_tag_set *set, int nr_queue)
3970{
3971	struct blk_mq_hw_ctx *hctx;
3972	unsigned long i;
3973
3974	queue_for_each_hw_ctx(q, hctx, i) {
3975		if (i == nr_queue)
3976			break;
3977		blk_mq_remove_cpuhp(hctx);
3978		blk_mq_exit_hctx(q, set, hctx, i);
3979	}
3980}
3981
3982static int blk_mq_init_hctx(struct request_queue *q,
3983		struct blk_mq_tag_set *set,
3984		struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3985{
3986	gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3987
3988	hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
3989	if (!hctx->fq)
3990		goto fail;
3991
3992	hctx->queue_num = hctx_idx;
3993
3994	hctx->tags = set->tags[hctx_idx];
3995
3996	if (set->ops->init_hctx &&
3997	    set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3998		goto fail_free_fq;
3999
4000	if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
4001				hctx->numa_node))
4002		goto exit_hctx;
4003
4004	return 0;
4005
4006 exit_hctx:
4007	if (set->ops->exit_hctx)
4008		set->ops->exit_hctx(hctx, hctx_idx);
4009 fail_free_fq:
4010	blk_free_flush_queue(hctx->fq);
4011	hctx->fq = NULL;
4012 fail:
4013	return -1;
4014}
4015
4016static struct blk_mq_hw_ctx *
4017blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
4018		int node)
4019{
4020	struct blk_mq_hw_ctx *hctx;
4021	gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
4022
4023	hctx = kzalloc_node(sizeof(struct blk_mq_hw_ctx), gfp, node);
4024	if (!hctx)
4025		goto fail_alloc_hctx;
4026
4027	if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
4028		goto free_hctx;
4029
4030	atomic_set(&hctx->nr_active, 0);
4031	if (node == NUMA_NO_NODE)
4032		node = set->numa_node;
4033	hctx->numa_node = node;
4034
4035	INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
4036	spin_lock_init(&hctx->lock);
4037	INIT_LIST_HEAD(&hctx->dispatch);
4038	INIT_HLIST_NODE(&hctx->cpuhp_dead);
4039	INIT_HLIST_NODE(&hctx->cpuhp_online);
4040	hctx->queue = q;
4041	hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
4042
4043	INIT_LIST_HEAD(&hctx->hctx_list);
4044
4045	/*
4046	 * Allocate space for all possible cpus to avoid allocation at
4047	 * runtime
4048	 */
4049	hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
4050			gfp, node);
4051	if (!hctx->ctxs)
4052		goto free_cpumask;
4053
4054	if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
4055				gfp, node, false, false))
4056		goto free_ctxs;
4057	hctx->nr_ctx = 0;
4058
4059	spin_lock_init(&hctx->dispatch_wait_lock);
4060	init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
4061	INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
4062
4063	blk_mq_hctx_kobj_init(hctx);
4064
4065	return hctx;
4066
4067 free_ctxs:
4068	kfree(hctx->ctxs);
4069 free_cpumask:
4070	free_cpumask_var(hctx->cpumask);
4071 free_hctx:
4072	kfree(hctx);
4073 fail_alloc_hctx:
4074	return NULL;
4075}
4076
4077static void blk_mq_init_cpu_queues(struct request_queue *q,
4078				   unsigned int nr_hw_queues)
4079{
4080	struct blk_mq_tag_set *set = q->tag_set;
4081	unsigned int i, j;
4082
4083	for_each_possible_cpu(i) {
4084		struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
4085		struct blk_mq_hw_ctx *hctx;
4086		int k;
4087
4088		__ctx->cpu = i;
4089		spin_lock_init(&__ctx->lock);
4090		for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
4091			INIT_LIST_HEAD(&__ctx->rq_lists[k]);
4092
4093		__ctx->queue = q;
4094
4095		/*
4096		 * Set local node, IFF we have more than one hw queue. If
4097		 * not, we remain on the home node of the device
4098		 */
4099		for (j = 0; j < set->nr_maps; j++) {
4100			hctx = blk_mq_map_queue_type(q, j, i);
4101			if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
4102				hctx->numa_node = cpu_to_node(i);
4103		}
4104	}
4105}
4106
4107struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4108					     unsigned int hctx_idx,
4109					     unsigned int depth)
4110{
4111	struct blk_mq_tags *tags;
4112	int ret;
4113
4114	tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
4115	if (!tags)
4116		return NULL;
4117
4118	ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
4119	if (ret) {
4120		blk_mq_free_rq_map(set, tags);
4121		return NULL;
4122	}
4123
4124	return tags;
4125}
4126
4127static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4128				       int hctx_idx)
4129{
4130	if (blk_mq_is_shared_tags(set->flags)) {
4131		set->tags[hctx_idx] = set->shared_tags;
4132
4133		return true;
4134	}
4135
4136	set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
4137						       set->queue_depth);
4138
4139	return set->tags[hctx_idx];
4140}
4141
4142void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4143			     struct blk_mq_tags *tags,
4144			     unsigned int hctx_idx)
4145{
4146	if (tags) {
4147		blk_mq_free_rqs(set, tags, hctx_idx);
4148		blk_mq_free_rq_map(set, tags);
4149	}
4150}
4151
4152static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4153				      unsigned int hctx_idx)
4154{
4155	if (!blk_mq_is_shared_tags(set->flags))
4156		blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
4157
4158	set->tags[hctx_idx] = NULL;
4159}
4160
4161static void blk_mq_map_swqueue(struct request_queue *q)
4162{
4163	unsigned int j, hctx_idx;
4164	unsigned long i;
4165	struct blk_mq_hw_ctx *hctx;
4166	struct blk_mq_ctx *ctx;
4167	struct blk_mq_tag_set *set = q->tag_set;
4168
4169	queue_for_each_hw_ctx(q, hctx, i) {
4170		cpumask_clear(hctx->cpumask);
4171		hctx->nr_ctx = 0;
4172		hctx->dispatch_from = NULL;
4173	}
4174
4175	/*
4176	 * Map software to hardware queues.
4177	 *
4178	 * If the cpu isn't present, the cpu is mapped to first hctx.
4179	 */
4180	for_each_possible_cpu(i) {
4181
4182		ctx = per_cpu_ptr(q->queue_ctx, i);
4183		for (j = 0; j < set->nr_maps; j++) {
4184			if (!set->map[j].nr_queues) {
4185				ctx->hctxs[j] = blk_mq_map_queue_type(q,
4186						HCTX_TYPE_DEFAULT, i);
4187				continue;
4188			}
4189			hctx_idx = set->map[j].mq_map[i];
4190			/* unmapped hw queue can be remapped after CPU topo changed */
4191			if (!set->tags[hctx_idx] &&
4192			    !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4193				/*
4194				 * If tags initialization fail for some hctx,
4195				 * that hctx won't be brought online.  In this
4196				 * case, remap the current ctx to hctx[0] which
4197				 * is guaranteed to always have tags allocated
4198				 */
4199				set->map[j].mq_map[i] = 0;
4200			}
4201
4202			hctx = blk_mq_map_queue_type(q, j, i);
4203			ctx->hctxs[j] = hctx;
4204			/*
4205			 * If the CPU is already set in the mask, then we've
4206			 * mapped this one already. This can happen if
4207			 * devices share queues across queue maps.
4208			 */
4209			if (cpumask_test_cpu(i, hctx->cpumask))
4210				continue;
4211
4212			cpumask_set_cpu(i, hctx->cpumask);
4213			hctx->type = j;
4214			ctx->index_hw[hctx->type] = hctx->nr_ctx;
4215			hctx->ctxs[hctx->nr_ctx++] = ctx;
4216
4217			/*
4218			 * If the nr_ctx type overflows, we have exceeded the
4219			 * amount of sw queues we can support.
4220			 */
4221			BUG_ON(!hctx->nr_ctx);
4222		}
4223
4224		for (; j < HCTX_MAX_TYPES; j++)
4225			ctx->hctxs[j] = blk_mq_map_queue_type(q,
4226					HCTX_TYPE_DEFAULT, i);
4227	}
4228
4229	queue_for_each_hw_ctx(q, hctx, i) {
4230		int cpu;
4231
4232		/*
4233		 * If no software queues are mapped to this hardware queue,
4234		 * disable it and free the request entries.
4235		 */
4236		if (!hctx->nr_ctx) {
4237			/* Never unmap queue 0.  We need it as a
4238			 * fallback in case of a new remap fails
4239			 * allocation
4240			 */
4241			if (i)
4242				__blk_mq_free_map_and_rqs(set, i);
4243
4244			hctx->tags = NULL;
4245			continue;
4246		}
4247
4248		hctx->tags = set->tags[i];
4249		WARN_ON(!hctx->tags);
4250
4251		/*
4252		 * Set the map size to the number of mapped software queues.
4253		 * This is more accurate and more efficient than looping
4254		 * over all possibly mapped software queues.
4255		 */
4256		sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4257
4258		/*
4259		 * Rule out isolated CPUs from hctx->cpumask to avoid
4260		 * running block kworker on isolated CPUs
4261		 */
4262		for_each_cpu(cpu, hctx->cpumask) {
4263			if (cpu_is_isolated(cpu))
4264				cpumask_clear_cpu(cpu, hctx->cpumask);
4265		}
4266
4267		/*
4268		 * Initialize batch roundrobin counts
4269		 */
4270		hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4271		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4272	}
4273}
4274
4275/*
4276 * Caller needs to ensure that we're either frozen/quiesced, or that
4277 * the queue isn't live yet.
4278 */
4279static void queue_set_hctx_shared(struct request_queue *q, bool shared)
4280{
4281	struct blk_mq_hw_ctx *hctx;
4282	unsigned long i;
4283
4284	queue_for_each_hw_ctx(q, hctx, i) {
4285		if (shared) {
4286			hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4287		} else {
4288			blk_mq_tag_idle(hctx);
4289			hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4290		}
4291	}
4292}
4293
4294static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
4295					 bool shared)
4296{
4297	struct request_queue *q;
4298	unsigned int memflags;
4299
4300	lockdep_assert_held(&set->tag_list_lock);
4301
4302	list_for_each_entry(q, &set->tag_list, tag_set_list) {
4303		memflags = blk_mq_freeze_queue(q);
4304		queue_set_hctx_shared(q, shared);
4305		blk_mq_unfreeze_queue(q, memflags);
4306	}
4307}
4308
4309static void blk_mq_del_queue_tag_set(struct request_queue *q)
4310{
4311	struct blk_mq_tag_set *set = q->tag_set;
4312
4313	mutex_lock(&set->tag_list_lock);
4314	list_del_rcu(&q->tag_set_list);
4315	if (list_is_singular(&set->tag_list)) {
4316		/* just transitioned to unshared */
4317		set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4318		/* update existing queue */
4319		blk_mq_update_tag_set_shared(set, false);
4320	}
4321	mutex_unlock(&set->tag_list_lock);
4322}
4323
4324static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4325				     struct request_queue *q)
4326{
4327	mutex_lock(&set->tag_list_lock);
4328
4329	/*
4330	 * Check to see if we're transitioning to shared (from 1 to 2 queues).
4331	 */
4332	if (!list_empty(&set->tag_list) &&
4333	    !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4334		set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4335		/* update existing queue */
4336		blk_mq_update_tag_set_shared(set, true);
4337	}
4338	if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4339		queue_set_hctx_shared(q, true);
4340	list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
4341
4342	mutex_unlock(&set->tag_list_lock);
4343}
4344
4345/* All allocations will be freed in release handler of q->mq_kobj */
4346static int blk_mq_alloc_ctxs(struct request_queue *q)
4347{
4348	struct blk_mq_ctxs *ctxs;
4349	int cpu;
4350
4351	ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
4352	if (!ctxs)
4353		return -ENOMEM;
4354
4355	ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
4356	if (!ctxs->queue_ctx)
4357		goto fail;
4358
4359	for_each_possible_cpu(cpu) {
4360		struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
4361		ctx->ctxs = ctxs;
4362	}
4363
4364	q->mq_kobj = &ctxs->kobj;
4365	q->queue_ctx = ctxs->queue_ctx;
4366
4367	return 0;
4368 fail:
4369	kfree(ctxs);
4370	return -ENOMEM;
4371}
4372
4373/*
4374 * It is the actual release handler for mq, but we do it from
4375 * request queue's release handler for avoiding use-after-free
4376 * and headache because q->mq_kobj shouldn't have been introduced,
4377 * but we can't group ctx/kctx kobj without it.
4378 */
4379void blk_mq_release(struct request_queue *q)
4380{
4381	struct blk_mq_hw_ctx *hctx, *next;
4382	unsigned long i;
4383
4384	queue_for_each_hw_ctx(q, hctx, i)
4385		WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
4386
4387	/* all hctx are in .unused_hctx_list now */
4388	list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
4389		list_del_init(&hctx->hctx_list);
4390		kobject_put(&hctx->kobj);
4391	}
4392
4393	kfree(q->queue_hw_ctx);
4394
4395	/*
4396	 * release .mq_kobj and sw queue's kobject now because
4397	 * both share lifetime with request queue.
4398	 */
4399	blk_mq_sysfs_deinit(q);
4400}
4401
4402struct request_queue *blk_mq_alloc_queue(struct blk_mq_tag_set *set,
4403		struct queue_limits *lim, void *queuedata)
4404{
4405	struct queue_limits default_lim = { };
4406	struct request_queue *q;
4407	int ret;
4408
4409	if (!lim)
4410		lim = &default_lim;
4411	lim->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT;
4412	if (set->nr_maps > HCTX_TYPE_POLL)
4413		lim->features |= BLK_FEAT_POLL;
4414
4415	q = blk_alloc_queue(lim, set->numa_node);
4416	if (IS_ERR(q))
4417		return q;
4418	q->queuedata = queuedata;
4419	ret = blk_mq_init_allocated_queue(set, q);
4420	if (ret) {
4421		blk_put_queue(q);
4422		return ERR_PTR(ret);
4423	}
4424	return q;
4425}
4426EXPORT_SYMBOL(blk_mq_alloc_queue);
4427
4428/**
4429 * blk_mq_destroy_queue - shutdown a request queue
4430 * @q: request queue to shutdown
4431 *
4432 * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4433 * requests will be failed with -ENODEV. The caller is responsible for dropping
4434 * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4435 *
4436 * Context: can sleep
4437 */
4438void blk_mq_destroy_queue(struct request_queue *q)
4439{
4440	WARN_ON_ONCE(!queue_is_mq(q));
4441	WARN_ON_ONCE(blk_queue_registered(q));
4442
4443	might_sleep();
4444
4445	blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4446	blk_queue_start_drain(q);
4447	blk_mq_freeze_queue_wait(q);
4448
4449	blk_sync_queue(q);
4450	blk_mq_cancel_work_sync(q);
4451	blk_mq_exit_queue(q);
4452}
4453EXPORT_SYMBOL(blk_mq_destroy_queue);
4454
4455struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4456		struct queue_limits *lim, void *queuedata,
4457		struct lock_class_key *lkclass)
4458{
4459	struct request_queue *q;
4460	struct gendisk *disk;
4461
4462	q = blk_mq_alloc_queue(set, lim, queuedata);
4463	if (IS_ERR(q))
4464		return ERR_CAST(q);
4465
4466	disk = __alloc_disk_node(q, set->numa_node, lkclass);
4467	if (!disk) {
4468		blk_mq_destroy_queue(q);
4469		blk_put_queue(q);
4470		return ERR_PTR(-ENOMEM);
4471	}
4472	set_bit(GD_OWNS_QUEUE, &disk->state);
4473	return disk;
4474}
4475EXPORT_SYMBOL(__blk_mq_alloc_disk);
4476
4477struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
4478		struct lock_class_key *lkclass)
4479{
4480	struct gendisk *disk;
4481
4482	if (!blk_get_queue(q))
4483		return NULL;
4484	disk = __alloc_disk_node(q, NUMA_NO_NODE, lkclass);
4485	if (!disk)
4486		blk_put_queue(q);
4487	return disk;
4488}
4489EXPORT_SYMBOL(blk_mq_alloc_disk_for_queue);
4490
4491/*
4492 * Only hctx removed from cpuhp list can be reused
4493 */
4494static bool blk_mq_hctx_is_reusable(struct blk_mq_hw_ctx *hctx)
4495{
4496	return hlist_unhashed(&hctx->cpuhp_online) &&
4497		hlist_unhashed(&hctx->cpuhp_dead);
4498}
4499
4500static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
4501		struct blk_mq_tag_set *set, struct request_queue *q,
4502		int hctx_idx, int node)
4503{
4504	struct blk_mq_hw_ctx *hctx = NULL, *tmp;
4505
4506	/* reuse dead hctx first */
4507	spin_lock(&q->unused_hctx_lock);
4508	list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
4509		if (tmp->numa_node == node && blk_mq_hctx_is_reusable(tmp)) {
4510			hctx = tmp;
4511			break;
4512		}
4513	}
4514	if (hctx)
4515		list_del_init(&hctx->hctx_list);
4516	spin_unlock(&q->unused_hctx_lock);
4517
4518	if (!hctx)
4519		hctx = blk_mq_alloc_hctx(q, set, node);
4520	if (!hctx)
4521		goto fail;
4522
4523	if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
4524		goto free_hctx;
4525
4526	return hctx;
4527
4528 free_hctx:
4529	kobject_put(&hctx->kobj);
4530 fail:
4531	return NULL;
4532}
4533
4534static void __blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4535				     struct request_queue *q)
4536{
4537	int i, j, end;
4538	struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
4539
4540	if (q->nr_hw_queues < set->nr_hw_queues) {
4541		struct blk_mq_hw_ctx **new_hctxs;
4542
4543		new_hctxs = kcalloc_node(set->nr_hw_queues,
4544				       sizeof(*new_hctxs), GFP_KERNEL,
4545				       set->numa_node);
4546		if (!new_hctxs)
4547			return;
4548		if (hctxs)
4549			memcpy(new_hctxs, hctxs, q->nr_hw_queues *
4550			       sizeof(*hctxs));
4551		rcu_assign_pointer(q->queue_hw_ctx, new_hctxs);
4552		/*
4553		 * Make sure reading the old queue_hw_ctx from other
4554		 * context concurrently won't trigger uaf.
4555		 */
4556		kfree_rcu_mightsleep(hctxs);
4557		hctxs = new_hctxs;
4558	}
4559
4560	for (i = 0; i < set->nr_hw_queues; i++) {
4561		int old_node;
4562		int node = blk_mq_get_hctx_node(set, i);
4563		struct blk_mq_hw_ctx *old_hctx = hctxs[i];
4564
4565		if (old_hctx) {
4566			old_node = old_hctx->numa_node;
4567			blk_mq_exit_hctx(q, set, old_hctx, i);
4568		}
4569
4570		hctxs[i] = blk_mq_alloc_and_init_hctx(set, q, i, node);
4571		if (!hctxs[i]) {
4572			if (!old_hctx)
4573				break;
4574			pr_warn("Allocate new hctx on node %d fails, fallback to previous one on node %d\n",
4575					node, old_node);
4576			hctxs[i] = blk_mq_alloc_and_init_hctx(set, q, i,
4577					old_node);
4578			WARN_ON_ONCE(!hctxs[i]);
4579		}
4580	}
4581	/*
4582	 * Increasing nr_hw_queues fails. Free the newly allocated
4583	 * hctxs and keep the previous q->nr_hw_queues.
4584	 */
4585	if (i != set->nr_hw_queues) {
4586		j = q->nr_hw_queues;
4587		end = i;
4588	} else {
4589		j = i;
4590		end = q->nr_hw_queues;
4591		q->nr_hw_queues = set->nr_hw_queues;
4592	}
4593
4594	for (; j < end; j++) {
4595		struct blk_mq_hw_ctx *hctx = hctxs[j];
4596
4597		if (hctx) {
4598			blk_mq_exit_hctx(q, set, hctx, j);
4599			hctxs[j] = NULL;
4600		}
4601	}
4602}
4603
4604static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4605				   struct request_queue *q)
4606{
4607	__blk_mq_realloc_hw_ctxs(set, q);
4608
4609	/* unregister cpuhp callbacks for exited hctxs */
4610	blk_mq_remove_hw_queues_cpuhp(q);
4611
4612	/* register cpuhp for new initialized hctxs */
4613	blk_mq_add_hw_queues_cpuhp(q);
4614}
4615
4616int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4617		struct request_queue *q)
4618{
4619	/* mark the queue as mq asap */
4620	q->mq_ops = set->ops;
4621
4622	/*
4623	 * ->tag_set has to be setup before initialize hctx, which cpuphp
4624	 * handler needs it for checking queue mapping
4625	 */
4626	q->tag_set = set;
4627
4628	if (blk_mq_alloc_ctxs(q))
4629		goto err_exit;
4630
4631	/* init q->mq_kobj and sw queues' kobjects */
4632	blk_mq_sysfs_init(q);
4633
4634	INIT_LIST_HEAD(&q->unused_hctx_list);
4635	spin_lock_init(&q->unused_hctx_lock);
4636
4637	blk_mq_realloc_hw_ctxs(set, q);
4638	if (!q->nr_hw_queues)
4639		goto err_hctxs;
4640
4641	INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4642	blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4643
4644	q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4645
4646	INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4647	INIT_LIST_HEAD(&q->flush_list);
4648	INIT_LIST_HEAD(&q->requeue_list);
4649	spin_lock_init(&q->requeue_lock);
4650
4651	q->nr_requests = set->queue_depth;
4652
4653	blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4654	blk_mq_map_swqueue(q);
4655	blk_mq_add_queue_tag_set(set, q);
4656	return 0;
4657
4658err_hctxs:
4659	blk_mq_release(q);
4660err_exit:
4661	q->mq_ops = NULL;
4662	return -ENOMEM;
4663}
4664EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4665
4666/* tags can _not_ be used after returning from blk_mq_exit_queue */
4667void blk_mq_exit_queue(struct request_queue *q)
4668{
4669	struct blk_mq_tag_set *set = q->tag_set;
4670
4671	/* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4672	blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4673	/* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4674	blk_mq_del_queue_tag_set(q);
4675}
4676
4677static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4678{
4679	int i;
4680
4681	if (blk_mq_is_shared_tags(set->flags)) {
4682		set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4683						BLK_MQ_NO_HCTX_IDX,
4684						set->queue_depth);
4685		if (!set->shared_tags)
4686			return -ENOMEM;
4687	}
4688
4689	for (i = 0; i < set->nr_hw_queues; i++) {
4690		if (!__blk_mq_alloc_map_and_rqs(set, i))
4691			goto out_unwind;
4692		cond_resched();
4693	}
4694
4695	return 0;
4696
4697out_unwind:
4698	while (--i >= 0)
4699		__blk_mq_free_map_and_rqs(set, i);
4700
4701	if (blk_mq_is_shared_tags(set->flags)) {
4702		blk_mq_free_map_and_rqs(set, set->shared_tags,
4703					BLK_MQ_NO_HCTX_IDX);
4704	}
4705
4706	return -ENOMEM;
4707}
4708
4709/*
4710 * Allocate the request maps associated with this tag_set. Note that this
4711 * may reduce the depth asked for, if memory is tight. set->queue_depth
4712 * will be updated to reflect the allocated depth.
4713 */
4714static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4715{
4716	unsigned int depth;
4717	int err;
4718
4719	depth = set->queue_depth;
4720	do {
4721		err = __blk_mq_alloc_rq_maps(set);
4722		if (!err)
4723			break;
4724
4725		set->queue_depth >>= 1;
4726		if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4727			err = -ENOMEM;
4728			break;
4729		}
4730	} while (set->queue_depth);
4731
4732	if (!set->queue_depth || err) {
4733		pr_err("blk-mq: failed to allocate request map\n");
4734		return -ENOMEM;
4735	}
4736
4737	if (depth != set->queue_depth)
4738		pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4739						depth, set->queue_depth);
4740
4741	return 0;
4742}
4743
4744static void blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4745{
4746	/*
4747	 * blk_mq_map_queues() and multiple .map_queues() implementations
4748	 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4749	 * number of hardware queues.
4750	 */
4751	if (set->nr_maps == 1)
4752		set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4753
4754	if (set->ops->map_queues) {
4755		int i;
4756
4757		/*
4758		 * transport .map_queues is usually done in the following
4759		 * way:
4760		 *
4761		 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4762		 * 	mask = get_cpu_mask(queue)
4763		 * 	for_each_cpu(cpu, mask)
4764		 * 		set->map[x].mq_map[cpu] = queue;
4765		 * }
4766		 *
4767		 * When we need to remap, the table has to be cleared for
4768		 * killing stale mapping since one CPU may not be mapped
4769		 * to any hw queue.
4770		 */
4771		for (i = 0; i < set->nr_maps; i++)
4772			blk_mq_clear_mq_map(&set->map[i]);
4773
4774		set->ops->map_queues(set);
4775	} else {
4776		BUG_ON(set->nr_maps > 1);
4777		blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4778	}
4779}
4780
4781static struct blk_mq_tags **blk_mq_prealloc_tag_set_tags(
4782				struct blk_mq_tag_set *set,
4783				int new_nr_hw_queues)
4784{
4785	struct blk_mq_tags **new_tags;
4786	int i;
4787
4788	if (set->nr_hw_queues >= new_nr_hw_queues)
4789		return NULL;
4790
4791	new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4792				GFP_KERNEL, set->numa_node);
4793	if (!new_tags)
4794		return ERR_PTR(-ENOMEM);
4795
4796	if (set->tags)
4797		memcpy(new_tags, set->tags, set->nr_hw_queues *
4798		       sizeof(*set->tags));
4799
4800	for (i = set->nr_hw_queues; i < new_nr_hw_queues; i++) {
4801		if (blk_mq_is_shared_tags(set->flags)) {
4802			new_tags[i] = set->shared_tags;
4803		} else {
4804			new_tags[i] = blk_mq_alloc_map_and_rqs(set, i,
4805					set->queue_depth);
4806			if (!new_tags[i])
4807				goto out_unwind;
4808		}
4809		cond_resched();
4810	}
4811
4812	return new_tags;
4813out_unwind:
4814	while (--i >= set->nr_hw_queues) {
4815		if (!blk_mq_is_shared_tags(set->flags))
4816			blk_mq_free_map_and_rqs(set, new_tags[i], i);
4817	}
4818	kfree(new_tags);
4819	return ERR_PTR(-ENOMEM);
4820}
4821
4822/*
4823 * Alloc a tag set to be associated with one or more request queues.
4824 * May fail with EINVAL for various error conditions. May adjust the
4825 * requested depth down, if it's too large. In that case, the set
4826 * value will be stored in set->queue_depth.
4827 */
4828int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4829{
4830	int i, ret;
4831
4832	BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4833
4834	if (!set->nr_hw_queues)
4835		return -EINVAL;
4836	if (!set->queue_depth)
4837		return -EINVAL;
4838	if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4839		return -EINVAL;
4840
4841	if (!set->ops->queue_rq)
4842		return -EINVAL;
4843
4844	if (!set->ops->get_budget ^ !set->ops->put_budget)
4845		return -EINVAL;
4846
4847	if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4848		pr_info("blk-mq: reduced tag depth to %u\n",
4849			BLK_MQ_MAX_DEPTH);
4850		set->queue_depth = BLK_MQ_MAX_DEPTH;
4851	}
4852
4853	if (!set->nr_maps)
4854		set->nr_maps = 1;
4855	else if (set->nr_maps > HCTX_MAX_TYPES)
4856		return -EINVAL;
4857
4858	/*
4859	 * If a crashdump is active, then we are potentially in a very
4860	 * memory constrained environment. Limit us to  64 tags to prevent
4861	 * using too much memory.
4862	 */
4863	if (is_kdump_kernel())
4864		set->queue_depth = min(64U, set->queue_depth);
4865
4866	/*
4867	 * There is no use for more h/w queues than cpus if we just have
4868	 * a single map
4869	 */
4870	if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4871		set->nr_hw_queues = nr_cpu_ids;
4872
4873	if (set->flags & BLK_MQ_F_BLOCKING) {
4874		set->srcu = kmalloc(sizeof(*set->srcu), GFP_KERNEL);
4875		if (!set->srcu)
4876			return -ENOMEM;
4877		ret = init_srcu_struct(set->srcu);
4878		if (ret)
4879			goto out_free_srcu;
4880	}
4881	ret = init_srcu_struct(&set->tags_srcu);
4882	if (ret)
4883		goto out_cleanup_srcu;
4884
4885	init_rwsem(&set->update_nr_hwq_lock);
4886
4887	ret = -ENOMEM;
4888	set->tags = kcalloc_node(set->nr_hw_queues,
4889				 sizeof(struct blk_mq_tags *), GFP_KERNEL,
4890				 set->numa_node);
4891	if (!set->tags)
4892		goto out_cleanup_tags_srcu;
4893
4894	for (i = 0; i < set->nr_maps; i++) {
4895		set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4896						  sizeof(set->map[i].mq_map[0]),
4897						  GFP_KERNEL, set->numa_node);
4898		if (!set->map[i].mq_map)
4899			goto out_free_mq_map;
4900		set->map[i].nr_queues = set->nr_hw_queues;
4901	}
4902
4903	blk_mq_update_queue_map(set);
4904
4905	ret = blk_mq_alloc_set_map_and_rqs(set);
4906	if (ret)
4907		goto out_free_mq_map;
4908
4909	mutex_init(&set->tag_list_lock);
4910	INIT_LIST_HEAD(&set->tag_list);
4911
4912	return 0;
4913
4914out_free_mq_map:
4915	for (i = 0; i < set->nr_maps; i++) {
4916		kfree(set->map[i].mq_map);
4917		set->map[i].mq_map = NULL;
4918	}
4919	kfree(set->tags);
4920	set->tags = NULL;
4921out_cleanup_tags_srcu:
4922	cleanup_srcu_struct(&set->tags_srcu);
4923out_cleanup_srcu:
4924	if (set->flags & BLK_MQ_F_BLOCKING)
4925		cleanup_srcu_struct(set->srcu);
4926out_free_srcu:
4927	if (set->flags & BLK_MQ_F_BLOCKING)
4928		kfree(set->srcu);
4929	return ret;
4930}
4931EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4932
4933/* allocate and initialize a tagset for a simple single-queue device */
4934int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4935		const struct blk_mq_ops *ops, unsigned int queue_depth,
4936		unsigned int set_flags)
4937{
4938	memset(set, 0, sizeof(*set));
4939	set->ops = ops;
4940	set->nr_hw_queues = 1;
4941	set->nr_maps = 1;
4942	set->queue_depth = queue_depth;
4943	set->numa_node = NUMA_NO_NODE;
4944	set->flags = set_flags;
4945	return blk_mq_alloc_tag_set(set);
4946}
4947EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4948
4949void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4950{
4951	int i, j;
4952
4953	for (i = 0; i < set->nr_hw_queues; i++)
4954		__blk_mq_free_map_and_rqs(set, i);
4955
4956	if (blk_mq_is_shared_tags(set->flags)) {
4957		blk_mq_free_map_and_rqs(set, set->shared_tags,
4958					BLK_MQ_NO_HCTX_IDX);
4959	}
4960
4961	for (j = 0; j < set->nr_maps; j++) {
4962		kfree(set->map[j].mq_map);
4963		set->map[j].mq_map = NULL;
4964	}
4965
4966	kfree(set->tags);
4967	set->tags = NULL;
4968
4969	srcu_barrier(&set->tags_srcu);
4970	cleanup_srcu_struct(&set->tags_srcu);
4971	if (set->flags & BLK_MQ_F_BLOCKING) {
4972		cleanup_srcu_struct(set->srcu);
4973		kfree(set->srcu);
4974	}
4975}
4976EXPORT_SYMBOL(blk_mq_free_tag_set);
4977
4978struct elevator_tags *blk_mq_update_nr_requests(struct request_queue *q,
4979						struct elevator_tags *et,
4980						unsigned int nr)
4981{
4982	struct blk_mq_tag_set *set = q->tag_set;
4983	struct elevator_tags *old_et = NULL;
4984	struct blk_mq_hw_ctx *hctx;
4985	unsigned long i;
4986
4987	blk_mq_quiesce_queue(q);
4988
4989	if (blk_mq_is_shared_tags(set->flags)) {
4990		/*
4991		 * Shared tags, for sched tags, we allocate max initially hence
4992		 * tags can't grow, see blk_mq_alloc_sched_tags().
4993		 */
4994		if (q->elevator)
4995			blk_mq_tag_update_sched_shared_tags(q, nr);
4996		else
4997			blk_mq_tag_resize_shared_tags(set, nr);
4998	} else if (!q->elevator) {
4999		/*
5000		 * Non-shared hardware tags, nr is already checked from
5001		 * queue_requests_store() and tags can't grow.
5002		 */
5003		queue_for_each_hw_ctx(q, hctx, i) {
5004			if (!hctx->tags)
5005				continue;
5006			sbitmap_queue_resize(&hctx->tags->bitmap_tags,
5007				nr - hctx->tags->nr_reserved_tags);
5008		}
5009	} else if (nr <= q->elevator->et->nr_requests) {
5010		/* Non-shared sched tags, and tags don't grow. */
5011		queue_for_each_hw_ctx(q, hctx, i) {
5012			if (!hctx->sched_tags)
5013				continue;
5014			sbitmap_queue_resize(&hctx->sched_tags->bitmap_tags,
5015				nr - hctx->sched_tags->nr_reserved_tags);
5016		}
5017	} else {
5018		/* Non-shared sched tags, and tags grow */
5019		queue_for_each_hw_ctx(q, hctx, i)
5020			hctx->sched_tags = et->tags[i];
5021		old_et =  q->elevator->et;
5022		q->elevator->et = et;
5023	}
5024
5025	q->nr_requests = nr;
5026	if (q->elevator && q->elevator->type->ops.depth_updated)
5027		q->elevator->type->ops.depth_updated(q);
5028
5029	blk_mq_unquiesce_queue(q);
5030	return old_et;
5031}
5032
5033/*
5034 * Switch back to the elevator type stored in the xarray.
5035 */
5036static void blk_mq_elv_switch_back(struct request_queue *q,
5037		struct xarray *elv_tbl)
5038{
5039	struct elv_change_ctx *ctx = xa_load(elv_tbl, q->id);
5040
5041	if (WARN_ON_ONCE(!ctx))
5042		return;
5043
5044	/* The elv_update_nr_hw_queues unfreezes the queue. */
5045	elv_update_nr_hw_queues(q, ctx);
5046
5047	/* Drop the reference acquired in blk_mq_elv_switch_none. */
5048	if (ctx->type)
5049		elevator_put(ctx->type);
5050}
5051
5052/*
5053 * Stores elevator name and type in ctx and set current elevator to none.
5054 */
5055static int blk_mq_elv_switch_none(struct request_queue *q,
5056		struct xarray *elv_tbl)
5057{
5058	struct elv_change_ctx *ctx;
5059
5060	lockdep_assert_held_write(&q->tag_set->update_nr_hwq_lock);
5061
5062	/*
5063	 * Accessing q->elevator without holding q->elevator_lock is safe here
5064	 * because we're called from nr_hw_queue update which is protected by
5065	 * set->update_nr_hwq_lock in the writer context. So, scheduler update/
5066	 * switch code (which acquires the same lock in the reader context)
5067	 * can't run concurrently.
5068	 */
5069	if (q->elevator) {
5070		ctx = xa_load(elv_tbl, q->id);
5071		if (WARN_ON_ONCE(!ctx))
5072			return -ENOENT;
5073
5074		ctx->name = q->elevator->type->elevator_name;
5075
5076		/*
5077		 * Before we switch elevator to 'none', take a reference to
5078		 * the elevator module so that while nr_hw_queue update is
5079		 * running, no one can remove elevator module. We'd put the
5080		 * reference to elevator module later when we switch back
5081		 * elevator.
5082		 */
5083		__elevator_get(q->elevator->type);
5084
5085		/*
5086		 * Store elevator type so that we can release the reference
5087		 * taken above later.
5088		 */
5089		ctx->type = q->elevator->type;
5090		elevator_set_none(q);
5091	}
5092	return 0;
5093}
5094
5095static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
5096							int nr_hw_queues)
5097{
5098	struct request_queue *q;
5099	int prev_nr_hw_queues = set->nr_hw_queues;
5100	unsigned int memflags;
5101	int i;
5102	struct xarray elv_tbl;
5103	struct blk_mq_tags **new_tags;
5104	bool queues_frozen = false;
5105
5106	lockdep_assert_held(&set->tag_list_lock);
5107
5108	if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
5109		nr_hw_queues = nr_cpu_ids;
5110	if (nr_hw_queues < 1)
5111		return;
5112	if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
5113		return;
5114
5115	memflags = memalloc_noio_save();
5116
5117	xa_init(&elv_tbl);
5118	if (blk_mq_alloc_sched_ctx_batch(&elv_tbl, set) < 0)
5119		goto out_free_ctx;
5120
5121	if (blk_mq_alloc_sched_res_batch(&elv_tbl, set, nr_hw_queues) < 0)
5122		goto out_free_ctx;
5123
5124	list_for_each_entry(q, &set->tag_list, tag_set_list) {
5125		blk_mq_debugfs_unregister_hctxs(q);
5126		blk_mq_sysfs_unregister_hctxs(q);
5127	}
5128
5129	/*
5130	 * Switch IO scheduler to 'none', cleaning up the data associated
5131	 * with the previous scheduler. We will switch back once we are done
5132	 * updating the new sw to hw queue mappings.
5133	 */
5134	list_for_each_entry(q, &set->tag_list, tag_set_list)
5135		if (blk_mq_elv_switch_none(q, &elv_tbl))
5136			goto switch_back;
5137
5138	new_tags = blk_mq_prealloc_tag_set_tags(set, nr_hw_queues);
5139	if (IS_ERR(new_tags))
5140		goto switch_back;
5141
5142	list_for_each_entry(q, &set->tag_list, tag_set_list)
5143		blk_mq_freeze_queue_nomemsave(q);
5144	queues_frozen = true;
5145	if (new_tags) {
5146		kfree(set->tags);
5147		set->tags = new_tags;
5148	}
5149	set->nr_hw_queues = nr_hw_queues;
5150
5151fallback:
5152	blk_mq_update_queue_map(set);
5153	list_for_each_entry(q, &set->tag_list, tag_set_list) {
5154		__blk_mq_realloc_hw_ctxs(set, q);
5155
5156		if (q->nr_hw_queues != set->nr_hw_queues) {
5157			int i = prev_nr_hw_queues;
5158
5159			pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
5160					nr_hw_queues, prev_nr_hw_queues);
5161			for (; i < set->nr_hw_queues; i++)
5162				__blk_mq_free_map_and_rqs(set, i);
5163
5164			set->nr_hw_queues = prev_nr_hw_queues;
5165			goto fallback;
5166		}
5167		blk_mq_map_swqueue(q);
5168	}
5169switch_back:
5170	/* The blk_mq_elv_switch_back unfreezes queue for us. */
5171	list_for_each_entry(q, &set->tag_list, tag_set_list) {
5172		/* switch_back expects queue to be frozen */
5173		if (!queues_frozen)
5174			blk_mq_freeze_queue_nomemsave(q);
5175		blk_mq_elv_switch_back(q, &elv_tbl);
5176	}
5177
5178	list_for_each_entry(q, &set->tag_list, tag_set_list) {
5179		blk_mq_sysfs_register_hctxs(q);
5180		blk_mq_debugfs_register_hctxs(q);
5181
5182		blk_mq_remove_hw_queues_cpuhp(q);
5183		blk_mq_add_hw_queues_cpuhp(q);
5184	}
5185
5186out_free_ctx:
5187	blk_mq_free_sched_ctx_batch(&elv_tbl);
5188	xa_destroy(&elv_tbl);
5189	memalloc_noio_restore(memflags);
5190
5191	/* Free the excess tags when nr_hw_queues shrink. */
5192	for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
5193		__blk_mq_free_map_and_rqs(set, i);
5194}
5195
5196void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
5197{
5198	down_write(&set->update_nr_hwq_lock);
5199	mutex_lock(&set->tag_list_lock);
5200	__blk_mq_update_nr_hw_queues(set, nr_hw_queues);
5201	mutex_unlock(&set->tag_list_lock);
5202	up_write(&set->update_nr_hwq_lock);
5203}
5204EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
5205
5206static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
5207			 struct io_comp_batch *iob, unsigned int flags)
5208{
5209	int ret;
5210
5211	do {
5212		ret = q->mq_ops->poll(hctx, iob);
5213		if (ret > 0)
5214			return ret;
5215		if (task_sigpending(current))
5216			return 1;
5217		if (ret < 0 || (flags & BLK_POLL_ONESHOT))
5218			break;
5219		cpu_relax();
5220	} while (!need_resched());
5221
5222	return 0;
5223}
5224
5225int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
5226		struct io_comp_batch *iob, unsigned int flags)
5227{
5228	if (!blk_mq_can_poll(q))
5229		return 0;
5230	return blk_hctx_poll(q, q->queue_hw_ctx[cookie], iob, flags);
5231}
5232
5233int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
5234		unsigned int poll_flags)
5235{
5236	struct request_queue *q = rq->q;
5237	int ret;
5238
5239	if (!blk_rq_is_poll(rq))
5240		return 0;
5241	if (!percpu_ref_tryget(&q->q_usage_counter))
5242		return 0;
5243
5244	ret = blk_hctx_poll(q, rq->mq_hctx, iob, poll_flags);
5245	blk_queue_exit(q);
5246
5247	return ret;
5248}
5249EXPORT_SYMBOL_GPL(blk_rq_poll);
5250
5251unsigned int blk_mq_rq_cpu(struct request *rq)
5252{
5253	return rq->mq_ctx->cpu;
5254}
5255EXPORT_SYMBOL(blk_mq_rq_cpu);
5256
5257void blk_mq_cancel_work_sync(struct request_queue *q)
5258{
5259	struct blk_mq_hw_ctx *hctx;
5260	unsigned long i;
5261
5262	cancel_delayed_work_sync(&q->requeue_work);
5263
5264	queue_for_each_hw_ctx(q, hctx, i)
5265		cancel_delayed_work_sync(&hctx->run_work);
5266}
5267
5268static int __init blk_mq_init(void)
5269{
5270	int i;
5271
5272	for_each_possible_cpu(i)
5273		init_llist_head(&per_cpu(blk_cpu_done, i));
5274	for_each_possible_cpu(i)
5275		INIT_CSD(&per_cpu(blk_cpu_csd, i),
5276			 __blk_mq_complete_request_remote, NULL);
5277	open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
5278
5279	cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
5280				  "block/softirq:dead", NULL,
5281				  blk_softirq_cpu_dead);
5282	cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
5283				blk_mq_hctx_notify_dead);
5284	cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
5285				blk_mq_hctx_notify_online,
5286				blk_mq_hctx_notify_offline);
5287	return 0;
5288}
5289subsys_initcall(blk_mq_init);
~/ Read-only file preview.