xref: /linux/block/blk-mq.c (revision e0c1b49f5b674cca7b10549c53b3791d0bbc90a8)
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/sysctl.h>
25 #include <linux/sched/topology.h>
26 #include <linux/sched/signal.h>
27 #include <linux/delay.h>
28 #include <linux/crash_dump.h>
29 #include <linux/prefetch.h>
30 #include <linux/blk-crypto.h>
31 
32 #include <trace/events/block.h>
33 
34 #include <linux/blk-mq.h>
35 #include <linux/t10-pi.h>
36 #include "blk.h"
37 #include "blk-mq.h"
38 #include "blk-mq-debugfs.h"
39 #include "blk-mq-tag.h"
40 #include "blk-pm.h"
41 #include "blk-stat.h"
42 #include "blk-mq-sched.h"
43 #include "blk-rq-qos.h"
44 
45 static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
46 
47 static void blk_mq_poll_stats_start(struct request_queue *q);
48 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
49 
50 static int blk_mq_poll_stats_bkt(const struct request *rq)
51 {
52 	int ddir, sectors, bucket;
53 
54 	ddir = rq_data_dir(rq);
55 	sectors = blk_rq_stats_sectors(rq);
56 
57 	bucket = ddir + 2 * ilog2(sectors);
58 
59 	if (bucket < 0)
60 		return -1;
61 	else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
62 		return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
63 
64 	return bucket;
65 }
66 
67 #define BLK_QC_T_SHIFT		16
68 #define BLK_QC_T_INTERNAL	(1U << 31)
69 
70 static inline struct blk_mq_hw_ctx *blk_qc_to_hctx(struct request_queue *q,
71 		blk_qc_t qc)
72 {
73 	return q->queue_hw_ctx[(qc & ~BLK_QC_T_INTERNAL) >> BLK_QC_T_SHIFT];
74 }
75 
76 static inline struct request *blk_qc_to_rq(struct blk_mq_hw_ctx *hctx,
77 		blk_qc_t qc)
78 {
79 	unsigned int tag = qc & ((1U << BLK_QC_T_SHIFT) - 1);
80 
81 	if (qc & BLK_QC_T_INTERNAL)
82 		return blk_mq_tag_to_rq(hctx->sched_tags, tag);
83 	return blk_mq_tag_to_rq(hctx->tags, tag);
84 }
85 
86 static inline blk_qc_t blk_rq_to_qc(struct request *rq)
87 {
88 	return (rq->mq_hctx->queue_num << BLK_QC_T_SHIFT) |
89 		(rq->tag != -1 ?
90 		 rq->tag : (rq->internal_tag | BLK_QC_T_INTERNAL));
91 }
92 
93 /*
94  * Check if any of the ctx, dispatch list or elevator
95  * have pending work in this hardware queue.
96  */
97 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
98 {
99 	return !list_empty_careful(&hctx->dispatch) ||
100 		sbitmap_any_bit_set(&hctx->ctx_map) ||
101 			blk_mq_sched_has_work(hctx);
102 }
103 
104 /*
105  * Mark this ctx as having pending work in this hardware queue
106  */
107 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
108 				     struct blk_mq_ctx *ctx)
109 {
110 	const int bit = ctx->index_hw[hctx->type];
111 
112 	if (!sbitmap_test_bit(&hctx->ctx_map, bit))
113 		sbitmap_set_bit(&hctx->ctx_map, bit);
114 }
115 
116 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
117 				      struct blk_mq_ctx *ctx)
118 {
119 	const int bit = ctx->index_hw[hctx->type];
120 
121 	sbitmap_clear_bit(&hctx->ctx_map, bit);
122 }
123 
124 struct mq_inflight {
125 	struct block_device *part;
126 	unsigned int inflight[2];
127 };
128 
129 static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
130 				  struct request *rq, void *priv,
131 				  bool reserved)
132 {
133 	struct mq_inflight *mi = priv;
134 
135 	if ((!mi->part->bd_partno || rq->part == mi->part) &&
136 	    blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
137 		mi->inflight[rq_data_dir(rq)]++;
138 
139 	return true;
140 }
141 
142 unsigned int blk_mq_in_flight(struct request_queue *q,
143 		struct block_device *part)
144 {
145 	struct mq_inflight mi = { .part = part };
146 
147 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
148 
149 	return mi.inflight[0] + mi.inflight[1];
150 }
151 
152 void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
153 		unsigned int inflight[2])
154 {
155 	struct mq_inflight mi = { .part = part };
156 
157 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
158 	inflight[0] = mi.inflight[0];
159 	inflight[1] = mi.inflight[1];
160 }
161 
162 void blk_freeze_queue_start(struct request_queue *q)
163 {
164 	mutex_lock(&q->mq_freeze_lock);
165 	if (++q->mq_freeze_depth == 1) {
166 		percpu_ref_kill(&q->q_usage_counter);
167 		mutex_unlock(&q->mq_freeze_lock);
168 		if (queue_is_mq(q))
169 			blk_mq_run_hw_queues(q, false);
170 	} else {
171 		mutex_unlock(&q->mq_freeze_lock);
172 	}
173 }
174 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
175 
176 void blk_mq_freeze_queue_wait(struct request_queue *q)
177 {
178 	wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
179 }
180 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
181 
182 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
183 				     unsigned long timeout)
184 {
185 	return wait_event_timeout(q->mq_freeze_wq,
186 					percpu_ref_is_zero(&q->q_usage_counter),
187 					timeout);
188 }
189 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
190 
191 /*
192  * Guarantee no request is in use, so we can change any data structure of
193  * the queue afterward.
194  */
195 void blk_freeze_queue(struct request_queue *q)
196 {
197 	/*
198 	 * In the !blk_mq case we are only calling this to kill the
199 	 * q_usage_counter, otherwise this increases the freeze depth
200 	 * and waits for it to return to zero.  For this reason there is
201 	 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
202 	 * exported to drivers as the only user for unfreeze is blk_mq.
203 	 */
204 	blk_freeze_queue_start(q);
205 	blk_mq_freeze_queue_wait(q);
206 }
207 
208 void blk_mq_freeze_queue(struct request_queue *q)
209 {
210 	/*
211 	 * ...just an alias to keep freeze and unfreeze actions balanced
212 	 * in the blk_mq_* namespace
213 	 */
214 	blk_freeze_queue(q);
215 }
216 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
217 
218 void __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
219 {
220 	mutex_lock(&q->mq_freeze_lock);
221 	if (force_atomic)
222 		q->q_usage_counter.data->force_atomic = true;
223 	q->mq_freeze_depth--;
224 	WARN_ON_ONCE(q->mq_freeze_depth < 0);
225 	if (!q->mq_freeze_depth) {
226 		percpu_ref_resurrect(&q->q_usage_counter);
227 		wake_up_all(&q->mq_freeze_wq);
228 	}
229 	mutex_unlock(&q->mq_freeze_lock);
230 }
231 
232 void blk_mq_unfreeze_queue(struct request_queue *q)
233 {
234 	__blk_mq_unfreeze_queue(q, false);
235 }
236 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
237 
238 /*
239  * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
240  * mpt3sas driver such that this function can be removed.
241  */
242 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
243 {
244 	unsigned long flags;
245 
246 	spin_lock_irqsave(&q->queue_lock, flags);
247 	if (!q->quiesce_depth++)
248 		blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
249 	spin_unlock_irqrestore(&q->queue_lock, flags);
250 }
251 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
252 
253 /**
254  * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
255  * @q: request queue.
256  *
257  * Note: this function does not prevent that the struct request end_io()
258  * callback function is invoked. Once this function is returned, we make
259  * sure no dispatch can happen until the queue is unquiesced via
260  * blk_mq_unquiesce_queue().
261  */
262 void blk_mq_quiesce_queue(struct request_queue *q)
263 {
264 	struct blk_mq_hw_ctx *hctx;
265 	unsigned int i;
266 	bool rcu = false;
267 
268 	blk_mq_quiesce_queue_nowait(q);
269 
270 	queue_for_each_hw_ctx(q, hctx, i) {
271 		if (hctx->flags & BLK_MQ_F_BLOCKING)
272 			synchronize_srcu(hctx->srcu);
273 		else
274 			rcu = true;
275 	}
276 	if (rcu)
277 		synchronize_rcu();
278 }
279 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
280 
281 /*
282  * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
283  * @q: request queue.
284  *
285  * This function recovers queue into the state before quiescing
286  * which is done by blk_mq_quiesce_queue.
287  */
288 void blk_mq_unquiesce_queue(struct request_queue *q)
289 {
290 	unsigned long flags;
291 	bool run_queue = false;
292 
293 	spin_lock_irqsave(&q->queue_lock, flags);
294 	if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
295 		;
296 	} else if (!--q->quiesce_depth) {
297 		blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
298 		run_queue = true;
299 	}
300 	spin_unlock_irqrestore(&q->queue_lock, flags);
301 
302 	/* dispatch requests which are inserted during quiescing */
303 	if (run_queue)
304 		blk_mq_run_hw_queues(q, true);
305 }
306 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
307 
308 void blk_mq_wake_waiters(struct request_queue *q)
309 {
310 	struct blk_mq_hw_ctx *hctx;
311 	unsigned int i;
312 
313 	queue_for_each_hw_ctx(q, hctx, i)
314 		if (blk_mq_hw_queue_mapped(hctx))
315 			blk_mq_tag_wakeup_all(hctx->tags, true);
316 }
317 
318 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
319 		struct blk_mq_tags *tags, unsigned int tag, u64 alloc_time_ns)
320 {
321 	struct blk_mq_ctx *ctx = data->ctx;
322 	struct blk_mq_hw_ctx *hctx = data->hctx;
323 	struct request_queue *q = data->q;
324 	struct request *rq = tags->static_rqs[tag];
325 
326 	rq->q = q;
327 	rq->mq_ctx = ctx;
328 	rq->mq_hctx = hctx;
329 	rq->cmd_flags = data->cmd_flags;
330 
331 	if (data->flags & BLK_MQ_REQ_PM)
332 		data->rq_flags |= RQF_PM;
333 	if (blk_queue_io_stat(q))
334 		data->rq_flags |= RQF_IO_STAT;
335 	rq->rq_flags = data->rq_flags;
336 
337 	if (!(data->rq_flags & RQF_ELV)) {
338 		rq->tag = tag;
339 		rq->internal_tag = BLK_MQ_NO_TAG;
340 	} else {
341 		rq->tag = BLK_MQ_NO_TAG;
342 		rq->internal_tag = tag;
343 	}
344 	rq->timeout = 0;
345 
346 	if (blk_mq_need_time_stamp(rq))
347 		rq->start_time_ns = ktime_get_ns();
348 	else
349 		rq->start_time_ns = 0;
350 	rq->rq_disk = NULL;
351 	rq->part = NULL;
352 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
353 	rq->alloc_time_ns = alloc_time_ns;
354 #endif
355 	rq->io_start_time_ns = 0;
356 	rq->stats_sectors = 0;
357 	rq->nr_phys_segments = 0;
358 #if defined(CONFIG_BLK_DEV_INTEGRITY)
359 	rq->nr_integrity_segments = 0;
360 #endif
361 	rq->end_io = NULL;
362 	rq->end_io_data = NULL;
363 
364 	blk_crypto_rq_set_defaults(rq);
365 	INIT_LIST_HEAD(&rq->queuelist);
366 	/* tag was already set */
367 	WRITE_ONCE(rq->deadline, 0);
368 	refcount_set(&rq->ref, 1);
369 
370 	if (rq->rq_flags & RQF_ELV) {
371 		struct elevator_queue *e = data->q->elevator;
372 
373 		rq->elv.icq = NULL;
374 		INIT_HLIST_NODE(&rq->hash);
375 		RB_CLEAR_NODE(&rq->rb_node);
376 
377 		if (!op_is_flush(data->cmd_flags) &&
378 		    e->type->ops.prepare_request) {
379 			if (e->type->icq_cache)
380 				blk_mq_sched_assign_ioc(rq);
381 
382 			e->type->ops.prepare_request(rq);
383 			rq->rq_flags |= RQF_ELVPRIV;
384 		}
385 	}
386 
387 	return rq;
388 }
389 
390 static inline struct request *
391 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data,
392 		u64 alloc_time_ns)
393 {
394 	unsigned int tag, tag_offset;
395 	struct blk_mq_tags *tags;
396 	struct request *rq;
397 	unsigned long tag_mask;
398 	int i, nr = 0;
399 
400 	tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
401 	if (unlikely(!tag_mask))
402 		return NULL;
403 
404 	tags = blk_mq_tags_from_data(data);
405 	for (i = 0; tag_mask; i++) {
406 		if (!(tag_mask & (1UL << i)))
407 			continue;
408 		prefetch(tags->static_rqs[tag]);
409 		tag = tag_offset + i;
410 		tag_mask &= ~(1UL << i);
411 		rq = blk_mq_rq_ctx_init(data, tags, tag, alloc_time_ns);
412 		rq_list_add(data->cached_rq, rq);
413 	}
414 	data->nr_tags -= nr;
415 
416 	return rq_list_pop(data->cached_rq);
417 }
418 
419 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
420 {
421 	struct request_queue *q = data->q;
422 	struct elevator_queue *e = q->elevator;
423 	u64 alloc_time_ns = 0;
424 	struct request *rq;
425 	unsigned int tag;
426 
427 	/* alloc_time includes depth and tag waits */
428 	if (blk_queue_rq_alloc_time(q))
429 		alloc_time_ns = ktime_get_ns();
430 
431 	if (data->cmd_flags & REQ_NOWAIT)
432 		data->flags |= BLK_MQ_REQ_NOWAIT;
433 
434 	if (e) {
435 		/*
436 		 * Flush/passthrough requests are special and go directly to the
437 		 * dispatch list. Don't include reserved tags in the
438 		 * limiting, as it isn't useful.
439 		 */
440 		if (!op_is_flush(data->cmd_flags) &&
441 		    !blk_op_is_passthrough(data->cmd_flags) &&
442 		    e->type->ops.limit_depth &&
443 		    !(data->flags & BLK_MQ_REQ_RESERVED))
444 			e->type->ops.limit_depth(data->cmd_flags, data);
445 	}
446 
447 retry:
448 	data->ctx = blk_mq_get_ctx(q);
449 	data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
450 	if (!e)
451 		blk_mq_tag_busy(data->hctx);
452 
453 	/*
454 	 * Try batched alloc if we want more than 1 tag.
455 	 */
456 	if (data->nr_tags > 1) {
457 		rq = __blk_mq_alloc_requests_batch(data, alloc_time_ns);
458 		if (rq)
459 			return rq;
460 		data->nr_tags = 1;
461 	}
462 
463 	/*
464 	 * Waiting allocations only fail because of an inactive hctx.  In that
465 	 * case just retry the hctx assignment and tag allocation as CPU hotplug
466 	 * should have migrated us to an online CPU by now.
467 	 */
468 	tag = blk_mq_get_tag(data);
469 	if (tag == BLK_MQ_NO_TAG) {
470 		if (data->flags & BLK_MQ_REQ_NOWAIT)
471 			return NULL;
472 		/*
473 		 * Give up the CPU and sleep for a random short time to
474 		 * ensure that thread using a realtime scheduling class
475 		 * are migrated off the CPU, and thus off the hctx that
476 		 * is going away.
477 		 */
478 		msleep(3);
479 		goto retry;
480 	}
481 
482 	return blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag,
483 					alloc_time_ns);
484 }
485 
486 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
487 		blk_mq_req_flags_t flags)
488 {
489 	struct blk_mq_alloc_data data = {
490 		.q		= q,
491 		.flags		= flags,
492 		.cmd_flags	= op,
493 		.rq_flags	= q->elevator ? RQF_ELV : 0,
494 		.nr_tags	= 1,
495 	};
496 	struct request *rq;
497 	int ret;
498 
499 	ret = blk_queue_enter(q, flags);
500 	if (ret)
501 		return ERR_PTR(ret);
502 
503 	rq = __blk_mq_alloc_requests(&data);
504 	if (!rq)
505 		goto out_queue_exit;
506 	rq->__data_len = 0;
507 	rq->__sector = (sector_t) -1;
508 	rq->bio = rq->biotail = NULL;
509 	return rq;
510 out_queue_exit:
511 	blk_queue_exit(q);
512 	return ERR_PTR(-EWOULDBLOCK);
513 }
514 EXPORT_SYMBOL(blk_mq_alloc_request);
515 
516 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
517 	unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
518 {
519 	struct blk_mq_alloc_data data = {
520 		.q		= q,
521 		.flags		= flags,
522 		.cmd_flags	= op,
523 		.rq_flags	= q->elevator ? RQF_ELV : 0,
524 		.nr_tags	= 1,
525 	};
526 	u64 alloc_time_ns = 0;
527 	unsigned int cpu;
528 	unsigned int tag;
529 	int ret;
530 
531 	/* alloc_time includes depth and tag waits */
532 	if (blk_queue_rq_alloc_time(q))
533 		alloc_time_ns = ktime_get_ns();
534 
535 	/*
536 	 * If the tag allocator sleeps we could get an allocation for a
537 	 * different hardware context.  No need to complicate the low level
538 	 * allocator for this for the rare use case of a command tied to
539 	 * a specific queue.
540 	 */
541 	if (WARN_ON_ONCE(!(flags & (BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED))))
542 		return ERR_PTR(-EINVAL);
543 
544 	if (hctx_idx >= q->nr_hw_queues)
545 		return ERR_PTR(-EIO);
546 
547 	ret = blk_queue_enter(q, flags);
548 	if (ret)
549 		return ERR_PTR(ret);
550 
551 	/*
552 	 * Check if the hardware context is actually mapped to anything.
553 	 * If not tell the caller that it should skip this queue.
554 	 */
555 	ret = -EXDEV;
556 	data.hctx = q->queue_hw_ctx[hctx_idx];
557 	if (!blk_mq_hw_queue_mapped(data.hctx))
558 		goto out_queue_exit;
559 	cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
560 	data.ctx = __blk_mq_get_ctx(q, cpu);
561 
562 	if (!q->elevator)
563 		blk_mq_tag_busy(data.hctx);
564 
565 	ret = -EWOULDBLOCK;
566 	tag = blk_mq_get_tag(&data);
567 	if (tag == BLK_MQ_NO_TAG)
568 		goto out_queue_exit;
569 	return blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag,
570 					alloc_time_ns);
571 
572 out_queue_exit:
573 	blk_queue_exit(q);
574 	return ERR_PTR(ret);
575 }
576 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
577 
578 static void __blk_mq_free_request(struct request *rq)
579 {
580 	struct request_queue *q = rq->q;
581 	struct blk_mq_ctx *ctx = rq->mq_ctx;
582 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
583 	const int sched_tag = rq->internal_tag;
584 
585 	blk_crypto_free_request(rq);
586 	blk_pm_mark_last_busy(rq);
587 	rq->mq_hctx = NULL;
588 	if (rq->tag != BLK_MQ_NO_TAG)
589 		blk_mq_put_tag(hctx->tags, ctx, rq->tag);
590 	if (sched_tag != BLK_MQ_NO_TAG)
591 		blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
592 	blk_mq_sched_restart(hctx);
593 	blk_queue_exit(q);
594 }
595 
596 void blk_mq_free_request(struct request *rq)
597 {
598 	struct request_queue *q = rq->q;
599 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
600 
601 	if (rq->rq_flags & RQF_ELVPRIV) {
602 		struct elevator_queue *e = q->elevator;
603 
604 		if (e->type->ops.finish_request)
605 			e->type->ops.finish_request(rq);
606 		if (rq->elv.icq) {
607 			put_io_context(rq->elv.icq->ioc);
608 			rq->elv.icq = NULL;
609 		}
610 	}
611 
612 	if (rq->rq_flags & RQF_MQ_INFLIGHT)
613 		__blk_mq_dec_active_requests(hctx);
614 
615 	if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
616 		laptop_io_completion(q->disk->bdi);
617 
618 	rq_qos_done(q, rq);
619 
620 	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
621 	if (refcount_dec_and_test(&rq->ref))
622 		__blk_mq_free_request(rq);
623 }
624 EXPORT_SYMBOL_GPL(blk_mq_free_request);
625 
626 void blk_mq_free_plug_rqs(struct blk_plug *plug)
627 {
628 	struct request *rq;
629 
630 	while ((rq = rq_list_pop(&plug->cached_rq)) != NULL) {
631 		percpu_ref_get(&rq->q->q_usage_counter);
632 		blk_mq_free_request(rq);
633 	}
634 }
635 
636 static void req_bio_endio(struct request *rq, struct bio *bio,
637 			  unsigned int nbytes, blk_status_t error)
638 {
639 	if (unlikely(error)) {
640 		bio->bi_status = error;
641 	} else if (req_op(rq) == REQ_OP_ZONE_APPEND) {
642 		/*
643 		 * Partial zone append completions cannot be supported as the
644 		 * BIO fragments may end up not being written sequentially.
645 		 */
646 		if (bio->bi_iter.bi_size != nbytes)
647 			bio->bi_status = BLK_STS_IOERR;
648 		else
649 			bio->bi_iter.bi_sector = rq->__sector;
650 	}
651 
652 	bio_advance(bio, nbytes);
653 
654 	if (unlikely(rq->rq_flags & RQF_QUIET))
655 		bio_set_flag(bio, BIO_QUIET);
656 	/* don't actually finish bio if it's part of flush sequence */
657 	if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
658 		bio_endio(bio);
659 }
660 
661 static void blk_account_io_completion(struct request *req, unsigned int bytes)
662 {
663 	if (req->part && blk_do_io_stat(req)) {
664 		const int sgrp = op_stat_group(req_op(req));
665 
666 		part_stat_lock();
667 		part_stat_add(req->part, sectors[sgrp], bytes >> 9);
668 		part_stat_unlock();
669 	}
670 }
671 
672 /**
673  * blk_update_request - Complete multiple bytes without completing the request
674  * @req:      the request being processed
675  * @error:    block status code
676  * @nr_bytes: number of bytes to complete for @req
677  *
678  * Description:
679  *     Ends I/O on a number of bytes attached to @req, but doesn't complete
680  *     the request structure even if @req doesn't have leftover.
681  *     If @req has leftover, sets it up for the next range of segments.
682  *
683  *     Passing the result of blk_rq_bytes() as @nr_bytes guarantees
684  *     %false return from this function.
685  *
686  * Note:
687  *	The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
688  *      except in the consistency check at the end of this function.
689  *
690  * Return:
691  *     %false - this request doesn't have any more data
692  *     %true  - this request has more data
693  **/
694 bool blk_update_request(struct request *req, blk_status_t error,
695 		unsigned int nr_bytes)
696 {
697 	int total_bytes;
698 
699 	trace_block_rq_complete(req, error, nr_bytes);
700 
701 	if (!req->bio)
702 		return false;
703 
704 #ifdef CONFIG_BLK_DEV_INTEGRITY
705 	if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
706 	    error == BLK_STS_OK)
707 		req->q->integrity.profile->complete_fn(req, nr_bytes);
708 #endif
709 
710 	if (unlikely(error && !blk_rq_is_passthrough(req) &&
711 		     !(req->rq_flags & RQF_QUIET)))
712 		blk_print_req_error(req, error);
713 
714 	blk_account_io_completion(req, nr_bytes);
715 
716 	total_bytes = 0;
717 	while (req->bio) {
718 		struct bio *bio = req->bio;
719 		unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
720 
721 		if (bio_bytes == bio->bi_iter.bi_size)
722 			req->bio = bio->bi_next;
723 
724 		/* Completion has already been traced */
725 		bio_clear_flag(bio, BIO_TRACE_COMPLETION);
726 		req_bio_endio(req, bio, bio_bytes, error);
727 
728 		total_bytes += bio_bytes;
729 		nr_bytes -= bio_bytes;
730 
731 		if (!nr_bytes)
732 			break;
733 	}
734 
735 	/*
736 	 * completely done
737 	 */
738 	if (!req->bio) {
739 		/*
740 		 * Reset counters so that the request stacking driver
741 		 * can find how many bytes remain in the request
742 		 * later.
743 		 */
744 		req->__data_len = 0;
745 		return false;
746 	}
747 
748 	req->__data_len -= total_bytes;
749 
750 	/* update sector only for requests with clear definition of sector */
751 	if (!blk_rq_is_passthrough(req))
752 		req->__sector += total_bytes >> 9;
753 
754 	/* mixed attributes always follow the first bio */
755 	if (req->rq_flags & RQF_MIXED_MERGE) {
756 		req->cmd_flags &= ~REQ_FAILFAST_MASK;
757 		req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
758 	}
759 
760 	if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
761 		/*
762 		 * If total number of sectors is less than the first segment
763 		 * size, something has gone terribly wrong.
764 		 */
765 		if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
766 			blk_dump_rq_flags(req, "request botched");
767 			req->__data_len = blk_rq_cur_bytes(req);
768 		}
769 
770 		/* recalculate the number of segments */
771 		req->nr_phys_segments = blk_recalc_rq_segments(req);
772 	}
773 
774 	return true;
775 }
776 EXPORT_SYMBOL_GPL(blk_update_request);
777 
778 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
779 {
780 	if (rq->rq_flags & RQF_STATS) {
781 		blk_mq_poll_stats_start(rq->q);
782 		blk_stat_add(rq, now);
783 	}
784 
785 	blk_mq_sched_completed_request(rq, now);
786 	blk_account_io_done(rq, now);
787 }
788 
789 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
790 {
791 	if (blk_mq_need_time_stamp(rq))
792 		__blk_mq_end_request_acct(rq, ktime_get_ns());
793 
794 	if (rq->end_io) {
795 		rq_qos_done(rq->q, rq);
796 		rq->end_io(rq, error);
797 	} else {
798 		blk_mq_free_request(rq);
799 	}
800 }
801 EXPORT_SYMBOL(__blk_mq_end_request);
802 
803 void blk_mq_end_request(struct request *rq, blk_status_t error)
804 {
805 	if (blk_update_request(rq, error, blk_rq_bytes(rq)))
806 		BUG();
807 	__blk_mq_end_request(rq, error);
808 }
809 EXPORT_SYMBOL(blk_mq_end_request);
810 
811 #define TAG_COMP_BATCH		32
812 
813 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
814 					  int *tag_array, int nr_tags)
815 {
816 	struct request_queue *q = hctx->queue;
817 
818 	blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
819 	percpu_ref_put_many(&q->q_usage_counter, nr_tags);
820 }
821 
822 void blk_mq_end_request_batch(struct io_comp_batch *iob)
823 {
824 	int tags[TAG_COMP_BATCH], nr_tags = 0;
825 	struct blk_mq_hw_ctx *cur_hctx = NULL;
826 	struct request *rq;
827 	u64 now = 0;
828 
829 	if (iob->need_ts)
830 		now = ktime_get_ns();
831 
832 	while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
833 		prefetch(rq->bio);
834 		prefetch(rq->rq_next);
835 
836 		blk_update_request(rq, BLK_STS_OK, blk_rq_bytes(rq));
837 		if (iob->need_ts)
838 			__blk_mq_end_request_acct(rq, now);
839 
840 		WRITE_ONCE(rq->state, MQ_RQ_IDLE);
841 		if (!refcount_dec_and_test(&rq->ref))
842 			continue;
843 
844 		blk_crypto_free_request(rq);
845 		blk_pm_mark_last_busy(rq);
846 		rq_qos_done(rq->q, rq);
847 
848 		if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
849 			if (cur_hctx)
850 				blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
851 			nr_tags = 0;
852 			cur_hctx = rq->mq_hctx;
853 		}
854 		tags[nr_tags++] = rq->tag;
855 	}
856 
857 	if (nr_tags)
858 		blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
859 }
860 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
861 
862 static void blk_complete_reqs(struct llist_head *list)
863 {
864 	struct llist_node *entry = llist_reverse_order(llist_del_all(list));
865 	struct request *rq, *next;
866 
867 	llist_for_each_entry_safe(rq, next, entry, ipi_list)
868 		rq->q->mq_ops->complete(rq);
869 }
870 
871 static __latent_entropy void blk_done_softirq(struct softirq_action *h)
872 {
873 	blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
874 }
875 
876 static int blk_softirq_cpu_dead(unsigned int cpu)
877 {
878 	blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
879 	return 0;
880 }
881 
882 static void __blk_mq_complete_request_remote(void *data)
883 {
884 	__raise_softirq_irqoff(BLOCK_SOFTIRQ);
885 }
886 
887 static inline bool blk_mq_complete_need_ipi(struct request *rq)
888 {
889 	int cpu = raw_smp_processor_id();
890 
891 	if (!IS_ENABLED(CONFIG_SMP) ||
892 	    !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
893 		return false;
894 	/*
895 	 * With force threaded interrupts enabled, raising softirq from an SMP
896 	 * function call will always result in waking the ksoftirqd thread.
897 	 * This is probably worse than completing the request on a different
898 	 * cache domain.
899 	 */
900 	if (force_irqthreads())
901 		return false;
902 
903 	/* same CPU or cache domain?  Complete locally */
904 	if (cpu == rq->mq_ctx->cpu ||
905 	    (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
906 	     cpus_share_cache(cpu, rq->mq_ctx->cpu)))
907 		return false;
908 
909 	/* don't try to IPI to an offline CPU */
910 	return cpu_online(rq->mq_ctx->cpu);
911 }
912 
913 static void blk_mq_complete_send_ipi(struct request *rq)
914 {
915 	struct llist_head *list;
916 	unsigned int cpu;
917 
918 	cpu = rq->mq_ctx->cpu;
919 	list = &per_cpu(blk_cpu_done, cpu);
920 	if (llist_add(&rq->ipi_list, list)) {
921 		INIT_CSD(&rq->csd, __blk_mq_complete_request_remote, rq);
922 		smp_call_function_single_async(cpu, &rq->csd);
923 	}
924 }
925 
926 static void blk_mq_raise_softirq(struct request *rq)
927 {
928 	struct llist_head *list;
929 
930 	preempt_disable();
931 	list = this_cpu_ptr(&blk_cpu_done);
932 	if (llist_add(&rq->ipi_list, list))
933 		raise_softirq(BLOCK_SOFTIRQ);
934 	preempt_enable();
935 }
936 
937 bool blk_mq_complete_request_remote(struct request *rq)
938 {
939 	WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
940 
941 	/*
942 	 * For a polled request, always complete locallly, it's pointless
943 	 * to redirect the completion.
944 	 */
945 	if (rq->cmd_flags & REQ_POLLED)
946 		return false;
947 
948 	if (blk_mq_complete_need_ipi(rq)) {
949 		blk_mq_complete_send_ipi(rq);
950 		return true;
951 	}
952 
953 	if (rq->q->nr_hw_queues == 1) {
954 		blk_mq_raise_softirq(rq);
955 		return true;
956 	}
957 	return false;
958 }
959 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
960 
961 /**
962  * blk_mq_complete_request - end I/O on a request
963  * @rq:		the request being processed
964  *
965  * Description:
966  *	Complete a request by scheduling the ->complete_rq operation.
967  **/
968 void blk_mq_complete_request(struct request *rq)
969 {
970 	if (!blk_mq_complete_request_remote(rq))
971 		rq->q->mq_ops->complete(rq);
972 }
973 EXPORT_SYMBOL(blk_mq_complete_request);
974 
975 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
976 	__releases(hctx->srcu)
977 {
978 	if (!(hctx->flags & BLK_MQ_F_BLOCKING))
979 		rcu_read_unlock();
980 	else
981 		srcu_read_unlock(hctx->srcu, srcu_idx);
982 }
983 
984 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
985 	__acquires(hctx->srcu)
986 {
987 	if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
988 		/* shut up gcc false positive */
989 		*srcu_idx = 0;
990 		rcu_read_lock();
991 	} else
992 		*srcu_idx = srcu_read_lock(hctx->srcu);
993 }
994 
995 /**
996  * blk_mq_start_request - Start processing a request
997  * @rq: Pointer to request to be started
998  *
999  * Function used by device drivers to notify the block layer that a request
1000  * is going to be processed now, so blk layer can do proper initializations
1001  * such as starting the timeout timer.
1002  */
1003 void blk_mq_start_request(struct request *rq)
1004 {
1005 	struct request_queue *q = rq->q;
1006 
1007 	trace_block_rq_issue(rq);
1008 
1009 	if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
1010 		u64 start_time;
1011 #ifdef CONFIG_BLK_CGROUP
1012 		if (rq->bio)
1013 			start_time = bio_issue_time(&rq->bio->bi_issue);
1014 		else
1015 #endif
1016 			start_time = ktime_get_ns();
1017 		rq->io_start_time_ns = start_time;
1018 		rq->stats_sectors = blk_rq_sectors(rq);
1019 		rq->rq_flags |= RQF_STATS;
1020 		rq_qos_issue(q, rq);
1021 	}
1022 
1023 	WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1024 
1025 	blk_add_timer(rq);
1026 	WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1027 
1028 #ifdef CONFIG_BLK_DEV_INTEGRITY
1029 	if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1030 		q->integrity.profile->prepare_fn(rq);
1031 #endif
1032 	if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1033 	        WRITE_ONCE(rq->bio->bi_cookie, blk_rq_to_qc(rq));
1034 }
1035 EXPORT_SYMBOL(blk_mq_start_request);
1036 
1037 static void __blk_mq_requeue_request(struct request *rq)
1038 {
1039 	struct request_queue *q = rq->q;
1040 
1041 	blk_mq_put_driver_tag(rq);
1042 
1043 	trace_block_rq_requeue(rq);
1044 	rq_qos_requeue(q, rq);
1045 
1046 	if (blk_mq_request_started(rq)) {
1047 		WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1048 		rq->rq_flags &= ~RQF_TIMED_OUT;
1049 	}
1050 }
1051 
1052 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1053 {
1054 	__blk_mq_requeue_request(rq);
1055 
1056 	/* this request will be re-inserted to io scheduler queue */
1057 	blk_mq_sched_requeue_request(rq);
1058 
1059 	blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
1060 }
1061 EXPORT_SYMBOL(blk_mq_requeue_request);
1062 
1063 static void blk_mq_requeue_work(struct work_struct *work)
1064 {
1065 	struct request_queue *q =
1066 		container_of(work, struct request_queue, requeue_work.work);
1067 	LIST_HEAD(rq_list);
1068 	struct request *rq, *next;
1069 
1070 	spin_lock_irq(&q->requeue_lock);
1071 	list_splice_init(&q->requeue_list, &rq_list);
1072 	spin_unlock_irq(&q->requeue_lock);
1073 
1074 	list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
1075 		if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
1076 			continue;
1077 
1078 		rq->rq_flags &= ~RQF_SOFTBARRIER;
1079 		list_del_init(&rq->queuelist);
1080 		/*
1081 		 * If RQF_DONTPREP, rq has contained some driver specific
1082 		 * data, so insert it to hctx dispatch list to avoid any
1083 		 * merge.
1084 		 */
1085 		if (rq->rq_flags & RQF_DONTPREP)
1086 			blk_mq_request_bypass_insert(rq, false, false);
1087 		else
1088 			blk_mq_sched_insert_request(rq, true, false, false);
1089 	}
1090 
1091 	while (!list_empty(&rq_list)) {
1092 		rq = list_entry(rq_list.next, struct request, queuelist);
1093 		list_del_init(&rq->queuelist);
1094 		blk_mq_sched_insert_request(rq, false, false, false);
1095 	}
1096 
1097 	blk_mq_run_hw_queues(q, false);
1098 }
1099 
1100 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
1101 				bool kick_requeue_list)
1102 {
1103 	struct request_queue *q = rq->q;
1104 	unsigned long flags;
1105 
1106 	/*
1107 	 * We abuse this flag that is otherwise used by the I/O scheduler to
1108 	 * request head insertion from the workqueue.
1109 	 */
1110 	BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
1111 
1112 	spin_lock_irqsave(&q->requeue_lock, flags);
1113 	if (at_head) {
1114 		rq->rq_flags |= RQF_SOFTBARRIER;
1115 		list_add(&rq->queuelist, &q->requeue_list);
1116 	} else {
1117 		list_add_tail(&rq->queuelist, &q->requeue_list);
1118 	}
1119 	spin_unlock_irqrestore(&q->requeue_lock, flags);
1120 
1121 	if (kick_requeue_list)
1122 		blk_mq_kick_requeue_list(q);
1123 }
1124 
1125 void blk_mq_kick_requeue_list(struct request_queue *q)
1126 {
1127 	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1128 }
1129 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1130 
1131 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1132 				    unsigned long msecs)
1133 {
1134 	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1135 				    msecs_to_jiffies(msecs));
1136 }
1137 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1138 
1139 static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
1140 			       void *priv, bool reserved)
1141 {
1142 	/*
1143 	 * If we find a request that isn't idle and the queue matches,
1144 	 * we know the queue is busy. Return false to stop the iteration.
1145 	 */
1146 	if (blk_mq_request_started(rq) && rq->q == hctx->queue) {
1147 		bool *busy = priv;
1148 
1149 		*busy = true;
1150 		return false;
1151 	}
1152 
1153 	return true;
1154 }
1155 
1156 bool blk_mq_queue_inflight(struct request_queue *q)
1157 {
1158 	bool busy = false;
1159 
1160 	blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1161 	return busy;
1162 }
1163 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1164 
1165 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
1166 {
1167 	req->rq_flags |= RQF_TIMED_OUT;
1168 	if (req->q->mq_ops->timeout) {
1169 		enum blk_eh_timer_return ret;
1170 
1171 		ret = req->q->mq_ops->timeout(req, reserved);
1172 		if (ret == BLK_EH_DONE)
1173 			return;
1174 		WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1175 	}
1176 
1177 	blk_add_timer(req);
1178 }
1179 
1180 static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
1181 {
1182 	unsigned long deadline;
1183 
1184 	if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1185 		return false;
1186 	if (rq->rq_flags & RQF_TIMED_OUT)
1187 		return false;
1188 
1189 	deadline = READ_ONCE(rq->deadline);
1190 	if (time_after_eq(jiffies, deadline))
1191 		return true;
1192 
1193 	if (*next == 0)
1194 		*next = deadline;
1195 	else if (time_after(*next, deadline))
1196 		*next = deadline;
1197 	return false;
1198 }
1199 
1200 void blk_mq_put_rq_ref(struct request *rq)
1201 {
1202 	if (is_flush_rq(rq))
1203 		rq->end_io(rq, 0);
1204 	else if (refcount_dec_and_test(&rq->ref))
1205 		__blk_mq_free_request(rq);
1206 }
1207 
1208 static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
1209 		struct request *rq, void *priv, bool reserved)
1210 {
1211 	unsigned long *next = priv;
1212 
1213 	/*
1214 	 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1215 	 * be reallocated underneath the timeout handler's processing, then
1216 	 * the expire check is reliable. If the request is not expired, then
1217 	 * it was completed and reallocated as a new request after returning
1218 	 * from blk_mq_check_expired().
1219 	 */
1220 	if (blk_mq_req_expired(rq, next))
1221 		blk_mq_rq_timed_out(rq, reserved);
1222 	return true;
1223 }
1224 
1225 static void blk_mq_timeout_work(struct work_struct *work)
1226 {
1227 	struct request_queue *q =
1228 		container_of(work, struct request_queue, timeout_work);
1229 	unsigned long next = 0;
1230 	struct blk_mq_hw_ctx *hctx;
1231 	int i;
1232 
1233 	/* A deadlock might occur if a request is stuck requiring a
1234 	 * timeout at the same time a queue freeze is waiting
1235 	 * completion, since the timeout code would not be able to
1236 	 * acquire the queue reference here.
1237 	 *
1238 	 * That's why we don't use blk_queue_enter here; instead, we use
1239 	 * percpu_ref_tryget directly, because we need to be able to
1240 	 * obtain a reference even in the short window between the queue
1241 	 * starting to freeze, by dropping the first reference in
1242 	 * blk_freeze_queue_start, and the moment the last request is
1243 	 * consumed, marked by the instant q_usage_counter reaches
1244 	 * zero.
1245 	 */
1246 	if (!percpu_ref_tryget(&q->q_usage_counter))
1247 		return;
1248 
1249 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
1250 
1251 	if (next != 0) {
1252 		mod_timer(&q->timeout, next);
1253 	} else {
1254 		/*
1255 		 * Request timeouts are handled as a forward rolling timer. If
1256 		 * we end up here it means that no requests are pending and
1257 		 * also that no request has been pending for a while. Mark
1258 		 * each hctx as idle.
1259 		 */
1260 		queue_for_each_hw_ctx(q, hctx, i) {
1261 			/* the hctx may be unmapped, so check it here */
1262 			if (blk_mq_hw_queue_mapped(hctx))
1263 				blk_mq_tag_idle(hctx);
1264 		}
1265 	}
1266 	blk_queue_exit(q);
1267 }
1268 
1269 struct flush_busy_ctx_data {
1270 	struct blk_mq_hw_ctx *hctx;
1271 	struct list_head *list;
1272 };
1273 
1274 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1275 {
1276 	struct flush_busy_ctx_data *flush_data = data;
1277 	struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1278 	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1279 	enum hctx_type type = hctx->type;
1280 
1281 	spin_lock(&ctx->lock);
1282 	list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1283 	sbitmap_clear_bit(sb, bitnr);
1284 	spin_unlock(&ctx->lock);
1285 	return true;
1286 }
1287 
1288 /*
1289  * Process software queues that have been marked busy, splicing them
1290  * to the for-dispatch
1291  */
1292 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1293 {
1294 	struct flush_busy_ctx_data data = {
1295 		.hctx = hctx,
1296 		.list = list,
1297 	};
1298 
1299 	sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1300 }
1301 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1302 
1303 struct dispatch_rq_data {
1304 	struct blk_mq_hw_ctx *hctx;
1305 	struct request *rq;
1306 };
1307 
1308 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1309 		void *data)
1310 {
1311 	struct dispatch_rq_data *dispatch_data = data;
1312 	struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1313 	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1314 	enum hctx_type type = hctx->type;
1315 
1316 	spin_lock(&ctx->lock);
1317 	if (!list_empty(&ctx->rq_lists[type])) {
1318 		dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1319 		list_del_init(&dispatch_data->rq->queuelist);
1320 		if (list_empty(&ctx->rq_lists[type]))
1321 			sbitmap_clear_bit(sb, bitnr);
1322 	}
1323 	spin_unlock(&ctx->lock);
1324 
1325 	return !dispatch_data->rq;
1326 }
1327 
1328 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1329 					struct blk_mq_ctx *start)
1330 {
1331 	unsigned off = start ? start->index_hw[hctx->type] : 0;
1332 	struct dispatch_rq_data data = {
1333 		.hctx = hctx,
1334 		.rq   = NULL,
1335 	};
1336 
1337 	__sbitmap_for_each_set(&hctx->ctx_map, off,
1338 			       dispatch_rq_from_ctx, &data);
1339 
1340 	return data.rq;
1341 }
1342 
1343 static bool __blk_mq_alloc_driver_tag(struct request *rq)
1344 {
1345 	struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1346 	unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1347 	int tag;
1348 
1349 	blk_mq_tag_busy(rq->mq_hctx);
1350 
1351 	if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1352 		bt = &rq->mq_hctx->tags->breserved_tags;
1353 		tag_offset = 0;
1354 	} else {
1355 		if (!hctx_may_queue(rq->mq_hctx, bt))
1356 			return false;
1357 	}
1358 
1359 	tag = __sbitmap_queue_get(bt);
1360 	if (tag == BLK_MQ_NO_TAG)
1361 		return false;
1362 
1363 	rq->tag = tag + tag_offset;
1364 	return true;
1365 }
1366 
1367 bool __blk_mq_get_driver_tag(struct blk_mq_hw_ctx *hctx, struct request *rq)
1368 {
1369 	if (rq->tag == BLK_MQ_NO_TAG && !__blk_mq_alloc_driver_tag(rq))
1370 		return false;
1371 
1372 	if ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1373 			!(rq->rq_flags & RQF_MQ_INFLIGHT)) {
1374 		rq->rq_flags |= RQF_MQ_INFLIGHT;
1375 		__blk_mq_inc_active_requests(hctx);
1376 	}
1377 	hctx->tags->rqs[rq->tag] = rq;
1378 	return true;
1379 }
1380 
1381 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1382 				int flags, void *key)
1383 {
1384 	struct blk_mq_hw_ctx *hctx;
1385 
1386 	hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1387 
1388 	spin_lock(&hctx->dispatch_wait_lock);
1389 	if (!list_empty(&wait->entry)) {
1390 		struct sbitmap_queue *sbq;
1391 
1392 		list_del_init(&wait->entry);
1393 		sbq = &hctx->tags->bitmap_tags;
1394 		atomic_dec(&sbq->ws_active);
1395 	}
1396 	spin_unlock(&hctx->dispatch_wait_lock);
1397 
1398 	blk_mq_run_hw_queue(hctx, true);
1399 	return 1;
1400 }
1401 
1402 /*
1403  * Mark us waiting for a tag. For shared tags, this involves hooking us into
1404  * the tag wakeups. For non-shared tags, we can simply mark us needing a
1405  * restart. For both cases, take care to check the condition again after
1406  * marking us as waiting.
1407  */
1408 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1409 				 struct request *rq)
1410 {
1411 	struct sbitmap_queue *sbq = &hctx->tags->bitmap_tags;
1412 	struct wait_queue_head *wq;
1413 	wait_queue_entry_t *wait;
1414 	bool ret;
1415 
1416 	if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
1417 		blk_mq_sched_mark_restart_hctx(hctx);
1418 
1419 		/*
1420 		 * It's possible that a tag was freed in the window between the
1421 		 * allocation failure and adding the hardware queue to the wait
1422 		 * queue.
1423 		 *
1424 		 * Don't clear RESTART here, someone else could have set it.
1425 		 * At most this will cost an extra queue run.
1426 		 */
1427 		return blk_mq_get_driver_tag(rq);
1428 	}
1429 
1430 	wait = &hctx->dispatch_wait;
1431 	if (!list_empty_careful(&wait->entry))
1432 		return false;
1433 
1434 	wq = &bt_wait_ptr(sbq, hctx)->wait;
1435 
1436 	spin_lock_irq(&wq->lock);
1437 	spin_lock(&hctx->dispatch_wait_lock);
1438 	if (!list_empty(&wait->entry)) {
1439 		spin_unlock(&hctx->dispatch_wait_lock);
1440 		spin_unlock_irq(&wq->lock);
1441 		return false;
1442 	}
1443 
1444 	atomic_inc(&sbq->ws_active);
1445 	wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1446 	__add_wait_queue(wq, wait);
1447 
1448 	/*
1449 	 * It's possible that a tag was freed in the window between the
1450 	 * allocation failure and adding the hardware queue to the wait
1451 	 * queue.
1452 	 */
1453 	ret = blk_mq_get_driver_tag(rq);
1454 	if (!ret) {
1455 		spin_unlock(&hctx->dispatch_wait_lock);
1456 		spin_unlock_irq(&wq->lock);
1457 		return false;
1458 	}
1459 
1460 	/*
1461 	 * We got a tag, remove ourselves from the wait queue to ensure
1462 	 * someone else gets the wakeup.
1463 	 */
1464 	list_del_init(&wait->entry);
1465 	atomic_dec(&sbq->ws_active);
1466 	spin_unlock(&hctx->dispatch_wait_lock);
1467 	spin_unlock_irq(&wq->lock);
1468 
1469 	return true;
1470 }
1471 
1472 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT  8
1473 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR  4
1474 /*
1475  * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1476  * - EWMA is one simple way to compute running average value
1477  * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1478  * - take 4 as factor for avoiding to get too small(0) result, and this
1479  *   factor doesn't matter because EWMA decreases exponentially
1480  */
1481 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1482 {
1483 	unsigned int ewma;
1484 
1485 	ewma = hctx->dispatch_busy;
1486 
1487 	if (!ewma && !busy)
1488 		return;
1489 
1490 	ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1491 	if (busy)
1492 		ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1493 	ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1494 
1495 	hctx->dispatch_busy = ewma;
1496 }
1497 
1498 #define BLK_MQ_RESOURCE_DELAY	3		/* ms units */
1499 
1500 static void blk_mq_handle_dev_resource(struct request *rq,
1501 				       struct list_head *list)
1502 {
1503 	struct request *next =
1504 		list_first_entry_or_null(list, struct request, queuelist);
1505 
1506 	/*
1507 	 * If an I/O scheduler has been configured and we got a driver tag for
1508 	 * the next request already, free it.
1509 	 */
1510 	if (next)
1511 		blk_mq_put_driver_tag(next);
1512 
1513 	list_add(&rq->queuelist, list);
1514 	__blk_mq_requeue_request(rq);
1515 }
1516 
1517 static void blk_mq_handle_zone_resource(struct request *rq,
1518 					struct list_head *zone_list)
1519 {
1520 	/*
1521 	 * If we end up here it is because we cannot dispatch a request to a
1522 	 * specific zone due to LLD level zone-write locking or other zone
1523 	 * related resource not being available. In this case, set the request
1524 	 * aside in zone_list for retrying it later.
1525 	 */
1526 	list_add(&rq->queuelist, zone_list);
1527 	__blk_mq_requeue_request(rq);
1528 }
1529 
1530 enum prep_dispatch {
1531 	PREP_DISPATCH_OK,
1532 	PREP_DISPATCH_NO_TAG,
1533 	PREP_DISPATCH_NO_BUDGET,
1534 };
1535 
1536 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
1537 						  bool need_budget)
1538 {
1539 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1540 	int budget_token = -1;
1541 
1542 	if (need_budget) {
1543 		budget_token = blk_mq_get_dispatch_budget(rq->q);
1544 		if (budget_token < 0) {
1545 			blk_mq_put_driver_tag(rq);
1546 			return PREP_DISPATCH_NO_BUDGET;
1547 		}
1548 		blk_mq_set_rq_budget_token(rq, budget_token);
1549 	}
1550 
1551 	if (!blk_mq_get_driver_tag(rq)) {
1552 		/*
1553 		 * The initial allocation attempt failed, so we need to
1554 		 * rerun the hardware queue when a tag is freed. The
1555 		 * waitqueue takes care of that. If the queue is run
1556 		 * before we add this entry back on the dispatch list,
1557 		 * we'll re-run it below.
1558 		 */
1559 		if (!blk_mq_mark_tag_wait(hctx, rq)) {
1560 			/*
1561 			 * All budgets not got from this function will be put
1562 			 * together during handling partial dispatch
1563 			 */
1564 			if (need_budget)
1565 				blk_mq_put_dispatch_budget(rq->q, budget_token);
1566 			return PREP_DISPATCH_NO_TAG;
1567 		}
1568 	}
1569 
1570 	return PREP_DISPATCH_OK;
1571 }
1572 
1573 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
1574 static void blk_mq_release_budgets(struct request_queue *q,
1575 		struct list_head *list)
1576 {
1577 	struct request *rq;
1578 
1579 	list_for_each_entry(rq, list, queuelist) {
1580 		int budget_token = blk_mq_get_rq_budget_token(rq);
1581 
1582 		if (budget_token >= 0)
1583 			blk_mq_put_dispatch_budget(q, budget_token);
1584 	}
1585 }
1586 
1587 /*
1588  * Returns true if we did some work AND can potentially do more.
1589  */
1590 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
1591 			     unsigned int nr_budgets)
1592 {
1593 	enum prep_dispatch prep;
1594 	struct request_queue *q = hctx->queue;
1595 	struct request *rq, *nxt;
1596 	int errors, queued;
1597 	blk_status_t ret = BLK_STS_OK;
1598 	LIST_HEAD(zone_list);
1599 	bool needs_resource = false;
1600 
1601 	if (list_empty(list))
1602 		return false;
1603 
1604 	/*
1605 	 * Now process all the entries, sending them to the driver.
1606 	 */
1607 	errors = queued = 0;
1608 	do {
1609 		struct blk_mq_queue_data bd;
1610 
1611 		rq = list_first_entry(list, struct request, queuelist);
1612 
1613 		WARN_ON_ONCE(hctx != rq->mq_hctx);
1614 		prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
1615 		if (prep != PREP_DISPATCH_OK)
1616 			break;
1617 
1618 		list_del_init(&rq->queuelist);
1619 
1620 		bd.rq = rq;
1621 
1622 		/*
1623 		 * Flag last if we have no more requests, or if we have more
1624 		 * but can't assign a driver tag to it.
1625 		 */
1626 		if (list_empty(list))
1627 			bd.last = true;
1628 		else {
1629 			nxt = list_first_entry(list, struct request, queuelist);
1630 			bd.last = !blk_mq_get_driver_tag(nxt);
1631 		}
1632 
1633 		/*
1634 		 * once the request is queued to lld, no need to cover the
1635 		 * budget any more
1636 		 */
1637 		if (nr_budgets)
1638 			nr_budgets--;
1639 		ret = q->mq_ops->queue_rq(hctx, &bd);
1640 		switch (ret) {
1641 		case BLK_STS_OK:
1642 			queued++;
1643 			break;
1644 		case BLK_STS_RESOURCE:
1645 			needs_resource = true;
1646 			fallthrough;
1647 		case BLK_STS_DEV_RESOURCE:
1648 			blk_mq_handle_dev_resource(rq, list);
1649 			goto out;
1650 		case BLK_STS_ZONE_RESOURCE:
1651 			/*
1652 			 * Move the request to zone_list and keep going through
1653 			 * the dispatch list to find more requests the drive can
1654 			 * accept.
1655 			 */
1656 			blk_mq_handle_zone_resource(rq, &zone_list);
1657 			needs_resource = true;
1658 			break;
1659 		default:
1660 			errors++;
1661 			blk_mq_end_request(rq, ret);
1662 		}
1663 	} while (!list_empty(list));
1664 out:
1665 	if (!list_empty(&zone_list))
1666 		list_splice_tail_init(&zone_list, list);
1667 
1668 	/* If we didn't flush the entire list, we could have told the driver
1669 	 * there was more coming, but that turned out to be a lie.
1670 	 */
1671 	if ((!list_empty(list) || errors) && q->mq_ops->commit_rqs && queued)
1672 		q->mq_ops->commit_rqs(hctx);
1673 	/*
1674 	 * Any items that need requeuing? Stuff them into hctx->dispatch,
1675 	 * that is where we will continue on next queue run.
1676 	 */
1677 	if (!list_empty(list)) {
1678 		bool needs_restart;
1679 		/* For non-shared tags, the RESTART check will suffice */
1680 		bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
1681 			(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED);
1682 
1683 		if (nr_budgets)
1684 			blk_mq_release_budgets(q, list);
1685 
1686 		spin_lock(&hctx->lock);
1687 		list_splice_tail_init(list, &hctx->dispatch);
1688 		spin_unlock(&hctx->lock);
1689 
1690 		/*
1691 		 * Order adding requests to hctx->dispatch and checking
1692 		 * SCHED_RESTART flag. The pair of this smp_mb() is the one
1693 		 * in blk_mq_sched_restart(). Avoid restart code path to
1694 		 * miss the new added requests to hctx->dispatch, meantime
1695 		 * SCHED_RESTART is observed here.
1696 		 */
1697 		smp_mb();
1698 
1699 		/*
1700 		 * If SCHED_RESTART was set by the caller of this function and
1701 		 * it is no longer set that means that it was cleared by another
1702 		 * thread and hence that a queue rerun is needed.
1703 		 *
1704 		 * If 'no_tag' is set, that means that we failed getting
1705 		 * a driver tag with an I/O scheduler attached. If our dispatch
1706 		 * waitqueue is no longer active, ensure that we run the queue
1707 		 * AFTER adding our entries back to the list.
1708 		 *
1709 		 * If no I/O scheduler has been configured it is possible that
1710 		 * the hardware queue got stopped and restarted before requests
1711 		 * were pushed back onto the dispatch list. Rerun the queue to
1712 		 * avoid starvation. Notes:
1713 		 * - blk_mq_run_hw_queue() checks whether or not a queue has
1714 		 *   been stopped before rerunning a queue.
1715 		 * - Some but not all block drivers stop a queue before
1716 		 *   returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1717 		 *   and dm-rq.
1718 		 *
1719 		 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1720 		 * bit is set, run queue after a delay to avoid IO stalls
1721 		 * that could otherwise occur if the queue is idle.  We'll do
1722 		 * similar if we couldn't get budget or couldn't lock a zone
1723 		 * and SCHED_RESTART is set.
1724 		 */
1725 		needs_restart = blk_mq_sched_needs_restart(hctx);
1726 		if (prep == PREP_DISPATCH_NO_BUDGET)
1727 			needs_resource = true;
1728 		if (!needs_restart ||
1729 		    (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1730 			blk_mq_run_hw_queue(hctx, true);
1731 		else if (needs_restart && needs_resource)
1732 			blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1733 
1734 		blk_mq_update_dispatch_busy(hctx, true);
1735 		return false;
1736 	} else
1737 		blk_mq_update_dispatch_busy(hctx, false);
1738 
1739 	return (queued + errors) != 0;
1740 }
1741 
1742 /**
1743  * __blk_mq_run_hw_queue - Run a hardware queue.
1744  * @hctx: Pointer to the hardware queue to run.
1745  *
1746  * Send pending requests to the hardware.
1747  */
1748 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1749 {
1750 	int srcu_idx;
1751 
1752 	/*
1753 	 * We can't run the queue inline with ints disabled. Ensure that
1754 	 * we catch bad users of this early.
1755 	 */
1756 	WARN_ON_ONCE(in_interrupt());
1757 
1758 	might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1759 
1760 	hctx_lock(hctx, &srcu_idx);
1761 	blk_mq_sched_dispatch_requests(hctx);
1762 	hctx_unlock(hctx, srcu_idx);
1763 }
1764 
1765 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1766 {
1767 	int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1768 
1769 	if (cpu >= nr_cpu_ids)
1770 		cpu = cpumask_first(hctx->cpumask);
1771 	return cpu;
1772 }
1773 
1774 /*
1775  * It'd be great if the workqueue API had a way to pass
1776  * in a mask and had some smarts for more clever placement.
1777  * For now we just round-robin here, switching for every
1778  * BLK_MQ_CPU_WORK_BATCH queued items.
1779  */
1780 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1781 {
1782 	bool tried = false;
1783 	int next_cpu = hctx->next_cpu;
1784 
1785 	if (hctx->queue->nr_hw_queues == 1)
1786 		return WORK_CPU_UNBOUND;
1787 
1788 	if (--hctx->next_cpu_batch <= 0) {
1789 select_cpu:
1790 		next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
1791 				cpu_online_mask);
1792 		if (next_cpu >= nr_cpu_ids)
1793 			next_cpu = blk_mq_first_mapped_cpu(hctx);
1794 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1795 	}
1796 
1797 	/*
1798 	 * Do unbound schedule if we can't find a online CPU for this hctx,
1799 	 * and it should only happen in the path of handling CPU DEAD.
1800 	 */
1801 	if (!cpu_online(next_cpu)) {
1802 		if (!tried) {
1803 			tried = true;
1804 			goto select_cpu;
1805 		}
1806 
1807 		/*
1808 		 * Make sure to re-select CPU next time once after CPUs
1809 		 * in hctx->cpumask become online again.
1810 		 */
1811 		hctx->next_cpu = next_cpu;
1812 		hctx->next_cpu_batch = 1;
1813 		return WORK_CPU_UNBOUND;
1814 	}
1815 
1816 	hctx->next_cpu = next_cpu;
1817 	return next_cpu;
1818 }
1819 
1820 /**
1821  * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
1822  * @hctx: Pointer to the hardware queue to run.
1823  * @async: If we want to run the queue asynchronously.
1824  * @msecs: Milliseconds of delay to wait before running the queue.
1825  *
1826  * If !@async, try to run the queue now. Else, run the queue asynchronously and
1827  * with a delay of @msecs.
1828  */
1829 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1830 					unsigned long msecs)
1831 {
1832 	if (unlikely(blk_mq_hctx_stopped(hctx)))
1833 		return;
1834 
1835 	if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1836 		int cpu = get_cpu();
1837 		if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1838 			__blk_mq_run_hw_queue(hctx);
1839 			put_cpu();
1840 			return;
1841 		}
1842 
1843 		put_cpu();
1844 	}
1845 
1846 	kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1847 				    msecs_to_jiffies(msecs));
1848 }
1849 
1850 /**
1851  * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
1852  * @hctx: Pointer to the hardware queue to run.
1853  * @msecs: Milliseconds of delay to wait before running the queue.
1854  *
1855  * Run a hardware queue asynchronously with a delay of @msecs.
1856  */
1857 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1858 {
1859 	__blk_mq_delay_run_hw_queue(hctx, true, msecs);
1860 }
1861 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1862 
1863 /**
1864  * blk_mq_run_hw_queue - Start to run a hardware queue.
1865  * @hctx: Pointer to the hardware queue to run.
1866  * @async: If we want to run the queue asynchronously.
1867  *
1868  * Check if the request queue is not in a quiesced state and if there are
1869  * pending requests to be sent. If this is true, run the queue to send requests
1870  * to hardware.
1871  */
1872 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1873 {
1874 	int srcu_idx;
1875 	bool need_run;
1876 
1877 	/*
1878 	 * When queue is quiesced, we may be switching io scheduler, or
1879 	 * updating nr_hw_queues, or other things, and we can't run queue
1880 	 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1881 	 *
1882 	 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1883 	 * quiesced.
1884 	 */
1885 	hctx_lock(hctx, &srcu_idx);
1886 	need_run = !blk_queue_quiesced(hctx->queue) &&
1887 		blk_mq_hctx_has_pending(hctx);
1888 	hctx_unlock(hctx, srcu_idx);
1889 
1890 	if (need_run)
1891 		__blk_mq_delay_run_hw_queue(hctx, async, 0);
1892 }
1893 EXPORT_SYMBOL(blk_mq_run_hw_queue);
1894 
1895 /*
1896  * Is the request queue handled by an IO scheduler that does not respect
1897  * hardware queues when dispatching?
1898  */
1899 static bool blk_mq_has_sqsched(struct request_queue *q)
1900 {
1901 	struct elevator_queue *e = q->elevator;
1902 
1903 	if (e && e->type->ops.dispatch_request &&
1904 	    !(e->type->elevator_features & ELEVATOR_F_MQ_AWARE))
1905 		return true;
1906 	return false;
1907 }
1908 
1909 /*
1910  * Return prefered queue to dispatch from (if any) for non-mq aware IO
1911  * scheduler.
1912  */
1913 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
1914 {
1915 	struct blk_mq_hw_ctx *hctx;
1916 
1917 	/*
1918 	 * If the IO scheduler does not respect hardware queues when
1919 	 * dispatching, we just don't bother with multiple HW queues and
1920 	 * dispatch from hctx for the current CPU since running multiple queues
1921 	 * just causes lock contention inside the scheduler and pointless cache
1922 	 * bouncing.
1923 	 */
1924 	hctx = blk_mq_map_queue_type(q, HCTX_TYPE_DEFAULT,
1925 				     raw_smp_processor_id());
1926 	if (!blk_mq_hctx_stopped(hctx))
1927 		return hctx;
1928 	return NULL;
1929 }
1930 
1931 /**
1932  * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
1933  * @q: Pointer to the request queue to run.
1934  * @async: If we want to run the queue asynchronously.
1935  */
1936 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1937 {
1938 	struct blk_mq_hw_ctx *hctx, *sq_hctx;
1939 	int i;
1940 
1941 	sq_hctx = NULL;
1942 	if (blk_mq_has_sqsched(q))
1943 		sq_hctx = blk_mq_get_sq_hctx(q);
1944 	queue_for_each_hw_ctx(q, hctx, i) {
1945 		if (blk_mq_hctx_stopped(hctx))
1946 			continue;
1947 		/*
1948 		 * Dispatch from this hctx either if there's no hctx preferred
1949 		 * by IO scheduler or if it has requests that bypass the
1950 		 * scheduler.
1951 		 */
1952 		if (!sq_hctx || sq_hctx == hctx ||
1953 		    !list_empty_careful(&hctx->dispatch))
1954 			blk_mq_run_hw_queue(hctx, async);
1955 	}
1956 }
1957 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1958 
1959 /**
1960  * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
1961  * @q: Pointer to the request queue to run.
1962  * @msecs: Milliseconds of delay to wait before running the queues.
1963  */
1964 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
1965 {
1966 	struct blk_mq_hw_ctx *hctx, *sq_hctx;
1967 	int i;
1968 
1969 	sq_hctx = NULL;
1970 	if (blk_mq_has_sqsched(q))
1971 		sq_hctx = blk_mq_get_sq_hctx(q);
1972 	queue_for_each_hw_ctx(q, hctx, i) {
1973 		if (blk_mq_hctx_stopped(hctx))
1974 			continue;
1975 		/*
1976 		 * Dispatch from this hctx either if there's no hctx preferred
1977 		 * by IO scheduler or if it has requests that bypass the
1978 		 * scheduler.
1979 		 */
1980 		if (!sq_hctx || sq_hctx == hctx ||
1981 		    !list_empty_careful(&hctx->dispatch))
1982 			blk_mq_delay_run_hw_queue(hctx, msecs);
1983 	}
1984 }
1985 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
1986 
1987 /**
1988  * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1989  * @q: request queue.
1990  *
1991  * The caller is responsible for serializing this function against
1992  * blk_mq_{start,stop}_hw_queue().
1993  */
1994 bool blk_mq_queue_stopped(struct request_queue *q)
1995 {
1996 	struct blk_mq_hw_ctx *hctx;
1997 	int i;
1998 
1999 	queue_for_each_hw_ctx(q, hctx, i)
2000 		if (blk_mq_hctx_stopped(hctx))
2001 			return true;
2002 
2003 	return false;
2004 }
2005 EXPORT_SYMBOL(blk_mq_queue_stopped);
2006 
2007 /*
2008  * This function is often used for pausing .queue_rq() by driver when
2009  * there isn't enough resource or some conditions aren't satisfied, and
2010  * BLK_STS_RESOURCE is usually returned.
2011  *
2012  * We do not guarantee that dispatch can be drained or blocked
2013  * after blk_mq_stop_hw_queue() returns. Please use
2014  * blk_mq_quiesce_queue() for that requirement.
2015  */
2016 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2017 {
2018 	cancel_delayed_work(&hctx->run_work);
2019 
2020 	set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2021 }
2022 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2023 
2024 /*
2025  * This function is often used for pausing .queue_rq() by driver when
2026  * there isn't enough resource or some conditions aren't satisfied, and
2027  * BLK_STS_RESOURCE is usually returned.
2028  *
2029  * We do not guarantee that dispatch can be drained or blocked
2030  * after blk_mq_stop_hw_queues() returns. Please use
2031  * blk_mq_quiesce_queue() for that requirement.
2032  */
2033 void blk_mq_stop_hw_queues(struct request_queue *q)
2034 {
2035 	struct blk_mq_hw_ctx *hctx;
2036 	int i;
2037 
2038 	queue_for_each_hw_ctx(q, hctx, i)
2039 		blk_mq_stop_hw_queue(hctx);
2040 }
2041 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2042 
2043 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2044 {
2045 	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2046 
2047 	blk_mq_run_hw_queue(hctx, false);
2048 }
2049 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2050 
2051 void blk_mq_start_hw_queues(struct request_queue *q)
2052 {
2053 	struct blk_mq_hw_ctx *hctx;
2054 	int i;
2055 
2056 	queue_for_each_hw_ctx(q, hctx, i)
2057 		blk_mq_start_hw_queue(hctx);
2058 }
2059 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2060 
2061 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2062 {
2063 	if (!blk_mq_hctx_stopped(hctx))
2064 		return;
2065 
2066 	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2067 	blk_mq_run_hw_queue(hctx, async);
2068 }
2069 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2070 
2071 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2072 {
2073 	struct blk_mq_hw_ctx *hctx;
2074 	int i;
2075 
2076 	queue_for_each_hw_ctx(q, hctx, i)
2077 		blk_mq_start_stopped_hw_queue(hctx, async);
2078 }
2079 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2080 
2081 static void blk_mq_run_work_fn(struct work_struct *work)
2082 {
2083 	struct blk_mq_hw_ctx *hctx;
2084 
2085 	hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
2086 
2087 	/*
2088 	 * If we are stopped, don't run the queue.
2089 	 */
2090 	if (blk_mq_hctx_stopped(hctx))
2091 		return;
2092 
2093 	__blk_mq_run_hw_queue(hctx);
2094 }
2095 
2096 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
2097 					    struct request *rq,
2098 					    bool at_head)
2099 {
2100 	struct blk_mq_ctx *ctx = rq->mq_ctx;
2101 	enum hctx_type type = hctx->type;
2102 
2103 	lockdep_assert_held(&ctx->lock);
2104 
2105 	trace_block_rq_insert(rq);
2106 
2107 	if (at_head)
2108 		list_add(&rq->queuelist, &ctx->rq_lists[type]);
2109 	else
2110 		list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
2111 }
2112 
2113 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
2114 			     bool at_head)
2115 {
2116 	struct blk_mq_ctx *ctx = rq->mq_ctx;
2117 
2118 	lockdep_assert_held(&ctx->lock);
2119 
2120 	__blk_mq_insert_req_list(hctx, rq, at_head);
2121 	blk_mq_hctx_mark_pending(hctx, ctx);
2122 }
2123 
2124 /**
2125  * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2126  * @rq: Pointer to request to be inserted.
2127  * @at_head: true if the request should be inserted at the head of the list.
2128  * @run_queue: If we should run the hardware queue after inserting the request.
2129  *
2130  * Should only be used carefully, when the caller knows we want to
2131  * bypass a potential IO scheduler on the target device.
2132  */
2133 void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
2134 				  bool run_queue)
2135 {
2136 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2137 
2138 	spin_lock(&hctx->lock);
2139 	if (at_head)
2140 		list_add(&rq->queuelist, &hctx->dispatch);
2141 	else
2142 		list_add_tail(&rq->queuelist, &hctx->dispatch);
2143 	spin_unlock(&hctx->lock);
2144 
2145 	if (run_queue)
2146 		blk_mq_run_hw_queue(hctx, false);
2147 }
2148 
2149 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
2150 			    struct list_head *list)
2151 
2152 {
2153 	struct request *rq;
2154 	enum hctx_type type = hctx->type;
2155 
2156 	/*
2157 	 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2158 	 * offline now
2159 	 */
2160 	list_for_each_entry(rq, list, queuelist) {
2161 		BUG_ON(rq->mq_ctx != ctx);
2162 		trace_block_rq_insert(rq);
2163 	}
2164 
2165 	spin_lock(&ctx->lock);
2166 	list_splice_tail_init(list, &ctx->rq_lists[type]);
2167 	blk_mq_hctx_mark_pending(hctx, ctx);
2168 	spin_unlock(&ctx->lock);
2169 }
2170 
2171 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int *queued,
2172 			      bool from_schedule)
2173 {
2174 	if (hctx->queue->mq_ops->commit_rqs) {
2175 		trace_block_unplug(hctx->queue, *queued, !from_schedule);
2176 		hctx->queue->mq_ops->commit_rqs(hctx);
2177 	}
2178 	*queued = 0;
2179 }
2180 
2181 static void blk_mq_plug_issue_direct(struct blk_plug *plug, bool from_schedule)
2182 {
2183 	struct blk_mq_hw_ctx *hctx = NULL;
2184 	struct request *rq;
2185 	int queued = 0;
2186 	int errors = 0;
2187 
2188 	while ((rq = rq_list_pop(&plug->mq_list))) {
2189 		bool last = rq_list_empty(plug->mq_list);
2190 		blk_status_t ret;
2191 
2192 		if (hctx != rq->mq_hctx) {
2193 			if (hctx)
2194 				blk_mq_commit_rqs(hctx, &queued, from_schedule);
2195 			hctx = rq->mq_hctx;
2196 		}
2197 
2198 		ret = blk_mq_request_issue_directly(rq, last);
2199 		switch (ret) {
2200 		case BLK_STS_OK:
2201 			queued++;
2202 			break;
2203 		case BLK_STS_RESOURCE:
2204 		case BLK_STS_DEV_RESOURCE:
2205 			blk_mq_request_bypass_insert(rq, false, last);
2206 			blk_mq_commit_rqs(hctx, &queued, from_schedule);
2207 			return;
2208 		default:
2209 			blk_mq_end_request(rq, ret);
2210 			errors++;
2211 			break;
2212 		}
2213 	}
2214 
2215 	/*
2216 	 * If we didn't flush the entire list, we could have told the driver
2217 	 * there was more coming, but that turned out to be a lie.
2218 	 */
2219 	if (errors)
2220 		blk_mq_commit_rqs(hctx, &queued, from_schedule);
2221 }
2222 
2223 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2224 {
2225 	struct blk_mq_hw_ctx *this_hctx;
2226 	struct blk_mq_ctx *this_ctx;
2227 	unsigned int depth;
2228 	LIST_HEAD(list);
2229 
2230 	if (rq_list_empty(plug->mq_list))
2231 		return;
2232 	plug->rq_count = 0;
2233 
2234 	if (!plug->multiple_queues && !plug->has_elevator && !from_schedule) {
2235 		blk_mq_plug_issue_direct(plug, from_schedule);
2236 		if (rq_list_empty(plug->mq_list))
2237 			return;
2238 	}
2239 
2240 	this_hctx = NULL;
2241 	this_ctx = NULL;
2242 	depth = 0;
2243 	do {
2244 		struct request *rq;
2245 
2246 		rq = rq_list_pop(&plug->mq_list);
2247 
2248 		if (!this_hctx) {
2249 			this_hctx = rq->mq_hctx;
2250 			this_ctx = rq->mq_ctx;
2251 		} else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx) {
2252 			trace_block_unplug(this_hctx->queue, depth,
2253 						!from_schedule);
2254 			blk_mq_sched_insert_requests(this_hctx, this_ctx,
2255 						&list, from_schedule);
2256 			depth = 0;
2257 			this_hctx = rq->mq_hctx;
2258 			this_ctx = rq->mq_ctx;
2259 
2260 		}
2261 
2262 		list_add(&rq->queuelist, &list);
2263 		depth++;
2264 	} while (!rq_list_empty(plug->mq_list));
2265 
2266 	if (!list_empty(&list)) {
2267 		trace_block_unplug(this_hctx->queue, depth, !from_schedule);
2268 		blk_mq_sched_insert_requests(this_hctx, this_ctx, &list,
2269 						from_schedule);
2270 	}
2271 }
2272 
2273 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2274 		unsigned int nr_segs)
2275 {
2276 	int err;
2277 
2278 	if (bio->bi_opf & REQ_RAHEAD)
2279 		rq->cmd_flags |= REQ_FAILFAST_MASK;
2280 
2281 	rq->__sector = bio->bi_iter.bi_sector;
2282 	rq->write_hint = bio->bi_write_hint;
2283 	blk_rq_bio_prep(rq, bio, nr_segs);
2284 
2285 	/* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2286 	err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2287 	WARN_ON_ONCE(err);
2288 
2289 	blk_account_io_start(rq);
2290 }
2291 
2292 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2293 					    struct request *rq, bool last)
2294 {
2295 	struct request_queue *q = rq->q;
2296 	struct blk_mq_queue_data bd = {
2297 		.rq = rq,
2298 		.last = last,
2299 	};
2300 	blk_status_t ret;
2301 
2302 	/*
2303 	 * For OK queue, we are done. For error, caller may kill it.
2304 	 * Any other error (busy), just add it to our list as we
2305 	 * previously would have done.
2306 	 */
2307 	ret = q->mq_ops->queue_rq(hctx, &bd);
2308 	switch (ret) {
2309 	case BLK_STS_OK:
2310 		blk_mq_update_dispatch_busy(hctx, false);
2311 		break;
2312 	case BLK_STS_RESOURCE:
2313 	case BLK_STS_DEV_RESOURCE:
2314 		blk_mq_update_dispatch_busy(hctx, true);
2315 		__blk_mq_requeue_request(rq);
2316 		break;
2317 	default:
2318 		blk_mq_update_dispatch_busy(hctx, false);
2319 		break;
2320 	}
2321 
2322 	return ret;
2323 }
2324 
2325 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2326 						struct request *rq,
2327 						bool bypass_insert, bool last)
2328 {
2329 	struct request_queue *q = rq->q;
2330 	bool run_queue = true;
2331 	int budget_token;
2332 
2333 	/*
2334 	 * RCU or SRCU read lock is needed before checking quiesced flag.
2335 	 *
2336 	 * When queue is stopped or quiesced, ignore 'bypass_insert' from
2337 	 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
2338 	 * and avoid driver to try to dispatch again.
2339 	 */
2340 	if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
2341 		run_queue = false;
2342 		bypass_insert = false;
2343 		goto insert;
2344 	}
2345 
2346 	if ((rq->rq_flags & RQF_ELV) && !bypass_insert)
2347 		goto insert;
2348 
2349 	budget_token = blk_mq_get_dispatch_budget(q);
2350 	if (budget_token < 0)
2351 		goto insert;
2352 
2353 	blk_mq_set_rq_budget_token(rq, budget_token);
2354 
2355 	if (!blk_mq_get_driver_tag(rq)) {
2356 		blk_mq_put_dispatch_budget(q, budget_token);
2357 		goto insert;
2358 	}
2359 
2360 	return __blk_mq_issue_directly(hctx, rq, last);
2361 insert:
2362 	if (bypass_insert)
2363 		return BLK_STS_RESOURCE;
2364 
2365 	blk_mq_sched_insert_request(rq, false, run_queue, false);
2366 
2367 	return BLK_STS_OK;
2368 }
2369 
2370 /**
2371  * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2372  * @hctx: Pointer of the associated hardware queue.
2373  * @rq: Pointer to request to be sent.
2374  *
2375  * If the device has enough resources to accept a new request now, send the
2376  * request directly to device driver. Else, insert at hctx->dispatch queue, so
2377  * we can try send it another time in the future. Requests inserted at this
2378  * queue have higher priority.
2379  */
2380 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2381 		struct request *rq)
2382 {
2383 	blk_status_t ret;
2384 	int srcu_idx;
2385 
2386 	might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
2387 
2388 	hctx_lock(hctx, &srcu_idx);
2389 
2390 	ret = __blk_mq_try_issue_directly(hctx, rq, false, true);
2391 	if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
2392 		blk_mq_request_bypass_insert(rq, false, true);
2393 	else if (ret != BLK_STS_OK)
2394 		blk_mq_end_request(rq, ret);
2395 
2396 	hctx_unlock(hctx, srcu_idx);
2397 }
2398 
2399 blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2400 {
2401 	blk_status_t ret;
2402 	int srcu_idx;
2403 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2404 
2405 	hctx_lock(hctx, &srcu_idx);
2406 	ret = __blk_mq_try_issue_directly(hctx, rq, true, last);
2407 	hctx_unlock(hctx, srcu_idx);
2408 
2409 	return ret;
2410 }
2411 
2412 void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2413 		struct list_head *list)
2414 {
2415 	int queued = 0;
2416 	int errors = 0;
2417 
2418 	while (!list_empty(list)) {
2419 		blk_status_t ret;
2420 		struct request *rq = list_first_entry(list, struct request,
2421 				queuelist);
2422 
2423 		list_del_init(&rq->queuelist);
2424 		ret = blk_mq_request_issue_directly(rq, list_empty(list));
2425 		if (ret != BLK_STS_OK) {
2426 			if (ret == BLK_STS_RESOURCE ||
2427 					ret == BLK_STS_DEV_RESOURCE) {
2428 				blk_mq_request_bypass_insert(rq, false,
2429 							list_empty(list));
2430 				break;
2431 			}
2432 			blk_mq_end_request(rq, ret);
2433 			errors++;
2434 		} else
2435 			queued++;
2436 	}
2437 
2438 	/*
2439 	 * If we didn't flush the entire list, we could have told
2440 	 * the driver there was more coming, but that turned out to
2441 	 * be a lie.
2442 	 */
2443 	if ((!list_empty(list) || errors) &&
2444 	     hctx->queue->mq_ops->commit_rqs && queued)
2445 		hctx->queue->mq_ops->commit_rqs(hctx);
2446 }
2447 
2448 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2449 {
2450 	if (!plug->multiple_queues) {
2451 		struct request *nxt = rq_list_peek(&plug->mq_list);
2452 
2453 		if (nxt && nxt->q != rq->q)
2454 			plug->multiple_queues = true;
2455 	}
2456 	if (!plug->has_elevator && (rq->rq_flags & RQF_ELV))
2457 		plug->has_elevator = true;
2458 	rq->rq_next = NULL;
2459 	rq_list_add(&plug->mq_list, rq);
2460 	plug->rq_count++;
2461 }
2462 
2463 /*
2464  * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
2465  * queues. This is important for md arrays to benefit from merging
2466  * requests.
2467  */
2468 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
2469 {
2470 	if (plug->multiple_queues)
2471 		return BLK_MAX_REQUEST_COUNT * 2;
2472 	return BLK_MAX_REQUEST_COUNT;
2473 }
2474 
2475 /**
2476  * blk_mq_submit_bio - Create and send a request to block device.
2477  * @bio: Bio pointer.
2478  *
2479  * Builds up a request structure from @q and @bio and send to the device. The
2480  * request may not be queued directly to hardware if:
2481  * * This request can be merged with another one
2482  * * We want to place request at plug queue for possible future merging
2483  * * There is an IO scheduler active at this queue
2484  *
2485  * It will not queue the request if there is an error with the bio, or at the
2486  * request creation.
2487  */
2488 void blk_mq_submit_bio(struct bio *bio)
2489 {
2490 	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2491 	const int is_sync = op_is_sync(bio->bi_opf);
2492 	struct request *rq;
2493 	struct blk_plug *plug;
2494 	bool same_queue_rq = false;
2495 	unsigned int nr_segs = 1;
2496 	blk_status_t ret;
2497 
2498 	blk_queue_bounce(q, &bio);
2499 	if (blk_may_split(q, bio))
2500 		__blk_queue_split(q, &bio, &nr_segs);
2501 
2502 	if (!bio_integrity_prep(bio))
2503 		goto queue_exit;
2504 
2505 	if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
2506 		if (blk_attempt_plug_merge(q, bio, nr_segs, &same_queue_rq))
2507 			goto queue_exit;
2508 		if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2509 			goto queue_exit;
2510 	}
2511 
2512 	rq_qos_throttle(q, bio);
2513 
2514 	plug = blk_mq_plug(q, bio);
2515 	if (plug && plug->cached_rq) {
2516 		rq = rq_list_pop(&plug->cached_rq);
2517 		INIT_LIST_HEAD(&rq->queuelist);
2518 	} else {
2519 		struct blk_mq_alloc_data data = {
2520 			.q		= q,
2521 			.nr_tags	= 1,
2522 			.cmd_flags	= bio->bi_opf,
2523 			.rq_flags	= q->elevator ? RQF_ELV : 0,
2524 		};
2525 
2526 		if (plug) {
2527 			data.nr_tags = plug->nr_ios;
2528 			plug->nr_ios = 1;
2529 			data.cached_rq = &plug->cached_rq;
2530 		}
2531 		rq = __blk_mq_alloc_requests(&data);
2532 		if (unlikely(!rq)) {
2533 			rq_qos_cleanup(q, bio);
2534 			if (bio->bi_opf & REQ_NOWAIT)
2535 				bio_wouldblock_error(bio);
2536 			goto queue_exit;
2537 		}
2538 	}
2539 
2540 	trace_block_getrq(bio);
2541 
2542 	rq_qos_track(q, rq, bio);
2543 
2544 	blk_mq_bio_to_request(rq, bio, nr_segs);
2545 
2546 	ret = blk_crypto_init_request(rq);
2547 	if (ret != BLK_STS_OK) {
2548 		bio->bi_status = ret;
2549 		bio_endio(bio);
2550 		blk_mq_free_request(rq);
2551 		return;
2552 	}
2553 
2554 	if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
2555 		return;
2556 
2557 	if (plug && (q->nr_hw_queues == 1 ||
2558 	    blk_mq_is_shared_tags(rq->mq_hctx->flags) ||
2559 	    q->mq_ops->commit_rqs || !blk_queue_nonrot(q))) {
2560 		/*
2561 		 * Use plugging if we have a ->commit_rqs() hook as well, as
2562 		 * we know the driver uses bd->last in a smart fashion.
2563 		 *
2564 		 * Use normal plugging if this disk is slow HDD, as sequential
2565 		 * IO may benefit a lot from plug merging.
2566 		 */
2567 		unsigned int request_count = plug->rq_count;
2568 		struct request *last = NULL;
2569 
2570 		if (!request_count) {
2571 			trace_block_plug(q);
2572 		} else if (!blk_queue_nomerges(q)) {
2573 			last = rq_list_peek(&plug->mq_list);
2574 			if (blk_rq_bytes(last) < BLK_PLUG_FLUSH_SIZE)
2575 				last = NULL;
2576 		}
2577 
2578 		if (request_count >= blk_plug_max_rq_count(plug) || last) {
2579 			blk_mq_flush_plug_list(plug, false);
2580 			trace_block_plug(q);
2581 		}
2582 
2583 		blk_add_rq_to_plug(plug, rq);
2584 	} else if (rq->rq_flags & RQF_ELV) {
2585 		/* Insert the request at the IO scheduler queue */
2586 		blk_mq_sched_insert_request(rq, false, true, true);
2587 	} else if (plug && !blk_queue_nomerges(q)) {
2588 		struct request *next_rq = NULL;
2589 
2590 		/*
2591 		 * We do limited plugging. If the bio can be merged, do that.
2592 		 * Otherwise the existing request in the plug list will be
2593 		 * issued. So the plug list will have one request at most
2594 		 * The plug list might get flushed before this. If that happens,
2595 		 * the plug list is empty, and same_queue_rq is invalid.
2596 		 */
2597 		if (same_queue_rq) {
2598 			next_rq = rq_list_pop(&plug->mq_list);
2599 			plug->rq_count--;
2600 		}
2601 		blk_add_rq_to_plug(plug, rq);
2602 		trace_block_plug(q);
2603 
2604 		if (next_rq) {
2605 			trace_block_unplug(q, 1, true);
2606 			blk_mq_try_issue_directly(next_rq->mq_hctx, next_rq);
2607 		}
2608 	} else if ((q->nr_hw_queues > 1 && is_sync) ||
2609 		   !rq->mq_hctx->dispatch_busy) {
2610 		/*
2611 		 * There is no scheduler and we can try to send directly
2612 		 * to the hardware.
2613 		 */
2614 		blk_mq_try_issue_directly(rq->mq_hctx, rq);
2615 	} else {
2616 		/* Default case. */
2617 		blk_mq_sched_insert_request(rq, false, true, true);
2618 	}
2619 
2620 	return;
2621 queue_exit:
2622 	blk_queue_exit(q);
2623 }
2624 
2625 static size_t order_to_size(unsigned int order)
2626 {
2627 	return (size_t)PAGE_SIZE << order;
2628 }
2629 
2630 /* called before freeing request pool in @tags */
2631 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
2632 				    struct blk_mq_tags *tags)
2633 {
2634 	struct page *page;
2635 	unsigned long flags;
2636 
2637 	/* There is no need to clear a driver tags own mapping */
2638 	if (drv_tags == tags)
2639 		return;
2640 
2641 	list_for_each_entry(page, &tags->page_list, lru) {
2642 		unsigned long start = (unsigned long)page_address(page);
2643 		unsigned long end = start + order_to_size(page->private);
2644 		int i;
2645 
2646 		for (i = 0; i < drv_tags->nr_tags; i++) {
2647 			struct request *rq = drv_tags->rqs[i];
2648 			unsigned long rq_addr = (unsigned long)rq;
2649 
2650 			if (rq_addr >= start && rq_addr < end) {
2651 				WARN_ON_ONCE(refcount_read(&rq->ref) != 0);
2652 				cmpxchg(&drv_tags->rqs[i], rq, NULL);
2653 			}
2654 		}
2655 	}
2656 
2657 	/*
2658 	 * Wait until all pending iteration is done.
2659 	 *
2660 	 * Request reference is cleared and it is guaranteed to be observed
2661 	 * after the ->lock is released.
2662 	 */
2663 	spin_lock_irqsave(&drv_tags->lock, flags);
2664 	spin_unlock_irqrestore(&drv_tags->lock, flags);
2665 }
2666 
2667 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2668 		     unsigned int hctx_idx)
2669 {
2670 	struct blk_mq_tags *drv_tags;
2671 	struct page *page;
2672 
2673 	if (blk_mq_is_shared_tags(set->flags))
2674 		drv_tags = set->shared_tags;
2675 	else
2676 		drv_tags = set->tags[hctx_idx];
2677 
2678 	if (tags->static_rqs && set->ops->exit_request) {
2679 		int i;
2680 
2681 		for (i = 0; i < tags->nr_tags; i++) {
2682 			struct request *rq = tags->static_rqs[i];
2683 
2684 			if (!rq)
2685 				continue;
2686 			set->ops->exit_request(set, rq, hctx_idx);
2687 			tags->static_rqs[i] = NULL;
2688 		}
2689 	}
2690 
2691 	blk_mq_clear_rq_mapping(drv_tags, tags);
2692 
2693 	while (!list_empty(&tags->page_list)) {
2694 		page = list_first_entry(&tags->page_list, struct page, lru);
2695 		list_del_init(&page->lru);
2696 		/*
2697 		 * Remove kmemleak object previously allocated in
2698 		 * blk_mq_alloc_rqs().
2699 		 */
2700 		kmemleak_free(page_address(page));
2701 		__free_pages(page, page->private);
2702 	}
2703 }
2704 
2705 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
2706 {
2707 	kfree(tags->rqs);
2708 	tags->rqs = NULL;
2709 	kfree(tags->static_rqs);
2710 	tags->static_rqs = NULL;
2711 
2712 	blk_mq_free_tags(tags);
2713 }
2714 
2715 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2716 					       unsigned int hctx_idx,
2717 					       unsigned int nr_tags,
2718 					       unsigned int reserved_tags)
2719 {
2720 	struct blk_mq_tags *tags;
2721 	int node;
2722 
2723 	node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2724 	if (node == NUMA_NO_NODE)
2725 		node = set->numa_node;
2726 
2727 	tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
2728 				BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
2729 	if (!tags)
2730 		return NULL;
2731 
2732 	tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2733 				 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2734 				 node);
2735 	if (!tags->rqs) {
2736 		blk_mq_free_tags(tags);
2737 		return NULL;
2738 	}
2739 
2740 	tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2741 					GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2742 					node);
2743 	if (!tags->static_rqs) {
2744 		kfree(tags->rqs);
2745 		blk_mq_free_tags(tags);
2746 		return NULL;
2747 	}
2748 
2749 	return tags;
2750 }
2751 
2752 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2753 			       unsigned int hctx_idx, int node)
2754 {
2755 	int ret;
2756 
2757 	if (set->ops->init_request) {
2758 		ret = set->ops->init_request(set, rq, hctx_idx, node);
2759 		if (ret)
2760 			return ret;
2761 	}
2762 
2763 	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
2764 	return 0;
2765 }
2766 
2767 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
2768 			    struct blk_mq_tags *tags,
2769 			    unsigned int hctx_idx, unsigned int depth)
2770 {
2771 	unsigned int i, j, entries_per_page, max_order = 4;
2772 	size_t rq_size, left;
2773 	int node;
2774 
2775 	node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2776 	if (node == NUMA_NO_NODE)
2777 		node = set->numa_node;
2778 
2779 	INIT_LIST_HEAD(&tags->page_list);
2780 
2781 	/*
2782 	 * rq_size is the size of the request plus driver payload, rounded
2783 	 * to the cacheline size
2784 	 */
2785 	rq_size = round_up(sizeof(struct request) + set->cmd_size,
2786 				cache_line_size());
2787 	left = rq_size * depth;
2788 
2789 	for (i = 0; i < depth; ) {
2790 		int this_order = max_order;
2791 		struct page *page;
2792 		int to_do;
2793 		void *p;
2794 
2795 		while (this_order && left < order_to_size(this_order - 1))
2796 			this_order--;
2797 
2798 		do {
2799 			page = alloc_pages_node(node,
2800 				GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
2801 				this_order);
2802 			if (page)
2803 				break;
2804 			if (!this_order--)
2805 				break;
2806 			if (order_to_size(this_order) < rq_size)
2807 				break;
2808 		} while (1);
2809 
2810 		if (!page)
2811 			goto fail;
2812 
2813 		page->private = this_order;
2814 		list_add_tail(&page->lru, &tags->page_list);
2815 
2816 		p = page_address(page);
2817 		/*
2818 		 * Allow kmemleak to scan these pages as they contain pointers
2819 		 * to additional allocations like via ops->init_request().
2820 		 */
2821 		kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
2822 		entries_per_page = order_to_size(this_order) / rq_size;
2823 		to_do = min(entries_per_page, depth - i);
2824 		left -= to_do * rq_size;
2825 		for (j = 0; j < to_do; j++) {
2826 			struct request *rq = p;
2827 
2828 			tags->static_rqs[i] = rq;
2829 			if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2830 				tags->static_rqs[i] = NULL;
2831 				goto fail;
2832 			}
2833 
2834 			p += rq_size;
2835 			i++;
2836 		}
2837 	}
2838 	return 0;
2839 
2840 fail:
2841 	blk_mq_free_rqs(set, tags, hctx_idx);
2842 	return -ENOMEM;
2843 }
2844 
2845 struct rq_iter_data {
2846 	struct blk_mq_hw_ctx *hctx;
2847 	bool has_rq;
2848 };
2849 
2850 static bool blk_mq_has_request(struct request *rq, void *data, bool reserved)
2851 {
2852 	struct rq_iter_data *iter_data = data;
2853 
2854 	if (rq->mq_hctx != iter_data->hctx)
2855 		return true;
2856 	iter_data->has_rq = true;
2857 	return false;
2858 }
2859 
2860 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
2861 {
2862 	struct blk_mq_tags *tags = hctx->sched_tags ?
2863 			hctx->sched_tags : hctx->tags;
2864 	struct rq_iter_data data = {
2865 		.hctx	= hctx,
2866 	};
2867 
2868 	blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
2869 	return data.has_rq;
2870 }
2871 
2872 static inline bool blk_mq_last_cpu_in_hctx(unsigned int cpu,
2873 		struct blk_mq_hw_ctx *hctx)
2874 {
2875 	if (cpumask_next_and(-1, hctx->cpumask, cpu_online_mask) != cpu)
2876 		return false;
2877 	if (cpumask_next_and(cpu, hctx->cpumask, cpu_online_mask) < nr_cpu_ids)
2878 		return false;
2879 	return true;
2880 }
2881 
2882 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
2883 {
2884 	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2885 			struct blk_mq_hw_ctx, cpuhp_online);
2886 
2887 	if (!cpumask_test_cpu(cpu, hctx->cpumask) ||
2888 	    !blk_mq_last_cpu_in_hctx(cpu, hctx))
2889 		return 0;
2890 
2891 	/*
2892 	 * Prevent new request from being allocated on the current hctx.
2893 	 *
2894 	 * The smp_mb__after_atomic() Pairs with the implied barrier in
2895 	 * test_and_set_bit_lock in sbitmap_get().  Ensures the inactive flag is
2896 	 * seen once we return from the tag allocator.
2897 	 */
2898 	set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2899 	smp_mb__after_atomic();
2900 
2901 	/*
2902 	 * Try to grab a reference to the queue and wait for any outstanding
2903 	 * requests.  If we could not grab a reference the queue has been
2904 	 * frozen and there are no requests.
2905 	 */
2906 	if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
2907 		while (blk_mq_hctx_has_requests(hctx))
2908 			msleep(5);
2909 		percpu_ref_put(&hctx->queue->q_usage_counter);
2910 	}
2911 
2912 	return 0;
2913 }
2914 
2915 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
2916 {
2917 	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2918 			struct blk_mq_hw_ctx, cpuhp_online);
2919 
2920 	if (cpumask_test_cpu(cpu, hctx->cpumask))
2921 		clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2922 	return 0;
2923 }
2924 
2925 /*
2926  * 'cpu' is going away. splice any existing rq_list entries from this
2927  * software queue to the hw queue dispatch list, and ensure that it
2928  * gets run.
2929  */
2930 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
2931 {
2932 	struct blk_mq_hw_ctx *hctx;
2933 	struct blk_mq_ctx *ctx;
2934 	LIST_HEAD(tmp);
2935 	enum hctx_type type;
2936 
2937 	hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
2938 	if (!cpumask_test_cpu(cpu, hctx->cpumask))
2939 		return 0;
2940 
2941 	ctx = __blk_mq_get_ctx(hctx->queue, cpu);
2942 	type = hctx->type;
2943 
2944 	spin_lock(&ctx->lock);
2945 	if (!list_empty(&ctx->rq_lists[type])) {
2946 		list_splice_init(&ctx->rq_lists[type], &tmp);
2947 		blk_mq_hctx_clear_pending(hctx, ctx);
2948 	}
2949 	spin_unlock(&ctx->lock);
2950 
2951 	if (list_empty(&tmp))
2952 		return 0;
2953 
2954 	spin_lock(&hctx->lock);
2955 	list_splice_tail_init(&tmp, &hctx->dispatch);
2956 	spin_unlock(&hctx->lock);
2957 
2958 	blk_mq_run_hw_queue(hctx, true);
2959 	return 0;
2960 }
2961 
2962 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
2963 {
2964 	if (!(hctx->flags & BLK_MQ_F_STACKING))
2965 		cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2966 						    &hctx->cpuhp_online);
2967 	cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2968 					    &hctx->cpuhp_dead);
2969 }
2970 
2971 /*
2972  * Before freeing hw queue, clearing the flush request reference in
2973  * tags->rqs[] for avoiding potential UAF.
2974  */
2975 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
2976 		unsigned int queue_depth, struct request *flush_rq)
2977 {
2978 	int i;
2979 	unsigned long flags;
2980 
2981 	/* The hw queue may not be mapped yet */
2982 	if (!tags)
2983 		return;
2984 
2985 	WARN_ON_ONCE(refcount_read(&flush_rq->ref) != 0);
2986 
2987 	for (i = 0; i < queue_depth; i++)
2988 		cmpxchg(&tags->rqs[i], flush_rq, NULL);
2989 
2990 	/*
2991 	 * Wait until all pending iteration is done.
2992 	 *
2993 	 * Request reference is cleared and it is guaranteed to be observed
2994 	 * after the ->lock is released.
2995 	 */
2996 	spin_lock_irqsave(&tags->lock, flags);
2997 	spin_unlock_irqrestore(&tags->lock, flags);
2998 }
2999 
3000 /* hctx->ctxs will be freed in queue's release handler */
3001 static void blk_mq_exit_hctx(struct request_queue *q,
3002 		struct blk_mq_tag_set *set,
3003 		struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3004 {
3005 	struct request *flush_rq = hctx->fq->flush_rq;
3006 
3007 	if (blk_mq_hw_queue_mapped(hctx))
3008 		blk_mq_tag_idle(hctx);
3009 
3010 	blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3011 			set->queue_depth, flush_rq);
3012 	if (set->ops->exit_request)
3013 		set->ops->exit_request(set, flush_rq, hctx_idx);
3014 
3015 	if (set->ops->exit_hctx)
3016 		set->ops->exit_hctx(hctx, hctx_idx);
3017 
3018 	blk_mq_remove_cpuhp(hctx);
3019 
3020 	spin_lock(&q->unused_hctx_lock);
3021 	list_add(&hctx->hctx_list, &q->unused_hctx_list);
3022 	spin_unlock(&q->unused_hctx_lock);
3023 }
3024 
3025 static void blk_mq_exit_hw_queues(struct request_queue *q,
3026 		struct blk_mq_tag_set *set, int nr_queue)
3027 {
3028 	struct blk_mq_hw_ctx *hctx;
3029 	unsigned int i;
3030 
3031 	queue_for_each_hw_ctx(q, hctx, i) {
3032 		if (i == nr_queue)
3033 			break;
3034 		blk_mq_debugfs_unregister_hctx(hctx);
3035 		blk_mq_exit_hctx(q, set, hctx, i);
3036 	}
3037 }
3038 
3039 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
3040 {
3041 	int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
3042 
3043 	BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
3044 			   __alignof__(struct blk_mq_hw_ctx)) !=
3045 		     sizeof(struct blk_mq_hw_ctx));
3046 
3047 	if (tag_set->flags & BLK_MQ_F_BLOCKING)
3048 		hw_ctx_size += sizeof(struct srcu_struct);
3049 
3050 	return hw_ctx_size;
3051 }
3052 
3053 static int blk_mq_init_hctx(struct request_queue *q,
3054 		struct blk_mq_tag_set *set,
3055 		struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3056 {
3057 	hctx->queue_num = hctx_idx;
3058 
3059 	if (!(hctx->flags & BLK_MQ_F_STACKING))
3060 		cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3061 				&hctx->cpuhp_online);
3062 	cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
3063 
3064 	hctx->tags = set->tags[hctx_idx];
3065 
3066 	if (set->ops->init_hctx &&
3067 	    set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3068 		goto unregister_cpu_notifier;
3069 
3070 	if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3071 				hctx->numa_node))
3072 		goto exit_hctx;
3073 	return 0;
3074 
3075  exit_hctx:
3076 	if (set->ops->exit_hctx)
3077 		set->ops->exit_hctx(hctx, hctx_idx);
3078  unregister_cpu_notifier:
3079 	blk_mq_remove_cpuhp(hctx);
3080 	return -1;
3081 }
3082 
3083 static struct blk_mq_hw_ctx *
3084 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3085 		int node)
3086 {
3087 	struct blk_mq_hw_ctx *hctx;
3088 	gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3089 
3090 	hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
3091 	if (!hctx)
3092 		goto fail_alloc_hctx;
3093 
3094 	if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
3095 		goto free_hctx;
3096 
3097 	atomic_set(&hctx->nr_active, 0);
3098 	if (node == NUMA_NO_NODE)
3099 		node = set->numa_node;
3100 	hctx->numa_node = node;
3101 
3102 	INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
3103 	spin_lock_init(&hctx->lock);
3104 	INIT_LIST_HEAD(&hctx->dispatch);
3105 	hctx->queue = q;
3106 	hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
3107 
3108 	INIT_LIST_HEAD(&hctx->hctx_list);
3109 
3110 	/*
3111 	 * Allocate space for all possible cpus to avoid allocation at
3112 	 * runtime
3113 	 */
3114 	hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
3115 			gfp, node);
3116 	if (!hctx->ctxs)
3117 		goto free_cpumask;
3118 
3119 	if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
3120 				gfp, node, false, false))
3121 		goto free_ctxs;
3122 	hctx->nr_ctx = 0;
3123 
3124 	spin_lock_init(&hctx->dispatch_wait_lock);
3125 	init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
3126 	INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
3127 
3128 	hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
3129 	if (!hctx->fq)
3130 		goto free_bitmap;
3131 
3132 	if (hctx->flags & BLK_MQ_F_BLOCKING)
3133 		init_srcu_struct(hctx->srcu);
3134 	blk_mq_hctx_kobj_init(hctx);
3135 
3136 	return hctx;
3137 
3138  free_bitmap:
3139 	sbitmap_free(&hctx->ctx_map);
3140  free_ctxs:
3141 	kfree(hctx->ctxs);
3142  free_cpumask:
3143 	free_cpumask_var(hctx->cpumask);
3144  free_hctx:
3145 	kfree(hctx);
3146  fail_alloc_hctx:
3147 	return NULL;
3148 }
3149 
3150 static void blk_mq_init_cpu_queues(struct request_queue *q,
3151 				   unsigned int nr_hw_queues)
3152 {
3153 	struct blk_mq_tag_set *set = q->tag_set;
3154 	unsigned int i, j;
3155 
3156 	for_each_possible_cpu(i) {
3157 		struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
3158 		struct blk_mq_hw_ctx *hctx;
3159 		int k;
3160 
3161 		__ctx->cpu = i;
3162 		spin_lock_init(&__ctx->lock);
3163 		for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
3164 			INIT_LIST_HEAD(&__ctx->rq_lists[k]);
3165 
3166 		__ctx->queue = q;
3167 
3168 		/*
3169 		 * Set local node, IFF we have more than one hw queue. If
3170 		 * not, we remain on the home node of the device
3171 		 */
3172 		for (j = 0; j < set->nr_maps; j++) {
3173 			hctx = blk_mq_map_queue_type(q, j, i);
3174 			if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
3175 				hctx->numa_node = cpu_to_node(i);
3176 		}
3177 	}
3178 }
3179 
3180 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3181 					     unsigned int hctx_idx,
3182 					     unsigned int depth)
3183 {
3184 	struct blk_mq_tags *tags;
3185 	int ret;
3186 
3187 	tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
3188 	if (!tags)
3189 		return NULL;
3190 
3191 	ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
3192 	if (ret) {
3193 		blk_mq_free_rq_map(tags);
3194 		return NULL;
3195 	}
3196 
3197 	return tags;
3198 }
3199 
3200 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
3201 				       int hctx_idx)
3202 {
3203 	if (blk_mq_is_shared_tags(set->flags)) {
3204 		set->tags[hctx_idx] = set->shared_tags;
3205 
3206 		return true;
3207 	}
3208 
3209 	set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
3210 						       set->queue_depth);
3211 
3212 	return set->tags[hctx_idx];
3213 }
3214 
3215 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3216 			     struct blk_mq_tags *tags,
3217 			     unsigned int hctx_idx)
3218 {
3219 	if (tags) {
3220 		blk_mq_free_rqs(set, tags, hctx_idx);
3221 		blk_mq_free_rq_map(tags);
3222 	}
3223 }
3224 
3225 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
3226 				      unsigned int hctx_idx)
3227 {
3228 	if (!blk_mq_is_shared_tags(set->flags))
3229 		blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
3230 
3231 	set->tags[hctx_idx] = NULL;
3232 }
3233 
3234 static void blk_mq_map_swqueue(struct request_queue *q)
3235 {
3236 	unsigned int i, j, hctx_idx;
3237 	struct blk_mq_hw_ctx *hctx;
3238 	struct blk_mq_ctx *ctx;
3239 	struct blk_mq_tag_set *set = q->tag_set;
3240 
3241 	queue_for_each_hw_ctx(q, hctx, i) {
3242 		cpumask_clear(hctx->cpumask);
3243 		hctx->nr_ctx = 0;
3244 		hctx->dispatch_from = NULL;
3245 	}
3246 
3247 	/*
3248 	 * Map software to hardware queues.
3249 	 *
3250 	 * If the cpu isn't present, the cpu is mapped to first hctx.
3251 	 */
3252 	for_each_possible_cpu(i) {
3253 
3254 		ctx = per_cpu_ptr(q->queue_ctx, i);
3255 		for (j = 0; j < set->nr_maps; j++) {
3256 			if (!set->map[j].nr_queues) {
3257 				ctx->hctxs[j] = blk_mq_map_queue_type(q,
3258 						HCTX_TYPE_DEFAULT, i);
3259 				continue;
3260 			}
3261 			hctx_idx = set->map[j].mq_map[i];
3262 			/* unmapped hw queue can be remapped after CPU topo changed */
3263 			if (!set->tags[hctx_idx] &&
3264 			    !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
3265 				/*
3266 				 * If tags initialization fail for some hctx,
3267 				 * that hctx won't be brought online.  In this
3268 				 * case, remap the current ctx to hctx[0] which
3269 				 * is guaranteed to always have tags allocated
3270 				 */
3271 				set->map[j].mq_map[i] = 0;
3272 			}
3273 
3274 			hctx = blk_mq_map_queue_type(q, j, i);
3275 			ctx->hctxs[j] = hctx;
3276 			/*
3277 			 * If the CPU is already set in the mask, then we've
3278 			 * mapped this one already. This can happen if
3279 			 * devices share queues across queue maps.
3280 			 */
3281 			if (cpumask_test_cpu(i, hctx->cpumask))
3282 				continue;
3283 
3284 			cpumask_set_cpu(i, hctx->cpumask);
3285 			hctx->type = j;
3286 			ctx->index_hw[hctx->type] = hctx->nr_ctx;
3287 			hctx->ctxs[hctx->nr_ctx++] = ctx;
3288 
3289 			/*
3290 			 * If the nr_ctx type overflows, we have exceeded the
3291 			 * amount of sw queues we can support.
3292 			 */
3293 			BUG_ON(!hctx->nr_ctx);
3294 		}
3295 
3296 		for (; j < HCTX_MAX_TYPES; j++)
3297 			ctx->hctxs[j] = blk_mq_map_queue_type(q,
3298 					HCTX_TYPE_DEFAULT, i);
3299 	}
3300 
3301 	queue_for_each_hw_ctx(q, hctx, i) {
3302 		/*
3303 		 * If no software queues are mapped to this hardware queue,
3304 		 * disable it and free the request entries.
3305 		 */
3306 		if (!hctx->nr_ctx) {
3307 			/* Never unmap queue 0.  We need it as a
3308 			 * fallback in case of a new remap fails
3309 			 * allocation
3310 			 */
3311 			if (i)
3312 				__blk_mq_free_map_and_rqs(set, i);
3313 
3314 			hctx->tags = NULL;
3315 			continue;
3316 		}
3317 
3318 		hctx->tags = set->tags[i];
3319 		WARN_ON(!hctx->tags);
3320 
3321 		/*
3322 		 * Set the map size to the number of mapped software queues.
3323 		 * This is more accurate and more efficient than looping
3324 		 * over all possibly mapped software queues.
3325 		 */
3326 		sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
3327 
3328 		/*
3329 		 * Initialize batch roundrobin counts
3330 		 */
3331 		hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
3332 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
3333 	}
3334 }
3335 
3336 /*
3337  * Caller needs to ensure that we're either frozen/quiesced, or that
3338  * the queue isn't live yet.
3339  */
3340 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
3341 {
3342 	struct blk_mq_hw_ctx *hctx;
3343 	int i;
3344 
3345 	queue_for_each_hw_ctx(q, hctx, i) {
3346 		if (shared) {
3347 			hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3348 		} else {
3349 			blk_mq_tag_idle(hctx);
3350 			hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3351 		}
3352 	}
3353 }
3354 
3355 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
3356 					 bool shared)
3357 {
3358 	struct request_queue *q;
3359 
3360 	lockdep_assert_held(&set->tag_list_lock);
3361 
3362 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
3363 		blk_mq_freeze_queue(q);
3364 		queue_set_hctx_shared(q, shared);
3365 		blk_mq_unfreeze_queue(q);
3366 	}
3367 }
3368 
3369 static void blk_mq_del_queue_tag_set(struct request_queue *q)
3370 {
3371 	struct blk_mq_tag_set *set = q->tag_set;
3372 
3373 	mutex_lock(&set->tag_list_lock);
3374 	list_del(&q->tag_set_list);
3375 	if (list_is_singular(&set->tag_list)) {
3376 		/* just transitioned to unshared */
3377 		set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3378 		/* update existing queue */
3379 		blk_mq_update_tag_set_shared(set, false);
3380 	}
3381 	mutex_unlock(&set->tag_list_lock);
3382 	INIT_LIST_HEAD(&q->tag_set_list);
3383 }
3384 
3385 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
3386 				     struct request_queue *q)
3387 {
3388 	mutex_lock(&set->tag_list_lock);
3389 
3390 	/*
3391 	 * Check to see if we're transitioning to shared (from 1 to 2 queues).
3392 	 */
3393 	if (!list_empty(&set->tag_list) &&
3394 	    !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
3395 		set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3396 		/* update existing queue */
3397 		blk_mq_update_tag_set_shared(set, true);
3398 	}
3399 	if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
3400 		queue_set_hctx_shared(q, true);
3401 	list_add_tail(&q->tag_set_list, &set->tag_list);
3402 
3403 	mutex_unlock(&set->tag_list_lock);
3404 }
3405 
3406 /* All allocations will be freed in release handler of q->mq_kobj */
3407 static int blk_mq_alloc_ctxs(struct request_queue *q)
3408 {
3409 	struct blk_mq_ctxs *ctxs;
3410 	int cpu;
3411 
3412 	ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
3413 	if (!ctxs)
3414 		return -ENOMEM;
3415 
3416 	ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
3417 	if (!ctxs->queue_ctx)
3418 		goto fail;
3419 
3420 	for_each_possible_cpu(cpu) {
3421 		struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
3422 		ctx->ctxs = ctxs;
3423 	}
3424 
3425 	q->mq_kobj = &ctxs->kobj;
3426 	q->queue_ctx = ctxs->queue_ctx;
3427 
3428 	return 0;
3429  fail:
3430 	kfree(ctxs);
3431 	return -ENOMEM;
3432 }
3433 
3434 /*
3435  * It is the actual release handler for mq, but we do it from
3436  * request queue's release handler for avoiding use-after-free
3437  * and headache because q->mq_kobj shouldn't have been introduced,
3438  * but we can't group ctx/kctx kobj without it.
3439  */
3440 void blk_mq_release(struct request_queue *q)
3441 {
3442 	struct blk_mq_hw_ctx *hctx, *next;
3443 	int i;
3444 
3445 	queue_for_each_hw_ctx(q, hctx, i)
3446 		WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
3447 
3448 	/* all hctx are in .unused_hctx_list now */
3449 	list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
3450 		list_del_init(&hctx->hctx_list);
3451 		kobject_put(&hctx->kobj);
3452 	}
3453 
3454 	kfree(q->queue_hw_ctx);
3455 
3456 	/*
3457 	 * release .mq_kobj and sw queue's kobject now because
3458 	 * both share lifetime with request queue.
3459 	 */
3460 	blk_mq_sysfs_deinit(q);
3461 }
3462 
3463 static struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
3464 		void *queuedata)
3465 {
3466 	struct request_queue *q;
3467 	int ret;
3468 
3469 	q = blk_alloc_queue(set->numa_node);
3470 	if (!q)
3471 		return ERR_PTR(-ENOMEM);
3472 	q->queuedata = queuedata;
3473 	ret = blk_mq_init_allocated_queue(set, q);
3474 	if (ret) {
3475 		blk_cleanup_queue(q);
3476 		return ERR_PTR(ret);
3477 	}
3478 	return q;
3479 }
3480 
3481 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
3482 {
3483 	return blk_mq_init_queue_data(set, NULL);
3484 }
3485 EXPORT_SYMBOL(blk_mq_init_queue);
3486 
3487 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set, void *queuedata,
3488 		struct lock_class_key *lkclass)
3489 {
3490 	struct request_queue *q;
3491 	struct gendisk *disk;
3492 
3493 	q = blk_mq_init_queue_data(set, queuedata);
3494 	if (IS_ERR(q))
3495 		return ERR_CAST(q);
3496 
3497 	disk = __alloc_disk_node(q, set->numa_node, lkclass);
3498 	if (!disk) {
3499 		blk_cleanup_queue(q);
3500 		return ERR_PTR(-ENOMEM);
3501 	}
3502 	return disk;
3503 }
3504 EXPORT_SYMBOL(__blk_mq_alloc_disk);
3505 
3506 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
3507 		struct blk_mq_tag_set *set, struct request_queue *q,
3508 		int hctx_idx, int node)
3509 {
3510 	struct blk_mq_hw_ctx *hctx = NULL, *tmp;
3511 
3512 	/* reuse dead hctx first */
3513 	spin_lock(&q->unused_hctx_lock);
3514 	list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
3515 		if (tmp->numa_node == node) {
3516 			hctx = tmp;
3517 			break;
3518 		}
3519 	}
3520 	if (hctx)
3521 		list_del_init(&hctx->hctx_list);
3522 	spin_unlock(&q->unused_hctx_lock);
3523 
3524 	if (!hctx)
3525 		hctx = blk_mq_alloc_hctx(q, set, node);
3526 	if (!hctx)
3527 		goto fail;
3528 
3529 	if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
3530 		goto free_hctx;
3531 
3532 	return hctx;
3533 
3534  free_hctx:
3535 	kobject_put(&hctx->kobj);
3536  fail:
3537 	return NULL;
3538 }
3539 
3540 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
3541 						struct request_queue *q)
3542 {
3543 	int i, j, end;
3544 	struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
3545 
3546 	if (q->nr_hw_queues < set->nr_hw_queues) {
3547 		struct blk_mq_hw_ctx **new_hctxs;
3548 
3549 		new_hctxs = kcalloc_node(set->nr_hw_queues,
3550 				       sizeof(*new_hctxs), GFP_KERNEL,
3551 				       set->numa_node);
3552 		if (!new_hctxs)
3553 			return;
3554 		if (hctxs)
3555 			memcpy(new_hctxs, hctxs, q->nr_hw_queues *
3556 			       sizeof(*hctxs));
3557 		q->queue_hw_ctx = new_hctxs;
3558 		kfree(hctxs);
3559 		hctxs = new_hctxs;
3560 	}
3561 
3562 	/* protect against switching io scheduler  */
3563 	mutex_lock(&q->sysfs_lock);
3564 	for (i = 0; i < set->nr_hw_queues; i++) {
3565 		int node;
3566 		struct blk_mq_hw_ctx *hctx;
3567 
3568 		node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
3569 		/*
3570 		 * If the hw queue has been mapped to another numa node,
3571 		 * we need to realloc the hctx. If allocation fails, fallback
3572 		 * to use the previous one.
3573 		 */
3574 		if (hctxs[i] && (hctxs[i]->numa_node == node))
3575 			continue;
3576 
3577 		hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
3578 		if (hctx) {
3579 			if (hctxs[i])
3580 				blk_mq_exit_hctx(q, set, hctxs[i], i);
3581 			hctxs[i] = hctx;
3582 		} else {
3583 			if (hctxs[i])
3584 				pr_warn("Allocate new hctx on node %d fails,\
3585 						fallback to previous one on node %d\n",
3586 						node, hctxs[i]->numa_node);
3587 			else
3588 				break;
3589 		}
3590 	}
3591 	/*
3592 	 * Increasing nr_hw_queues fails. Free the newly allocated
3593 	 * hctxs and keep the previous q->nr_hw_queues.
3594 	 */
3595 	if (i != set->nr_hw_queues) {
3596 		j = q->nr_hw_queues;
3597 		end = i;
3598 	} else {
3599 		j = i;
3600 		end = q->nr_hw_queues;
3601 		q->nr_hw_queues = set->nr_hw_queues;
3602 	}
3603 
3604 	for (; j < end; j++) {
3605 		struct blk_mq_hw_ctx *hctx = hctxs[j];
3606 
3607 		if (hctx) {
3608 			__blk_mq_free_map_and_rqs(set, j);
3609 			blk_mq_exit_hctx(q, set, hctx, j);
3610 			hctxs[j] = NULL;
3611 		}
3612 	}
3613 	mutex_unlock(&q->sysfs_lock);
3614 }
3615 
3616 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
3617 		struct request_queue *q)
3618 {
3619 	/* mark the queue as mq asap */
3620 	q->mq_ops = set->ops;
3621 
3622 	q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
3623 					     blk_mq_poll_stats_bkt,
3624 					     BLK_MQ_POLL_STATS_BKTS, q);
3625 	if (!q->poll_cb)
3626 		goto err_exit;
3627 
3628 	if (blk_mq_alloc_ctxs(q))
3629 		goto err_poll;
3630 
3631 	/* init q->mq_kobj and sw queues' kobjects */
3632 	blk_mq_sysfs_init(q);
3633 
3634 	INIT_LIST_HEAD(&q->unused_hctx_list);
3635 	spin_lock_init(&q->unused_hctx_lock);
3636 
3637 	blk_mq_realloc_hw_ctxs(set, q);
3638 	if (!q->nr_hw_queues)
3639 		goto err_hctxs;
3640 
3641 	INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
3642 	blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
3643 
3644 	q->tag_set = set;
3645 
3646 	q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
3647 	if (set->nr_maps > HCTX_TYPE_POLL &&
3648 	    set->map[HCTX_TYPE_POLL].nr_queues)
3649 		blk_queue_flag_set(QUEUE_FLAG_POLL, q);
3650 
3651 	INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
3652 	INIT_LIST_HEAD(&q->requeue_list);
3653 	spin_lock_init(&q->requeue_lock);
3654 
3655 	q->nr_requests = set->queue_depth;
3656 
3657 	/*
3658 	 * Default to classic polling
3659 	 */
3660 	q->poll_nsec = BLK_MQ_POLL_CLASSIC;
3661 
3662 	blk_mq_init_cpu_queues(q, set->nr_hw_queues);
3663 	blk_mq_add_queue_tag_set(set, q);
3664 	blk_mq_map_swqueue(q);
3665 	return 0;
3666 
3667 err_hctxs:
3668 	kfree(q->queue_hw_ctx);
3669 	q->nr_hw_queues = 0;
3670 	blk_mq_sysfs_deinit(q);
3671 err_poll:
3672 	blk_stat_free_callback(q->poll_cb);
3673 	q->poll_cb = NULL;
3674 err_exit:
3675 	q->mq_ops = NULL;
3676 	return -ENOMEM;
3677 }
3678 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
3679 
3680 /* tags can _not_ be used after returning from blk_mq_exit_queue */
3681 void blk_mq_exit_queue(struct request_queue *q)
3682 {
3683 	struct blk_mq_tag_set *set = q->tag_set;
3684 
3685 	/* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
3686 	blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
3687 	/* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
3688 	blk_mq_del_queue_tag_set(q);
3689 }
3690 
3691 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
3692 {
3693 	int i;
3694 
3695 	if (blk_mq_is_shared_tags(set->flags)) {
3696 		set->shared_tags = blk_mq_alloc_map_and_rqs(set,
3697 						BLK_MQ_NO_HCTX_IDX,
3698 						set->queue_depth);
3699 		if (!set->shared_tags)
3700 			return -ENOMEM;
3701 	}
3702 
3703 	for (i = 0; i < set->nr_hw_queues; i++) {
3704 		if (!__blk_mq_alloc_map_and_rqs(set, i))
3705 			goto out_unwind;
3706 		cond_resched();
3707 	}
3708 
3709 	return 0;
3710 
3711 out_unwind:
3712 	while (--i >= 0)
3713 		__blk_mq_free_map_and_rqs(set, i);
3714 
3715 	if (blk_mq_is_shared_tags(set->flags)) {
3716 		blk_mq_free_map_and_rqs(set, set->shared_tags,
3717 					BLK_MQ_NO_HCTX_IDX);
3718 	}
3719 
3720 	return -ENOMEM;
3721 }
3722 
3723 /*
3724  * Allocate the request maps associated with this tag_set. Note that this
3725  * may reduce the depth asked for, if memory is tight. set->queue_depth
3726  * will be updated to reflect the allocated depth.
3727  */
3728 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
3729 {
3730 	unsigned int depth;
3731 	int err;
3732 
3733 	depth = set->queue_depth;
3734 	do {
3735 		err = __blk_mq_alloc_rq_maps(set);
3736 		if (!err)
3737 			break;
3738 
3739 		set->queue_depth >>= 1;
3740 		if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
3741 			err = -ENOMEM;
3742 			break;
3743 		}
3744 	} while (set->queue_depth);
3745 
3746 	if (!set->queue_depth || err) {
3747 		pr_err("blk-mq: failed to allocate request map\n");
3748 		return -ENOMEM;
3749 	}
3750 
3751 	if (depth != set->queue_depth)
3752 		pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
3753 						depth, set->queue_depth);
3754 
3755 	return 0;
3756 }
3757 
3758 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
3759 {
3760 	/*
3761 	 * blk_mq_map_queues() and multiple .map_queues() implementations
3762 	 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
3763 	 * number of hardware queues.
3764 	 */
3765 	if (set->nr_maps == 1)
3766 		set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
3767 
3768 	if (set->ops->map_queues && !is_kdump_kernel()) {
3769 		int i;
3770 
3771 		/*
3772 		 * transport .map_queues is usually done in the following
3773 		 * way:
3774 		 *
3775 		 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
3776 		 * 	mask = get_cpu_mask(queue)
3777 		 * 	for_each_cpu(cpu, mask)
3778 		 * 		set->map[x].mq_map[cpu] = queue;
3779 		 * }
3780 		 *
3781 		 * When we need to remap, the table has to be cleared for
3782 		 * killing stale mapping since one CPU may not be mapped
3783 		 * to any hw queue.
3784 		 */
3785 		for (i = 0; i < set->nr_maps; i++)
3786 			blk_mq_clear_mq_map(&set->map[i]);
3787 
3788 		return set->ops->map_queues(set);
3789 	} else {
3790 		BUG_ON(set->nr_maps > 1);
3791 		return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3792 	}
3793 }
3794 
3795 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
3796 				  int cur_nr_hw_queues, int new_nr_hw_queues)
3797 {
3798 	struct blk_mq_tags **new_tags;
3799 
3800 	if (cur_nr_hw_queues >= new_nr_hw_queues)
3801 		return 0;
3802 
3803 	new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
3804 				GFP_KERNEL, set->numa_node);
3805 	if (!new_tags)
3806 		return -ENOMEM;
3807 
3808 	if (set->tags)
3809 		memcpy(new_tags, set->tags, cur_nr_hw_queues *
3810 		       sizeof(*set->tags));
3811 	kfree(set->tags);
3812 	set->tags = new_tags;
3813 	set->nr_hw_queues = new_nr_hw_queues;
3814 
3815 	return 0;
3816 }
3817 
3818 static int blk_mq_alloc_tag_set_tags(struct blk_mq_tag_set *set,
3819 				int new_nr_hw_queues)
3820 {
3821 	return blk_mq_realloc_tag_set_tags(set, 0, new_nr_hw_queues);
3822 }
3823 
3824 /*
3825  * Alloc a tag set to be associated with one or more request queues.
3826  * May fail with EINVAL for various error conditions. May adjust the
3827  * requested depth down, if it's too large. In that case, the set
3828  * value will be stored in set->queue_depth.
3829  */
3830 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
3831 {
3832 	int i, ret;
3833 
3834 	BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
3835 
3836 	if (!set->nr_hw_queues)
3837 		return -EINVAL;
3838 	if (!set->queue_depth)
3839 		return -EINVAL;
3840 	if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
3841 		return -EINVAL;
3842 
3843 	if (!set->ops->queue_rq)
3844 		return -EINVAL;
3845 
3846 	if (!set->ops->get_budget ^ !set->ops->put_budget)
3847 		return -EINVAL;
3848 
3849 	if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
3850 		pr_info("blk-mq: reduced tag depth to %u\n",
3851 			BLK_MQ_MAX_DEPTH);
3852 		set->queue_depth = BLK_MQ_MAX_DEPTH;
3853 	}
3854 
3855 	if (!set->nr_maps)
3856 		set->nr_maps = 1;
3857 	else if (set->nr_maps > HCTX_MAX_TYPES)
3858 		return -EINVAL;
3859 
3860 	/*
3861 	 * If a crashdump is active, then we are potentially in a very
3862 	 * memory constrained environment. Limit us to 1 queue and
3863 	 * 64 tags to prevent using too much memory.
3864 	 */
3865 	if (is_kdump_kernel()) {
3866 		set->nr_hw_queues = 1;
3867 		set->nr_maps = 1;
3868 		set->queue_depth = min(64U, set->queue_depth);
3869 	}
3870 	/*
3871 	 * There is no use for more h/w queues than cpus if we just have
3872 	 * a single map
3873 	 */
3874 	if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
3875 		set->nr_hw_queues = nr_cpu_ids;
3876 
3877 	if (blk_mq_alloc_tag_set_tags(set, set->nr_hw_queues) < 0)
3878 		return -ENOMEM;
3879 
3880 	ret = -ENOMEM;
3881 	for (i = 0; i < set->nr_maps; i++) {
3882 		set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
3883 						  sizeof(set->map[i].mq_map[0]),
3884 						  GFP_KERNEL, set->numa_node);
3885 		if (!set->map[i].mq_map)
3886 			goto out_free_mq_map;
3887 		set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
3888 	}
3889 
3890 	ret = blk_mq_update_queue_map(set);
3891 	if (ret)
3892 		goto out_free_mq_map;
3893 
3894 	ret = blk_mq_alloc_set_map_and_rqs(set);
3895 	if (ret)
3896 		goto out_free_mq_map;
3897 
3898 	mutex_init(&set->tag_list_lock);
3899 	INIT_LIST_HEAD(&set->tag_list);
3900 
3901 	return 0;
3902 
3903 out_free_mq_map:
3904 	for (i = 0; i < set->nr_maps; i++) {
3905 		kfree(set->map[i].mq_map);
3906 		set->map[i].mq_map = NULL;
3907 	}
3908 	kfree(set->tags);
3909 	set->tags = NULL;
3910 	return ret;
3911 }
3912 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
3913 
3914 /* allocate and initialize a tagset for a simple single-queue device */
3915 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
3916 		const struct blk_mq_ops *ops, unsigned int queue_depth,
3917 		unsigned int set_flags)
3918 {
3919 	memset(set, 0, sizeof(*set));
3920 	set->ops = ops;
3921 	set->nr_hw_queues = 1;
3922 	set->nr_maps = 1;
3923 	set->queue_depth = queue_depth;
3924 	set->numa_node = NUMA_NO_NODE;
3925 	set->flags = set_flags;
3926 	return blk_mq_alloc_tag_set(set);
3927 }
3928 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
3929 
3930 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
3931 {
3932 	int i, j;
3933 
3934 	for (i = 0; i < set->nr_hw_queues; i++)
3935 		__blk_mq_free_map_and_rqs(set, i);
3936 
3937 	if (blk_mq_is_shared_tags(set->flags)) {
3938 		blk_mq_free_map_and_rqs(set, set->shared_tags,
3939 					BLK_MQ_NO_HCTX_IDX);
3940 	}
3941 
3942 	for (j = 0; j < set->nr_maps; j++) {
3943 		kfree(set->map[j].mq_map);
3944 		set->map[j].mq_map = NULL;
3945 	}
3946 
3947 	kfree(set->tags);
3948 	set->tags = NULL;
3949 }
3950 EXPORT_SYMBOL(blk_mq_free_tag_set);
3951 
3952 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
3953 {
3954 	struct blk_mq_tag_set *set = q->tag_set;
3955 	struct blk_mq_hw_ctx *hctx;
3956 	int i, ret;
3957 
3958 	if (!set)
3959 		return -EINVAL;
3960 
3961 	if (q->nr_requests == nr)
3962 		return 0;
3963 
3964 	blk_mq_freeze_queue(q);
3965 	blk_mq_quiesce_queue(q);
3966 
3967 	ret = 0;
3968 	queue_for_each_hw_ctx(q, hctx, i) {
3969 		if (!hctx->tags)
3970 			continue;
3971 		/*
3972 		 * If we're using an MQ scheduler, just update the scheduler
3973 		 * queue depth. This is similar to what the old code would do.
3974 		 */
3975 		if (hctx->sched_tags) {
3976 			ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
3977 						      nr, true);
3978 		} else {
3979 			ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
3980 						      false);
3981 		}
3982 		if (ret)
3983 			break;
3984 		if (q->elevator && q->elevator->type->ops.depth_updated)
3985 			q->elevator->type->ops.depth_updated(hctx);
3986 	}
3987 	if (!ret) {
3988 		q->nr_requests = nr;
3989 		if (blk_mq_is_shared_tags(set->flags)) {
3990 			if (q->elevator)
3991 				blk_mq_tag_update_sched_shared_tags(q);
3992 			else
3993 				blk_mq_tag_resize_shared_tags(set, nr);
3994 		}
3995 	}
3996 
3997 	blk_mq_unquiesce_queue(q);
3998 	blk_mq_unfreeze_queue(q);
3999 
4000 	return ret;
4001 }
4002 
4003 /*
4004  * request_queue and elevator_type pair.
4005  * It is just used by __blk_mq_update_nr_hw_queues to cache
4006  * the elevator_type associated with a request_queue.
4007  */
4008 struct blk_mq_qe_pair {
4009 	struct list_head node;
4010 	struct request_queue *q;
4011 	struct elevator_type *type;
4012 };
4013 
4014 /*
4015  * Cache the elevator_type in qe pair list and switch the
4016  * io scheduler to 'none'
4017  */
4018 static bool blk_mq_elv_switch_none(struct list_head *head,
4019 		struct request_queue *q)
4020 {
4021 	struct blk_mq_qe_pair *qe;
4022 
4023 	if (!q->elevator)
4024 		return true;
4025 
4026 	qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
4027 	if (!qe)
4028 		return false;
4029 
4030 	INIT_LIST_HEAD(&qe->node);
4031 	qe->q = q;
4032 	qe->type = q->elevator->type;
4033 	list_add(&qe->node, head);
4034 
4035 	mutex_lock(&q->sysfs_lock);
4036 	/*
4037 	 * After elevator_switch_mq, the previous elevator_queue will be
4038 	 * released by elevator_release. The reference of the io scheduler
4039 	 * module get by elevator_get will also be put. So we need to get
4040 	 * a reference of the io scheduler module here to prevent it to be
4041 	 * removed.
4042 	 */
4043 	__module_get(qe->type->elevator_owner);
4044 	elevator_switch_mq(q, NULL);
4045 	mutex_unlock(&q->sysfs_lock);
4046 
4047 	return true;
4048 }
4049 
4050 static void blk_mq_elv_switch_back(struct list_head *head,
4051 		struct request_queue *q)
4052 {
4053 	struct blk_mq_qe_pair *qe;
4054 	struct elevator_type *t = NULL;
4055 
4056 	list_for_each_entry(qe, head, node)
4057 		if (qe->q == q) {
4058 			t = qe->type;
4059 			break;
4060 		}
4061 
4062 	if (!t)
4063 		return;
4064 
4065 	list_del(&qe->node);
4066 	kfree(qe);
4067 
4068 	mutex_lock(&q->sysfs_lock);
4069 	elevator_switch_mq(q, t);
4070 	mutex_unlock(&q->sysfs_lock);
4071 }
4072 
4073 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
4074 							int nr_hw_queues)
4075 {
4076 	struct request_queue *q;
4077 	LIST_HEAD(head);
4078 	int prev_nr_hw_queues;
4079 
4080 	lockdep_assert_held(&set->tag_list_lock);
4081 
4082 	if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
4083 		nr_hw_queues = nr_cpu_ids;
4084 	if (nr_hw_queues < 1)
4085 		return;
4086 	if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
4087 		return;
4088 
4089 	list_for_each_entry(q, &set->tag_list, tag_set_list)
4090 		blk_mq_freeze_queue(q);
4091 	/*
4092 	 * Switch IO scheduler to 'none', cleaning up the data associated
4093 	 * with the previous scheduler. We will switch back once we are done
4094 	 * updating the new sw to hw queue mappings.
4095 	 */
4096 	list_for_each_entry(q, &set->tag_list, tag_set_list)
4097 		if (!blk_mq_elv_switch_none(&head, q))
4098 			goto switch_back;
4099 
4100 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
4101 		blk_mq_debugfs_unregister_hctxs(q);
4102 		blk_mq_sysfs_unregister(q);
4103 	}
4104 
4105 	prev_nr_hw_queues = set->nr_hw_queues;
4106 	if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
4107 	    0)
4108 		goto reregister;
4109 
4110 	set->nr_hw_queues = nr_hw_queues;
4111 fallback:
4112 	blk_mq_update_queue_map(set);
4113 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
4114 		blk_mq_realloc_hw_ctxs(set, q);
4115 		if (q->nr_hw_queues != set->nr_hw_queues) {
4116 			pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
4117 					nr_hw_queues, prev_nr_hw_queues);
4118 			set->nr_hw_queues = prev_nr_hw_queues;
4119 			blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4120 			goto fallback;
4121 		}
4122 		blk_mq_map_swqueue(q);
4123 	}
4124 
4125 reregister:
4126 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
4127 		blk_mq_sysfs_register(q);
4128 		blk_mq_debugfs_register_hctxs(q);
4129 	}
4130 
4131 switch_back:
4132 	list_for_each_entry(q, &set->tag_list, tag_set_list)
4133 		blk_mq_elv_switch_back(&head, q);
4134 
4135 	list_for_each_entry(q, &set->tag_list, tag_set_list)
4136 		blk_mq_unfreeze_queue(q);
4137 }
4138 
4139 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
4140 {
4141 	mutex_lock(&set->tag_list_lock);
4142 	__blk_mq_update_nr_hw_queues(set, nr_hw_queues);
4143 	mutex_unlock(&set->tag_list_lock);
4144 }
4145 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
4146 
4147 /* Enable polling stats and return whether they were already enabled. */
4148 static bool blk_poll_stats_enable(struct request_queue *q)
4149 {
4150 	if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
4151 	    blk_queue_flag_test_and_set(QUEUE_FLAG_POLL_STATS, q))
4152 		return true;
4153 	blk_stat_add_callback(q, q->poll_cb);
4154 	return false;
4155 }
4156 
4157 static void blk_mq_poll_stats_start(struct request_queue *q)
4158 {
4159 	/*
4160 	 * We don't arm the callback if polling stats are not enabled or the
4161 	 * callback is already active.
4162 	 */
4163 	if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
4164 	    blk_stat_is_active(q->poll_cb))
4165 		return;
4166 
4167 	blk_stat_activate_msecs(q->poll_cb, 100);
4168 }
4169 
4170 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
4171 {
4172 	struct request_queue *q = cb->data;
4173 	int bucket;
4174 
4175 	for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
4176 		if (cb->stat[bucket].nr_samples)
4177 			q->poll_stat[bucket] = cb->stat[bucket];
4178 	}
4179 }
4180 
4181 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
4182 				       struct request *rq)
4183 {
4184 	unsigned long ret = 0;
4185 	int bucket;
4186 
4187 	/*
4188 	 * If stats collection isn't on, don't sleep but turn it on for
4189 	 * future users
4190 	 */
4191 	if (!blk_poll_stats_enable(q))
4192 		return 0;
4193 
4194 	/*
4195 	 * As an optimistic guess, use half of the mean service time
4196 	 * for this type of request. We can (and should) make this smarter.
4197 	 * For instance, if the completion latencies are tight, we can
4198 	 * get closer than just half the mean. This is especially
4199 	 * important on devices where the completion latencies are longer
4200 	 * than ~10 usec. We do use the stats for the relevant IO size
4201 	 * if available which does lead to better estimates.
4202 	 */
4203 	bucket = blk_mq_poll_stats_bkt(rq);
4204 	if (bucket < 0)
4205 		return ret;
4206 
4207 	if (q->poll_stat[bucket].nr_samples)
4208 		ret = (q->poll_stat[bucket].mean + 1) / 2;
4209 
4210 	return ret;
4211 }
4212 
4213 static bool blk_mq_poll_hybrid(struct request_queue *q, blk_qc_t qc)
4214 {
4215 	struct blk_mq_hw_ctx *hctx = blk_qc_to_hctx(q, qc);
4216 	struct request *rq = blk_qc_to_rq(hctx, qc);
4217 	struct hrtimer_sleeper hs;
4218 	enum hrtimer_mode mode;
4219 	unsigned int nsecs;
4220 	ktime_t kt;
4221 
4222 	/*
4223 	 * If a request has completed on queue that uses an I/O scheduler, we
4224 	 * won't get back a request from blk_qc_to_rq.
4225 	 */
4226 	if (!rq || (rq->rq_flags & RQF_MQ_POLL_SLEPT))
4227 		return false;
4228 
4229 	/*
4230 	 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
4231 	 *
4232 	 *  0:	use half of prev avg
4233 	 * >0:	use this specific value
4234 	 */
4235 	if (q->poll_nsec > 0)
4236 		nsecs = q->poll_nsec;
4237 	else
4238 		nsecs = blk_mq_poll_nsecs(q, rq);
4239 
4240 	if (!nsecs)
4241 		return false;
4242 
4243 	rq->rq_flags |= RQF_MQ_POLL_SLEPT;
4244 
4245 	/*
4246 	 * This will be replaced with the stats tracking code, using
4247 	 * 'avg_completion_time / 2' as the pre-sleep target.
4248 	 */
4249 	kt = nsecs;
4250 
4251 	mode = HRTIMER_MODE_REL;
4252 	hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
4253 	hrtimer_set_expires(&hs.timer, kt);
4254 
4255 	do {
4256 		if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
4257 			break;
4258 		set_current_state(TASK_UNINTERRUPTIBLE);
4259 		hrtimer_sleeper_start_expires(&hs, mode);
4260 		if (hs.task)
4261 			io_schedule();
4262 		hrtimer_cancel(&hs.timer);
4263 		mode = HRTIMER_MODE_ABS;
4264 	} while (hs.task && !signal_pending(current));
4265 
4266 	__set_current_state(TASK_RUNNING);
4267 	destroy_hrtimer_on_stack(&hs.timer);
4268 
4269 	/*
4270 	 * If we sleep, have the caller restart the poll loop to reset the
4271 	 * state.  Like for the other success return cases, the caller is
4272 	 * responsible for checking if the IO completed.  If the IO isn't
4273 	 * complete, we'll get called again and will go straight to the busy
4274 	 * poll loop.
4275 	 */
4276 	return true;
4277 }
4278 
4279 static int blk_mq_poll_classic(struct request_queue *q, blk_qc_t cookie,
4280 			       struct io_comp_batch *iob, unsigned int flags)
4281 {
4282 	struct blk_mq_hw_ctx *hctx = blk_qc_to_hctx(q, cookie);
4283 	long state = get_current_state();
4284 	int ret;
4285 
4286 	do {
4287 		ret = q->mq_ops->poll(hctx, iob);
4288 		if (ret > 0) {
4289 			__set_current_state(TASK_RUNNING);
4290 			return ret;
4291 		}
4292 
4293 		if (signal_pending_state(state, current))
4294 			__set_current_state(TASK_RUNNING);
4295 		if (task_is_running(current))
4296 			return 1;
4297 
4298 		if (ret < 0 || (flags & BLK_POLL_ONESHOT))
4299 			break;
4300 		cpu_relax();
4301 	} while (!need_resched());
4302 
4303 	__set_current_state(TASK_RUNNING);
4304 	return 0;
4305 }
4306 
4307 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie, struct io_comp_batch *iob,
4308 		unsigned int flags)
4309 {
4310 	if (!(flags & BLK_POLL_NOSLEEP) &&
4311 	    q->poll_nsec != BLK_MQ_POLL_CLASSIC) {
4312 		if (blk_mq_poll_hybrid(q, cookie))
4313 			return 1;
4314 	}
4315 	return blk_mq_poll_classic(q, cookie, iob, flags);
4316 }
4317 
4318 unsigned int blk_mq_rq_cpu(struct request *rq)
4319 {
4320 	return rq->mq_ctx->cpu;
4321 }
4322 EXPORT_SYMBOL(blk_mq_rq_cpu);
4323 
4324 static int __init blk_mq_init(void)
4325 {
4326 	int i;
4327 
4328 	for_each_possible_cpu(i)
4329 		init_llist_head(&per_cpu(blk_cpu_done, i));
4330 	open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
4331 
4332 	cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
4333 				  "block/softirq:dead", NULL,
4334 				  blk_softirq_cpu_dead);
4335 	cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
4336 				blk_mq_hctx_notify_dead);
4337 	cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
4338 				blk_mq_hctx_notify_online,
4339 				blk_mq_hctx_notify_offline);
4340 	return 0;
4341 }
4342 subsys_initcall(blk_mq_init);
4343