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