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