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