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