• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/kmemleak.h>
14 #include <linux/mm.h>
15 #include <linux/init.h>
16 #include <linux/slab.h>
17 #include <linux/workqueue.h>
18 #include <linux/smp.h>
19 #include <linux/llist.h>
20 #include <linux/list_sort.h>
21 #include <linux/cpu.h>
22 #include <linux/cache.h>
23 #include <linux/sched/sysctl.h>
24 #include <linux/sched/topology.h>
25 #include <linux/sched/signal.h>
26 #include <linux/delay.h>
27 #include <linux/crash_dump.h>
28 #include <linux/prefetch.h>
29 #include <linux/blk-crypto.h>
30 
31 #include <trace/events/block.h>
32 
33 #include <linux/blk-mq.h>
34 #include <linux/t10-pi.h>
35 #include "blk.h"
36 #include "blk-mq.h"
37 #include "blk-mq-debugfs.h"
38 #include "blk-mq-tag.h"
39 #include "blk-pm.h"
40 #include "blk-stat.h"
41 #include "blk-mq-sched.h"
42 #include "blk-rq-qos.h"
43 
44 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
45 
46 static void blk_mq_poll_stats_start(struct request_queue *q);
47 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
48 
blk_mq_poll_stats_bkt(const struct request * rq)49 static int blk_mq_poll_stats_bkt(const struct request *rq)
50 {
51 	int ddir, sectors, bucket;
52 
53 	ddir = rq_data_dir(rq);
54 	sectors = blk_rq_stats_sectors(rq);
55 
56 	bucket = ddir + 2 * ilog2(sectors);
57 
58 	if (bucket < 0)
59 		return -1;
60 	else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
61 		return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
62 
63 	return bucket;
64 }
65 
66 /*
67  * Check if any of the ctx, dispatch list or elevator
68  * have pending work in this hardware queue.
69  */
blk_mq_hctx_has_pending(struct blk_mq_hw_ctx * hctx)70 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
71 {
72 	return !list_empty_careful(&hctx->dispatch) ||
73 		sbitmap_any_bit_set(&hctx->ctx_map) ||
74 			blk_mq_sched_has_work(hctx);
75 }
76 
77 /*
78  * Mark this ctx as having pending work in this hardware queue
79  */
blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)80 static void blk_mq_hctx_mark_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 	if (!sbitmap_test_bit(&hctx->ctx_map, bit))
86 		sbitmap_set_bit(&hctx->ctx_map, bit);
87 }
88 
blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)89 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
90 				      struct blk_mq_ctx *ctx)
91 {
92 	const int bit = ctx->index_hw[hctx->type];
93 
94 	sbitmap_clear_bit(&hctx->ctx_map, bit);
95 }
96 
97 struct mq_inflight {
98 	struct hd_struct *part;
99 	unsigned int inflight[2];
100 };
101 
blk_mq_check_inflight(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)102 static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
103 				  struct request *rq, void *priv,
104 				  bool reserved)
105 {
106 	struct mq_inflight *mi = priv;
107 
108 	if ((!mi->part->partno || rq->part == mi->part) &&
109 	    blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
110 		mi->inflight[rq_data_dir(rq)]++;
111 
112 	return true;
113 }
114 
blk_mq_in_flight(struct request_queue * q,struct hd_struct * part)115 unsigned int blk_mq_in_flight(struct request_queue *q, struct hd_struct *part)
116 {
117 	struct mq_inflight mi = { .part = part };
118 
119 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
120 
121 	return mi.inflight[0] + mi.inflight[1];
122 }
123 
blk_mq_in_flight_rw(struct request_queue * q,struct hd_struct * part,unsigned int inflight[2])124 void blk_mq_in_flight_rw(struct request_queue *q, struct hd_struct *part,
125 			 unsigned int inflight[2])
126 {
127 	struct mq_inflight mi = { .part = part };
128 
129 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
130 	inflight[0] = mi.inflight[0];
131 	inflight[1] = mi.inflight[1];
132 }
133 
blk_freeze_queue_start(struct request_queue * q)134 void blk_freeze_queue_start(struct request_queue *q)
135 {
136 	mutex_lock(&q->mq_freeze_lock);
137 	if (++q->mq_freeze_depth == 1) {
138 		percpu_ref_kill(&q->q_usage_counter);
139 		mutex_unlock(&q->mq_freeze_lock);
140 		if (queue_is_mq(q))
141 			blk_mq_run_hw_queues(q, false);
142 	} else {
143 		mutex_unlock(&q->mq_freeze_lock);
144 	}
145 }
146 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
147 
blk_mq_freeze_queue_wait(struct request_queue * q)148 void blk_mq_freeze_queue_wait(struct request_queue *q)
149 {
150 	wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
151 }
152 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
153 
blk_mq_freeze_queue_wait_timeout(struct request_queue * q,unsigned long timeout)154 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
155 				     unsigned long timeout)
156 {
157 	return wait_event_timeout(q->mq_freeze_wq,
158 					percpu_ref_is_zero(&q->q_usage_counter),
159 					timeout);
160 }
161 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
162 
163 /*
164  * Guarantee no request is in use, so we can change any data structure of
165  * the queue afterward.
166  */
blk_freeze_queue(struct request_queue * q)167 void blk_freeze_queue(struct request_queue *q)
168 {
169 	/*
170 	 * In the !blk_mq case we are only calling this to kill the
171 	 * q_usage_counter, otherwise this increases the freeze depth
172 	 * and waits for it to return to zero.  For this reason there is
173 	 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
174 	 * exported to drivers as the only user for unfreeze is blk_mq.
175 	 */
176 	blk_freeze_queue_start(q);
177 	blk_mq_freeze_queue_wait(q);
178 }
179 
blk_mq_freeze_queue(struct request_queue * q)180 void blk_mq_freeze_queue(struct request_queue *q)
181 {
182 	/*
183 	 * ...just an alias to keep freeze and unfreeze actions balanced
184 	 * in the blk_mq_* namespace
185 	 */
186 	blk_freeze_queue(q);
187 }
188 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
189 
blk_mq_unfreeze_queue(struct request_queue * q)190 void blk_mq_unfreeze_queue(struct request_queue *q)
191 {
192 	mutex_lock(&q->mq_freeze_lock);
193 	q->mq_freeze_depth--;
194 	WARN_ON_ONCE(q->mq_freeze_depth < 0);
195 	if (!q->mq_freeze_depth) {
196 		percpu_ref_resurrect(&q->q_usage_counter);
197 		wake_up_all(&q->mq_freeze_wq);
198 	}
199 	mutex_unlock(&q->mq_freeze_lock);
200 }
201 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
202 
203 /*
204  * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
205  * mpt3sas driver such that this function can be removed.
206  */
blk_mq_quiesce_queue_nowait(struct request_queue * q)207 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
208 {
209 	unsigned long flags;
210 
211 	spin_lock_irqsave(&q->queue_lock, flags);
212 	if (!q->quiesce_depth++)
213 		blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
214 	spin_unlock_irqrestore(&q->queue_lock, flags);
215 }
216 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
217 
218 /**
219  * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
220  * @q: request queue.
221  *
222  * Note: this function does not prevent that the struct request end_io()
223  * callback function is invoked. Once this function is returned, we make
224  * sure no dispatch can happen until the queue is unquiesced via
225  * blk_mq_unquiesce_queue().
226  */
blk_mq_quiesce_queue(struct request_queue * q)227 void blk_mq_quiesce_queue(struct request_queue *q)
228 {
229 	struct blk_mq_hw_ctx *hctx;
230 	unsigned int i;
231 	bool rcu = false;
232 
233 	blk_mq_quiesce_queue_nowait(q);
234 
235 	queue_for_each_hw_ctx(q, hctx, i) {
236 		if (hctx->flags & BLK_MQ_F_BLOCKING)
237 			synchronize_srcu(hctx->srcu);
238 		else
239 			rcu = true;
240 	}
241 	if (rcu)
242 		synchronize_rcu();
243 }
244 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
245 
246 /*
247  * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
248  * @q: request queue.
249  *
250  * This function recovers queue into the state before quiescing
251  * which is done by blk_mq_quiesce_queue.
252  */
blk_mq_unquiesce_queue(struct request_queue * q)253 void blk_mq_unquiesce_queue(struct request_queue *q)
254 {
255 	unsigned long flags;
256 	bool run_queue = false;
257 
258 	spin_lock_irqsave(&q->queue_lock, flags);
259 	if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
260 		;
261 	} else if (!--q->quiesce_depth) {
262 		blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
263 		run_queue = true;
264 	}
265 	spin_unlock_irqrestore(&q->queue_lock, flags);
266 
267 	/* dispatch requests which are inserted during quiescing */
268 	if (run_queue)
269 		blk_mq_run_hw_queues(q, true);
270 }
271 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
272 
blk_mq_wake_waiters(struct request_queue * q)273 void blk_mq_wake_waiters(struct request_queue *q)
274 {
275 	struct blk_mq_hw_ctx *hctx;
276 	unsigned int i;
277 
278 	queue_for_each_hw_ctx(q, hctx, i)
279 		if (blk_mq_hw_queue_mapped(hctx))
280 			blk_mq_tag_wakeup_all(hctx->tags, true);
281 }
282 
283 /*
284  * Only need start/end time stamping if we have iostat or
285  * blk stats enabled, or using an IO scheduler.
286  */
blk_mq_need_time_stamp(struct request * rq)287 static inline bool blk_mq_need_time_stamp(struct request *rq)
288 {
289 	return (rq->rq_flags & (RQF_IO_STAT | RQF_STATS)) || rq->q->elevator;
290 }
291 
blk_mq_rq_ctx_init(struct blk_mq_alloc_data * data,unsigned int tag,u64 alloc_time_ns)292 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
293 		unsigned int tag, u64 alloc_time_ns)
294 {
295 	struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
296 	struct request *rq = tags->static_rqs[tag];
297 
298 	if (data->q->elevator) {
299 		rq->tag = BLK_MQ_NO_TAG;
300 		rq->internal_tag = tag;
301 	} else {
302 		rq->tag = tag;
303 		rq->internal_tag = BLK_MQ_NO_TAG;
304 	}
305 
306 	/* csd/requeue_work/fifo_time is initialized before use */
307 	rq->q = data->q;
308 	rq->mq_ctx = data->ctx;
309 	rq->mq_hctx = data->hctx;
310 	rq->rq_flags = 0;
311 	rq->cmd_flags = data->cmd_flags;
312 	if (data->flags & BLK_MQ_REQ_PM)
313 		rq->rq_flags |= RQF_PM;
314 	if (blk_queue_io_stat(data->q))
315 		rq->rq_flags |= RQF_IO_STAT;
316 	INIT_LIST_HEAD(&rq->queuelist);
317 	INIT_HLIST_NODE(&rq->hash);
318 	RB_CLEAR_NODE(&rq->rb_node);
319 	rq->rq_disk = NULL;
320 	rq->part = NULL;
321 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
322 	rq->alloc_time_ns = alloc_time_ns;
323 #endif
324 	if (blk_mq_need_time_stamp(rq))
325 		rq->start_time_ns = ktime_get_ns();
326 	else
327 		rq->start_time_ns = 0;
328 	rq->io_start_time_ns = 0;
329 	rq->stats_sectors = 0;
330 	rq->nr_phys_segments = 0;
331 #if defined(CONFIG_BLK_DEV_INTEGRITY)
332 	rq->nr_integrity_segments = 0;
333 #endif
334 	blk_crypto_rq_set_defaults(rq);
335 	/* tag was already set */
336 	WRITE_ONCE(rq->deadline, 0);
337 
338 	rq->timeout = 0;
339 
340 	rq->end_io = NULL;
341 	rq->end_io_data = NULL;
342 
343 	data->ctx->rq_dispatched[op_is_sync(data->cmd_flags)]++;
344 	refcount_set(&rq->ref, 1);
345 
346 	if (!op_is_flush(data->cmd_flags)) {
347 		struct elevator_queue *e = data->q->elevator;
348 
349 		rq->elv.icq = NULL;
350 		if (e && e->type->ops.prepare_request) {
351 			if (e->type->icq_cache)
352 				blk_mq_sched_assign_ioc(rq);
353 
354 			e->type->ops.prepare_request(rq);
355 			rq->rq_flags |= RQF_ELVPRIV;
356 		}
357 	}
358 
359 	data->hctx->queued++;
360 	return rq;
361 }
362 
__blk_mq_alloc_request(struct blk_mq_alloc_data * data)363 static struct request *__blk_mq_alloc_request(struct blk_mq_alloc_data *data)
364 {
365 	struct request_queue *q = data->q;
366 	struct elevator_queue *e = q->elevator;
367 	u64 alloc_time_ns = 0;
368 	unsigned int tag;
369 
370 	/* alloc_time includes depth and tag waits */
371 	if (blk_queue_rq_alloc_time(q))
372 		alloc_time_ns = ktime_get_ns();
373 
374 	if (data->cmd_flags & REQ_NOWAIT)
375 		data->flags |= BLK_MQ_REQ_NOWAIT;
376 
377 	if (e) {
378 		/*
379 		 * Flush requests are special and go directly to the
380 		 * dispatch list. Don't include reserved tags in the
381 		 * limiting, as it isn't useful.
382 		 */
383 		if (!op_is_flush(data->cmd_flags) &&
384 		    e->type->ops.limit_depth &&
385 		    !(data->flags & BLK_MQ_REQ_RESERVED))
386 			e->type->ops.limit_depth(data->cmd_flags, data);
387 	}
388 
389 retry:
390 	data->ctx = blk_mq_get_ctx(q);
391 	data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
392 	if (!e)
393 		blk_mq_tag_busy(data->hctx);
394 
395 	/*
396 	 * Waiting allocations only fail because of an inactive hctx.  In that
397 	 * case just retry the hctx assignment and tag allocation as CPU hotplug
398 	 * should have migrated us to an online CPU by now.
399 	 */
400 	tag = blk_mq_get_tag(data);
401 	if (tag == BLK_MQ_NO_TAG) {
402 		if (data->flags & BLK_MQ_REQ_NOWAIT)
403 			return NULL;
404 
405 		/*
406 		 * Give up the CPU and sleep for a random short time to ensure
407 		 * that thread using a realtime scheduling class are migrated
408 		 * off the CPU, and thus off the hctx that is going away.
409 		 */
410 		msleep(3);
411 		goto retry;
412 	}
413 	return blk_mq_rq_ctx_init(data, tag, alloc_time_ns);
414 }
415 
blk_mq_alloc_request(struct request_queue * q,unsigned int op,blk_mq_req_flags_t flags)416 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
417 		blk_mq_req_flags_t flags)
418 {
419 	struct blk_mq_alloc_data data = {
420 		.q		= q,
421 		.flags		= flags,
422 		.cmd_flags	= op,
423 	};
424 	struct request *rq;
425 	int ret;
426 
427 	ret = blk_queue_enter(q, flags);
428 	if (ret)
429 		return ERR_PTR(ret);
430 
431 	rq = __blk_mq_alloc_request(&data);
432 	if (!rq)
433 		goto out_queue_exit;
434 	rq->__data_len = 0;
435 	rq->__sector = (sector_t) -1;
436 	rq->bio = rq->biotail = NULL;
437 	return rq;
438 out_queue_exit:
439 	blk_queue_exit(q);
440 	return ERR_PTR(-EWOULDBLOCK);
441 }
442 EXPORT_SYMBOL(blk_mq_alloc_request);
443 
blk_mq_alloc_request_hctx(struct request_queue * q,unsigned int op,blk_mq_req_flags_t flags,unsigned int hctx_idx)444 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
445 	unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
446 {
447 	struct blk_mq_alloc_data data = {
448 		.q		= q,
449 		.flags		= flags,
450 		.cmd_flags	= op,
451 	};
452 	u64 alloc_time_ns = 0;
453 	unsigned int cpu;
454 	unsigned int tag;
455 	int ret;
456 
457 	/* alloc_time includes depth and tag waits */
458 	if (blk_queue_rq_alloc_time(q))
459 		alloc_time_ns = ktime_get_ns();
460 
461 	/*
462 	 * If the tag allocator sleeps we could get an allocation for a
463 	 * different hardware context.  No need to complicate the low level
464 	 * allocator for this for the rare use case of a command tied to
465 	 * a specific queue.
466 	 */
467 	if (WARN_ON_ONCE(!(flags & (BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED))))
468 		return ERR_PTR(-EINVAL);
469 
470 	if (hctx_idx >= q->nr_hw_queues)
471 		return ERR_PTR(-EIO);
472 
473 	ret = blk_queue_enter(q, flags);
474 	if (ret)
475 		return ERR_PTR(ret);
476 
477 	/*
478 	 * Check if the hardware context is actually mapped to anything.
479 	 * If not tell the caller that it should skip this queue.
480 	 */
481 	ret = -EXDEV;
482 	data.hctx = q->queue_hw_ctx[hctx_idx];
483 	if (!blk_mq_hw_queue_mapped(data.hctx))
484 		goto out_queue_exit;
485 	cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
486 	data.ctx = __blk_mq_get_ctx(q, cpu);
487 
488 	if (!q->elevator)
489 		blk_mq_tag_busy(data.hctx);
490 
491 	ret = -EWOULDBLOCK;
492 	tag = blk_mq_get_tag(&data);
493 	if (tag == BLK_MQ_NO_TAG)
494 		goto out_queue_exit;
495 	return blk_mq_rq_ctx_init(&data, tag, alloc_time_ns);
496 
497 out_queue_exit:
498 	blk_queue_exit(q);
499 	return ERR_PTR(ret);
500 }
501 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
502 
__blk_mq_free_request(struct request * rq)503 static void __blk_mq_free_request(struct request *rq)
504 {
505 	struct request_queue *q = rq->q;
506 	struct blk_mq_ctx *ctx = rq->mq_ctx;
507 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
508 	const int sched_tag = rq->internal_tag;
509 
510 	blk_crypto_free_request(rq);
511 	blk_pm_mark_last_busy(rq);
512 	rq->mq_hctx = NULL;
513 	if (rq->tag != BLK_MQ_NO_TAG)
514 		blk_mq_put_tag(hctx->tags, ctx, rq->tag);
515 	if (sched_tag != BLK_MQ_NO_TAG)
516 		blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
517 	blk_mq_sched_restart(hctx);
518 	blk_queue_exit(q);
519 }
520 
blk_mq_free_request(struct request * rq)521 void blk_mq_free_request(struct request *rq)
522 {
523 	struct request_queue *q = rq->q;
524 	struct elevator_queue *e = q->elevator;
525 	struct blk_mq_ctx *ctx = rq->mq_ctx;
526 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
527 
528 	if (rq->rq_flags & RQF_ELVPRIV) {
529 		if (e && e->type->ops.finish_request)
530 			e->type->ops.finish_request(rq);
531 		if (rq->elv.icq) {
532 			put_io_context(rq->elv.icq->ioc);
533 			rq->elv.icq = NULL;
534 		}
535 	}
536 
537 	ctx->rq_completed[rq_is_sync(rq)]++;
538 	if (rq->rq_flags & RQF_MQ_INFLIGHT)
539 		__blk_mq_dec_active_requests(hctx);
540 
541 	if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
542 		laptop_io_completion(q->backing_dev_info);
543 
544 	rq_qos_done(q, rq);
545 
546 	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
547 	if (refcount_dec_and_test(&rq->ref))
548 		__blk_mq_free_request(rq);
549 }
550 EXPORT_SYMBOL_GPL(blk_mq_free_request);
551 
__blk_mq_end_request(struct request * rq,blk_status_t error)552 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
553 {
554 	u64 now = 0;
555 
556 	if (blk_mq_need_time_stamp(rq))
557 		now = ktime_get_ns();
558 
559 	if (rq->rq_flags & RQF_STATS) {
560 		blk_mq_poll_stats_start(rq->q);
561 		blk_stat_add(rq, now);
562 	}
563 
564 	blk_mq_sched_completed_request(rq, now);
565 
566 	blk_account_io_done(rq, now);
567 
568 	if (rq->end_io) {
569 		rq_qos_done(rq->q, rq);
570 		rq->end_io(rq, error);
571 	} else {
572 		blk_mq_free_request(rq);
573 	}
574 }
575 EXPORT_SYMBOL(__blk_mq_end_request);
576 
blk_mq_end_request(struct request * rq,blk_status_t error)577 void blk_mq_end_request(struct request *rq, blk_status_t error)
578 {
579 	if (blk_update_request(rq, error, blk_rq_bytes(rq)))
580 		BUG();
581 	__blk_mq_end_request(rq, error);
582 }
583 EXPORT_SYMBOL(blk_mq_end_request);
584 
585 /*
586  * Softirq action handler - move entries to local list and loop over them
587  * while passing them to the queue registered handler.
588  */
blk_done_softirq(struct softirq_action * h)589 static __latent_entropy void blk_done_softirq(struct softirq_action *h)
590 {
591 	struct list_head *cpu_list, local_list;
592 
593 	local_irq_disable();
594 	cpu_list = this_cpu_ptr(&blk_cpu_done);
595 	list_replace_init(cpu_list, &local_list);
596 	local_irq_enable();
597 
598 	while (!list_empty(&local_list)) {
599 		struct request *rq;
600 
601 		rq = list_entry(local_list.next, struct request, ipi_list);
602 		list_del_init(&rq->ipi_list);
603 		rq->q->mq_ops->complete(rq);
604 	}
605 }
606 
blk_mq_trigger_softirq(struct request * rq)607 static void blk_mq_trigger_softirq(struct request *rq)
608 {
609 	struct list_head *list;
610 	unsigned long flags;
611 
612 	local_irq_save(flags);
613 	list = this_cpu_ptr(&blk_cpu_done);
614 	list_add_tail(&rq->ipi_list, list);
615 
616 	/*
617 	 * If the list only contains our just added request, signal a raise of
618 	 * the softirq.  If there are already entries there, someone already
619 	 * raised the irq but it hasn't run yet.
620 	 */
621 	if (list->next == &rq->ipi_list)
622 		raise_softirq_irqoff(BLOCK_SOFTIRQ);
623 	local_irq_restore(flags);
624 }
625 
blk_softirq_cpu_dead(unsigned int cpu)626 static int blk_softirq_cpu_dead(unsigned int cpu)
627 {
628 	/*
629 	 * If a CPU goes away, splice its entries to the current CPU
630 	 * and trigger a run of the softirq
631 	 */
632 	local_irq_disable();
633 	list_splice_init(&per_cpu(blk_cpu_done, cpu),
634 			 this_cpu_ptr(&blk_cpu_done));
635 	raise_softirq_irqoff(BLOCK_SOFTIRQ);
636 	local_irq_enable();
637 
638 	return 0;
639 }
640 
641 
__blk_mq_complete_request_remote(void * data)642 static void __blk_mq_complete_request_remote(void *data)
643 {
644 	struct request *rq = data;
645 
646 	/*
647 	 * For most of single queue controllers, there is only one irq vector
648 	 * for handling I/O completion, and the only irq's affinity is set
649 	 * to all possible CPUs.  On most of ARCHs, this affinity means the irq
650 	 * is handled on one specific CPU.
651 	 *
652 	 * So complete I/O requests in softirq context in case of single queue
653 	 * devices to avoid degrading I/O performance due to irqsoff latency.
654 	 */
655 	if (rq->q->nr_hw_queues == 1)
656 		blk_mq_trigger_softirq(rq);
657 	else
658 		rq->q->mq_ops->complete(rq);
659 }
660 
blk_mq_complete_need_ipi(struct request * rq)661 static inline bool blk_mq_complete_need_ipi(struct request *rq)
662 {
663 	int cpu = raw_smp_processor_id();
664 
665 	if (!IS_ENABLED(CONFIG_SMP) ||
666 	    !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
667 		return false;
668 
669 	/* same CPU or cache domain?  Complete locally */
670 	if (cpu == rq->mq_ctx->cpu ||
671 	    (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
672 	     cpus_share_cache(cpu, rq->mq_ctx->cpu)))
673 		return false;
674 
675 	/* don't try to IPI to an offline CPU */
676 	return cpu_online(rq->mq_ctx->cpu);
677 }
678 
blk_mq_complete_request_remote(struct request * rq)679 bool blk_mq_complete_request_remote(struct request *rq)
680 {
681 	WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
682 
683 	/*
684 	 * For a polled request, always complete locallly, it's pointless
685 	 * to redirect the completion.
686 	 */
687 	if (rq->cmd_flags & REQ_HIPRI)
688 		return false;
689 
690 	if (blk_mq_complete_need_ipi(rq)) {
691 		rq->csd.func = __blk_mq_complete_request_remote;
692 		rq->csd.info = rq;
693 		rq->csd.flags = 0;
694 		smp_call_function_single_async(rq->mq_ctx->cpu, &rq->csd);
695 	} else {
696 		if (rq->q->nr_hw_queues > 1)
697 			return false;
698 		blk_mq_trigger_softirq(rq);
699 	}
700 
701 	return true;
702 }
703 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
704 
705 /**
706  * blk_mq_complete_request - end I/O on a request
707  * @rq:		the request being processed
708  *
709  * Description:
710  *	Complete a request by scheduling the ->complete_rq operation.
711  **/
blk_mq_complete_request(struct request * rq)712 void blk_mq_complete_request(struct request *rq)
713 {
714 	if (!blk_mq_complete_request_remote(rq))
715 		rq->q->mq_ops->complete(rq);
716 }
717 EXPORT_SYMBOL(blk_mq_complete_request);
718 
hctx_unlock(struct blk_mq_hw_ctx * hctx,int srcu_idx)719 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
720 	__releases(hctx->srcu)
721 {
722 	if (!(hctx->flags & BLK_MQ_F_BLOCKING))
723 		rcu_read_unlock();
724 	else
725 		srcu_read_unlock(hctx->srcu, srcu_idx);
726 }
727 
hctx_lock(struct blk_mq_hw_ctx * hctx,int * srcu_idx)728 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
729 	__acquires(hctx->srcu)
730 {
731 	if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
732 		/* shut up gcc false positive */
733 		*srcu_idx = 0;
734 		rcu_read_lock();
735 	} else
736 		*srcu_idx = srcu_read_lock(hctx->srcu);
737 }
738 
739 /**
740  * blk_mq_start_request - Start processing a request
741  * @rq: Pointer to request to be started
742  *
743  * Function used by device drivers to notify the block layer that a request
744  * is going to be processed now, so blk layer can do proper initializations
745  * such as starting the timeout timer.
746  */
blk_mq_start_request(struct request * rq)747 void blk_mq_start_request(struct request *rq)
748 {
749 	struct request_queue *q = rq->q;
750 
751 	trace_block_rq_issue(q, rq);
752 
753 	if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
754 		rq->io_start_time_ns = ktime_get_ns();
755 		rq->stats_sectors = blk_rq_sectors(rq);
756 		rq->rq_flags |= RQF_STATS;
757 		rq_qos_issue(q, rq);
758 	}
759 
760 	WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
761 
762 	blk_add_timer(rq);
763 	WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
764 
765 #ifdef CONFIG_BLK_DEV_INTEGRITY
766 	if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
767 		q->integrity.profile->prepare_fn(rq);
768 #endif
769 }
770 EXPORT_SYMBOL(blk_mq_start_request);
771 
__blk_mq_requeue_request(struct request * rq)772 static void __blk_mq_requeue_request(struct request *rq)
773 {
774 	struct request_queue *q = rq->q;
775 
776 	blk_mq_put_driver_tag(rq);
777 
778 	trace_block_rq_requeue(q, rq);
779 	rq_qos_requeue(q, rq);
780 
781 	if (blk_mq_request_started(rq)) {
782 		WRITE_ONCE(rq->state, MQ_RQ_IDLE);
783 		rq->rq_flags &= ~RQF_TIMED_OUT;
784 	}
785 }
786 
blk_mq_requeue_request(struct request * rq,bool kick_requeue_list)787 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
788 {
789 	__blk_mq_requeue_request(rq);
790 
791 	/* this request will be re-inserted to io scheduler queue */
792 	blk_mq_sched_requeue_request(rq);
793 
794 	BUG_ON(!list_empty(&rq->queuelist));
795 	blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
796 }
797 EXPORT_SYMBOL(blk_mq_requeue_request);
798 
blk_mq_requeue_work(struct work_struct * work)799 static void blk_mq_requeue_work(struct work_struct *work)
800 {
801 	struct request_queue *q =
802 		container_of(work, struct request_queue, requeue_work.work);
803 	LIST_HEAD(rq_list);
804 	struct request *rq, *next;
805 
806 	spin_lock_irq(&q->requeue_lock);
807 	list_splice_init(&q->requeue_list, &rq_list);
808 	spin_unlock_irq(&q->requeue_lock);
809 
810 	list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
811 		if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
812 			continue;
813 
814 		rq->rq_flags &= ~RQF_SOFTBARRIER;
815 		list_del_init(&rq->queuelist);
816 		/*
817 		 * If RQF_DONTPREP, rq has contained some driver specific
818 		 * data, so insert it to hctx dispatch list to avoid any
819 		 * merge.
820 		 */
821 		if (rq->rq_flags & RQF_DONTPREP)
822 			blk_mq_request_bypass_insert(rq, false, false);
823 		else
824 			blk_mq_sched_insert_request(rq, true, false, false);
825 	}
826 
827 	while (!list_empty(&rq_list)) {
828 		rq = list_entry(rq_list.next, struct request, queuelist);
829 		list_del_init(&rq->queuelist);
830 		blk_mq_sched_insert_request(rq, false, false, false);
831 	}
832 
833 	blk_mq_run_hw_queues(q, false);
834 }
835 
blk_mq_add_to_requeue_list(struct request * rq,bool at_head,bool kick_requeue_list)836 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
837 				bool kick_requeue_list)
838 {
839 	struct request_queue *q = rq->q;
840 	unsigned long flags;
841 
842 	/*
843 	 * We abuse this flag that is otherwise used by the I/O scheduler to
844 	 * request head insertion from the workqueue.
845 	 */
846 	BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
847 
848 	spin_lock_irqsave(&q->requeue_lock, flags);
849 	if (at_head) {
850 		rq->rq_flags |= RQF_SOFTBARRIER;
851 		list_add(&rq->queuelist, &q->requeue_list);
852 	} else {
853 		list_add_tail(&rq->queuelist, &q->requeue_list);
854 	}
855 	spin_unlock_irqrestore(&q->requeue_lock, flags);
856 
857 	if (kick_requeue_list)
858 		blk_mq_kick_requeue_list(q);
859 }
860 
blk_mq_kick_requeue_list(struct request_queue * q)861 void blk_mq_kick_requeue_list(struct request_queue *q)
862 {
863 	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
864 }
865 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
866 
blk_mq_delay_kick_requeue_list(struct request_queue * q,unsigned long msecs)867 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
868 				    unsigned long msecs)
869 {
870 	kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
871 				    msecs_to_jiffies(msecs));
872 }
873 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
874 
blk_mq_tag_to_rq(struct blk_mq_tags * tags,unsigned int tag)875 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
876 {
877 	if (tag < tags->nr_tags) {
878 		prefetch(tags->rqs[tag]);
879 		return tags->rqs[tag];
880 	}
881 
882 	return NULL;
883 }
884 EXPORT_SYMBOL(blk_mq_tag_to_rq);
885 
blk_mq_rq_inflight(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)886 static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
887 			       void *priv, bool reserved)
888 {
889 	/*
890 	 * If we find a request that isn't idle and the queue matches,
891 	 * we know the queue is busy. Return false to stop the iteration.
892 	 */
893 	if (blk_mq_request_started(rq) && rq->q == hctx->queue) {
894 		bool *busy = priv;
895 
896 		*busy = true;
897 		return false;
898 	}
899 
900 	return true;
901 }
902 
blk_mq_queue_inflight(struct request_queue * q)903 bool blk_mq_queue_inflight(struct request_queue *q)
904 {
905 	bool busy = false;
906 
907 	blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
908 	return busy;
909 }
910 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
911 
blk_mq_rq_timed_out(struct request * req,bool reserved)912 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
913 {
914 	req->rq_flags |= RQF_TIMED_OUT;
915 	if (req->q->mq_ops->timeout) {
916 		enum blk_eh_timer_return ret;
917 
918 		ret = req->q->mq_ops->timeout(req, reserved);
919 		if (ret == BLK_EH_DONE)
920 			return;
921 		WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
922 	}
923 
924 	blk_add_timer(req);
925 }
926 
blk_mq_req_expired(struct request * rq,unsigned long * next)927 static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
928 {
929 	unsigned long deadline;
930 
931 	if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
932 		return false;
933 	if (rq->rq_flags & RQF_TIMED_OUT)
934 		return false;
935 
936 	deadline = READ_ONCE(rq->deadline);
937 	if (time_after_eq(jiffies, deadline))
938 		return true;
939 
940 	if (*next == 0)
941 		*next = deadline;
942 	else if (time_after(*next, deadline))
943 		*next = deadline;
944 	return false;
945 }
946 
blk_mq_put_rq_ref(struct request * rq)947 void blk_mq_put_rq_ref(struct request *rq)
948 {
949 	if (is_flush_rq(rq))
950 		rq->end_io(rq, 0);
951 	else if (refcount_dec_and_test(&rq->ref))
952 		__blk_mq_free_request(rq);
953 }
954 
blk_mq_check_expired(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)955 static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
956 		struct request *rq, void *priv, bool reserved)
957 {
958 	unsigned long *next = priv;
959 
960 	/*
961 	 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
962 	 * be reallocated underneath the timeout handler's processing, then
963 	 * the expire check is reliable. If the request is not expired, then
964 	 * it was completed and reallocated as a new request after returning
965 	 * from blk_mq_check_expired().
966 	 */
967 	if (blk_mq_req_expired(rq, next))
968 		blk_mq_rq_timed_out(rq, reserved);
969 	return true;
970 }
971 
blk_mq_timeout_work(struct work_struct * work)972 static void blk_mq_timeout_work(struct work_struct *work)
973 {
974 	struct request_queue *q =
975 		container_of(work, struct request_queue, timeout_work);
976 	unsigned long next = 0;
977 	struct blk_mq_hw_ctx *hctx;
978 	int i;
979 
980 	/* A deadlock might occur if a request is stuck requiring a
981 	 * timeout at the same time a queue freeze is waiting
982 	 * completion, since the timeout code would not be able to
983 	 * acquire the queue reference here.
984 	 *
985 	 * That's why we don't use blk_queue_enter here; instead, we use
986 	 * percpu_ref_tryget directly, because we need to be able to
987 	 * obtain a reference even in the short window between the queue
988 	 * starting to freeze, by dropping the first reference in
989 	 * blk_freeze_queue_start, and the moment the last request is
990 	 * consumed, marked by the instant q_usage_counter reaches
991 	 * zero.
992 	 */
993 	if (!percpu_ref_tryget(&q->q_usage_counter))
994 		return;
995 
996 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
997 
998 	if (next != 0) {
999 		mod_timer(&q->timeout, next);
1000 	} else {
1001 		/*
1002 		 * Request timeouts are handled as a forward rolling timer. If
1003 		 * we end up here it means that no requests are pending and
1004 		 * also that no request has been pending for a while. Mark
1005 		 * each hctx as idle.
1006 		 */
1007 		queue_for_each_hw_ctx(q, hctx, i) {
1008 			/* the hctx may be unmapped, so check it here */
1009 			if (blk_mq_hw_queue_mapped(hctx))
1010 				blk_mq_tag_idle(hctx);
1011 		}
1012 	}
1013 	blk_queue_exit(q);
1014 }
1015 
1016 struct flush_busy_ctx_data {
1017 	struct blk_mq_hw_ctx *hctx;
1018 	struct list_head *list;
1019 };
1020 
flush_busy_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1021 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1022 {
1023 	struct flush_busy_ctx_data *flush_data = data;
1024 	struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1025 	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1026 	enum hctx_type type = hctx->type;
1027 
1028 	spin_lock(&ctx->lock);
1029 	list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1030 	sbitmap_clear_bit(sb, bitnr);
1031 	spin_unlock(&ctx->lock);
1032 	return true;
1033 }
1034 
1035 /*
1036  * Process software queues that have been marked busy, splicing them
1037  * to the for-dispatch
1038  */
blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx * hctx,struct list_head * list)1039 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1040 {
1041 	struct flush_busy_ctx_data data = {
1042 		.hctx = hctx,
1043 		.list = list,
1044 	};
1045 
1046 	sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1047 }
1048 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1049 
1050 struct dispatch_rq_data {
1051 	struct blk_mq_hw_ctx *hctx;
1052 	struct request *rq;
1053 };
1054 
dispatch_rq_from_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1055 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1056 		void *data)
1057 {
1058 	struct dispatch_rq_data *dispatch_data = data;
1059 	struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1060 	struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1061 	enum hctx_type type = hctx->type;
1062 
1063 	spin_lock(&ctx->lock);
1064 	if (!list_empty(&ctx->rq_lists[type])) {
1065 		dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1066 		list_del_init(&dispatch_data->rq->queuelist);
1067 		if (list_empty(&ctx->rq_lists[type]))
1068 			sbitmap_clear_bit(sb, bitnr);
1069 	}
1070 	spin_unlock(&ctx->lock);
1071 
1072 	return !dispatch_data->rq;
1073 }
1074 
blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * start)1075 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1076 					struct blk_mq_ctx *start)
1077 {
1078 	unsigned off = start ? start->index_hw[hctx->type] : 0;
1079 	struct dispatch_rq_data data = {
1080 		.hctx = hctx,
1081 		.rq   = NULL,
1082 	};
1083 
1084 	__sbitmap_for_each_set(&hctx->ctx_map, off,
1085 			       dispatch_rq_from_ctx, &data);
1086 
1087 	return data.rq;
1088 }
1089 
queued_to_index(unsigned int queued)1090 static inline unsigned int queued_to_index(unsigned int queued)
1091 {
1092 	if (!queued)
1093 		return 0;
1094 
1095 	return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
1096 }
1097 
__blk_mq_get_driver_tag(struct request * rq)1098 static bool __blk_mq_get_driver_tag(struct request *rq)
1099 {
1100 	struct sbitmap_queue *bt = rq->mq_hctx->tags->bitmap_tags;
1101 	unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1102 	int tag;
1103 
1104 	blk_mq_tag_busy(rq->mq_hctx);
1105 
1106 	if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1107 		bt = rq->mq_hctx->tags->breserved_tags;
1108 		tag_offset = 0;
1109 	} else {
1110 		if (!hctx_may_queue(rq->mq_hctx, bt))
1111 			return false;
1112 	}
1113 
1114 	tag = __sbitmap_queue_get(bt);
1115 	if (tag == BLK_MQ_NO_TAG)
1116 		return false;
1117 
1118 	rq->tag = tag + tag_offset;
1119 	return true;
1120 }
1121 
blk_mq_get_driver_tag(struct request * rq)1122 static bool blk_mq_get_driver_tag(struct request *rq)
1123 {
1124 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1125 
1126 	if (rq->tag == BLK_MQ_NO_TAG && !__blk_mq_get_driver_tag(rq))
1127 		return false;
1128 
1129 	if ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1130 			!(rq->rq_flags & RQF_MQ_INFLIGHT)) {
1131 		rq->rq_flags |= RQF_MQ_INFLIGHT;
1132 		__blk_mq_inc_active_requests(hctx);
1133 	}
1134 	hctx->tags->rqs[rq->tag] = rq;
1135 	return true;
1136 }
1137 
blk_mq_dispatch_wake(wait_queue_entry_t * wait,unsigned mode,int flags,void * key)1138 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1139 				int flags, void *key)
1140 {
1141 	struct blk_mq_hw_ctx *hctx;
1142 
1143 	hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1144 
1145 	spin_lock(&hctx->dispatch_wait_lock);
1146 	if (!list_empty(&wait->entry)) {
1147 		struct sbitmap_queue *sbq;
1148 
1149 		list_del_init(&wait->entry);
1150 		sbq = hctx->tags->bitmap_tags;
1151 		atomic_dec(&sbq->ws_active);
1152 	}
1153 	spin_unlock(&hctx->dispatch_wait_lock);
1154 
1155 	blk_mq_run_hw_queue(hctx, true);
1156 	return 1;
1157 }
1158 
1159 /*
1160  * Mark us waiting for a tag. For shared tags, this involves hooking us into
1161  * the tag wakeups. For non-shared tags, we can simply mark us needing a
1162  * restart. For both cases, take care to check the condition again after
1163  * marking us as waiting.
1164  */
blk_mq_mark_tag_wait(struct blk_mq_hw_ctx * hctx,struct request * rq)1165 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1166 				 struct request *rq)
1167 {
1168 	struct sbitmap_queue *sbq = hctx->tags->bitmap_tags;
1169 	struct wait_queue_head *wq;
1170 	wait_queue_entry_t *wait;
1171 	bool ret;
1172 
1173 	if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
1174 		blk_mq_sched_mark_restart_hctx(hctx);
1175 
1176 		/*
1177 		 * It's possible that a tag was freed in the window between the
1178 		 * allocation failure and adding the hardware queue to the wait
1179 		 * queue.
1180 		 *
1181 		 * Don't clear RESTART here, someone else could have set it.
1182 		 * At most this will cost an extra queue run.
1183 		 */
1184 		return blk_mq_get_driver_tag(rq);
1185 	}
1186 
1187 	wait = &hctx->dispatch_wait;
1188 	if (!list_empty_careful(&wait->entry))
1189 		return false;
1190 
1191 	wq = &bt_wait_ptr(sbq, hctx)->wait;
1192 
1193 	spin_lock_irq(&wq->lock);
1194 	spin_lock(&hctx->dispatch_wait_lock);
1195 	if (!list_empty(&wait->entry)) {
1196 		spin_unlock(&hctx->dispatch_wait_lock);
1197 		spin_unlock_irq(&wq->lock);
1198 		return false;
1199 	}
1200 
1201 	atomic_inc(&sbq->ws_active);
1202 	wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1203 	__add_wait_queue(wq, wait);
1204 
1205 	/*
1206 	 * It's possible that a tag was freed in the window between the
1207 	 * allocation failure and adding the hardware queue to the wait
1208 	 * queue.
1209 	 */
1210 	ret = blk_mq_get_driver_tag(rq);
1211 	if (!ret) {
1212 		spin_unlock(&hctx->dispatch_wait_lock);
1213 		spin_unlock_irq(&wq->lock);
1214 		return false;
1215 	}
1216 
1217 	/*
1218 	 * We got a tag, remove ourselves from the wait queue to ensure
1219 	 * someone else gets the wakeup.
1220 	 */
1221 	list_del_init(&wait->entry);
1222 	atomic_dec(&sbq->ws_active);
1223 	spin_unlock(&hctx->dispatch_wait_lock);
1224 	spin_unlock_irq(&wq->lock);
1225 
1226 	return true;
1227 }
1228 
1229 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT  8
1230 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR  4
1231 /*
1232  * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1233  * - EWMA is one simple way to compute running average value
1234  * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1235  * - take 4 as factor for avoiding to get too small(0) result, and this
1236  *   factor doesn't matter because EWMA decreases exponentially
1237  */
blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx * hctx,bool busy)1238 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1239 {
1240 	unsigned int ewma;
1241 
1242 	ewma = hctx->dispatch_busy;
1243 
1244 	if (!ewma && !busy)
1245 		return;
1246 
1247 	ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1248 	if (busy)
1249 		ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1250 	ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1251 
1252 	hctx->dispatch_busy = ewma;
1253 }
1254 
1255 #define BLK_MQ_RESOURCE_DELAY	3		/* ms units */
1256 
blk_mq_handle_dev_resource(struct request * rq,struct list_head * list)1257 static void blk_mq_handle_dev_resource(struct request *rq,
1258 				       struct list_head *list)
1259 {
1260 	struct request *next =
1261 		list_first_entry_or_null(list, struct request, queuelist);
1262 
1263 	/*
1264 	 * If an I/O scheduler has been configured and we got a driver tag for
1265 	 * the next request already, free it.
1266 	 */
1267 	if (next)
1268 		blk_mq_put_driver_tag(next);
1269 
1270 	list_add(&rq->queuelist, list);
1271 	__blk_mq_requeue_request(rq);
1272 }
1273 
blk_mq_handle_zone_resource(struct request * rq,struct list_head * zone_list)1274 static void blk_mq_handle_zone_resource(struct request *rq,
1275 					struct list_head *zone_list)
1276 {
1277 	/*
1278 	 * If we end up here it is because we cannot dispatch a request to a
1279 	 * specific zone due to LLD level zone-write locking or other zone
1280 	 * related resource not being available. In this case, set the request
1281 	 * aside in zone_list for retrying it later.
1282 	 */
1283 	list_add(&rq->queuelist, zone_list);
1284 	__blk_mq_requeue_request(rq);
1285 }
1286 
1287 enum prep_dispatch {
1288 	PREP_DISPATCH_OK,
1289 	PREP_DISPATCH_NO_TAG,
1290 	PREP_DISPATCH_NO_BUDGET,
1291 };
1292 
blk_mq_prep_dispatch_rq(struct request * rq,bool need_budget)1293 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
1294 						  bool need_budget)
1295 {
1296 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1297 
1298 	if (need_budget && !blk_mq_get_dispatch_budget(rq->q)) {
1299 		blk_mq_put_driver_tag(rq);
1300 		return PREP_DISPATCH_NO_BUDGET;
1301 	}
1302 
1303 	if (!blk_mq_get_driver_tag(rq)) {
1304 		/*
1305 		 * The initial allocation attempt failed, so we need to
1306 		 * rerun the hardware queue when a tag is freed. The
1307 		 * waitqueue takes care of that. If the queue is run
1308 		 * before we add this entry back on the dispatch list,
1309 		 * we'll re-run it below.
1310 		 */
1311 		if (!blk_mq_mark_tag_wait(hctx, rq)) {
1312 			/*
1313 			 * All budgets not got from this function will be put
1314 			 * together during handling partial dispatch
1315 			 */
1316 			if (need_budget)
1317 				blk_mq_put_dispatch_budget(rq->q);
1318 			return PREP_DISPATCH_NO_TAG;
1319 		}
1320 	}
1321 
1322 	return PREP_DISPATCH_OK;
1323 }
1324 
1325 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
blk_mq_release_budgets(struct request_queue * q,unsigned int nr_budgets)1326 static void blk_mq_release_budgets(struct request_queue *q,
1327 		unsigned int nr_budgets)
1328 {
1329 	int i;
1330 
1331 	for (i = 0; i < nr_budgets; i++)
1332 		blk_mq_put_dispatch_budget(q);
1333 }
1334 
1335 /*
1336  * Returns true if we did some work AND can potentially do more.
1337  */
blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx * hctx,struct list_head * list,unsigned int nr_budgets)1338 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
1339 			     unsigned int nr_budgets)
1340 {
1341 	enum prep_dispatch prep;
1342 	struct request_queue *q = hctx->queue;
1343 	struct request *rq, *nxt;
1344 	int errors, queued;
1345 	blk_status_t ret = BLK_STS_OK;
1346 	LIST_HEAD(zone_list);
1347 
1348 	if (list_empty(list))
1349 		return false;
1350 
1351 	/*
1352 	 * Now process all the entries, sending them to the driver.
1353 	 */
1354 	errors = queued = 0;
1355 	do {
1356 		struct blk_mq_queue_data bd;
1357 
1358 		rq = list_first_entry(list, struct request, queuelist);
1359 
1360 		WARN_ON_ONCE(hctx != rq->mq_hctx);
1361 		prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
1362 		if (prep != PREP_DISPATCH_OK)
1363 			break;
1364 
1365 		list_del_init(&rq->queuelist);
1366 
1367 		bd.rq = rq;
1368 
1369 		/*
1370 		 * Flag last if we have no more requests, or if we have more
1371 		 * but can't assign a driver tag to it.
1372 		 */
1373 		if (list_empty(list))
1374 			bd.last = true;
1375 		else {
1376 			nxt = list_first_entry(list, struct request, queuelist);
1377 			bd.last = !blk_mq_get_driver_tag(nxt);
1378 		}
1379 
1380 		/*
1381 		 * once the request is queued to lld, no need to cover the
1382 		 * budget any more
1383 		 */
1384 		if (nr_budgets)
1385 			nr_budgets--;
1386 		ret = q->mq_ops->queue_rq(hctx, &bd);
1387 		switch (ret) {
1388 		case BLK_STS_OK:
1389 			queued++;
1390 			break;
1391 		case BLK_STS_RESOURCE:
1392 		case BLK_STS_DEV_RESOURCE:
1393 			blk_mq_handle_dev_resource(rq, list);
1394 			goto out;
1395 		case BLK_STS_ZONE_RESOURCE:
1396 			/*
1397 			 * Move the request to zone_list and keep going through
1398 			 * the dispatch list to find more requests the drive can
1399 			 * accept.
1400 			 */
1401 			blk_mq_handle_zone_resource(rq, &zone_list);
1402 			break;
1403 		default:
1404 			errors++;
1405 			blk_mq_end_request(rq, BLK_STS_IOERR);
1406 		}
1407 	} while (!list_empty(list));
1408 out:
1409 	if (!list_empty(&zone_list))
1410 		list_splice_tail_init(&zone_list, list);
1411 
1412 	hctx->dispatched[queued_to_index(queued)]++;
1413 
1414 	/* If we didn't flush the entire list, we could have told the driver
1415 	 * there was more coming, but that turned out to be a lie.
1416 	 */
1417 	if ((!list_empty(list) || errors) && q->mq_ops->commit_rqs && queued)
1418 		q->mq_ops->commit_rqs(hctx);
1419 	/*
1420 	 * Any items that need requeuing? Stuff them into hctx->dispatch,
1421 	 * that is where we will continue on next queue run.
1422 	 */
1423 	if (!list_empty(list)) {
1424 		bool needs_restart;
1425 		/* For non-shared tags, the RESTART check will suffice */
1426 		bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
1427 			(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED);
1428 		bool no_budget_avail = prep == PREP_DISPATCH_NO_BUDGET;
1429 
1430 		blk_mq_release_budgets(q, nr_budgets);
1431 
1432 		spin_lock(&hctx->lock);
1433 		list_splice_tail_init(list, &hctx->dispatch);
1434 		spin_unlock(&hctx->lock);
1435 
1436 		/*
1437 		 * Order adding requests to hctx->dispatch and checking
1438 		 * SCHED_RESTART flag. The pair of this smp_mb() is the one
1439 		 * in blk_mq_sched_restart(). Avoid restart code path to
1440 		 * miss the new added requests to hctx->dispatch, meantime
1441 		 * SCHED_RESTART is observed here.
1442 		 */
1443 		smp_mb();
1444 
1445 		/*
1446 		 * If SCHED_RESTART was set by the caller of this function and
1447 		 * it is no longer set that means that it was cleared by another
1448 		 * thread and hence that a queue rerun is needed.
1449 		 *
1450 		 * If 'no_tag' is set, that means that we failed getting
1451 		 * a driver tag with an I/O scheduler attached. If our dispatch
1452 		 * waitqueue is no longer active, ensure that we run the queue
1453 		 * AFTER adding our entries back to the list.
1454 		 *
1455 		 * If no I/O scheduler has been configured it is possible that
1456 		 * the hardware queue got stopped and restarted before requests
1457 		 * were pushed back onto the dispatch list. Rerun the queue to
1458 		 * avoid starvation. Notes:
1459 		 * - blk_mq_run_hw_queue() checks whether or not a queue has
1460 		 *   been stopped before rerunning a queue.
1461 		 * - Some but not all block drivers stop a queue before
1462 		 *   returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1463 		 *   and dm-rq.
1464 		 *
1465 		 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1466 		 * bit is set, run queue after a delay to avoid IO stalls
1467 		 * that could otherwise occur if the queue is idle.  We'll do
1468 		 * similar if we couldn't get budget and SCHED_RESTART is set.
1469 		 */
1470 		needs_restart = blk_mq_sched_needs_restart(hctx);
1471 		if (!needs_restart ||
1472 		    (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1473 			blk_mq_run_hw_queue(hctx, true);
1474 		else if (needs_restart && (ret == BLK_STS_RESOURCE ||
1475 					   no_budget_avail))
1476 			blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1477 
1478 		blk_mq_update_dispatch_busy(hctx, true);
1479 		return false;
1480 	} else
1481 		blk_mq_update_dispatch_busy(hctx, false);
1482 
1483 	return (queued + errors) != 0;
1484 }
1485 
1486 /**
1487  * __blk_mq_run_hw_queue - Run a hardware queue.
1488  * @hctx: Pointer to the hardware queue to run.
1489  *
1490  * Send pending requests to the hardware.
1491  */
__blk_mq_run_hw_queue(struct blk_mq_hw_ctx * hctx)1492 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1493 {
1494 	int srcu_idx;
1495 
1496 	/*
1497 	 * We should be running this queue from one of the CPUs that
1498 	 * are mapped to it.
1499 	 *
1500 	 * There are at least two related races now between setting
1501 	 * hctx->next_cpu from blk_mq_hctx_next_cpu() and running
1502 	 * __blk_mq_run_hw_queue():
1503 	 *
1504 	 * - hctx->next_cpu is found offline in blk_mq_hctx_next_cpu(),
1505 	 *   but later it becomes online, then this warning is harmless
1506 	 *   at all
1507 	 *
1508 	 * - hctx->next_cpu is found online in blk_mq_hctx_next_cpu(),
1509 	 *   but later it becomes offline, then the warning can't be
1510 	 *   triggered, and we depend on blk-mq timeout handler to
1511 	 *   handle dispatched requests to this hctx
1512 	 */
1513 	if (!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask) &&
1514 		cpu_online(hctx->next_cpu)) {
1515 		printk(KERN_WARNING "run queue from wrong CPU %d, hctx %s\n",
1516 			raw_smp_processor_id(),
1517 			cpumask_empty(hctx->cpumask) ? "inactive": "active");
1518 		dump_stack();
1519 	}
1520 
1521 	/*
1522 	 * We can't run the queue inline with ints disabled. Ensure that
1523 	 * we catch bad users of this early.
1524 	 */
1525 	WARN_ON_ONCE(in_interrupt());
1526 
1527 	might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1528 
1529 	hctx_lock(hctx, &srcu_idx);
1530 	blk_mq_sched_dispatch_requests(hctx);
1531 	hctx_unlock(hctx, srcu_idx);
1532 }
1533 
blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx * hctx)1534 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1535 {
1536 	int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1537 
1538 	if (cpu >= nr_cpu_ids)
1539 		cpu = cpumask_first(hctx->cpumask);
1540 	return cpu;
1541 }
1542 
1543 /*
1544  * It'd be great if the workqueue API had a way to pass
1545  * in a mask and had some smarts for more clever placement.
1546  * For now we just round-robin here, switching for every
1547  * BLK_MQ_CPU_WORK_BATCH queued items.
1548  */
blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx * hctx)1549 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1550 {
1551 	bool tried = false;
1552 	int next_cpu = hctx->next_cpu;
1553 
1554 	if (hctx->queue->nr_hw_queues == 1)
1555 		return WORK_CPU_UNBOUND;
1556 
1557 	if (--hctx->next_cpu_batch <= 0) {
1558 select_cpu:
1559 		next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
1560 				cpu_online_mask);
1561 		if (next_cpu >= nr_cpu_ids)
1562 			next_cpu = blk_mq_first_mapped_cpu(hctx);
1563 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1564 	}
1565 
1566 	/*
1567 	 * Do unbound schedule if we can't find a online CPU for this hctx,
1568 	 * and it should only happen in the path of handling CPU DEAD.
1569 	 */
1570 	if (!cpu_online(next_cpu)) {
1571 		if (!tried) {
1572 			tried = true;
1573 			goto select_cpu;
1574 		}
1575 
1576 		/*
1577 		 * Make sure to re-select CPU next time once after CPUs
1578 		 * in hctx->cpumask become online again.
1579 		 */
1580 		hctx->next_cpu = next_cpu;
1581 		hctx->next_cpu_batch = 1;
1582 		return WORK_CPU_UNBOUND;
1583 	}
1584 
1585 	hctx->next_cpu = next_cpu;
1586 	return next_cpu;
1587 }
1588 
1589 /**
1590  * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
1591  * @hctx: Pointer to the hardware queue to run.
1592  * @async: If we want to run the queue asynchronously.
1593  * @msecs: Microseconds of delay to wait before running the queue.
1594  *
1595  * If !@async, try to run the queue now. Else, run the queue asynchronously and
1596  * with a delay of @msecs.
1597  */
__blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx * hctx,bool async,unsigned long msecs)1598 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1599 					unsigned long msecs)
1600 {
1601 	if (unlikely(blk_mq_hctx_stopped(hctx)))
1602 		return;
1603 
1604 	if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1605 		int cpu = get_cpu();
1606 		if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1607 			__blk_mq_run_hw_queue(hctx);
1608 			put_cpu();
1609 			return;
1610 		}
1611 
1612 		put_cpu();
1613 	}
1614 
1615 	kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1616 				    msecs_to_jiffies(msecs));
1617 }
1618 
1619 /**
1620  * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
1621  * @hctx: Pointer to the hardware queue to run.
1622  * @msecs: Microseconds of delay to wait before running the queue.
1623  *
1624  * Run a hardware queue asynchronously with a delay of @msecs.
1625  */
blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx * hctx,unsigned long msecs)1626 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1627 {
1628 	__blk_mq_delay_run_hw_queue(hctx, true, msecs);
1629 }
1630 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1631 
1632 /**
1633  * blk_mq_run_hw_queue - Start to run a hardware queue.
1634  * @hctx: Pointer to the hardware queue to run.
1635  * @async: If we want to run the queue asynchronously.
1636  *
1637  * Check if the request queue is not in a quiesced state and if there are
1638  * pending requests to be sent. If this is true, run the queue to send requests
1639  * to hardware.
1640  */
blk_mq_run_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)1641 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1642 {
1643 	int srcu_idx;
1644 	bool need_run;
1645 
1646 	/*
1647 	 * When queue is quiesced, we may be switching io scheduler, or
1648 	 * updating nr_hw_queues, or other things, and we can't run queue
1649 	 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1650 	 *
1651 	 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1652 	 * quiesced.
1653 	 */
1654 	hctx_lock(hctx, &srcu_idx);
1655 	need_run = !blk_queue_quiesced(hctx->queue) &&
1656 		blk_mq_hctx_has_pending(hctx);
1657 	hctx_unlock(hctx, srcu_idx);
1658 
1659 	if (need_run)
1660 		__blk_mq_delay_run_hw_queue(hctx, async, 0);
1661 }
1662 EXPORT_SYMBOL(blk_mq_run_hw_queue);
1663 
1664 /**
1665  * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
1666  * @q: Pointer to the request queue to run.
1667  * @async: If we want to run the queue asynchronously.
1668  */
blk_mq_run_hw_queues(struct request_queue * q,bool async)1669 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1670 {
1671 	struct blk_mq_hw_ctx *hctx;
1672 	int i;
1673 
1674 	queue_for_each_hw_ctx(q, hctx, i) {
1675 		if (blk_mq_hctx_stopped(hctx))
1676 			continue;
1677 
1678 		blk_mq_run_hw_queue(hctx, async);
1679 	}
1680 }
1681 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1682 
1683 /**
1684  * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
1685  * @q: Pointer to the request queue to run.
1686  * @msecs: Microseconds of delay to wait before running the queues.
1687  */
blk_mq_delay_run_hw_queues(struct request_queue * q,unsigned long msecs)1688 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
1689 {
1690 	struct blk_mq_hw_ctx *hctx;
1691 	int i;
1692 
1693 	queue_for_each_hw_ctx(q, hctx, i) {
1694 		if (blk_mq_hctx_stopped(hctx))
1695 			continue;
1696 
1697 		blk_mq_delay_run_hw_queue(hctx, msecs);
1698 	}
1699 }
1700 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
1701 
1702 /**
1703  * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1704  * @q: request queue.
1705  *
1706  * The caller is responsible for serializing this function against
1707  * blk_mq_{start,stop}_hw_queue().
1708  */
blk_mq_queue_stopped(struct request_queue * q)1709 bool blk_mq_queue_stopped(struct request_queue *q)
1710 {
1711 	struct blk_mq_hw_ctx *hctx;
1712 	int i;
1713 
1714 	queue_for_each_hw_ctx(q, hctx, i)
1715 		if (blk_mq_hctx_stopped(hctx))
1716 			return true;
1717 
1718 	return false;
1719 }
1720 EXPORT_SYMBOL(blk_mq_queue_stopped);
1721 
1722 /*
1723  * This function is often used for pausing .queue_rq() by driver when
1724  * there isn't enough resource or some conditions aren't satisfied, and
1725  * BLK_STS_RESOURCE is usually returned.
1726  *
1727  * We do not guarantee that dispatch can be drained or blocked
1728  * after blk_mq_stop_hw_queue() returns. Please use
1729  * blk_mq_quiesce_queue() for that requirement.
1730  */
blk_mq_stop_hw_queue(struct blk_mq_hw_ctx * hctx)1731 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1732 {
1733 	cancel_delayed_work(&hctx->run_work);
1734 
1735 	set_bit(BLK_MQ_S_STOPPED, &hctx->state);
1736 }
1737 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
1738 
1739 /*
1740  * This function is often used for pausing .queue_rq() by driver when
1741  * there isn't enough resource or some conditions aren't satisfied, and
1742  * BLK_STS_RESOURCE is usually returned.
1743  *
1744  * We do not guarantee that dispatch can be drained or blocked
1745  * after blk_mq_stop_hw_queues() returns. Please use
1746  * blk_mq_quiesce_queue() for that requirement.
1747  */
blk_mq_stop_hw_queues(struct request_queue * q)1748 void blk_mq_stop_hw_queues(struct request_queue *q)
1749 {
1750 	struct blk_mq_hw_ctx *hctx;
1751 	int i;
1752 
1753 	queue_for_each_hw_ctx(q, hctx, i)
1754 		blk_mq_stop_hw_queue(hctx);
1755 }
1756 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1757 
blk_mq_start_hw_queue(struct blk_mq_hw_ctx * hctx)1758 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1759 {
1760 	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1761 
1762 	blk_mq_run_hw_queue(hctx, false);
1763 }
1764 EXPORT_SYMBOL(blk_mq_start_hw_queue);
1765 
blk_mq_start_hw_queues(struct request_queue * q)1766 void blk_mq_start_hw_queues(struct request_queue *q)
1767 {
1768 	struct blk_mq_hw_ctx *hctx;
1769 	int i;
1770 
1771 	queue_for_each_hw_ctx(q, hctx, i)
1772 		blk_mq_start_hw_queue(hctx);
1773 }
1774 EXPORT_SYMBOL(blk_mq_start_hw_queues);
1775 
blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)1776 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1777 {
1778 	if (!blk_mq_hctx_stopped(hctx))
1779 		return;
1780 
1781 	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1782 	blk_mq_run_hw_queue(hctx, async);
1783 }
1784 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1785 
blk_mq_start_stopped_hw_queues(struct request_queue * q,bool async)1786 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
1787 {
1788 	struct blk_mq_hw_ctx *hctx;
1789 	int i;
1790 
1791 	queue_for_each_hw_ctx(q, hctx, i)
1792 		blk_mq_start_stopped_hw_queue(hctx, async);
1793 }
1794 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1795 
blk_mq_run_work_fn(struct work_struct * work)1796 static void blk_mq_run_work_fn(struct work_struct *work)
1797 {
1798 	struct blk_mq_hw_ctx *hctx;
1799 
1800 	hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
1801 
1802 	/*
1803 	 * If we are stopped, don't run the queue.
1804 	 */
1805 	if (blk_mq_hctx_stopped(hctx))
1806 		return;
1807 
1808 	__blk_mq_run_hw_queue(hctx);
1809 }
1810 
__blk_mq_insert_req_list(struct blk_mq_hw_ctx * hctx,struct request * rq,bool at_head)1811 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
1812 					    struct request *rq,
1813 					    bool at_head)
1814 {
1815 	struct blk_mq_ctx *ctx = rq->mq_ctx;
1816 	enum hctx_type type = hctx->type;
1817 
1818 	lockdep_assert_held(&ctx->lock);
1819 
1820 	trace_block_rq_insert(hctx->queue, rq);
1821 
1822 	if (at_head)
1823 		list_add(&rq->queuelist, &ctx->rq_lists[type]);
1824 	else
1825 		list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
1826 }
1827 
__blk_mq_insert_request(struct blk_mq_hw_ctx * hctx,struct request * rq,bool at_head)1828 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1829 			     bool at_head)
1830 {
1831 	struct blk_mq_ctx *ctx = rq->mq_ctx;
1832 
1833 	lockdep_assert_held(&ctx->lock);
1834 
1835 	__blk_mq_insert_req_list(hctx, rq, at_head);
1836 	blk_mq_hctx_mark_pending(hctx, ctx);
1837 }
1838 
1839 /**
1840  * blk_mq_request_bypass_insert - Insert a request at dispatch list.
1841  * @rq: Pointer to request to be inserted.
1842  * @at_head: true if the request should be inserted at the head of the list.
1843  * @run_queue: If we should run the hardware queue after inserting the request.
1844  *
1845  * Should only be used carefully, when the caller knows we want to
1846  * bypass a potential IO scheduler on the target device.
1847  */
blk_mq_request_bypass_insert(struct request * rq,bool at_head,bool run_queue)1848 void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
1849 				  bool run_queue)
1850 {
1851 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1852 
1853 	spin_lock(&hctx->lock);
1854 	if (at_head)
1855 		list_add(&rq->queuelist, &hctx->dispatch);
1856 	else
1857 		list_add_tail(&rq->queuelist, &hctx->dispatch);
1858 	spin_unlock(&hctx->lock);
1859 
1860 	if (run_queue)
1861 		blk_mq_run_hw_queue(hctx, false);
1862 }
1863 
blk_mq_insert_requests(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx,struct list_head * list)1864 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1865 			    struct list_head *list)
1866 
1867 {
1868 	struct request *rq;
1869 	enum hctx_type type = hctx->type;
1870 
1871 	/*
1872 	 * preemption doesn't flush plug list, so it's possible ctx->cpu is
1873 	 * offline now
1874 	 */
1875 	list_for_each_entry(rq, list, queuelist) {
1876 		BUG_ON(rq->mq_ctx != ctx);
1877 		trace_block_rq_insert(hctx->queue, rq);
1878 	}
1879 
1880 	spin_lock(&ctx->lock);
1881 	list_splice_tail_init(list, &ctx->rq_lists[type]);
1882 	blk_mq_hctx_mark_pending(hctx, ctx);
1883 	spin_unlock(&ctx->lock);
1884 }
1885 
plug_rq_cmp(void * priv,const struct list_head * a,const struct list_head * b)1886 static int plug_rq_cmp(void *priv, const struct list_head *a,
1887 		       const struct list_head *b)
1888 {
1889 	struct request *rqa = container_of(a, struct request, queuelist);
1890 	struct request *rqb = container_of(b, struct request, queuelist);
1891 
1892 	if (rqa->mq_ctx != rqb->mq_ctx)
1893 		return rqa->mq_ctx > rqb->mq_ctx;
1894 	if (rqa->mq_hctx != rqb->mq_hctx)
1895 		return rqa->mq_hctx > rqb->mq_hctx;
1896 
1897 	return blk_rq_pos(rqa) > blk_rq_pos(rqb);
1898 }
1899 
blk_mq_flush_plug_list(struct blk_plug * plug,bool from_schedule)1900 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1901 {
1902 	LIST_HEAD(list);
1903 
1904 	if (list_empty(&plug->mq_list))
1905 		return;
1906 	list_splice_init(&plug->mq_list, &list);
1907 
1908 	if (plug->rq_count > 2 && plug->multiple_queues)
1909 		list_sort(NULL, &list, plug_rq_cmp);
1910 
1911 	plug->rq_count = 0;
1912 
1913 	do {
1914 		struct list_head rq_list;
1915 		struct request *rq, *head_rq = list_entry_rq(list.next);
1916 		struct list_head *pos = &head_rq->queuelist; /* skip first */
1917 		struct blk_mq_hw_ctx *this_hctx = head_rq->mq_hctx;
1918 		struct blk_mq_ctx *this_ctx = head_rq->mq_ctx;
1919 		unsigned int depth = 1;
1920 
1921 		list_for_each_continue(pos, &list) {
1922 			rq = list_entry_rq(pos);
1923 			BUG_ON(!rq->q);
1924 			if (rq->mq_hctx != this_hctx || rq->mq_ctx != this_ctx)
1925 				break;
1926 			depth++;
1927 		}
1928 
1929 		list_cut_before(&rq_list, &list, pos);
1930 		trace_block_unplug(head_rq->q, depth, !from_schedule);
1931 		blk_mq_sched_insert_requests(this_hctx, this_ctx, &rq_list,
1932 						from_schedule);
1933 	} while(!list_empty(&list));
1934 }
1935 
blk_mq_bio_to_request(struct request * rq,struct bio * bio,unsigned int nr_segs)1936 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
1937 		unsigned int nr_segs)
1938 {
1939 	int err;
1940 
1941 	if (bio->bi_opf & REQ_RAHEAD)
1942 		rq->cmd_flags |= REQ_FAILFAST_MASK;
1943 
1944 	rq->__sector = bio->bi_iter.bi_sector;
1945 	rq->write_hint = bio->bi_write_hint;
1946 	blk_rq_bio_prep(rq, bio, nr_segs);
1947 
1948 	/* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
1949 	err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
1950 	WARN_ON_ONCE(err);
1951 
1952 	blk_account_io_start(rq);
1953 }
1954 
__blk_mq_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie,bool last)1955 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
1956 					    struct request *rq,
1957 					    blk_qc_t *cookie, bool last)
1958 {
1959 	struct request_queue *q = rq->q;
1960 	struct blk_mq_queue_data bd = {
1961 		.rq = rq,
1962 		.last = last,
1963 	};
1964 	blk_qc_t new_cookie;
1965 	blk_status_t ret;
1966 
1967 	new_cookie = request_to_qc_t(hctx, rq);
1968 
1969 	/*
1970 	 * For OK queue, we are done. For error, caller may kill it.
1971 	 * Any other error (busy), just add it to our list as we
1972 	 * previously would have done.
1973 	 */
1974 	ret = q->mq_ops->queue_rq(hctx, &bd);
1975 	switch (ret) {
1976 	case BLK_STS_OK:
1977 		blk_mq_update_dispatch_busy(hctx, false);
1978 		*cookie = new_cookie;
1979 		break;
1980 	case BLK_STS_RESOURCE:
1981 	case BLK_STS_DEV_RESOURCE:
1982 		blk_mq_update_dispatch_busy(hctx, true);
1983 		__blk_mq_requeue_request(rq);
1984 		break;
1985 	default:
1986 		blk_mq_update_dispatch_busy(hctx, false);
1987 		*cookie = BLK_QC_T_NONE;
1988 		break;
1989 	}
1990 
1991 	return ret;
1992 }
1993 
__blk_mq_try_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie,bool bypass_insert,bool last)1994 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1995 						struct request *rq,
1996 						blk_qc_t *cookie,
1997 						bool bypass_insert, bool last)
1998 {
1999 	struct request_queue *q = rq->q;
2000 	bool run_queue = true;
2001 
2002 	/*
2003 	 * RCU or SRCU read lock is needed before checking quiesced flag.
2004 	 *
2005 	 * When queue is stopped or quiesced, ignore 'bypass_insert' from
2006 	 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
2007 	 * and avoid driver to try to dispatch again.
2008 	 */
2009 	if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
2010 		run_queue = false;
2011 		bypass_insert = false;
2012 		goto insert;
2013 	}
2014 
2015 	if (q->elevator && !bypass_insert)
2016 		goto insert;
2017 
2018 	if (!blk_mq_get_dispatch_budget(q))
2019 		goto insert;
2020 
2021 	if (!blk_mq_get_driver_tag(rq)) {
2022 		blk_mq_put_dispatch_budget(q);
2023 		goto insert;
2024 	}
2025 
2026 	return __blk_mq_issue_directly(hctx, rq, cookie, last);
2027 insert:
2028 	if (bypass_insert)
2029 		return BLK_STS_RESOURCE;
2030 
2031 	blk_mq_sched_insert_request(rq, false, run_queue, false);
2032 
2033 	return BLK_STS_OK;
2034 }
2035 
2036 /**
2037  * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2038  * @hctx: Pointer of the associated hardware queue.
2039  * @rq: Pointer to request to be sent.
2040  * @cookie: Request queue cookie.
2041  *
2042  * If the device has enough resources to accept a new request now, send the
2043  * request directly to device driver. Else, insert at hctx->dispatch queue, so
2044  * we can try send it another time in the future. Requests inserted at this
2045  * queue have higher priority.
2046  */
blk_mq_try_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie)2047 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2048 		struct request *rq, blk_qc_t *cookie)
2049 {
2050 	blk_status_t ret;
2051 	int srcu_idx;
2052 
2053 	might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
2054 
2055 	hctx_lock(hctx, &srcu_idx);
2056 
2057 	ret = __blk_mq_try_issue_directly(hctx, rq, cookie, false, true);
2058 	if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
2059 		blk_mq_request_bypass_insert(rq, false, true);
2060 	else if (ret != BLK_STS_OK)
2061 		blk_mq_end_request(rq, ret);
2062 
2063 	hctx_unlock(hctx, srcu_idx);
2064 }
2065 
blk_mq_request_issue_directly(struct request * rq,bool last)2066 blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2067 {
2068 	blk_status_t ret;
2069 	int srcu_idx;
2070 	blk_qc_t unused_cookie;
2071 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2072 
2073 	hctx_lock(hctx, &srcu_idx);
2074 	ret = __blk_mq_try_issue_directly(hctx, rq, &unused_cookie, true, last);
2075 	hctx_unlock(hctx, srcu_idx);
2076 
2077 	return ret;
2078 }
2079 
blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx * hctx,struct list_head * list)2080 void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2081 		struct list_head *list)
2082 {
2083 	int queued = 0;
2084 	int errors = 0;
2085 
2086 	while (!list_empty(list)) {
2087 		blk_status_t ret;
2088 		struct request *rq = list_first_entry(list, struct request,
2089 				queuelist);
2090 
2091 		list_del_init(&rq->queuelist);
2092 		ret = blk_mq_request_issue_directly(rq, list_empty(list));
2093 		if (ret != BLK_STS_OK) {
2094 			if (ret == BLK_STS_RESOURCE ||
2095 					ret == BLK_STS_DEV_RESOURCE) {
2096 				blk_mq_request_bypass_insert(rq, false,
2097 							list_empty(list));
2098 				break;
2099 			}
2100 			blk_mq_end_request(rq, ret);
2101 			errors++;
2102 		} else
2103 			queued++;
2104 	}
2105 
2106 	/*
2107 	 * If we didn't flush the entire list, we could have told
2108 	 * the driver there was more coming, but that turned out to
2109 	 * be a lie.
2110 	 */
2111 	if ((!list_empty(list) || errors) &&
2112 	     hctx->queue->mq_ops->commit_rqs && queued)
2113 		hctx->queue->mq_ops->commit_rqs(hctx);
2114 }
2115 
blk_add_rq_to_plug(struct blk_plug * plug,struct request * rq)2116 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2117 {
2118 	list_add_tail(&rq->queuelist, &plug->mq_list);
2119 	plug->rq_count++;
2120 	if (!plug->multiple_queues && !list_is_singular(&plug->mq_list)) {
2121 		struct request *tmp;
2122 
2123 		tmp = list_first_entry(&plug->mq_list, struct request,
2124 						queuelist);
2125 		if (tmp->q != rq->q)
2126 			plug->multiple_queues = true;
2127 	}
2128 }
2129 
2130 /*
2131  * Allow 4x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
2132  * queues. This is important for md arrays to benefit from merging
2133  * requests.
2134  */
blk_plug_max_rq_count(struct blk_plug * plug)2135 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
2136 {
2137 	if (plug->multiple_queues)
2138 		return BLK_MAX_REQUEST_COUNT * 4;
2139 	return BLK_MAX_REQUEST_COUNT;
2140 }
2141 
2142 /**
2143  * blk_mq_submit_bio - Create and send a request to block device.
2144  * @bio: Bio pointer.
2145  *
2146  * Builds up a request structure from @q and @bio and send to the device. The
2147  * request may not be queued directly to hardware if:
2148  * * This request can be merged with another one
2149  * * We want to place request at plug queue for possible future merging
2150  * * There is an IO scheduler active at this queue
2151  *
2152  * It will not queue the request if there is an error with the bio, or at the
2153  * request creation.
2154  *
2155  * Returns: Request queue cookie.
2156  */
blk_mq_submit_bio(struct bio * bio)2157 blk_qc_t blk_mq_submit_bio(struct bio *bio)
2158 {
2159 	struct request_queue *q = bio->bi_disk->queue;
2160 	const int is_sync = op_is_sync(bio->bi_opf);
2161 	const int is_flush_fua = op_is_flush(bio->bi_opf);
2162 	struct blk_mq_alloc_data data = {
2163 		.q		= q,
2164 	};
2165 	struct request *rq;
2166 	struct blk_plug *plug;
2167 	struct request *same_queue_rq = NULL;
2168 	unsigned int nr_segs;
2169 	blk_qc_t cookie;
2170 	blk_status_t ret;
2171 
2172 	blk_queue_bounce(q, &bio);
2173 	__blk_queue_split(&bio, &nr_segs);
2174 
2175 	if (!bio_integrity_prep(bio))
2176 		goto queue_exit;
2177 
2178 	if (!is_flush_fua && !blk_queue_nomerges(q) &&
2179 	    blk_attempt_plug_merge(q, bio, nr_segs, &same_queue_rq))
2180 		goto queue_exit;
2181 
2182 	if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2183 		goto queue_exit;
2184 
2185 	rq_qos_throttle(q, bio);
2186 
2187 	data.cmd_flags = bio->bi_opf;
2188 	rq = __blk_mq_alloc_request(&data);
2189 	if (unlikely(!rq)) {
2190 		rq_qos_cleanup(q, bio);
2191 		if (bio->bi_opf & REQ_NOWAIT)
2192 			bio_wouldblock_error(bio);
2193 		goto queue_exit;
2194 	}
2195 
2196 	trace_block_getrq(q, bio, bio->bi_opf);
2197 
2198 	rq_qos_track(q, rq, bio);
2199 
2200 	cookie = request_to_qc_t(data.hctx, rq);
2201 
2202 	blk_mq_bio_to_request(rq, bio, nr_segs);
2203 
2204 	ret = blk_crypto_init_request(rq);
2205 	if (ret != BLK_STS_OK) {
2206 		bio->bi_status = ret;
2207 		bio_endio(bio);
2208 		blk_mq_free_request(rq);
2209 		return BLK_QC_T_NONE;
2210 	}
2211 
2212 	plug = blk_mq_plug(q, bio);
2213 	if (unlikely(is_flush_fua)) {
2214 		/* Bypass scheduler for flush requests */
2215 		blk_insert_flush(rq);
2216 		blk_mq_run_hw_queue(data.hctx, true);
2217 	} else if (plug && (q->nr_hw_queues == 1 ||
2218 		   blk_mq_is_sbitmap_shared(rq->mq_hctx->flags) ||
2219 		   q->mq_ops->commit_rqs || !blk_queue_nonrot(q))) {
2220 		/*
2221 		 * Use plugging if we have a ->commit_rqs() hook as well, as
2222 		 * we know the driver uses bd->last in a smart fashion.
2223 		 *
2224 		 * Use normal plugging if this disk is slow HDD, as sequential
2225 		 * IO may benefit a lot from plug merging.
2226 		 */
2227 		unsigned int request_count = plug->rq_count;
2228 		struct request *last = NULL;
2229 
2230 		if (!request_count)
2231 			trace_block_plug(q);
2232 		else
2233 			last = list_entry_rq(plug->mq_list.prev);
2234 
2235 		if (request_count >= blk_plug_max_rq_count(plug) || (last &&
2236 		    blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
2237 			blk_flush_plug_list(plug, false);
2238 			trace_block_plug(q);
2239 		}
2240 
2241 		blk_add_rq_to_plug(plug, rq);
2242 	} else if (q->elevator) {
2243 		/* Insert the request at the IO scheduler queue */
2244 		blk_mq_sched_insert_request(rq, false, true, true);
2245 	} else if (plug && !blk_queue_nomerges(q)) {
2246 		/*
2247 		 * We do limited plugging. If the bio can be merged, do that.
2248 		 * Otherwise the existing request in the plug list will be
2249 		 * issued. So the plug list will have one request at most
2250 		 * The plug list might get flushed before this. If that happens,
2251 		 * the plug list is empty, and same_queue_rq is invalid.
2252 		 */
2253 		if (list_empty(&plug->mq_list))
2254 			same_queue_rq = NULL;
2255 		if (same_queue_rq) {
2256 			list_del_init(&same_queue_rq->queuelist);
2257 			plug->rq_count--;
2258 		}
2259 		blk_add_rq_to_plug(plug, rq);
2260 		trace_block_plug(q);
2261 
2262 		if (same_queue_rq) {
2263 			data.hctx = same_queue_rq->mq_hctx;
2264 			trace_block_unplug(q, 1, true);
2265 			blk_mq_try_issue_directly(data.hctx, same_queue_rq,
2266 					&cookie);
2267 		}
2268 	} else if ((q->nr_hw_queues > 1 && is_sync) ||
2269 			!data.hctx->dispatch_busy) {
2270 		/*
2271 		 * There is no scheduler and we can try to send directly
2272 		 * to the hardware.
2273 		 */
2274 		blk_mq_try_issue_directly(data.hctx, rq, &cookie);
2275 	} else {
2276 		/* Default case. */
2277 		blk_mq_sched_insert_request(rq, false, true, true);
2278 	}
2279 
2280 	return cookie;
2281 queue_exit:
2282 	blk_queue_exit(q);
2283 	return BLK_QC_T_NONE;
2284 }
2285 
order_to_size(unsigned int order)2286 static size_t order_to_size(unsigned int order)
2287 {
2288 	return (size_t)PAGE_SIZE << order;
2289 }
2290 
2291 /* called before freeing request pool in @tags */
blk_mq_clear_rq_mapping(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)2292 static void blk_mq_clear_rq_mapping(struct blk_mq_tag_set *set,
2293 		struct blk_mq_tags *tags, unsigned int hctx_idx)
2294 {
2295 	struct blk_mq_tags *drv_tags = set->tags[hctx_idx];
2296 	struct page *page;
2297 	unsigned long flags;
2298 
2299 	list_for_each_entry(page, &tags->page_list, lru) {
2300 		unsigned long start = (unsigned long)page_address(page);
2301 		unsigned long end = start + order_to_size(page->private);
2302 		int i;
2303 
2304 		for (i = 0; i < set->queue_depth; i++) {
2305 			struct request *rq = drv_tags->rqs[i];
2306 			unsigned long rq_addr = (unsigned long)rq;
2307 
2308 			if (rq_addr >= start && rq_addr < end) {
2309 				WARN_ON_ONCE(refcount_read(&rq->ref) != 0);
2310 				cmpxchg(&drv_tags->rqs[i], rq, NULL);
2311 			}
2312 		}
2313 	}
2314 
2315 	/*
2316 	 * Wait until all pending iteration is done.
2317 	 *
2318 	 * Request reference is cleared and it is guaranteed to be observed
2319 	 * after the ->lock is released.
2320 	 */
2321 	spin_lock_irqsave(&drv_tags->lock, flags);
2322 	spin_unlock_irqrestore(&drv_tags->lock, flags);
2323 }
2324 
blk_mq_free_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)2325 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2326 		     unsigned int hctx_idx)
2327 {
2328 	struct page *page;
2329 
2330 	if (tags->rqs && set->ops->exit_request) {
2331 		int i;
2332 
2333 		for (i = 0; i < tags->nr_tags; i++) {
2334 			struct request *rq = tags->static_rqs[i];
2335 
2336 			if (!rq)
2337 				continue;
2338 			set->ops->exit_request(set, rq, hctx_idx);
2339 			tags->static_rqs[i] = NULL;
2340 		}
2341 	}
2342 
2343 	blk_mq_clear_rq_mapping(set, tags, hctx_idx);
2344 
2345 	while (!list_empty(&tags->page_list)) {
2346 		page = list_first_entry(&tags->page_list, struct page, lru);
2347 		list_del_init(&page->lru);
2348 		/*
2349 		 * Remove kmemleak object previously allocated in
2350 		 * blk_mq_alloc_rqs().
2351 		 */
2352 		kmemleak_free(page_address(page));
2353 		__free_pages(page, page->private);
2354 	}
2355 }
2356 
blk_mq_free_rq_map(struct blk_mq_tags * tags,unsigned int flags)2357 void blk_mq_free_rq_map(struct blk_mq_tags *tags, unsigned int flags)
2358 {
2359 	kfree(tags->rqs);
2360 	tags->rqs = NULL;
2361 	kfree(tags->static_rqs);
2362 	tags->static_rqs = NULL;
2363 
2364 	blk_mq_free_tags(tags, flags);
2365 }
2366 
blk_mq_alloc_rq_map(struct blk_mq_tag_set * set,unsigned int hctx_idx,unsigned int nr_tags,unsigned int reserved_tags,unsigned int flags)2367 struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2368 					unsigned int hctx_idx,
2369 					unsigned int nr_tags,
2370 					unsigned int reserved_tags,
2371 					unsigned int flags)
2372 {
2373 	struct blk_mq_tags *tags;
2374 	int node;
2375 
2376 	node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2377 	if (node == NUMA_NO_NODE)
2378 		node = set->numa_node;
2379 
2380 	tags = blk_mq_init_tags(nr_tags, reserved_tags, node, flags);
2381 	if (!tags)
2382 		return NULL;
2383 
2384 	tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2385 				 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2386 				 node);
2387 	if (!tags->rqs) {
2388 		blk_mq_free_tags(tags, flags);
2389 		return NULL;
2390 	}
2391 
2392 	tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2393 					GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2394 					node);
2395 	if (!tags->static_rqs) {
2396 		kfree(tags->rqs);
2397 		blk_mq_free_tags(tags, flags);
2398 		return NULL;
2399 	}
2400 
2401 	return tags;
2402 }
2403 
blk_mq_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,int node)2404 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2405 			       unsigned int hctx_idx, int node)
2406 {
2407 	int ret;
2408 
2409 	if (set->ops->init_request) {
2410 		ret = set->ops->init_request(set, rq, hctx_idx, node);
2411 		if (ret)
2412 			return ret;
2413 	}
2414 
2415 	WRITE_ONCE(rq->state, MQ_RQ_IDLE);
2416 	return 0;
2417 }
2418 
blk_mq_alloc_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx,unsigned int depth)2419 int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2420 		     unsigned int hctx_idx, unsigned int depth)
2421 {
2422 	unsigned int i, j, entries_per_page, max_order = 4;
2423 	size_t rq_size, left;
2424 	int node;
2425 
2426 	node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2427 	if (node == NUMA_NO_NODE)
2428 		node = set->numa_node;
2429 
2430 	INIT_LIST_HEAD(&tags->page_list);
2431 
2432 	/*
2433 	 * rq_size is the size of the request plus driver payload, rounded
2434 	 * to the cacheline size
2435 	 */
2436 	rq_size = round_up(sizeof(struct request) + set->cmd_size,
2437 				cache_line_size());
2438 	left = rq_size * depth;
2439 
2440 	for (i = 0; i < depth; ) {
2441 		int this_order = max_order;
2442 		struct page *page;
2443 		int to_do;
2444 		void *p;
2445 
2446 		while (this_order && left < order_to_size(this_order - 1))
2447 			this_order--;
2448 
2449 		do {
2450 			page = alloc_pages_node(node,
2451 				GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
2452 				this_order);
2453 			if (page)
2454 				break;
2455 			if (!this_order--)
2456 				break;
2457 			if (order_to_size(this_order) < rq_size)
2458 				break;
2459 		} while (1);
2460 
2461 		if (!page)
2462 			goto fail;
2463 
2464 		page->private = this_order;
2465 		list_add_tail(&page->lru, &tags->page_list);
2466 
2467 		p = page_address(page);
2468 		/*
2469 		 * Allow kmemleak to scan these pages as they contain pointers
2470 		 * to additional allocations like via ops->init_request().
2471 		 */
2472 		kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
2473 		entries_per_page = order_to_size(this_order) / rq_size;
2474 		to_do = min(entries_per_page, depth - i);
2475 		left -= to_do * rq_size;
2476 		for (j = 0; j < to_do; j++) {
2477 			struct request *rq = p;
2478 
2479 			tags->static_rqs[i] = rq;
2480 			if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2481 				tags->static_rqs[i] = NULL;
2482 				goto fail;
2483 			}
2484 
2485 			p += rq_size;
2486 			i++;
2487 		}
2488 	}
2489 	return 0;
2490 
2491 fail:
2492 	blk_mq_free_rqs(set, tags, hctx_idx);
2493 	return -ENOMEM;
2494 }
2495 
2496 struct rq_iter_data {
2497 	struct blk_mq_hw_ctx *hctx;
2498 	bool has_rq;
2499 };
2500 
blk_mq_has_request(struct request * rq,void * data,bool reserved)2501 static bool blk_mq_has_request(struct request *rq, void *data, bool reserved)
2502 {
2503 	struct rq_iter_data *iter_data = data;
2504 
2505 	if (rq->mq_hctx != iter_data->hctx)
2506 		return true;
2507 	iter_data->has_rq = true;
2508 	return false;
2509 }
2510 
blk_mq_hctx_has_requests(struct blk_mq_hw_ctx * hctx)2511 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
2512 {
2513 	struct blk_mq_tags *tags = hctx->sched_tags ?
2514 			hctx->sched_tags : hctx->tags;
2515 	struct rq_iter_data data = {
2516 		.hctx	= hctx,
2517 	};
2518 
2519 	blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
2520 	return data.has_rq;
2521 }
2522 
blk_mq_last_cpu_in_hctx(unsigned int cpu,struct blk_mq_hw_ctx * hctx)2523 static inline bool blk_mq_last_cpu_in_hctx(unsigned int cpu,
2524 		struct blk_mq_hw_ctx *hctx)
2525 {
2526 	if (cpumask_next_and(-1, hctx->cpumask, cpu_online_mask) != cpu)
2527 		return false;
2528 	if (cpumask_next_and(cpu, hctx->cpumask, cpu_online_mask) < nr_cpu_ids)
2529 		return false;
2530 	return true;
2531 }
2532 
blk_mq_hctx_notify_offline(unsigned int cpu,struct hlist_node * node)2533 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
2534 {
2535 	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2536 			struct blk_mq_hw_ctx, cpuhp_online);
2537 
2538 	if (!cpumask_test_cpu(cpu, hctx->cpumask) ||
2539 	    !blk_mq_last_cpu_in_hctx(cpu, hctx))
2540 		return 0;
2541 
2542 	/*
2543 	 * Prevent new request from being allocated on the current hctx.
2544 	 *
2545 	 * The smp_mb__after_atomic() Pairs with the implied barrier in
2546 	 * test_and_set_bit_lock in sbitmap_get().  Ensures the inactive flag is
2547 	 * seen once we return from the tag allocator.
2548 	 */
2549 	set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2550 	smp_mb__after_atomic();
2551 
2552 	/*
2553 	 * Try to grab a reference to the queue and wait for any outstanding
2554 	 * requests.  If we could not grab a reference the queue has been
2555 	 * frozen and there are no requests.
2556 	 */
2557 	if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
2558 		while (blk_mq_hctx_has_requests(hctx))
2559 			msleep(5);
2560 		percpu_ref_put(&hctx->queue->q_usage_counter);
2561 	}
2562 
2563 	return 0;
2564 }
2565 
blk_mq_hctx_notify_online(unsigned int cpu,struct hlist_node * node)2566 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
2567 {
2568 	struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2569 			struct blk_mq_hw_ctx, cpuhp_online);
2570 
2571 	if (cpumask_test_cpu(cpu, hctx->cpumask))
2572 		clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2573 	return 0;
2574 }
2575 
2576 /*
2577  * 'cpu' is going away. splice any existing rq_list entries from this
2578  * software queue to the hw queue dispatch list, and ensure that it
2579  * gets run.
2580  */
blk_mq_hctx_notify_dead(unsigned int cpu,struct hlist_node * node)2581 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
2582 {
2583 	struct blk_mq_hw_ctx *hctx;
2584 	struct blk_mq_ctx *ctx;
2585 	LIST_HEAD(tmp);
2586 	enum hctx_type type;
2587 
2588 	hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
2589 	if (!cpumask_test_cpu(cpu, hctx->cpumask))
2590 		return 0;
2591 
2592 	ctx = __blk_mq_get_ctx(hctx->queue, cpu);
2593 	type = hctx->type;
2594 
2595 	spin_lock(&ctx->lock);
2596 	if (!list_empty(&ctx->rq_lists[type])) {
2597 		list_splice_init(&ctx->rq_lists[type], &tmp);
2598 		blk_mq_hctx_clear_pending(hctx, ctx);
2599 	}
2600 	spin_unlock(&ctx->lock);
2601 
2602 	if (list_empty(&tmp))
2603 		return 0;
2604 
2605 	spin_lock(&hctx->lock);
2606 	list_splice_tail_init(&tmp, &hctx->dispatch);
2607 	spin_unlock(&hctx->lock);
2608 
2609 	blk_mq_run_hw_queue(hctx, true);
2610 	return 0;
2611 }
2612 
blk_mq_remove_cpuhp(struct blk_mq_hw_ctx * hctx)2613 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
2614 {
2615 	if (!(hctx->flags & BLK_MQ_F_STACKING))
2616 		cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2617 						    &hctx->cpuhp_online);
2618 	cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2619 					    &hctx->cpuhp_dead);
2620 }
2621 
2622 /*
2623  * Before freeing hw queue, clearing the flush request reference in
2624  * tags->rqs[] for avoiding potential UAF.
2625  */
blk_mq_clear_flush_rq_mapping(struct blk_mq_tags * tags,unsigned int queue_depth,struct request * flush_rq)2626 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
2627 		unsigned int queue_depth, struct request *flush_rq)
2628 {
2629 	int i;
2630 	unsigned long flags;
2631 
2632 	/* The hw queue may not be mapped yet */
2633 	if (!tags)
2634 		return;
2635 
2636 	WARN_ON_ONCE(refcount_read(&flush_rq->ref) != 0);
2637 
2638 	for (i = 0; i < queue_depth; i++)
2639 		cmpxchg(&tags->rqs[i], flush_rq, NULL);
2640 
2641 	/*
2642 	 * Wait until all pending iteration is done.
2643 	 *
2644 	 * Request reference is cleared and it is guaranteed to be observed
2645 	 * after the ->lock is released.
2646 	 */
2647 	spin_lock_irqsave(&tags->lock, flags);
2648 	spin_unlock_irqrestore(&tags->lock, flags);
2649 }
2650 
2651 /* 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)2652 static void blk_mq_exit_hctx(struct request_queue *q,
2653 		struct blk_mq_tag_set *set,
2654 		struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
2655 {
2656 	struct request *flush_rq = hctx->fq->flush_rq;
2657 
2658 	if (blk_mq_hw_queue_mapped(hctx))
2659 		blk_mq_tag_idle(hctx);
2660 
2661 	blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
2662 			set->queue_depth, flush_rq);
2663 	if (set->ops->exit_request)
2664 		set->ops->exit_request(set, flush_rq, hctx_idx);
2665 
2666 	if (set->ops->exit_hctx)
2667 		set->ops->exit_hctx(hctx, hctx_idx);
2668 
2669 	blk_mq_remove_cpuhp(hctx);
2670 
2671 	spin_lock(&q->unused_hctx_lock);
2672 	list_add(&hctx->hctx_list, &q->unused_hctx_list);
2673 	spin_unlock(&q->unused_hctx_lock);
2674 }
2675 
blk_mq_exit_hw_queues(struct request_queue * q,struct blk_mq_tag_set * set,int nr_queue)2676 static void blk_mq_exit_hw_queues(struct request_queue *q,
2677 		struct blk_mq_tag_set *set, int nr_queue)
2678 {
2679 	struct blk_mq_hw_ctx *hctx;
2680 	unsigned int i;
2681 
2682 	queue_for_each_hw_ctx(q, hctx, i) {
2683 		if (i == nr_queue)
2684 			break;
2685 		blk_mq_debugfs_unregister_hctx(hctx);
2686 		blk_mq_exit_hctx(q, set, hctx, i);
2687 	}
2688 }
2689 
blk_mq_hw_ctx_size(struct blk_mq_tag_set * tag_set)2690 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
2691 {
2692 	int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
2693 
2694 	BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
2695 			   __alignof__(struct blk_mq_hw_ctx)) !=
2696 		     sizeof(struct blk_mq_hw_ctx));
2697 
2698 	if (tag_set->flags & BLK_MQ_F_BLOCKING)
2699 		hw_ctx_size += sizeof(struct srcu_struct);
2700 
2701 	return hw_ctx_size;
2702 }
2703 
blk_mq_init_hctx(struct request_queue * q,struct blk_mq_tag_set * set,struct blk_mq_hw_ctx * hctx,unsigned hctx_idx)2704 static int blk_mq_init_hctx(struct request_queue *q,
2705 		struct blk_mq_tag_set *set,
2706 		struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
2707 {
2708 	hctx->queue_num = hctx_idx;
2709 
2710 	if (!(hctx->flags & BLK_MQ_F_STACKING))
2711 		cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2712 				&hctx->cpuhp_online);
2713 	cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
2714 
2715 	hctx->tags = set->tags[hctx_idx];
2716 
2717 	if (set->ops->init_hctx &&
2718 	    set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
2719 		goto unregister_cpu_notifier;
2720 
2721 	if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
2722 				hctx->numa_node))
2723 		goto exit_hctx;
2724 	return 0;
2725 
2726  exit_hctx:
2727 	if (set->ops->exit_hctx)
2728 		set->ops->exit_hctx(hctx, hctx_idx);
2729  unregister_cpu_notifier:
2730 	blk_mq_remove_cpuhp(hctx);
2731 	return -1;
2732 }
2733 
2734 static struct blk_mq_hw_ctx *
blk_mq_alloc_hctx(struct request_queue * q,struct blk_mq_tag_set * set,int node)2735 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
2736 		int node)
2737 {
2738 	struct blk_mq_hw_ctx *hctx;
2739 	gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
2740 
2741 	hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
2742 	if (!hctx)
2743 		goto fail_alloc_hctx;
2744 
2745 	if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
2746 		goto free_hctx;
2747 
2748 	atomic_set(&hctx->nr_active, 0);
2749 	atomic_set(&hctx->elevator_queued, 0);
2750 	if (node == NUMA_NO_NODE)
2751 		node = set->numa_node;
2752 	hctx->numa_node = node;
2753 
2754 	INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
2755 	spin_lock_init(&hctx->lock);
2756 	INIT_LIST_HEAD(&hctx->dispatch);
2757 	hctx->queue = q;
2758 	hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
2759 
2760 	INIT_LIST_HEAD(&hctx->hctx_list);
2761 
2762 	/*
2763 	 * Allocate space for all possible cpus to avoid allocation at
2764 	 * runtime
2765 	 */
2766 	hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
2767 			gfp, node);
2768 	if (!hctx->ctxs)
2769 		goto free_cpumask;
2770 
2771 	if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
2772 				gfp, node))
2773 		goto free_ctxs;
2774 	hctx->nr_ctx = 0;
2775 
2776 	spin_lock_init(&hctx->dispatch_wait_lock);
2777 	init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
2778 	INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
2779 
2780 	hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
2781 	if (!hctx->fq)
2782 		goto free_bitmap;
2783 
2784 	if (hctx->flags & BLK_MQ_F_BLOCKING)
2785 		init_srcu_struct(hctx->srcu);
2786 	blk_mq_hctx_kobj_init(hctx);
2787 
2788 	return hctx;
2789 
2790  free_bitmap:
2791 	sbitmap_free(&hctx->ctx_map);
2792  free_ctxs:
2793 	kfree(hctx->ctxs);
2794  free_cpumask:
2795 	free_cpumask_var(hctx->cpumask);
2796  free_hctx:
2797 	kfree(hctx);
2798  fail_alloc_hctx:
2799 	return NULL;
2800 }
2801 
blk_mq_init_cpu_queues(struct request_queue * q,unsigned int nr_hw_queues)2802 static void blk_mq_init_cpu_queues(struct request_queue *q,
2803 				   unsigned int nr_hw_queues)
2804 {
2805 	struct blk_mq_tag_set *set = q->tag_set;
2806 	unsigned int i, j;
2807 
2808 	for_each_possible_cpu(i) {
2809 		struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
2810 		struct blk_mq_hw_ctx *hctx;
2811 		int k;
2812 
2813 		__ctx->cpu = i;
2814 		spin_lock_init(&__ctx->lock);
2815 		for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
2816 			INIT_LIST_HEAD(&__ctx->rq_lists[k]);
2817 
2818 		__ctx->queue = q;
2819 
2820 		/*
2821 		 * Set local node, IFF we have more than one hw queue. If
2822 		 * not, we remain on the home node of the device
2823 		 */
2824 		for (j = 0; j < set->nr_maps; j++) {
2825 			hctx = blk_mq_map_queue_type(q, j, i);
2826 			if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
2827 				hctx->numa_node = cpu_to_node(i);
2828 		}
2829 	}
2830 }
2831 
__blk_mq_alloc_map_and_request(struct blk_mq_tag_set * set,int hctx_idx)2832 static bool __blk_mq_alloc_map_and_request(struct blk_mq_tag_set *set,
2833 					int hctx_idx)
2834 {
2835 	unsigned int flags = set->flags;
2836 	int ret = 0;
2837 
2838 	set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
2839 					set->queue_depth, set->reserved_tags, flags);
2840 	if (!set->tags[hctx_idx])
2841 		return false;
2842 
2843 	ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
2844 				set->queue_depth);
2845 	if (!ret)
2846 		return true;
2847 
2848 	blk_mq_free_rq_map(set->tags[hctx_idx], flags);
2849 	set->tags[hctx_idx] = NULL;
2850 	return false;
2851 }
2852 
blk_mq_free_map_and_requests(struct blk_mq_tag_set * set,unsigned int hctx_idx)2853 static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2854 					 unsigned int hctx_idx)
2855 {
2856 	unsigned int flags = set->flags;
2857 
2858 	if (set->tags && set->tags[hctx_idx]) {
2859 		blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
2860 		blk_mq_free_rq_map(set->tags[hctx_idx], flags);
2861 		set->tags[hctx_idx] = NULL;
2862 	}
2863 }
2864 
blk_mq_map_swqueue(struct request_queue * q)2865 static void blk_mq_map_swqueue(struct request_queue *q)
2866 {
2867 	unsigned int i, j, hctx_idx;
2868 	struct blk_mq_hw_ctx *hctx;
2869 	struct blk_mq_ctx *ctx;
2870 	struct blk_mq_tag_set *set = q->tag_set;
2871 
2872 	queue_for_each_hw_ctx(q, hctx, i) {
2873 		cpumask_clear(hctx->cpumask);
2874 		hctx->nr_ctx = 0;
2875 		hctx->dispatch_from = NULL;
2876 	}
2877 
2878 	/*
2879 	 * Map software to hardware queues.
2880 	 *
2881 	 * If the cpu isn't present, the cpu is mapped to first hctx.
2882 	 */
2883 	for_each_possible_cpu(i) {
2884 
2885 		ctx = per_cpu_ptr(q->queue_ctx, i);
2886 		for (j = 0; j < set->nr_maps; j++) {
2887 			if (!set->map[j].nr_queues) {
2888 				ctx->hctxs[j] = blk_mq_map_queue_type(q,
2889 						HCTX_TYPE_DEFAULT, i);
2890 				continue;
2891 			}
2892 			hctx_idx = set->map[j].mq_map[i];
2893 			/* unmapped hw queue can be remapped after CPU topo changed */
2894 			if (!set->tags[hctx_idx] &&
2895 			    !__blk_mq_alloc_map_and_request(set, hctx_idx)) {
2896 				/*
2897 				 * If tags initialization fail for some hctx,
2898 				 * that hctx won't be brought online.  In this
2899 				 * case, remap the current ctx to hctx[0] which
2900 				 * is guaranteed to always have tags allocated
2901 				 */
2902 				set->map[j].mq_map[i] = 0;
2903 			}
2904 
2905 			hctx = blk_mq_map_queue_type(q, j, i);
2906 			ctx->hctxs[j] = hctx;
2907 			/*
2908 			 * If the CPU is already set in the mask, then we've
2909 			 * mapped this one already. This can happen if
2910 			 * devices share queues across queue maps.
2911 			 */
2912 			if (cpumask_test_cpu(i, hctx->cpumask))
2913 				continue;
2914 
2915 			cpumask_set_cpu(i, hctx->cpumask);
2916 			hctx->type = j;
2917 			ctx->index_hw[hctx->type] = hctx->nr_ctx;
2918 			hctx->ctxs[hctx->nr_ctx++] = ctx;
2919 
2920 			/*
2921 			 * If the nr_ctx type overflows, we have exceeded the
2922 			 * amount of sw queues we can support.
2923 			 */
2924 			BUG_ON(!hctx->nr_ctx);
2925 		}
2926 
2927 		for (; j < HCTX_MAX_TYPES; j++)
2928 			ctx->hctxs[j] = blk_mq_map_queue_type(q,
2929 					HCTX_TYPE_DEFAULT, i);
2930 	}
2931 
2932 	queue_for_each_hw_ctx(q, hctx, i) {
2933 		/*
2934 		 * If no software queues are mapped to this hardware queue,
2935 		 * disable it and free the request entries.
2936 		 */
2937 		if (!hctx->nr_ctx) {
2938 			/* Never unmap queue 0.  We need it as a
2939 			 * fallback in case of a new remap fails
2940 			 * allocation
2941 			 */
2942 			if (i && set->tags[i])
2943 				blk_mq_free_map_and_requests(set, i);
2944 
2945 			hctx->tags = NULL;
2946 			continue;
2947 		}
2948 
2949 		hctx->tags = set->tags[i];
2950 		WARN_ON(!hctx->tags);
2951 
2952 		/*
2953 		 * Set the map size to the number of mapped software queues.
2954 		 * This is more accurate and more efficient than looping
2955 		 * over all possibly mapped software queues.
2956 		 */
2957 		sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
2958 
2959 		/*
2960 		 * Initialize batch roundrobin counts
2961 		 */
2962 		hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
2963 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2964 	}
2965 }
2966 
2967 /*
2968  * Caller needs to ensure that we're either frozen/quiesced, or that
2969  * the queue isn't live yet.
2970  */
queue_set_hctx_shared(struct request_queue * q,bool shared)2971 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
2972 {
2973 	struct blk_mq_hw_ctx *hctx;
2974 	int i;
2975 
2976 	queue_for_each_hw_ctx(q, hctx, i) {
2977 		if (shared) {
2978 			hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
2979 		} else {
2980 			blk_mq_tag_idle(hctx);
2981 			hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
2982 		}
2983 	}
2984 }
2985 
blk_mq_update_tag_set_shared(struct blk_mq_tag_set * set,bool shared)2986 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
2987 					 bool shared)
2988 {
2989 	struct request_queue *q;
2990 
2991 	lockdep_assert_held(&set->tag_list_lock);
2992 
2993 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
2994 		blk_mq_freeze_queue(q);
2995 		queue_set_hctx_shared(q, shared);
2996 		blk_mq_unfreeze_queue(q);
2997 	}
2998 }
2999 
blk_mq_del_queue_tag_set(struct request_queue * q)3000 static void blk_mq_del_queue_tag_set(struct request_queue *q)
3001 {
3002 	struct blk_mq_tag_set *set = q->tag_set;
3003 
3004 	mutex_lock(&set->tag_list_lock);
3005 	list_del(&q->tag_set_list);
3006 	if (list_is_singular(&set->tag_list)) {
3007 		/* just transitioned to unshared */
3008 		set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3009 		/* update existing queue */
3010 		blk_mq_update_tag_set_shared(set, false);
3011 	}
3012 	mutex_unlock(&set->tag_list_lock);
3013 	INIT_LIST_HEAD(&q->tag_set_list);
3014 }
3015 
blk_mq_add_queue_tag_set(struct blk_mq_tag_set * set,struct request_queue * q)3016 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
3017 				     struct request_queue *q)
3018 {
3019 	mutex_lock(&set->tag_list_lock);
3020 
3021 	/*
3022 	 * Check to see if we're transitioning to shared (from 1 to 2 queues).
3023 	 */
3024 	if (!list_empty(&set->tag_list) &&
3025 	    !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
3026 		set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3027 		/* update existing queue */
3028 		blk_mq_update_tag_set_shared(set, true);
3029 	}
3030 	if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
3031 		queue_set_hctx_shared(q, true);
3032 	list_add_tail(&q->tag_set_list, &set->tag_list);
3033 
3034 	mutex_unlock(&set->tag_list_lock);
3035 }
3036 
3037 /* All allocations will be freed in release handler of q->mq_kobj */
blk_mq_alloc_ctxs(struct request_queue * q)3038 static int blk_mq_alloc_ctxs(struct request_queue *q)
3039 {
3040 	struct blk_mq_ctxs *ctxs;
3041 	int cpu;
3042 
3043 	ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
3044 	if (!ctxs)
3045 		return -ENOMEM;
3046 
3047 	ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
3048 	if (!ctxs->queue_ctx)
3049 		goto fail;
3050 
3051 	for_each_possible_cpu(cpu) {
3052 		struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
3053 		ctx->ctxs = ctxs;
3054 	}
3055 
3056 	q->mq_kobj = &ctxs->kobj;
3057 	q->queue_ctx = ctxs->queue_ctx;
3058 
3059 	return 0;
3060  fail:
3061 	kfree(ctxs);
3062 	return -ENOMEM;
3063 }
3064 
3065 /*
3066  * It is the actual release handler for mq, but we do it from
3067  * request queue's release handler for avoiding use-after-free
3068  * and headache because q->mq_kobj shouldn't have been introduced,
3069  * but we can't group ctx/kctx kobj without it.
3070  */
blk_mq_release(struct request_queue * q)3071 void blk_mq_release(struct request_queue *q)
3072 {
3073 	struct blk_mq_hw_ctx *hctx, *next;
3074 	int i;
3075 
3076 	queue_for_each_hw_ctx(q, hctx, i)
3077 		WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
3078 
3079 	/* all hctx are in .unused_hctx_list now */
3080 	list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
3081 		list_del_init(&hctx->hctx_list);
3082 		kobject_put(&hctx->kobj);
3083 	}
3084 
3085 	kfree(q->queue_hw_ctx);
3086 
3087 	/*
3088 	 * release .mq_kobj and sw queue's kobject now because
3089 	 * both share lifetime with request queue.
3090 	 */
3091 	blk_mq_sysfs_deinit(q);
3092 }
3093 
blk_mq_init_queue_data(struct blk_mq_tag_set * set,void * queuedata)3094 struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
3095 		void *queuedata)
3096 {
3097 	struct request_queue *uninit_q, *q;
3098 
3099 	uninit_q = blk_alloc_queue(set->numa_node);
3100 	if (!uninit_q)
3101 		return ERR_PTR(-ENOMEM);
3102 	uninit_q->queuedata = queuedata;
3103 
3104 	/*
3105 	 * Initialize the queue without an elevator. device_add_disk() will do
3106 	 * the initialization.
3107 	 */
3108 	q = blk_mq_init_allocated_queue(set, uninit_q, false);
3109 	if (IS_ERR(q))
3110 		blk_cleanup_queue(uninit_q);
3111 
3112 	return q;
3113 }
3114 EXPORT_SYMBOL_GPL(blk_mq_init_queue_data);
3115 
blk_mq_init_queue(struct blk_mq_tag_set * set)3116 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
3117 {
3118 	return blk_mq_init_queue_data(set, NULL);
3119 }
3120 EXPORT_SYMBOL(blk_mq_init_queue);
3121 
3122 /*
3123  * Helper for setting up a queue with mq ops, given queue depth, and
3124  * the passed in mq ops flags.
3125  */
blk_mq_init_sq_queue(struct blk_mq_tag_set * set,const struct blk_mq_ops * ops,unsigned int queue_depth,unsigned int set_flags)3126 struct request_queue *blk_mq_init_sq_queue(struct blk_mq_tag_set *set,
3127 					   const struct blk_mq_ops *ops,
3128 					   unsigned int queue_depth,
3129 					   unsigned int set_flags)
3130 {
3131 	struct request_queue *q;
3132 	int ret;
3133 
3134 	memset(set, 0, sizeof(*set));
3135 	set->ops = ops;
3136 	set->nr_hw_queues = 1;
3137 	set->nr_maps = 1;
3138 	set->queue_depth = queue_depth;
3139 	set->numa_node = NUMA_NO_NODE;
3140 	set->flags = set_flags;
3141 
3142 	ret = blk_mq_alloc_tag_set(set);
3143 	if (ret)
3144 		return ERR_PTR(ret);
3145 
3146 	q = blk_mq_init_queue(set);
3147 	if (IS_ERR(q)) {
3148 		blk_mq_free_tag_set(set);
3149 		return q;
3150 	}
3151 
3152 	return q;
3153 }
3154 EXPORT_SYMBOL(blk_mq_init_sq_queue);
3155 
blk_mq_alloc_and_init_hctx(struct blk_mq_tag_set * set,struct request_queue * q,int hctx_idx,int node)3156 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
3157 		struct blk_mq_tag_set *set, struct request_queue *q,
3158 		int hctx_idx, int node)
3159 {
3160 	struct blk_mq_hw_ctx *hctx = NULL, *tmp;
3161 
3162 	/* reuse dead hctx first */
3163 	spin_lock(&q->unused_hctx_lock);
3164 	list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
3165 		if (tmp->numa_node == node) {
3166 			hctx = tmp;
3167 			break;
3168 		}
3169 	}
3170 	if (hctx)
3171 		list_del_init(&hctx->hctx_list);
3172 	spin_unlock(&q->unused_hctx_lock);
3173 
3174 	if (!hctx)
3175 		hctx = blk_mq_alloc_hctx(q, set, node);
3176 	if (!hctx)
3177 		goto fail;
3178 
3179 	if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
3180 		goto free_hctx;
3181 
3182 	return hctx;
3183 
3184  free_hctx:
3185 	kobject_put(&hctx->kobj);
3186  fail:
3187 	return NULL;
3188 }
3189 
blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set * set,struct request_queue * q)3190 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
3191 						struct request_queue *q)
3192 {
3193 	int i, j, end;
3194 	struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
3195 
3196 	if (q->nr_hw_queues < set->nr_hw_queues) {
3197 		struct blk_mq_hw_ctx **new_hctxs;
3198 
3199 		new_hctxs = kcalloc_node(set->nr_hw_queues,
3200 				       sizeof(*new_hctxs), GFP_KERNEL,
3201 				       set->numa_node);
3202 		if (!new_hctxs)
3203 			return;
3204 		if (hctxs)
3205 			memcpy(new_hctxs, hctxs, q->nr_hw_queues *
3206 			       sizeof(*hctxs));
3207 		q->queue_hw_ctx = new_hctxs;
3208 		kfree(hctxs);
3209 		hctxs = new_hctxs;
3210 	}
3211 
3212 	/* protect against switching io scheduler  */
3213 	mutex_lock(&q->sysfs_lock);
3214 	for (i = 0; i < set->nr_hw_queues; i++) {
3215 		int node;
3216 		struct blk_mq_hw_ctx *hctx;
3217 
3218 		node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
3219 		/*
3220 		 * If the hw queue has been mapped to another numa node,
3221 		 * we need to realloc the hctx. If allocation fails, fallback
3222 		 * to use the previous one.
3223 		 */
3224 		if (hctxs[i] && (hctxs[i]->numa_node == node))
3225 			continue;
3226 
3227 		hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
3228 		if (hctx) {
3229 			if (hctxs[i])
3230 				blk_mq_exit_hctx(q, set, hctxs[i], i);
3231 			hctxs[i] = hctx;
3232 		} else {
3233 			if (hctxs[i])
3234 				pr_warn("Allocate new hctx on node %d fails,\
3235 						fallback to previous one on node %d\n",
3236 						node, hctxs[i]->numa_node);
3237 			else
3238 				break;
3239 		}
3240 	}
3241 	/*
3242 	 * Increasing nr_hw_queues fails. Free the newly allocated
3243 	 * hctxs and keep the previous q->nr_hw_queues.
3244 	 */
3245 	if (i != set->nr_hw_queues) {
3246 		j = q->nr_hw_queues;
3247 		end = i;
3248 	} else {
3249 		j = i;
3250 		end = q->nr_hw_queues;
3251 		q->nr_hw_queues = set->nr_hw_queues;
3252 	}
3253 
3254 	for (; j < end; j++) {
3255 		struct blk_mq_hw_ctx *hctx = hctxs[j];
3256 
3257 		if (hctx) {
3258 			blk_mq_exit_hctx(q, set, hctx, j);
3259 			hctxs[j] = NULL;
3260 		}
3261 	}
3262 	mutex_unlock(&q->sysfs_lock);
3263 }
3264 
blk_mq_init_allocated_queue(struct blk_mq_tag_set * set,struct request_queue * q,bool elevator_init)3265 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
3266 						  struct request_queue *q,
3267 						  bool elevator_init)
3268 {
3269 	/* mark the queue as mq asap */
3270 	q->mq_ops = set->ops;
3271 
3272 	q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
3273 					     blk_mq_poll_stats_bkt,
3274 					     BLK_MQ_POLL_STATS_BKTS, q);
3275 	if (!q->poll_cb)
3276 		goto err_exit;
3277 
3278 	if (blk_mq_alloc_ctxs(q))
3279 		goto err_poll;
3280 
3281 	/* init q->mq_kobj and sw queues' kobjects */
3282 	blk_mq_sysfs_init(q);
3283 
3284 	INIT_LIST_HEAD(&q->unused_hctx_list);
3285 	spin_lock_init(&q->unused_hctx_lock);
3286 
3287 	blk_mq_realloc_hw_ctxs(set, q);
3288 	if (!q->nr_hw_queues)
3289 		goto err_hctxs;
3290 
3291 	INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
3292 	blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
3293 
3294 	q->tag_set = set;
3295 
3296 	q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
3297 	if (set->nr_maps > HCTX_TYPE_POLL &&
3298 	    set->map[HCTX_TYPE_POLL].nr_queues)
3299 		blk_queue_flag_set(QUEUE_FLAG_POLL, q);
3300 
3301 	q->sg_reserved_size = INT_MAX;
3302 
3303 	INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
3304 	INIT_LIST_HEAD(&q->requeue_list);
3305 	spin_lock_init(&q->requeue_lock);
3306 
3307 	q->nr_requests = set->queue_depth;
3308 
3309 	/*
3310 	 * Default to classic polling
3311 	 */
3312 	q->poll_nsec = BLK_MQ_POLL_CLASSIC;
3313 
3314 	blk_mq_init_cpu_queues(q, set->nr_hw_queues);
3315 	blk_mq_add_queue_tag_set(set, q);
3316 	blk_mq_map_swqueue(q);
3317 
3318 	if (elevator_init)
3319 		elevator_init_mq(q);
3320 
3321 	return q;
3322 
3323 err_hctxs:
3324 	kfree(q->queue_hw_ctx);
3325 	q->nr_hw_queues = 0;
3326 	blk_mq_sysfs_deinit(q);
3327 err_poll:
3328 	blk_stat_free_callback(q->poll_cb);
3329 	q->poll_cb = NULL;
3330 err_exit:
3331 	q->mq_ops = NULL;
3332 	return ERR_PTR(-ENOMEM);
3333 }
3334 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
3335 
3336 /* tags can _not_ be used after returning from blk_mq_exit_queue */
blk_mq_exit_queue(struct request_queue * q)3337 void blk_mq_exit_queue(struct request_queue *q)
3338 {
3339 	struct blk_mq_tag_set *set = q->tag_set;
3340 
3341 	/* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
3342 	blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
3343 	/* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
3344 	blk_mq_del_queue_tag_set(q);
3345 }
3346 
__blk_mq_alloc_rq_maps(struct blk_mq_tag_set * set)3347 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
3348 {
3349 	int i;
3350 
3351 	for (i = 0; i < set->nr_hw_queues; i++) {
3352 		if (!__blk_mq_alloc_map_and_request(set, i))
3353 			goto out_unwind;
3354 		cond_resched();
3355 	}
3356 
3357 	return 0;
3358 
3359 out_unwind:
3360 	while (--i >= 0)
3361 		blk_mq_free_map_and_requests(set, i);
3362 
3363 	return -ENOMEM;
3364 }
3365 
3366 /*
3367  * Allocate the request maps associated with this tag_set. Note that this
3368  * may reduce the depth asked for, if memory is tight. set->queue_depth
3369  * will be updated to reflect the allocated depth.
3370  */
blk_mq_alloc_map_and_requests(struct blk_mq_tag_set * set)3371 static int blk_mq_alloc_map_and_requests(struct blk_mq_tag_set *set)
3372 {
3373 	unsigned int depth;
3374 	int err;
3375 
3376 	depth = set->queue_depth;
3377 	do {
3378 		err = __blk_mq_alloc_rq_maps(set);
3379 		if (!err)
3380 			break;
3381 
3382 		set->queue_depth >>= 1;
3383 		if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
3384 			err = -ENOMEM;
3385 			break;
3386 		}
3387 	} while (set->queue_depth);
3388 
3389 	if (!set->queue_depth || err) {
3390 		pr_err("blk-mq: failed to allocate request map\n");
3391 		return -ENOMEM;
3392 	}
3393 
3394 	if (depth != set->queue_depth)
3395 		pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
3396 						depth, set->queue_depth);
3397 
3398 	return 0;
3399 }
3400 
blk_mq_update_queue_map(struct blk_mq_tag_set * set)3401 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
3402 {
3403 	/*
3404 	 * blk_mq_map_queues() and multiple .map_queues() implementations
3405 	 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
3406 	 * number of hardware queues.
3407 	 */
3408 	if (set->nr_maps == 1)
3409 		set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
3410 
3411 	if (set->ops->map_queues && !is_kdump_kernel()) {
3412 		int i;
3413 
3414 		/*
3415 		 * transport .map_queues is usually done in the following
3416 		 * way:
3417 		 *
3418 		 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
3419 		 * 	mask = get_cpu_mask(queue)
3420 		 * 	for_each_cpu(cpu, mask)
3421 		 * 		set->map[x].mq_map[cpu] = queue;
3422 		 * }
3423 		 *
3424 		 * When we need to remap, the table has to be cleared for
3425 		 * killing stale mapping since one CPU may not be mapped
3426 		 * to any hw queue.
3427 		 */
3428 		for (i = 0; i < set->nr_maps; i++)
3429 			blk_mq_clear_mq_map(&set->map[i]);
3430 
3431 		return set->ops->map_queues(set);
3432 	} else {
3433 		BUG_ON(set->nr_maps > 1);
3434 		return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3435 	}
3436 }
3437 
blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set * set,int cur_nr_hw_queues,int new_nr_hw_queues)3438 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
3439 				  int cur_nr_hw_queues, int new_nr_hw_queues)
3440 {
3441 	struct blk_mq_tags **new_tags;
3442 
3443 	if (cur_nr_hw_queues >= new_nr_hw_queues)
3444 		return 0;
3445 
3446 	new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
3447 				GFP_KERNEL, set->numa_node);
3448 	if (!new_tags)
3449 		return -ENOMEM;
3450 
3451 	if (set->tags)
3452 		memcpy(new_tags, set->tags, cur_nr_hw_queues *
3453 		       sizeof(*set->tags));
3454 	kfree(set->tags);
3455 	set->tags = new_tags;
3456 	set->nr_hw_queues = new_nr_hw_queues;
3457 
3458 	return 0;
3459 }
3460 
3461 /*
3462  * Alloc a tag set to be associated with one or more request queues.
3463  * May fail with EINVAL for various error conditions. May adjust the
3464  * requested depth down, if it's too large. In that case, the set
3465  * value will be stored in set->queue_depth.
3466  */
blk_mq_alloc_tag_set(struct blk_mq_tag_set * set)3467 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
3468 {
3469 	int i, ret;
3470 
3471 	BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
3472 
3473 	if (!set->nr_hw_queues)
3474 		return -EINVAL;
3475 	if (!set->queue_depth)
3476 		return -EINVAL;
3477 	if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
3478 		return -EINVAL;
3479 
3480 	if (!set->ops->queue_rq)
3481 		return -EINVAL;
3482 
3483 	if (!set->ops->get_budget ^ !set->ops->put_budget)
3484 		return -EINVAL;
3485 
3486 	if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
3487 		pr_info("blk-mq: reduced tag depth to %u\n",
3488 			BLK_MQ_MAX_DEPTH);
3489 		set->queue_depth = BLK_MQ_MAX_DEPTH;
3490 	}
3491 
3492 	if (!set->nr_maps)
3493 		set->nr_maps = 1;
3494 	else if (set->nr_maps > HCTX_MAX_TYPES)
3495 		return -EINVAL;
3496 
3497 	/*
3498 	 * If a crashdump is active, then we are potentially in a very
3499 	 * memory constrained environment. Limit us to 1 queue and
3500 	 * 64 tags to prevent using too much memory.
3501 	 */
3502 	if (is_kdump_kernel()) {
3503 		set->nr_hw_queues = 1;
3504 		set->nr_maps = 1;
3505 		set->queue_depth = min(64U, set->queue_depth);
3506 	}
3507 	/*
3508 	 * There is no use for more h/w queues than cpus if we just have
3509 	 * a single map
3510 	 */
3511 	if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
3512 		set->nr_hw_queues = nr_cpu_ids;
3513 
3514 	if (blk_mq_realloc_tag_set_tags(set, 0, set->nr_hw_queues) < 0)
3515 		return -ENOMEM;
3516 
3517 	ret = -ENOMEM;
3518 	for (i = 0; i < set->nr_maps; i++) {
3519 		set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
3520 						  sizeof(set->map[i].mq_map[0]),
3521 						  GFP_KERNEL, set->numa_node);
3522 		if (!set->map[i].mq_map)
3523 			goto out_free_mq_map;
3524 		set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
3525 	}
3526 
3527 	ret = blk_mq_update_queue_map(set);
3528 	if (ret)
3529 		goto out_free_mq_map;
3530 
3531 	ret = blk_mq_alloc_map_and_requests(set);
3532 	if (ret)
3533 		goto out_free_mq_map;
3534 
3535 	if (blk_mq_is_sbitmap_shared(set->flags)) {
3536 		atomic_set(&set->active_queues_shared_sbitmap, 0);
3537 
3538 		if (blk_mq_init_shared_sbitmap(set, set->flags)) {
3539 			ret = -ENOMEM;
3540 			goto out_free_mq_rq_maps;
3541 		}
3542 	}
3543 
3544 	mutex_init(&set->tag_list_lock);
3545 	INIT_LIST_HEAD(&set->tag_list);
3546 
3547 	return 0;
3548 
3549 out_free_mq_rq_maps:
3550 	for (i = 0; i < set->nr_hw_queues; i++)
3551 		blk_mq_free_map_and_requests(set, i);
3552 out_free_mq_map:
3553 	for (i = 0; i < set->nr_maps; i++) {
3554 		kfree(set->map[i].mq_map);
3555 		set->map[i].mq_map = NULL;
3556 	}
3557 	kfree(set->tags);
3558 	set->tags = NULL;
3559 	return ret;
3560 }
3561 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
3562 
blk_mq_free_tag_set(struct blk_mq_tag_set * set)3563 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
3564 {
3565 	int i, j;
3566 
3567 	for (i = 0; i < set->nr_hw_queues; i++)
3568 		blk_mq_free_map_and_requests(set, i);
3569 
3570 	if (blk_mq_is_sbitmap_shared(set->flags))
3571 		blk_mq_exit_shared_sbitmap(set);
3572 
3573 	for (j = 0; j < set->nr_maps; j++) {
3574 		kfree(set->map[j].mq_map);
3575 		set->map[j].mq_map = NULL;
3576 	}
3577 
3578 	kfree(set->tags);
3579 	set->tags = NULL;
3580 }
3581 EXPORT_SYMBOL(blk_mq_free_tag_set);
3582 
blk_mq_update_nr_requests(struct request_queue * q,unsigned int nr)3583 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
3584 {
3585 	struct blk_mq_tag_set *set = q->tag_set;
3586 	struct blk_mq_hw_ctx *hctx;
3587 	int i, ret;
3588 
3589 	if (!set)
3590 		return -EINVAL;
3591 
3592 	if (q->nr_requests == nr)
3593 		return 0;
3594 
3595 	blk_mq_freeze_queue(q);
3596 	blk_mq_quiesce_queue(q);
3597 
3598 	ret = 0;
3599 	queue_for_each_hw_ctx(q, hctx, i) {
3600 		if (!hctx->tags)
3601 			continue;
3602 		/*
3603 		 * If we're using an MQ scheduler, just update the scheduler
3604 		 * queue depth. This is similar to what the old code would do.
3605 		 */
3606 		if (!hctx->sched_tags) {
3607 			ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
3608 							false);
3609 			if (!ret && blk_mq_is_sbitmap_shared(set->flags))
3610 				blk_mq_tag_resize_shared_sbitmap(set, nr);
3611 		} else {
3612 			ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
3613 							nr, true);
3614 		}
3615 		if (ret)
3616 			break;
3617 		if (q->elevator && q->elevator->type->ops.depth_updated)
3618 			q->elevator->type->ops.depth_updated(hctx);
3619 	}
3620 
3621 	if (!ret)
3622 		q->nr_requests = nr;
3623 
3624 	blk_mq_unquiesce_queue(q);
3625 	blk_mq_unfreeze_queue(q);
3626 
3627 	return ret;
3628 }
3629 
3630 /*
3631  * request_queue and elevator_type pair.
3632  * It is just used by __blk_mq_update_nr_hw_queues to cache
3633  * the elevator_type associated with a request_queue.
3634  */
3635 struct blk_mq_qe_pair {
3636 	struct list_head node;
3637 	struct request_queue *q;
3638 	struct elevator_type *type;
3639 };
3640 
3641 /*
3642  * Cache the elevator_type in qe pair list and switch the
3643  * io scheduler to 'none'
3644  */
blk_mq_elv_switch_none(struct list_head * head,struct request_queue * q)3645 static bool blk_mq_elv_switch_none(struct list_head *head,
3646 		struct request_queue *q)
3647 {
3648 	struct blk_mq_qe_pair *qe;
3649 
3650 	if (!q->elevator)
3651 		return true;
3652 
3653 	qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
3654 	if (!qe)
3655 		return false;
3656 
3657 	INIT_LIST_HEAD(&qe->node);
3658 	qe->q = q;
3659 	qe->type = q->elevator->type;
3660 	list_add(&qe->node, head);
3661 
3662 	mutex_lock(&q->sysfs_lock);
3663 	/*
3664 	 * After elevator_switch_mq, the previous elevator_queue will be
3665 	 * released by elevator_release. The reference of the io scheduler
3666 	 * module get by elevator_get will also be put. So we need to get
3667 	 * a reference of the io scheduler module here to prevent it to be
3668 	 * removed.
3669 	 */
3670 	__module_get(qe->type->elevator_owner);
3671 	elevator_switch_mq(q, NULL);
3672 	mutex_unlock(&q->sysfs_lock);
3673 
3674 	return true;
3675 }
3676 
blk_mq_elv_switch_back(struct list_head * head,struct request_queue * q)3677 static void blk_mq_elv_switch_back(struct list_head *head,
3678 		struct request_queue *q)
3679 {
3680 	struct blk_mq_qe_pair *qe;
3681 	struct elevator_type *t = NULL;
3682 
3683 	list_for_each_entry(qe, head, node)
3684 		if (qe->q == q) {
3685 			t = qe->type;
3686 			break;
3687 		}
3688 
3689 	if (!t)
3690 		return;
3691 
3692 	list_del(&qe->node);
3693 	kfree(qe);
3694 
3695 	mutex_lock(&q->sysfs_lock);
3696 	elevator_switch_mq(q, t);
3697 	mutex_unlock(&q->sysfs_lock);
3698 }
3699 
__blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)3700 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
3701 							int nr_hw_queues)
3702 {
3703 	struct request_queue *q;
3704 	LIST_HEAD(head);
3705 	int prev_nr_hw_queues;
3706 
3707 	lockdep_assert_held(&set->tag_list_lock);
3708 
3709 	if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
3710 		nr_hw_queues = nr_cpu_ids;
3711 	if (nr_hw_queues < 1)
3712 		return;
3713 	if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
3714 		return;
3715 
3716 	list_for_each_entry(q, &set->tag_list, tag_set_list)
3717 		blk_mq_freeze_queue(q);
3718 	/*
3719 	 * Switch IO scheduler to 'none', cleaning up the data associated
3720 	 * with the previous scheduler. We will switch back once we are done
3721 	 * updating the new sw to hw queue mappings.
3722 	 */
3723 	list_for_each_entry(q, &set->tag_list, tag_set_list)
3724 		if (!blk_mq_elv_switch_none(&head, q))
3725 			goto switch_back;
3726 
3727 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
3728 		blk_mq_debugfs_unregister_hctxs(q);
3729 		blk_mq_sysfs_unregister(q);
3730 	}
3731 
3732 	prev_nr_hw_queues = set->nr_hw_queues;
3733 	if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
3734 	    0)
3735 		goto reregister;
3736 
3737 	set->nr_hw_queues = nr_hw_queues;
3738 fallback:
3739 	blk_mq_update_queue_map(set);
3740 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
3741 		blk_mq_realloc_hw_ctxs(set, q);
3742 		if (q->nr_hw_queues != set->nr_hw_queues) {
3743 			int i = prev_nr_hw_queues;
3744 
3745 			pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
3746 					nr_hw_queues, prev_nr_hw_queues);
3747 			for (; i < set->nr_hw_queues; i++)
3748 				blk_mq_free_map_and_requests(set, i);
3749 
3750 			set->nr_hw_queues = prev_nr_hw_queues;
3751 			blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3752 			goto fallback;
3753 		}
3754 		blk_mq_map_swqueue(q);
3755 	}
3756 
3757 reregister:
3758 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
3759 		blk_mq_sysfs_register(q);
3760 		blk_mq_debugfs_register_hctxs(q);
3761 	}
3762 
3763 switch_back:
3764 	list_for_each_entry(q, &set->tag_list, tag_set_list)
3765 		blk_mq_elv_switch_back(&head, q);
3766 
3767 	list_for_each_entry(q, &set->tag_list, tag_set_list)
3768 		blk_mq_unfreeze_queue(q);
3769 }
3770 
blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)3771 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
3772 {
3773 	mutex_lock(&set->tag_list_lock);
3774 	__blk_mq_update_nr_hw_queues(set, nr_hw_queues);
3775 	mutex_unlock(&set->tag_list_lock);
3776 }
3777 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
3778 
3779 /* Enable polling stats and return whether they were already enabled. */
blk_poll_stats_enable(struct request_queue * q)3780 static bool blk_poll_stats_enable(struct request_queue *q)
3781 {
3782 	if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3783 	    blk_queue_flag_test_and_set(QUEUE_FLAG_POLL_STATS, q))
3784 		return true;
3785 	blk_stat_add_callback(q, q->poll_cb);
3786 	return false;
3787 }
3788 
blk_mq_poll_stats_start(struct request_queue * q)3789 static void blk_mq_poll_stats_start(struct request_queue *q)
3790 {
3791 	/*
3792 	 * We don't arm the callback if polling stats are not enabled or the
3793 	 * callback is already active.
3794 	 */
3795 	if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3796 	    blk_stat_is_active(q->poll_cb))
3797 		return;
3798 
3799 	blk_stat_activate_msecs(q->poll_cb, 100);
3800 }
3801 
blk_mq_poll_stats_fn(struct blk_stat_callback * cb)3802 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
3803 {
3804 	struct request_queue *q = cb->data;
3805 	int bucket;
3806 
3807 	for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
3808 		if (cb->stat[bucket].nr_samples)
3809 			q->poll_stat[bucket] = cb->stat[bucket];
3810 	}
3811 }
3812 
blk_mq_poll_nsecs(struct request_queue * q,struct request * rq)3813 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
3814 				       struct request *rq)
3815 {
3816 	unsigned long ret = 0;
3817 	int bucket;
3818 
3819 	/*
3820 	 * If stats collection isn't on, don't sleep but turn it on for
3821 	 * future users
3822 	 */
3823 	if (!blk_poll_stats_enable(q))
3824 		return 0;
3825 
3826 	/*
3827 	 * As an optimistic guess, use half of the mean service time
3828 	 * for this type of request. We can (and should) make this smarter.
3829 	 * For instance, if the completion latencies are tight, we can
3830 	 * get closer than just half the mean. This is especially
3831 	 * important on devices where the completion latencies are longer
3832 	 * than ~10 usec. We do use the stats for the relevant IO size
3833 	 * if available which does lead to better estimates.
3834 	 */
3835 	bucket = blk_mq_poll_stats_bkt(rq);
3836 	if (bucket < 0)
3837 		return ret;
3838 
3839 	if (q->poll_stat[bucket].nr_samples)
3840 		ret = (q->poll_stat[bucket].mean + 1) / 2;
3841 
3842 	return ret;
3843 }
3844 
blk_mq_poll_hybrid_sleep(struct request_queue * q,struct request * rq)3845 static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
3846 				     struct request *rq)
3847 {
3848 	struct hrtimer_sleeper hs;
3849 	enum hrtimer_mode mode;
3850 	unsigned int nsecs;
3851 	ktime_t kt;
3852 
3853 	if (rq->rq_flags & RQF_MQ_POLL_SLEPT)
3854 		return false;
3855 
3856 	/*
3857 	 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
3858 	 *
3859 	 *  0:	use half of prev avg
3860 	 * >0:	use this specific value
3861 	 */
3862 	if (q->poll_nsec > 0)
3863 		nsecs = q->poll_nsec;
3864 	else
3865 		nsecs = blk_mq_poll_nsecs(q, rq);
3866 
3867 	if (!nsecs)
3868 		return false;
3869 
3870 	rq->rq_flags |= RQF_MQ_POLL_SLEPT;
3871 
3872 	/*
3873 	 * This will be replaced with the stats tracking code, using
3874 	 * 'avg_completion_time / 2' as the pre-sleep target.
3875 	 */
3876 	kt = nsecs;
3877 
3878 	mode = HRTIMER_MODE_REL;
3879 	hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
3880 	hrtimer_set_expires(&hs.timer, kt);
3881 
3882 	do {
3883 		if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
3884 			break;
3885 		set_current_state(TASK_UNINTERRUPTIBLE);
3886 		hrtimer_sleeper_start_expires(&hs, mode);
3887 		if (hs.task)
3888 			io_schedule();
3889 		hrtimer_cancel(&hs.timer);
3890 		mode = HRTIMER_MODE_ABS;
3891 	} while (hs.task && !signal_pending(current));
3892 
3893 	__set_current_state(TASK_RUNNING);
3894 	destroy_hrtimer_on_stack(&hs.timer);
3895 	return true;
3896 }
3897 
blk_mq_poll_hybrid(struct request_queue * q,struct blk_mq_hw_ctx * hctx,blk_qc_t cookie)3898 static bool blk_mq_poll_hybrid(struct request_queue *q,
3899 			       struct blk_mq_hw_ctx *hctx, blk_qc_t cookie)
3900 {
3901 	struct request *rq;
3902 
3903 	if (q->poll_nsec == BLK_MQ_POLL_CLASSIC)
3904 		return false;
3905 
3906 	if (!blk_qc_t_is_internal(cookie))
3907 		rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
3908 	else {
3909 		rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
3910 		/*
3911 		 * With scheduling, if the request has completed, we'll
3912 		 * get a NULL return here, as we clear the sched tag when
3913 		 * that happens. The request still remains valid, like always,
3914 		 * so we should be safe with just the NULL check.
3915 		 */
3916 		if (!rq)
3917 			return false;
3918 	}
3919 
3920 	return blk_mq_poll_hybrid_sleep(q, rq);
3921 }
3922 
3923 /**
3924  * blk_poll - poll for IO completions
3925  * @q:  the queue
3926  * @cookie: cookie passed back at IO submission time
3927  * @spin: whether to spin for completions
3928  *
3929  * Description:
3930  *    Poll for completions on the passed in queue. Returns number of
3931  *    completed entries found. If @spin is true, then blk_poll will continue
3932  *    looping until at least one completion is found, unless the task is
3933  *    otherwise marked running (or we need to reschedule).
3934  */
blk_poll(struct request_queue * q,blk_qc_t cookie,bool spin)3935 int blk_poll(struct request_queue *q, blk_qc_t cookie, bool spin)
3936 {
3937 	struct blk_mq_hw_ctx *hctx;
3938 	long state;
3939 
3940 	if (!blk_qc_t_valid(cookie) ||
3941 	    !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3942 		return 0;
3943 
3944 	if (current->plug)
3945 		blk_flush_plug_list(current->plug, false);
3946 
3947 	hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
3948 
3949 	/*
3950 	 * If we sleep, have the caller restart the poll loop to reset
3951 	 * the state. Like for the other success return cases, the
3952 	 * caller is responsible for checking if the IO completed. If
3953 	 * the IO isn't complete, we'll get called again and will go
3954 	 * straight to the busy poll loop.
3955 	 */
3956 	if (blk_mq_poll_hybrid(q, hctx, cookie))
3957 		return 1;
3958 
3959 	hctx->poll_considered++;
3960 
3961 	state = current->state;
3962 	do {
3963 		int ret;
3964 
3965 		hctx->poll_invoked++;
3966 
3967 		ret = q->mq_ops->poll(hctx);
3968 		if (ret > 0) {
3969 			hctx->poll_success++;
3970 			__set_current_state(TASK_RUNNING);
3971 			return ret;
3972 		}
3973 
3974 		if (signal_pending_state(state, current))
3975 			__set_current_state(TASK_RUNNING);
3976 
3977 		if (current->state == TASK_RUNNING)
3978 			return 1;
3979 		if (ret < 0 || !spin)
3980 			break;
3981 		cpu_relax();
3982 	} while (!need_resched());
3983 
3984 	__set_current_state(TASK_RUNNING);
3985 	return 0;
3986 }
3987 EXPORT_SYMBOL_GPL(blk_poll);
3988 
blk_mq_rq_cpu(struct request * rq)3989 unsigned int blk_mq_rq_cpu(struct request *rq)
3990 {
3991 	return rq->mq_ctx->cpu;
3992 }
3993 EXPORT_SYMBOL(blk_mq_rq_cpu);
3994 
blk_mq_cancel_work_sync(struct request_queue * q)3995 void blk_mq_cancel_work_sync(struct request_queue *q)
3996 {
3997 	if (queue_is_mq(q)) {
3998 		struct blk_mq_hw_ctx *hctx;
3999 		int i;
4000 
4001 		cancel_delayed_work_sync(&q->requeue_work);
4002 
4003 		queue_for_each_hw_ctx(q, hctx, i)
4004 			cancel_delayed_work_sync(&hctx->run_work);
4005 	}
4006 }
4007 
blk_mq_init(void)4008 static int __init blk_mq_init(void)
4009 {
4010 	int i;
4011 
4012 	for_each_possible_cpu(i)
4013 		INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
4014 	open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
4015 
4016 	cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
4017 				  "block/softirq:dead", NULL,
4018 				  blk_softirq_cpu_dead);
4019 	cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
4020 				blk_mq_hctx_notify_dead);
4021 	cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
4022 				blk_mq_hctx_notify_online,
4023 				blk_mq_hctx_notify_offline);
4024 	return 0;
4025 }
4026 subsys_initcall(blk_mq_init);
4027