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