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