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