xref: /openbmc/linux/block/blk-mq.c (revision 3805e6a1)
1 /*
2  * Block multiqueue core code
3  *
4  * Copyright (C) 2013-2014 Jens Axboe
5  * Copyright (C) 2013-2014 Christoph Hellwig
6  */
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/backing-dev.h>
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/kmemleak.h>
13 #include <linux/mm.h>
14 #include <linux/init.h>
15 #include <linux/slab.h>
16 #include <linux/workqueue.h>
17 #include <linux/smp.h>
18 #include <linux/llist.h>
19 #include <linux/list_sort.h>
20 #include <linux/cpu.h>
21 #include <linux/cache.h>
22 #include <linux/sched/sysctl.h>
23 #include <linux/delay.h>
24 #include <linux/crash_dump.h>
25 
26 #include <trace/events/block.h>
27 
28 #include <linux/blk-mq.h>
29 #include "blk.h"
30 #include "blk-mq.h"
31 #include "blk-mq-tag.h"
32 
33 static DEFINE_MUTEX(all_q_mutex);
34 static LIST_HEAD(all_q_list);
35 
36 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx);
37 
38 /*
39  * Check if any of the ctx's have pending work in this hardware queue
40  */
41 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
42 {
43 	unsigned int i;
44 
45 	for (i = 0; i < hctx->ctx_map.size; i++)
46 		if (hctx->ctx_map.map[i].word)
47 			return true;
48 
49 	return false;
50 }
51 
52 static inline struct blk_align_bitmap *get_bm(struct blk_mq_hw_ctx *hctx,
53 					      struct blk_mq_ctx *ctx)
54 {
55 	return &hctx->ctx_map.map[ctx->index_hw / hctx->ctx_map.bits_per_word];
56 }
57 
58 #define CTX_TO_BIT(hctx, ctx)	\
59 	((ctx)->index_hw & ((hctx)->ctx_map.bits_per_word - 1))
60 
61 /*
62  * Mark this ctx as having pending work in this hardware queue
63  */
64 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
65 				     struct blk_mq_ctx *ctx)
66 {
67 	struct blk_align_bitmap *bm = get_bm(hctx, ctx);
68 
69 	if (!test_bit(CTX_TO_BIT(hctx, ctx), &bm->word))
70 		set_bit(CTX_TO_BIT(hctx, ctx), &bm->word);
71 }
72 
73 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
74 				      struct blk_mq_ctx *ctx)
75 {
76 	struct blk_align_bitmap *bm = get_bm(hctx, ctx);
77 
78 	clear_bit(CTX_TO_BIT(hctx, ctx), &bm->word);
79 }
80 
81 void blk_mq_freeze_queue_start(struct request_queue *q)
82 {
83 	int freeze_depth;
84 
85 	freeze_depth = atomic_inc_return(&q->mq_freeze_depth);
86 	if (freeze_depth == 1) {
87 		percpu_ref_kill(&q->q_usage_counter);
88 		blk_mq_run_hw_queues(q, false);
89 	}
90 }
91 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_start);
92 
93 static void blk_mq_freeze_queue_wait(struct request_queue *q)
94 {
95 	wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
96 }
97 
98 /*
99  * Guarantee no request is in use, so we can change any data structure of
100  * the queue afterward.
101  */
102 void blk_freeze_queue(struct request_queue *q)
103 {
104 	/*
105 	 * In the !blk_mq case we are only calling this to kill the
106 	 * q_usage_counter, otherwise this increases the freeze depth
107 	 * and waits for it to return to zero.  For this reason there is
108 	 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
109 	 * exported to drivers as the only user for unfreeze is blk_mq.
110 	 */
111 	blk_mq_freeze_queue_start(q);
112 	blk_mq_freeze_queue_wait(q);
113 }
114 
115 void blk_mq_freeze_queue(struct request_queue *q)
116 {
117 	/*
118 	 * ...just an alias to keep freeze and unfreeze actions balanced
119 	 * in the blk_mq_* namespace
120 	 */
121 	blk_freeze_queue(q);
122 }
123 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
124 
125 void blk_mq_unfreeze_queue(struct request_queue *q)
126 {
127 	int freeze_depth;
128 
129 	freeze_depth = atomic_dec_return(&q->mq_freeze_depth);
130 	WARN_ON_ONCE(freeze_depth < 0);
131 	if (!freeze_depth) {
132 		percpu_ref_reinit(&q->q_usage_counter);
133 		wake_up_all(&q->mq_freeze_wq);
134 	}
135 }
136 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
137 
138 void blk_mq_wake_waiters(struct request_queue *q)
139 {
140 	struct blk_mq_hw_ctx *hctx;
141 	unsigned int i;
142 
143 	queue_for_each_hw_ctx(q, hctx, i)
144 		if (blk_mq_hw_queue_mapped(hctx))
145 			blk_mq_tag_wakeup_all(hctx->tags, true);
146 
147 	/*
148 	 * If we are called because the queue has now been marked as
149 	 * dying, we need to ensure that processes currently waiting on
150 	 * the queue are notified as well.
151 	 */
152 	wake_up_all(&q->mq_freeze_wq);
153 }
154 
155 bool blk_mq_can_queue(struct blk_mq_hw_ctx *hctx)
156 {
157 	return blk_mq_has_free_tags(hctx->tags);
158 }
159 EXPORT_SYMBOL(blk_mq_can_queue);
160 
161 static void blk_mq_rq_ctx_init(struct request_queue *q, struct blk_mq_ctx *ctx,
162 			       struct request *rq, unsigned int rw_flags)
163 {
164 	if (blk_queue_io_stat(q))
165 		rw_flags |= REQ_IO_STAT;
166 
167 	INIT_LIST_HEAD(&rq->queuelist);
168 	/* csd/requeue_work/fifo_time is initialized before use */
169 	rq->q = q;
170 	rq->mq_ctx = ctx;
171 	rq->cmd_flags |= rw_flags;
172 	/* do not touch atomic flags, it needs atomic ops against the timer */
173 	rq->cpu = -1;
174 	INIT_HLIST_NODE(&rq->hash);
175 	RB_CLEAR_NODE(&rq->rb_node);
176 	rq->rq_disk = NULL;
177 	rq->part = NULL;
178 	rq->start_time = jiffies;
179 #ifdef CONFIG_BLK_CGROUP
180 	rq->rl = NULL;
181 	set_start_time_ns(rq);
182 	rq->io_start_time_ns = 0;
183 #endif
184 	rq->nr_phys_segments = 0;
185 #if defined(CONFIG_BLK_DEV_INTEGRITY)
186 	rq->nr_integrity_segments = 0;
187 #endif
188 	rq->special = NULL;
189 	/* tag was already set */
190 	rq->errors = 0;
191 
192 	rq->cmd = rq->__cmd;
193 
194 	rq->extra_len = 0;
195 	rq->sense_len = 0;
196 	rq->resid_len = 0;
197 	rq->sense = NULL;
198 
199 	INIT_LIST_HEAD(&rq->timeout_list);
200 	rq->timeout = 0;
201 
202 	rq->end_io = NULL;
203 	rq->end_io_data = NULL;
204 	rq->next_rq = NULL;
205 
206 	ctx->rq_dispatched[rw_is_sync(rw_flags)]++;
207 }
208 
209 static struct request *
210 __blk_mq_alloc_request(struct blk_mq_alloc_data *data, int rw)
211 {
212 	struct request *rq;
213 	unsigned int tag;
214 
215 	tag = blk_mq_get_tag(data);
216 	if (tag != BLK_MQ_TAG_FAIL) {
217 		rq = data->hctx->tags->rqs[tag];
218 
219 		if (blk_mq_tag_busy(data->hctx)) {
220 			rq->cmd_flags = REQ_MQ_INFLIGHT;
221 			atomic_inc(&data->hctx->nr_active);
222 		}
223 
224 		rq->tag = tag;
225 		blk_mq_rq_ctx_init(data->q, data->ctx, rq, rw);
226 		return rq;
227 	}
228 
229 	return NULL;
230 }
231 
232 struct request *blk_mq_alloc_request(struct request_queue *q, int rw,
233 		unsigned int flags)
234 {
235 	struct blk_mq_ctx *ctx;
236 	struct blk_mq_hw_ctx *hctx;
237 	struct request *rq;
238 	struct blk_mq_alloc_data alloc_data;
239 	int ret;
240 
241 	ret = blk_queue_enter(q, flags & BLK_MQ_REQ_NOWAIT);
242 	if (ret)
243 		return ERR_PTR(ret);
244 
245 	ctx = blk_mq_get_ctx(q);
246 	hctx = q->mq_ops->map_queue(q, ctx->cpu);
247 	blk_mq_set_alloc_data(&alloc_data, q, flags, ctx, hctx);
248 
249 	rq = __blk_mq_alloc_request(&alloc_data, rw);
250 	if (!rq && !(flags & BLK_MQ_REQ_NOWAIT)) {
251 		__blk_mq_run_hw_queue(hctx);
252 		blk_mq_put_ctx(ctx);
253 
254 		ctx = blk_mq_get_ctx(q);
255 		hctx = q->mq_ops->map_queue(q, ctx->cpu);
256 		blk_mq_set_alloc_data(&alloc_data, q, flags, ctx, hctx);
257 		rq =  __blk_mq_alloc_request(&alloc_data, rw);
258 		ctx = alloc_data.ctx;
259 	}
260 	blk_mq_put_ctx(ctx);
261 	if (!rq) {
262 		blk_queue_exit(q);
263 		return ERR_PTR(-EWOULDBLOCK);
264 	}
265 	return rq;
266 }
267 EXPORT_SYMBOL(blk_mq_alloc_request);
268 
269 static void __blk_mq_free_request(struct blk_mq_hw_ctx *hctx,
270 				  struct blk_mq_ctx *ctx, struct request *rq)
271 {
272 	const int tag = rq->tag;
273 	struct request_queue *q = rq->q;
274 
275 	if (rq->cmd_flags & REQ_MQ_INFLIGHT)
276 		atomic_dec(&hctx->nr_active);
277 	rq->cmd_flags = 0;
278 
279 	clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
280 	blk_mq_put_tag(hctx, tag, &ctx->last_tag);
281 	blk_queue_exit(q);
282 }
283 
284 void blk_mq_free_hctx_request(struct blk_mq_hw_ctx *hctx, struct request *rq)
285 {
286 	struct blk_mq_ctx *ctx = rq->mq_ctx;
287 
288 	ctx->rq_completed[rq_is_sync(rq)]++;
289 	__blk_mq_free_request(hctx, ctx, rq);
290 
291 }
292 EXPORT_SYMBOL_GPL(blk_mq_free_hctx_request);
293 
294 void blk_mq_free_request(struct request *rq)
295 {
296 	struct blk_mq_hw_ctx *hctx;
297 	struct request_queue *q = rq->q;
298 
299 	hctx = q->mq_ops->map_queue(q, rq->mq_ctx->cpu);
300 	blk_mq_free_hctx_request(hctx, rq);
301 }
302 EXPORT_SYMBOL_GPL(blk_mq_free_request);
303 
304 inline void __blk_mq_end_request(struct request *rq, int error)
305 {
306 	blk_account_io_done(rq);
307 
308 	if (rq->end_io) {
309 		rq->end_io(rq, error);
310 	} else {
311 		if (unlikely(blk_bidi_rq(rq)))
312 			blk_mq_free_request(rq->next_rq);
313 		blk_mq_free_request(rq);
314 	}
315 }
316 EXPORT_SYMBOL(__blk_mq_end_request);
317 
318 void blk_mq_end_request(struct request *rq, int error)
319 {
320 	if (blk_update_request(rq, error, blk_rq_bytes(rq)))
321 		BUG();
322 	__blk_mq_end_request(rq, error);
323 }
324 EXPORT_SYMBOL(blk_mq_end_request);
325 
326 static void __blk_mq_complete_request_remote(void *data)
327 {
328 	struct request *rq = data;
329 
330 	rq->q->softirq_done_fn(rq);
331 }
332 
333 static void blk_mq_ipi_complete_request(struct request *rq)
334 {
335 	struct blk_mq_ctx *ctx = rq->mq_ctx;
336 	bool shared = false;
337 	int cpu;
338 
339 	if (!test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags)) {
340 		rq->q->softirq_done_fn(rq);
341 		return;
342 	}
343 
344 	cpu = get_cpu();
345 	if (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags))
346 		shared = cpus_share_cache(cpu, ctx->cpu);
347 
348 	if (cpu != ctx->cpu && !shared && cpu_online(ctx->cpu)) {
349 		rq->csd.func = __blk_mq_complete_request_remote;
350 		rq->csd.info = rq;
351 		rq->csd.flags = 0;
352 		smp_call_function_single_async(ctx->cpu, &rq->csd);
353 	} else {
354 		rq->q->softirq_done_fn(rq);
355 	}
356 	put_cpu();
357 }
358 
359 static void __blk_mq_complete_request(struct request *rq)
360 {
361 	struct request_queue *q = rq->q;
362 
363 	if (!q->softirq_done_fn)
364 		blk_mq_end_request(rq, rq->errors);
365 	else
366 		blk_mq_ipi_complete_request(rq);
367 }
368 
369 /**
370  * blk_mq_complete_request - end I/O on a request
371  * @rq:		the request being processed
372  *
373  * Description:
374  *	Ends all I/O on a request. It does not handle partial completions.
375  *	The actual completion happens out-of-order, through a IPI handler.
376  **/
377 void blk_mq_complete_request(struct request *rq, int error)
378 {
379 	struct request_queue *q = rq->q;
380 
381 	if (unlikely(blk_should_fake_timeout(q)))
382 		return;
383 	if (!blk_mark_rq_complete(rq)) {
384 		rq->errors = error;
385 		__blk_mq_complete_request(rq);
386 	}
387 }
388 EXPORT_SYMBOL(blk_mq_complete_request);
389 
390 int blk_mq_request_started(struct request *rq)
391 {
392 	return test_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
393 }
394 EXPORT_SYMBOL_GPL(blk_mq_request_started);
395 
396 void blk_mq_start_request(struct request *rq)
397 {
398 	struct request_queue *q = rq->q;
399 
400 	trace_block_rq_issue(q, rq);
401 
402 	rq->resid_len = blk_rq_bytes(rq);
403 	if (unlikely(blk_bidi_rq(rq)))
404 		rq->next_rq->resid_len = blk_rq_bytes(rq->next_rq);
405 
406 	blk_add_timer(rq);
407 
408 	/*
409 	 * Ensure that ->deadline is visible before set the started
410 	 * flag and clear the completed flag.
411 	 */
412 	smp_mb__before_atomic();
413 
414 	/*
415 	 * Mark us as started and clear complete. Complete might have been
416 	 * set if requeue raced with timeout, which then marked it as
417 	 * complete. So be sure to clear complete again when we start
418 	 * the request, otherwise we'll ignore the completion event.
419 	 */
420 	if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags))
421 		set_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
422 	if (test_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags))
423 		clear_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags);
424 
425 	if (q->dma_drain_size && blk_rq_bytes(rq)) {
426 		/*
427 		 * Make sure space for the drain appears.  We know we can do
428 		 * this because max_hw_segments has been adjusted to be one
429 		 * fewer than the device can handle.
430 		 */
431 		rq->nr_phys_segments++;
432 	}
433 }
434 EXPORT_SYMBOL(blk_mq_start_request);
435 
436 static void __blk_mq_requeue_request(struct request *rq)
437 {
438 	struct request_queue *q = rq->q;
439 
440 	trace_block_rq_requeue(q, rq);
441 
442 	if (test_and_clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
443 		if (q->dma_drain_size && blk_rq_bytes(rq))
444 			rq->nr_phys_segments--;
445 	}
446 }
447 
448 void blk_mq_requeue_request(struct request *rq)
449 {
450 	__blk_mq_requeue_request(rq);
451 
452 	BUG_ON(blk_queued_rq(rq));
453 	blk_mq_add_to_requeue_list(rq, true);
454 }
455 EXPORT_SYMBOL(blk_mq_requeue_request);
456 
457 static void blk_mq_requeue_work(struct work_struct *work)
458 {
459 	struct request_queue *q =
460 		container_of(work, struct request_queue, requeue_work);
461 	LIST_HEAD(rq_list);
462 	struct request *rq, *next;
463 	unsigned long flags;
464 
465 	spin_lock_irqsave(&q->requeue_lock, flags);
466 	list_splice_init(&q->requeue_list, &rq_list);
467 	spin_unlock_irqrestore(&q->requeue_lock, flags);
468 
469 	list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
470 		if (!(rq->cmd_flags & REQ_SOFTBARRIER))
471 			continue;
472 
473 		rq->cmd_flags &= ~REQ_SOFTBARRIER;
474 		list_del_init(&rq->queuelist);
475 		blk_mq_insert_request(rq, true, false, false);
476 	}
477 
478 	while (!list_empty(&rq_list)) {
479 		rq = list_entry(rq_list.next, struct request, queuelist);
480 		list_del_init(&rq->queuelist);
481 		blk_mq_insert_request(rq, false, false, false);
482 	}
483 
484 	/*
485 	 * Use the start variant of queue running here, so that running
486 	 * the requeue work will kick stopped queues.
487 	 */
488 	blk_mq_start_hw_queues(q);
489 }
490 
491 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head)
492 {
493 	struct request_queue *q = rq->q;
494 	unsigned long flags;
495 
496 	/*
497 	 * We abuse this flag that is otherwise used by the I/O scheduler to
498 	 * request head insertation from the workqueue.
499 	 */
500 	BUG_ON(rq->cmd_flags & REQ_SOFTBARRIER);
501 
502 	spin_lock_irqsave(&q->requeue_lock, flags);
503 	if (at_head) {
504 		rq->cmd_flags |= REQ_SOFTBARRIER;
505 		list_add(&rq->queuelist, &q->requeue_list);
506 	} else {
507 		list_add_tail(&rq->queuelist, &q->requeue_list);
508 	}
509 	spin_unlock_irqrestore(&q->requeue_lock, flags);
510 }
511 EXPORT_SYMBOL(blk_mq_add_to_requeue_list);
512 
513 void blk_mq_cancel_requeue_work(struct request_queue *q)
514 {
515 	cancel_work_sync(&q->requeue_work);
516 }
517 EXPORT_SYMBOL_GPL(blk_mq_cancel_requeue_work);
518 
519 void blk_mq_kick_requeue_list(struct request_queue *q)
520 {
521 	kblockd_schedule_work(&q->requeue_work);
522 }
523 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
524 
525 void blk_mq_abort_requeue_list(struct request_queue *q)
526 {
527 	unsigned long flags;
528 	LIST_HEAD(rq_list);
529 
530 	spin_lock_irqsave(&q->requeue_lock, flags);
531 	list_splice_init(&q->requeue_list, &rq_list);
532 	spin_unlock_irqrestore(&q->requeue_lock, flags);
533 
534 	while (!list_empty(&rq_list)) {
535 		struct request *rq;
536 
537 		rq = list_first_entry(&rq_list, struct request, queuelist);
538 		list_del_init(&rq->queuelist);
539 		rq->errors = -EIO;
540 		blk_mq_end_request(rq, rq->errors);
541 	}
542 }
543 EXPORT_SYMBOL(blk_mq_abort_requeue_list);
544 
545 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
546 {
547 	if (tag < tags->nr_tags)
548 		return tags->rqs[tag];
549 
550 	return NULL;
551 }
552 EXPORT_SYMBOL(blk_mq_tag_to_rq);
553 
554 struct blk_mq_timeout_data {
555 	unsigned long next;
556 	unsigned int next_set;
557 };
558 
559 void blk_mq_rq_timed_out(struct request *req, bool reserved)
560 {
561 	struct blk_mq_ops *ops = req->q->mq_ops;
562 	enum blk_eh_timer_return ret = BLK_EH_RESET_TIMER;
563 
564 	/*
565 	 * We know that complete is set at this point. If STARTED isn't set
566 	 * anymore, then the request isn't active and the "timeout" should
567 	 * just be ignored. This can happen due to the bitflag ordering.
568 	 * Timeout first checks if STARTED is set, and if it is, assumes
569 	 * the request is active. But if we race with completion, then
570 	 * we both flags will get cleared. So check here again, and ignore
571 	 * a timeout event with a request that isn't active.
572 	 */
573 	if (!test_bit(REQ_ATOM_STARTED, &req->atomic_flags))
574 		return;
575 
576 	if (ops->timeout)
577 		ret = ops->timeout(req, reserved);
578 
579 	switch (ret) {
580 	case BLK_EH_HANDLED:
581 		__blk_mq_complete_request(req);
582 		break;
583 	case BLK_EH_RESET_TIMER:
584 		blk_add_timer(req);
585 		blk_clear_rq_complete(req);
586 		break;
587 	case BLK_EH_NOT_HANDLED:
588 		break;
589 	default:
590 		printk(KERN_ERR "block: bad eh return: %d\n", ret);
591 		break;
592 	}
593 }
594 
595 static void blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
596 		struct request *rq, void *priv, bool reserved)
597 {
598 	struct blk_mq_timeout_data *data = priv;
599 
600 	if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
601 		/*
602 		 * If a request wasn't started before the queue was
603 		 * marked dying, kill it here or it'll go unnoticed.
604 		 */
605 		if (unlikely(blk_queue_dying(rq->q))) {
606 			rq->errors = -EIO;
607 			blk_mq_end_request(rq, rq->errors);
608 		}
609 		return;
610 	}
611 
612 	if (time_after_eq(jiffies, rq->deadline)) {
613 		if (!blk_mark_rq_complete(rq))
614 			blk_mq_rq_timed_out(rq, reserved);
615 	} else if (!data->next_set || time_after(data->next, rq->deadline)) {
616 		data->next = rq->deadline;
617 		data->next_set = 1;
618 	}
619 }
620 
621 static void blk_mq_timeout_work(struct work_struct *work)
622 {
623 	struct request_queue *q =
624 		container_of(work, struct request_queue, timeout_work);
625 	struct blk_mq_timeout_data data = {
626 		.next		= 0,
627 		.next_set	= 0,
628 	};
629 	int i;
630 
631 	if (blk_queue_enter(q, true))
632 		return;
633 
634 	blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &data);
635 
636 	if (data.next_set) {
637 		data.next = blk_rq_timeout(round_jiffies_up(data.next));
638 		mod_timer(&q->timeout, data.next);
639 	} else {
640 		struct blk_mq_hw_ctx *hctx;
641 
642 		queue_for_each_hw_ctx(q, hctx, i) {
643 			/* the hctx may be unmapped, so check it here */
644 			if (blk_mq_hw_queue_mapped(hctx))
645 				blk_mq_tag_idle(hctx);
646 		}
647 	}
648 	blk_queue_exit(q);
649 }
650 
651 /*
652  * Reverse check our software queue for entries that we could potentially
653  * merge with. Currently includes a hand-wavy stop count of 8, to not spend
654  * too much time checking for merges.
655  */
656 static bool blk_mq_attempt_merge(struct request_queue *q,
657 				 struct blk_mq_ctx *ctx, struct bio *bio)
658 {
659 	struct request *rq;
660 	int checked = 8;
661 
662 	list_for_each_entry_reverse(rq, &ctx->rq_list, queuelist) {
663 		int el_ret;
664 
665 		if (!checked--)
666 			break;
667 
668 		if (!blk_rq_merge_ok(rq, bio))
669 			continue;
670 
671 		el_ret = blk_try_merge(rq, bio);
672 		if (el_ret == ELEVATOR_BACK_MERGE) {
673 			if (bio_attempt_back_merge(q, rq, bio)) {
674 				ctx->rq_merged++;
675 				return true;
676 			}
677 			break;
678 		} else if (el_ret == ELEVATOR_FRONT_MERGE) {
679 			if (bio_attempt_front_merge(q, rq, bio)) {
680 				ctx->rq_merged++;
681 				return true;
682 			}
683 			break;
684 		}
685 	}
686 
687 	return false;
688 }
689 
690 /*
691  * Process software queues that have been marked busy, splicing them
692  * to the for-dispatch
693  */
694 static void flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
695 {
696 	struct blk_mq_ctx *ctx;
697 	int i;
698 
699 	for (i = 0; i < hctx->ctx_map.size; i++) {
700 		struct blk_align_bitmap *bm = &hctx->ctx_map.map[i];
701 		unsigned int off, bit;
702 
703 		if (!bm->word)
704 			continue;
705 
706 		bit = 0;
707 		off = i * hctx->ctx_map.bits_per_word;
708 		do {
709 			bit = find_next_bit(&bm->word, bm->depth, bit);
710 			if (bit >= bm->depth)
711 				break;
712 
713 			ctx = hctx->ctxs[bit + off];
714 			clear_bit(bit, &bm->word);
715 			spin_lock(&ctx->lock);
716 			list_splice_tail_init(&ctx->rq_list, list);
717 			spin_unlock(&ctx->lock);
718 
719 			bit++;
720 		} while (1);
721 	}
722 }
723 
724 /*
725  * Run this hardware queue, pulling any software queues mapped to it in.
726  * Note that this function currently has various problems around ordering
727  * of IO. In particular, we'd like FIFO behaviour on handling existing
728  * items on the hctx->dispatch list. Ignore that for now.
729  */
730 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
731 {
732 	struct request_queue *q = hctx->queue;
733 	struct request *rq;
734 	LIST_HEAD(rq_list);
735 	LIST_HEAD(driver_list);
736 	struct list_head *dptr;
737 	int queued;
738 
739 	WARN_ON(!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask));
740 
741 	if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state)))
742 		return;
743 
744 	hctx->run++;
745 
746 	/*
747 	 * Touch any software queue that has pending entries.
748 	 */
749 	flush_busy_ctxs(hctx, &rq_list);
750 
751 	/*
752 	 * If we have previous entries on our dispatch list, grab them
753 	 * and stuff them at the front for more fair dispatch.
754 	 */
755 	if (!list_empty_careful(&hctx->dispatch)) {
756 		spin_lock(&hctx->lock);
757 		if (!list_empty(&hctx->dispatch))
758 			list_splice_init(&hctx->dispatch, &rq_list);
759 		spin_unlock(&hctx->lock);
760 	}
761 
762 	/*
763 	 * Start off with dptr being NULL, so we start the first request
764 	 * immediately, even if we have more pending.
765 	 */
766 	dptr = NULL;
767 
768 	/*
769 	 * Now process all the entries, sending them to the driver.
770 	 */
771 	queued = 0;
772 	while (!list_empty(&rq_list)) {
773 		struct blk_mq_queue_data bd;
774 		int ret;
775 
776 		rq = list_first_entry(&rq_list, struct request, queuelist);
777 		list_del_init(&rq->queuelist);
778 
779 		bd.rq = rq;
780 		bd.list = dptr;
781 		bd.last = list_empty(&rq_list);
782 
783 		ret = q->mq_ops->queue_rq(hctx, &bd);
784 		switch (ret) {
785 		case BLK_MQ_RQ_QUEUE_OK:
786 			queued++;
787 			continue;
788 		case BLK_MQ_RQ_QUEUE_BUSY:
789 			list_add(&rq->queuelist, &rq_list);
790 			__blk_mq_requeue_request(rq);
791 			break;
792 		default:
793 			pr_err("blk-mq: bad return on queue: %d\n", ret);
794 		case BLK_MQ_RQ_QUEUE_ERROR:
795 			rq->errors = -EIO;
796 			blk_mq_end_request(rq, rq->errors);
797 			break;
798 		}
799 
800 		if (ret == BLK_MQ_RQ_QUEUE_BUSY)
801 			break;
802 
803 		/*
804 		 * We've done the first request. If we have more than 1
805 		 * left in the list, set dptr to defer issue.
806 		 */
807 		if (!dptr && rq_list.next != rq_list.prev)
808 			dptr = &driver_list;
809 	}
810 
811 	if (!queued)
812 		hctx->dispatched[0]++;
813 	else if (queued < (1 << (BLK_MQ_MAX_DISPATCH_ORDER - 1)))
814 		hctx->dispatched[ilog2(queued) + 1]++;
815 
816 	/*
817 	 * Any items that need requeuing? Stuff them into hctx->dispatch,
818 	 * that is where we will continue on next queue run.
819 	 */
820 	if (!list_empty(&rq_list)) {
821 		spin_lock(&hctx->lock);
822 		list_splice(&rq_list, &hctx->dispatch);
823 		spin_unlock(&hctx->lock);
824 		/*
825 		 * the queue is expected stopped with BLK_MQ_RQ_QUEUE_BUSY, but
826 		 * it's possible the queue is stopped and restarted again
827 		 * before this. Queue restart will dispatch requests. And since
828 		 * requests in rq_list aren't added into hctx->dispatch yet,
829 		 * the requests in rq_list might get lost.
830 		 *
831 		 * blk_mq_run_hw_queue() already checks the STOPPED bit
832 		 **/
833 		blk_mq_run_hw_queue(hctx, true);
834 	}
835 }
836 
837 /*
838  * It'd be great if the workqueue API had a way to pass
839  * in a mask and had some smarts for more clever placement.
840  * For now we just round-robin here, switching for every
841  * BLK_MQ_CPU_WORK_BATCH queued items.
842  */
843 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
844 {
845 	if (hctx->queue->nr_hw_queues == 1)
846 		return WORK_CPU_UNBOUND;
847 
848 	if (--hctx->next_cpu_batch <= 0) {
849 		int cpu = hctx->next_cpu, next_cpu;
850 
851 		next_cpu = cpumask_next(hctx->next_cpu, hctx->cpumask);
852 		if (next_cpu >= nr_cpu_ids)
853 			next_cpu = cpumask_first(hctx->cpumask);
854 
855 		hctx->next_cpu = next_cpu;
856 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
857 
858 		return cpu;
859 	}
860 
861 	return hctx->next_cpu;
862 }
863 
864 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
865 {
866 	if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state) ||
867 	    !blk_mq_hw_queue_mapped(hctx)))
868 		return;
869 
870 	if (!async) {
871 		int cpu = get_cpu();
872 		if (cpumask_test_cpu(cpu, hctx->cpumask)) {
873 			__blk_mq_run_hw_queue(hctx);
874 			put_cpu();
875 			return;
876 		}
877 
878 		put_cpu();
879 	}
880 
881 	kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
882 			&hctx->run_work, 0);
883 }
884 
885 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
886 {
887 	struct blk_mq_hw_ctx *hctx;
888 	int i;
889 
890 	queue_for_each_hw_ctx(q, hctx, i) {
891 		if ((!blk_mq_hctx_has_pending(hctx) &&
892 		    list_empty_careful(&hctx->dispatch)) ||
893 		    test_bit(BLK_MQ_S_STOPPED, &hctx->state))
894 			continue;
895 
896 		blk_mq_run_hw_queue(hctx, async);
897 	}
898 }
899 EXPORT_SYMBOL(blk_mq_run_hw_queues);
900 
901 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
902 {
903 	cancel_delayed_work(&hctx->run_work);
904 	cancel_delayed_work(&hctx->delay_work);
905 	set_bit(BLK_MQ_S_STOPPED, &hctx->state);
906 }
907 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
908 
909 void blk_mq_stop_hw_queues(struct request_queue *q)
910 {
911 	struct blk_mq_hw_ctx *hctx;
912 	int i;
913 
914 	queue_for_each_hw_ctx(q, hctx, i)
915 		blk_mq_stop_hw_queue(hctx);
916 }
917 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
918 
919 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
920 {
921 	clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
922 
923 	blk_mq_run_hw_queue(hctx, false);
924 }
925 EXPORT_SYMBOL(blk_mq_start_hw_queue);
926 
927 void blk_mq_start_hw_queues(struct request_queue *q)
928 {
929 	struct blk_mq_hw_ctx *hctx;
930 	int i;
931 
932 	queue_for_each_hw_ctx(q, hctx, i)
933 		blk_mq_start_hw_queue(hctx);
934 }
935 EXPORT_SYMBOL(blk_mq_start_hw_queues);
936 
937 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
938 {
939 	struct blk_mq_hw_ctx *hctx;
940 	int i;
941 
942 	queue_for_each_hw_ctx(q, hctx, i) {
943 		if (!test_bit(BLK_MQ_S_STOPPED, &hctx->state))
944 			continue;
945 
946 		clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
947 		blk_mq_run_hw_queue(hctx, async);
948 	}
949 }
950 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
951 
952 static void blk_mq_run_work_fn(struct work_struct *work)
953 {
954 	struct blk_mq_hw_ctx *hctx;
955 
956 	hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
957 
958 	__blk_mq_run_hw_queue(hctx);
959 }
960 
961 static void blk_mq_delay_work_fn(struct work_struct *work)
962 {
963 	struct blk_mq_hw_ctx *hctx;
964 
965 	hctx = container_of(work, struct blk_mq_hw_ctx, delay_work.work);
966 
967 	if (test_and_clear_bit(BLK_MQ_S_STOPPED, &hctx->state))
968 		__blk_mq_run_hw_queue(hctx);
969 }
970 
971 void blk_mq_delay_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
972 {
973 	if (unlikely(!blk_mq_hw_queue_mapped(hctx)))
974 		return;
975 
976 	kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
977 			&hctx->delay_work, msecs_to_jiffies(msecs));
978 }
979 EXPORT_SYMBOL(blk_mq_delay_queue);
980 
981 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
982 					    struct blk_mq_ctx *ctx,
983 					    struct request *rq,
984 					    bool at_head)
985 {
986 	trace_block_rq_insert(hctx->queue, rq);
987 
988 	if (at_head)
989 		list_add(&rq->queuelist, &ctx->rq_list);
990 	else
991 		list_add_tail(&rq->queuelist, &ctx->rq_list);
992 }
993 
994 static void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx,
995 				    struct request *rq, bool at_head)
996 {
997 	struct blk_mq_ctx *ctx = rq->mq_ctx;
998 
999 	__blk_mq_insert_req_list(hctx, ctx, rq, at_head);
1000 	blk_mq_hctx_mark_pending(hctx, ctx);
1001 }
1002 
1003 void blk_mq_insert_request(struct request *rq, bool at_head, bool run_queue,
1004 		bool async)
1005 {
1006 	struct request_queue *q = rq->q;
1007 	struct blk_mq_hw_ctx *hctx;
1008 	struct blk_mq_ctx *ctx = rq->mq_ctx, *current_ctx;
1009 
1010 	current_ctx = blk_mq_get_ctx(q);
1011 	if (!cpu_online(ctx->cpu))
1012 		rq->mq_ctx = ctx = current_ctx;
1013 
1014 	hctx = q->mq_ops->map_queue(q, ctx->cpu);
1015 
1016 	spin_lock(&ctx->lock);
1017 	__blk_mq_insert_request(hctx, rq, at_head);
1018 	spin_unlock(&ctx->lock);
1019 
1020 	if (run_queue)
1021 		blk_mq_run_hw_queue(hctx, async);
1022 
1023 	blk_mq_put_ctx(current_ctx);
1024 }
1025 
1026 static void blk_mq_insert_requests(struct request_queue *q,
1027 				     struct blk_mq_ctx *ctx,
1028 				     struct list_head *list,
1029 				     int depth,
1030 				     bool from_schedule)
1031 
1032 {
1033 	struct blk_mq_hw_ctx *hctx;
1034 	struct blk_mq_ctx *current_ctx;
1035 
1036 	trace_block_unplug(q, depth, !from_schedule);
1037 
1038 	current_ctx = blk_mq_get_ctx(q);
1039 
1040 	if (!cpu_online(ctx->cpu))
1041 		ctx = current_ctx;
1042 	hctx = q->mq_ops->map_queue(q, ctx->cpu);
1043 
1044 	/*
1045 	 * preemption doesn't flush plug list, so it's possible ctx->cpu is
1046 	 * offline now
1047 	 */
1048 	spin_lock(&ctx->lock);
1049 	while (!list_empty(list)) {
1050 		struct request *rq;
1051 
1052 		rq = list_first_entry(list, struct request, queuelist);
1053 		list_del_init(&rq->queuelist);
1054 		rq->mq_ctx = ctx;
1055 		__blk_mq_insert_req_list(hctx, ctx, rq, false);
1056 	}
1057 	blk_mq_hctx_mark_pending(hctx, ctx);
1058 	spin_unlock(&ctx->lock);
1059 
1060 	blk_mq_run_hw_queue(hctx, from_schedule);
1061 	blk_mq_put_ctx(current_ctx);
1062 }
1063 
1064 static int plug_ctx_cmp(void *priv, struct list_head *a, struct list_head *b)
1065 {
1066 	struct request *rqa = container_of(a, struct request, queuelist);
1067 	struct request *rqb = container_of(b, struct request, queuelist);
1068 
1069 	return !(rqa->mq_ctx < rqb->mq_ctx ||
1070 		 (rqa->mq_ctx == rqb->mq_ctx &&
1071 		  blk_rq_pos(rqa) < blk_rq_pos(rqb)));
1072 }
1073 
1074 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1075 {
1076 	struct blk_mq_ctx *this_ctx;
1077 	struct request_queue *this_q;
1078 	struct request *rq;
1079 	LIST_HEAD(list);
1080 	LIST_HEAD(ctx_list);
1081 	unsigned int depth;
1082 
1083 	list_splice_init(&plug->mq_list, &list);
1084 
1085 	list_sort(NULL, &list, plug_ctx_cmp);
1086 
1087 	this_q = NULL;
1088 	this_ctx = NULL;
1089 	depth = 0;
1090 
1091 	while (!list_empty(&list)) {
1092 		rq = list_entry_rq(list.next);
1093 		list_del_init(&rq->queuelist);
1094 		BUG_ON(!rq->q);
1095 		if (rq->mq_ctx != this_ctx) {
1096 			if (this_ctx) {
1097 				blk_mq_insert_requests(this_q, this_ctx,
1098 							&ctx_list, depth,
1099 							from_schedule);
1100 			}
1101 
1102 			this_ctx = rq->mq_ctx;
1103 			this_q = rq->q;
1104 			depth = 0;
1105 		}
1106 
1107 		depth++;
1108 		list_add_tail(&rq->queuelist, &ctx_list);
1109 	}
1110 
1111 	/*
1112 	 * If 'this_ctx' is set, we know we have entries to complete
1113 	 * on 'ctx_list'. Do those.
1114 	 */
1115 	if (this_ctx) {
1116 		blk_mq_insert_requests(this_q, this_ctx, &ctx_list, depth,
1117 				       from_schedule);
1118 	}
1119 }
1120 
1121 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio)
1122 {
1123 	init_request_from_bio(rq, bio);
1124 
1125 	blk_account_io_start(rq, 1);
1126 }
1127 
1128 static inline bool hctx_allow_merges(struct blk_mq_hw_ctx *hctx)
1129 {
1130 	return (hctx->flags & BLK_MQ_F_SHOULD_MERGE) &&
1131 		!blk_queue_nomerges(hctx->queue);
1132 }
1133 
1134 static inline bool blk_mq_merge_queue_io(struct blk_mq_hw_ctx *hctx,
1135 					 struct blk_mq_ctx *ctx,
1136 					 struct request *rq, struct bio *bio)
1137 {
1138 	if (!hctx_allow_merges(hctx) || !bio_mergeable(bio)) {
1139 		blk_mq_bio_to_request(rq, bio);
1140 		spin_lock(&ctx->lock);
1141 insert_rq:
1142 		__blk_mq_insert_request(hctx, rq, false);
1143 		spin_unlock(&ctx->lock);
1144 		return false;
1145 	} else {
1146 		struct request_queue *q = hctx->queue;
1147 
1148 		spin_lock(&ctx->lock);
1149 		if (!blk_mq_attempt_merge(q, ctx, bio)) {
1150 			blk_mq_bio_to_request(rq, bio);
1151 			goto insert_rq;
1152 		}
1153 
1154 		spin_unlock(&ctx->lock);
1155 		__blk_mq_free_request(hctx, ctx, rq);
1156 		return true;
1157 	}
1158 }
1159 
1160 struct blk_map_ctx {
1161 	struct blk_mq_hw_ctx *hctx;
1162 	struct blk_mq_ctx *ctx;
1163 };
1164 
1165 static struct request *blk_mq_map_request(struct request_queue *q,
1166 					  struct bio *bio,
1167 					  struct blk_map_ctx *data)
1168 {
1169 	struct blk_mq_hw_ctx *hctx;
1170 	struct blk_mq_ctx *ctx;
1171 	struct request *rq;
1172 	int rw = bio_data_dir(bio);
1173 	struct blk_mq_alloc_data alloc_data;
1174 
1175 	blk_queue_enter_live(q);
1176 	ctx = blk_mq_get_ctx(q);
1177 	hctx = q->mq_ops->map_queue(q, ctx->cpu);
1178 
1179 	if (rw_is_sync(bio->bi_rw))
1180 		rw |= REQ_SYNC;
1181 
1182 	trace_block_getrq(q, bio, rw);
1183 	blk_mq_set_alloc_data(&alloc_data, q, BLK_MQ_REQ_NOWAIT, ctx, hctx);
1184 	rq = __blk_mq_alloc_request(&alloc_data, rw);
1185 	if (unlikely(!rq)) {
1186 		__blk_mq_run_hw_queue(hctx);
1187 		blk_mq_put_ctx(ctx);
1188 		trace_block_sleeprq(q, bio, rw);
1189 
1190 		ctx = blk_mq_get_ctx(q);
1191 		hctx = q->mq_ops->map_queue(q, ctx->cpu);
1192 		blk_mq_set_alloc_data(&alloc_data, q, 0, ctx, hctx);
1193 		rq = __blk_mq_alloc_request(&alloc_data, rw);
1194 		ctx = alloc_data.ctx;
1195 		hctx = alloc_data.hctx;
1196 	}
1197 
1198 	hctx->queued++;
1199 	data->hctx = hctx;
1200 	data->ctx = ctx;
1201 	return rq;
1202 }
1203 
1204 static int blk_mq_direct_issue_request(struct request *rq, blk_qc_t *cookie)
1205 {
1206 	int ret;
1207 	struct request_queue *q = rq->q;
1208 	struct blk_mq_hw_ctx *hctx = q->mq_ops->map_queue(q,
1209 			rq->mq_ctx->cpu);
1210 	struct blk_mq_queue_data bd = {
1211 		.rq = rq,
1212 		.list = NULL,
1213 		.last = 1
1214 	};
1215 	blk_qc_t new_cookie = blk_tag_to_qc_t(rq->tag, hctx->queue_num);
1216 
1217 	/*
1218 	 * For OK queue, we are done. For error, kill it. Any other
1219 	 * error (busy), just add it to our list as we previously
1220 	 * would have done
1221 	 */
1222 	ret = q->mq_ops->queue_rq(hctx, &bd);
1223 	if (ret == BLK_MQ_RQ_QUEUE_OK) {
1224 		*cookie = new_cookie;
1225 		return 0;
1226 	}
1227 
1228 	__blk_mq_requeue_request(rq);
1229 
1230 	if (ret == BLK_MQ_RQ_QUEUE_ERROR) {
1231 		*cookie = BLK_QC_T_NONE;
1232 		rq->errors = -EIO;
1233 		blk_mq_end_request(rq, rq->errors);
1234 		return 0;
1235 	}
1236 
1237 	return -1;
1238 }
1239 
1240 /*
1241  * Multiple hardware queue variant. This will not use per-process plugs,
1242  * but will attempt to bypass the hctx queueing if we can go straight to
1243  * hardware for SYNC IO.
1244  */
1245 static blk_qc_t blk_mq_make_request(struct request_queue *q, struct bio *bio)
1246 {
1247 	const int is_sync = rw_is_sync(bio->bi_rw);
1248 	const int is_flush_fua = bio->bi_rw & (REQ_FLUSH | REQ_FUA);
1249 	struct blk_map_ctx data;
1250 	struct request *rq;
1251 	unsigned int request_count = 0;
1252 	struct blk_plug *plug;
1253 	struct request *same_queue_rq = NULL;
1254 	blk_qc_t cookie;
1255 
1256 	blk_queue_bounce(q, &bio);
1257 
1258 	if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1259 		bio_io_error(bio);
1260 		return BLK_QC_T_NONE;
1261 	}
1262 
1263 	blk_queue_split(q, &bio, q->bio_split);
1264 
1265 	if (!is_flush_fua && !blk_queue_nomerges(q)) {
1266 		if (blk_attempt_plug_merge(q, bio, &request_count,
1267 					   &same_queue_rq))
1268 			return BLK_QC_T_NONE;
1269 	} else
1270 		request_count = blk_plug_queued_count(q);
1271 
1272 	rq = blk_mq_map_request(q, bio, &data);
1273 	if (unlikely(!rq))
1274 		return BLK_QC_T_NONE;
1275 
1276 	cookie = blk_tag_to_qc_t(rq->tag, data.hctx->queue_num);
1277 
1278 	if (unlikely(is_flush_fua)) {
1279 		blk_mq_bio_to_request(rq, bio);
1280 		blk_insert_flush(rq);
1281 		goto run_queue;
1282 	}
1283 
1284 	plug = current->plug;
1285 	/*
1286 	 * If the driver supports defer issued based on 'last', then
1287 	 * queue it up like normal since we can potentially save some
1288 	 * CPU this way.
1289 	 */
1290 	if (((plug && !blk_queue_nomerges(q)) || is_sync) &&
1291 	    !(data.hctx->flags & BLK_MQ_F_DEFER_ISSUE)) {
1292 		struct request *old_rq = NULL;
1293 
1294 		blk_mq_bio_to_request(rq, bio);
1295 
1296 		/*
1297 		 * We do limited pluging. If the bio can be merged, do that.
1298 		 * Otherwise the existing request in the plug list will be
1299 		 * issued. So the plug list will have one request at most
1300 		 */
1301 		if (plug) {
1302 			/*
1303 			 * The plug list might get flushed before this. If that
1304 			 * happens, same_queue_rq is invalid and plug list is
1305 			 * empty
1306 			 */
1307 			if (same_queue_rq && !list_empty(&plug->mq_list)) {
1308 				old_rq = same_queue_rq;
1309 				list_del_init(&old_rq->queuelist);
1310 			}
1311 			list_add_tail(&rq->queuelist, &plug->mq_list);
1312 		} else /* is_sync */
1313 			old_rq = rq;
1314 		blk_mq_put_ctx(data.ctx);
1315 		if (!old_rq)
1316 			goto done;
1317 		if (!blk_mq_direct_issue_request(old_rq, &cookie))
1318 			goto done;
1319 		blk_mq_insert_request(old_rq, false, true, true);
1320 		goto done;
1321 	}
1322 
1323 	if (!blk_mq_merge_queue_io(data.hctx, data.ctx, rq, bio)) {
1324 		/*
1325 		 * For a SYNC request, send it to the hardware immediately. For
1326 		 * an ASYNC request, just ensure that we run it later on. The
1327 		 * latter allows for merging opportunities and more efficient
1328 		 * dispatching.
1329 		 */
1330 run_queue:
1331 		blk_mq_run_hw_queue(data.hctx, !is_sync || is_flush_fua);
1332 	}
1333 	blk_mq_put_ctx(data.ctx);
1334 done:
1335 	return cookie;
1336 }
1337 
1338 /*
1339  * Single hardware queue variant. This will attempt to use any per-process
1340  * plug for merging and IO deferral.
1341  */
1342 static blk_qc_t blk_sq_make_request(struct request_queue *q, struct bio *bio)
1343 {
1344 	const int is_sync = rw_is_sync(bio->bi_rw);
1345 	const int is_flush_fua = bio->bi_rw & (REQ_FLUSH | REQ_FUA);
1346 	struct blk_plug *plug;
1347 	unsigned int request_count = 0;
1348 	struct blk_map_ctx data;
1349 	struct request *rq;
1350 	blk_qc_t cookie;
1351 
1352 	blk_queue_bounce(q, &bio);
1353 
1354 	if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1355 		bio_io_error(bio);
1356 		return BLK_QC_T_NONE;
1357 	}
1358 
1359 	blk_queue_split(q, &bio, q->bio_split);
1360 
1361 	if (!is_flush_fua && !blk_queue_nomerges(q) &&
1362 	    blk_attempt_plug_merge(q, bio, &request_count, NULL))
1363 		return BLK_QC_T_NONE;
1364 
1365 	rq = blk_mq_map_request(q, bio, &data);
1366 	if (unlikely(!rq))
1367 		return BLK_QC_T_NONE;
1368 
1369 	cookie = blk_tag_to_qc_t(rq->tag, data.hctx->queue_num);
1370 
1371 	if (unlikely(is_flush_fua)) {
1372 		blk_mq_bio_to_request(rq, bio);
1373 		blk_insert_flush(rq);
1374 		goto run_queue;
1375 	}
1376 
1377 	/*
1378 	 * A task plug currently exists. Since this is completely lockless,
1379 	 * utilize that to temporarily store requests until the task is
1380 	 * either done or scheduled away.
1381 	 */
1382 	plug = current->plug;
1383 	if (plug) {
1384 		blk_mq_bio_to_request(rq, bio);
1385 		if (!request_count)
1386 			trace_block_plug(q);
1387 
1388 		blk_mq_put_ctx(data.ctx);
1389 
1390 		if (request_count >= BLK_MAX_REQUEST_COUNT) {
1391 			blk_flush_plug_list(plug, false);
1392 			trace_block_plug(q);
1393 		}
1394 
1395 		list_add_tail(&rq->queuelist, &plug->mq_list);
1396 		return cookie;
1397 	}
1398 
1399 	if (!blk_mq_merge_queue_io(data.hctx, data.ctx, rq, bio)) {
1400 		/*
1401 		 * For a SYNC request, send it to the hardware immediately. For
1402 		 * an ASYNC request, just ensure that we run it later on. The
1403 		 * latter allows for merging opportunities and more efficient
1404 		 * dispatching.
1405 		 */
1406 run_queue:
1407 		blk_mq_run_hw_queue(data.hctx, !is_sync || is_flush_fua);
1408 	}
1409 
1410 	blk_mq_put_ctx(data.ctx);
1411 	return cookie;
1412 }
1413 
1414 /*
1415  * Default mapping to a software queue, since we use one per CPU.
1416  */
1417 struct blk_mq_hw_ctx *blk_mq_map_queue(struct request_queue *q, const int cpu)
1418 {
1419 	return q->queue_hw_ctx[q->mq_map[cpu]];
1420 }
1421 EXPORT_SYMBOL(blk_mq_map_queue);
1422 
1423 static void blk_mq_free_rq_map(struct blk_mq_tag_set *set,
1424 		struct blk_mq_tags *tags, unsigned int hctx_idx)
1425 {
1426 	struct page *page;
1427 
1428 	if (tags->rqs && set->ops->exit_request) {
1429 		int i;
1430 
1431 		for (i = 0; i < tags->nr_tags; i++) {
1432 			if (!tags->rqs[i])
1433 				continue;
1434 			set->ops->exit_request(set->driver_data, tags->rqs[i],
1435 						hctx_idx, i);
1436 			tags->rqs[i] = NULL;
1437 		}
1438 	}
1439 
1440 	while (!list_empty(&tags->page_list)) {
1441 		page = list_first_entry(&tags->page_list, struct page, lru);
1442 		list_del_init(&page->lru);
1443 		/*
1444 		 * Remove kmemleak object previously allocated in
1445 		 * blk_mq_init_rq_map().
1446 		 */
1447 		kmemleak_free(page_address(page));
1448 		__free_pages(page, page->private);
1449 	}
1450 
1451 	kfree(tags->rqs);
1452 
1453 	blk_mq_free_tags(tags);
1454 }
1455 
1456 static size_t order_to_size(unsigned int order)
1457 {
1458 	return (size_t)PAGE_SIZE << order;
1459 }
1460 
1461 static struct blk_mq_tags *blk_mq_init_rq_map(struct blk_mq_tag_set *set,
1462 		unsigned int hctx_idx)
1463 {
1464 	struct blk_mq_tags *tags;
1465 	unsigned int i, j, entries_per_page, max_order = 4;
1466 	size_t rq_size, left;
1467 
1468 	tags = blk_mq_init_tags(set->queue_depth, set->reserved_tags,
1469 				set->numa_node,
1470 				BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
1471 	if (!tags)
1472 		return NULL;
1473 
1474 	INIT_LIST_HEAD(&tags->page_list);
1475 
1476 	tags->rqs = kzalloc_node(set->queue_depth * sizeof(struct request *),
1477 				 GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY,
1478 				 set->numa_node);
1479 	if (!tags->rqs) {
1480 		blk_mq_free_tags(tags);
1481 		return NULL;
1482 	}
1483 
1484 	/*
1485 	 * rq_size is the size of the request plus driver payload, rounded
1486 	 * to the cacheline size
1487 	 */
1488 	rq_size = round_up(sizeof(struct request) + set->cmd_size,
1489 				cache_line_size());
1490 	left = rq_size * set->queue_depth;
1491 
1492 	for (i = 0; i < set->queue_depth; ) {
1493 		int this_order = max_order;
1494 		struct page *page;
1495 		int to_do;
1496 		void *p;
1497 
1498 		while (this_order && left < order_to_size(this_order - 1))
1499 			this_order--;
1500 
1501 		do {
1502 			page = alloc_pages_node(set->numa_node,
1503 				GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
1504 				this_order);
1505 			if (page)
1506 				break;
1507 			if (!this_order--)
1508 				break;
1509 			if (order_to_size(this_order) < rq_size)
1510 				break;
1511 		} while (1);
1512 
1513 		if (!page)
1514 			goto fail;
1515 
1516 		page->private = this_order;
1517 		list_add_tail(&page->lru, &tags->page_list);
1518 
1519 		p = page_address(page);
1520 		/*
1521 		 * Allow kmemleak to scan these pages as they contain pointers
1522 		 * to additional allocations like via ops->init_request().
1523 		 */
1524 		kmemleak_alloc(p, order_to_size(this_order), 1, GFP_KERNEL);
1525 		entries_per_page = order_to_size(this_order) / rq_size;
1526 		to_do = min(entries_per_page, set->queue_depth - i);
1527 		left -= to_do * rq_size;
1528 		for (j = 0; j < to_do; j++) {
1529 			tags->rqs[i] = p;
1530 			if (set->ops->init_request) {
1531 				if (set->ops->init_request(set->driver_data,
1532 						tags->rqs[i], hctx_idx, i,
1533 						set->numa_node)) {
1534 					tags->rqs[i] = NULL;
1535 					goto fail;
1536 				}
1537 			}
1538 
1539 			p += rq_size;
1540 			i++;
1541 		}
1542 	}
1543 	return tags;
1544 
1545 fail:
1546 	blk_mq_free_rq_map(set, tags, hctx_idx);
1547 	return NULL;
1548 }
1549 
1550 static void blk_mq_free_bitmap(struct blk_mq_ctxmap *bitmap)
1551 {
1552 	kfree(bitmap->map);
1553 }
1554 
1555 static int blk_mq_alloc_bitmap(struct blk_mq_ctxmap *bitmap, int node)
1556 {
1557 	unsigned int bpw = 8, total, num_maps, i;
1558 
1559 	bitmap->bits_per_word = bpw;
1560 
1561 	num_maps = ALIGN(nr_cpu_ids, bpw) / bpw;
1562 	bitmap->map = kzalloc_node(num_maps * sizeof(struct blk_align_bitmap),
1563 					GFP_KERNEL, node);
1564 	if (!bitmap->map)
1565 		return -ENOMEM;
1566 
1567 	total = nr_cpu_ids;
1568 	for (i = 0; i < num_maps; i++) {
1569 		bitmap->map[i].depth = min(total, bitmap->bits_per_word);
1570 		total -= bitmap->map[i].depth;
1571 	}
1572 
1573 	return 0;
1574 }
1575 
1576 static int blk_mq_hctx_cpu_offline(struct blk_mq_hw_ctx *hctx, int cpu)
1577 {
1578 	struct request_queue *q = hctx->queue;
1579 	struct blk_mq_ctx *ctx;
1580 	LIST_HEAD(tmp);
1581 
1582 	/*
1583 	 * Move ctx entries to new CPU, if this one is going away.
1584 	 */
1585 	ctx = __blk_mq_get_ctx(q, cpu);
1586 
1587 	spin_lock(&ctx->lock);
1588 	if (!list_empty(&ctx->rq_list)) {
1589 		list_splice_init(&ctx->rq_list, &tmp);
1590 		blk_mq_hctx_clear_pending(hctx, ctx);
1591 	}
1592 	spin_unlock(&ctx->lock);
1593 
1594 	if (list_empty(&tmp))
1595 		return NOTIFY_OK;
1596 
1597 	ctx = blk_mq_get_ctx(q);
1598 	spin_lock(&ctx->lock);
1599 
1600 	while (!list_empty(&tmp)) {
1601 		struct request *rq;
1602 
1603 		rq = list_first_entry(&tmp, struct request, queuelist);
1604 		rq->mq_ctx = ctx;
1605 		list_move_tail(&rq->queuelist, &ctx->rq_list);
1606 	}
1607 
1608 	hctx = q->mq_ops->map_queue(q, ctx->cpu);
1609 	blk_mq_hctx_mark_pending(hctx, ctx);
1610 
1611 	spin_unlock(&ctx->lock);
1612 
1613 	blk_mq_run_hw_queue(hctx, true);
1614 	blk_mq_put_ctx(ctx);
1615 	return NOTIFY_OK;
1616 }
1617 
1618 static int blk_mq_hctx_notify(void *data, unsigned long action,
1619 			      unsigned int cpu)
1620 {
1621 	struct blk_mq_hw_ctx *hctx = data;
1622 
1623 	if (action == CPU_DEAD || action == CPU_DEAD_FROZEN)
1624 		return blk_mq_hctx_cpu_offline(hctx, cpu);
1625 
1626 	/*
1627 	 * In case of CPU online, tags may be reallocated
1628 	 * in blk_mq_map_swqueue() after mapping is updated.
1629 	 */
1630 
1631 	return NOTIFY_OK;
1632 }
1633 
1634 /* hctx->ctxs will be freed in queue's release handler */
1635 static void blk_mq_exit_hctx(struct request_queue *q,
1636 		struct blk_mq_tag_set *set,
1637 		struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
1638 {
1639 	unsigned flush_start_tag = set->queue_depth;
1640 
1641 	blk_mq_tag_idle(hctx);
1642 
1643 	if (set->ops->exit_request)
1644 		set->ops->exit_request(set->driver_data,
1645 				       hctx->fq->flush_rq, hctx_idx,
1646 				       flush_start_tag + hctx_idx);
1647 
1648 	if (set->ops->exit_hctx)
1649 		set->ops->exit_hctx(hctx, hctx_idx);
1650 
1651 	blk_mq_unregister_cpu_notifier(&hctx->cpu_notifier);
1652 	blk_free_flush_queue(hctx->fq);
1653 	blk_mq_free_bitmap(&hctx->ctx_map);
1654 }
1655 
1656 static void blk_mq_exit_hw_queues(struct request_queue *q,
1657 		struct blk_mq_tag_set *set, int nr_queue)
1658 {
1659 	struct blk_mq_hw_ctx *hctx;
1660 	unsigned int i;
1661 
1662 	queue_for_each_hw_ctx(q, hctx, i) {
1663 		if (i == nr_queue)
1664 			break;
1665 		blk_mq_exit_hctx(q, set, hctx, i);
1666 	}
1667 }
1668 
1669 static void blk_mq_free_hw_queues(struct request_queue *q,
1670 		struct blk_mq_tag_set *set)
1671 {
1672 	struct blk_mq_hw_ctx *hctx;
1673 	unsigned int i;
1674 
1675 	queue_for_each_hw_ctx(q, hctx, i)
1676 		free_cpumask_var(hctx->cpumask);
1677 }
1678 
1679 static int blk_mq_init_hctx(struct request_queue *q,
1680 		struct blk_mq_tag_set *set,
1681 		struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
1682 {
1683 	int node;
1684 	unsigned flush_start_tag = set->queue_depth;
1685 
1686 	node = hctx->numa_node;
1687 	if (node == NUMA_NO_NODE)
1688 		node = hctx->numa_node = set->numa_node;
1689 
1690 	INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
1691 	INIT_DELAYED_WORK(&hctx->delay_work, blk_mq_delay_work_fn);
1692 	spin_lock_init(&hctx->lock);
1693 	INIT_LIST_HEAD(&hctx->dispatch);
1694 	hctx->queue = q;
1695 	hctx->queue_num = hctx_idx;
1696 	hctx->flags = set->flags & ~BLK_MQ_F_TAG_SHARED;
1697 
1698 	blk_mq_init_cpu_notifier(&hctx->cpu_notifier,
1699 					blk_mq_hctx_notify, hctx);
1700 	blk_mq_register_cpu_notifier(&hctx->cpu_notifier);
1701 
1702 	hctx->tags = set->tags[hctx_idx];
1703 
1704 	/*
1705 	 * Allocate space for all possible cpus to avoid allocation at
1706 	 * runtime
1707 	 */
1708 	hctx->ctxs = kmalloc_node(nr_cpu_ids * sizeof(void *),
1709 					GFP_KERNEL, node);
1710 	if (!hctx->ctxs)
1711 		goto unregister_cpu_notifier;
1712 
1713 	if (blk_mq_alloc_bitmap(&hctx->ctx_map, node))
1714 		goto free_ctxs;
1715 
1716 	hctx->nr_ctx = 0;
1717 
1718 	if (set->ops->init_hctx &&
1719 	    set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
1720 		goto free_bitmap;
1721 
1722 	hctx->fq = blk_alloc_flush_queue(q, hctx->numa_node, set->cmd_size);
1723 	if (!hctx->fq)
1724 		goto exit_hctx;
1725 
1726 	if (set->ops->init_request &&
1727 	    set->ops->init_request(set->driver_data,
1728 				   hctx->fq->flush_rq, hctx_idx,
1729 				   flush_start_tag + hctx_idx, node))
1730 		goto free_fq;
1731 
1732 	return 0;
1733 
1734  free_fq:
1735 	kfree(hctx->fq);
1736  exit_hctx:
1737 	if (set->ops->exit_hctx)
1738 		set->ops->exit_hctx(hctx, hctx_idx);
1739  free_bitmap:
1740 	blk_mq_free_bitmap(&hctx->ctx_map);
1741  free_ctxs:
1742 	kfree(hctx->ctxs);
1743  unregister_cpu_notifier:
1744 	blk_mq_unregister_cpu_notifier(&hctx->cpu_notifier);
1745 
1746 	return -1;
1747 }
1748 
1749 static void blk_mq_init_cpu_queues(struct request_queue *q,
1750 				   unsigned int nr_hw_queues)
1751 {
1752 	unsigned int i;
1753 
1754 	for_each_possible_cpu(i) {
1755 		struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
1756 		struct blk_mq_hw_ctx *hctx;
1757 
1758 		memset(__ctx, 0, sizeof(*__ctx));
1759 		__ctx->cpu = i;
1760 		spin_lock_init(&__ctx->lock);
1761 		INIT_LIST_HEAD(&__ctx->rq_list);
1762 		__ctx->queue = q;
1763 
1764 		/* If the cpu isn't online, the cpu is mapped to first hctx */
1765 		if (!cpu_online(i))
1766 			continue;
1767 
1768 		hctx = q->mq_ops->map_queue(q, i);
1769 
1770 		/*
1771 		 * Set local node, IFF we have more than one hw queue. If
1772 		 * not, we remain on the home node of the device
1773 		 */
1774 		if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
1775 			hctx->numa_node = local_memory_node(cpu_to_node(i));
1776 	}
1777 }
1778 
1779 static void blk_mq_map_swqueue(struct request_queue *q,
1780 			       const struct cpumask *online_mask)
1781 {
1782 	unsigned int i;
1783 	struct blk_mq_hw_ctx *hctx;
1784 	struct blk_mq_ctx *ctx;
1785 	struct blk_mq_tag_set *set = q->tag_set;
1786 
1787 	/*
1788 	 * Avoid others reading imcomplete hctx->cpumask through sysfs
1789 	 */
1790 	mutex_lock(&q->sysfs_lock);
1791 
1792 	queue_for_each_hw_ctx(q, hctx, i) {
1793 		cpumask_clear(hctx->cpumask);
1794 		hctx->nr_ctx = 0;
1795 	}
1796 
1797 	/*
1798 	 * Map software to hardware queues
1799 	 */
1800 	for_each_possible_cpu(i) {
1801 		/* If the cpu isn't online, the cpu is mapped to first hctx */
1802 		if (!cpumask_test_cpu(i, online_mask))
1803 			continue;
1804 
1805 		ctx = per_cpu_ptr(q->queue_ctx, i);
1806 		hctx = q->mq_ops->map_queue(q, i);
1807 
1808 		cpumask_set_cpu(i, hctx->cpumask);
1809 		ctx->index_hw = hctx->nr_ctx;
1810 		hctx->ctxs[hctx->nr_ctx++] = ctx;
1811 	}
1812 
1813 	mutex_unlock(&q->sysfs_lock);
1814 
1815 	queue_for_each_hw_ctx(q, hctx, i) {
1816 		struct blk_mq_ctxmap *map = &hctx->ctx_map;
1817 
1818 		/*
1819 		 * If no software queues are mapped to this hardware queue,
1820 		 * disable it and free the request entries.
1821 		 */
1822 		if (!hctx->nr_ctx) {
1823 			if (set->tags[i]) {
1824 				blk_mq_free_rq_map(set, set->tags[i], i);
1825 				set->tags[i] = NULL;
1826 			}
1827 			hctx->tags = NULL;
1828 			continue;
1829 		}
1830 
1831 		/* unmapped hw queue can be remapped after CPU topo changed */
1832 		if (!set->tags[i])
1833 			set->tags[i] = blk_mq_init_rq_map(set, i);
1834 		hctx->tags = set->tags[i];
1835 		WARN_ON(!hctx->tags);
1836 
1837 		cpumask_copy(hctx->tags->cpumask, hctx->cpumask);
1838 		/*
1839 		 * Set the map size to the number of mapped software queues.
1840 		 * This is more accurate and more efficient than looping
1841 		 * over all possibly mapped software queues.
1842 		 */
1843 		map->size = DIV_ROUND_UP(hctx->nr_ctx, map->bits_per_word);
1844 
1845 		/*
1846 		 * Initialize batch roundrobin counts
1847 		 */
1848 		hctx->next_cpu = cpumask_first(hctx->cpumask);
1849 		hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1850 	}
1851 }
1852 
1853 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
1854 {
1855 	struct blk_mq_hw_ctx *hctx;
1856 	int i;
1857 
1858 	queue_for_each_hw_ctx(q, hctx, i) {
1859 		if (shared)
1860 			hctx->flags |= BLK_MQ_F_TAG_SHARED;
1861 		else
1862 			hctx->flags &= ~BLK_MQ_F_TAG_SHARED;
1863 	}
1864 }
1865 
1866 static void blk_mq_update_tag_set_depth(struct blk_mq_tag_set *set, bool shared)
1867 {
1868 	struct request_queue *q;
1869 
1870 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
1871 		blk_mq_freeze_queue(q);
1872 		queue_set_hctx_shared(q, shared);
1873 		blk_mq_unfreeze_queue(q);
1874 	}
1875 }
1876 
1877 static void blk_mq_del_queue_tag_set(struct request_queue *q)
1878 {
1879 	struct blk_mq_tag_set *set = q->tag_set;
1880 
1881 	mutex_lock(&set->tag_list_lock);
1882 	list_del_init(&q->tag_set_list);
1883 	if (list_is_singular(&set->tag_list)) {
1884 		/* just transitioned to unshared */
1885 		set->flags &= ~BLK_MQ_F_TAG_SHARED;
1886 		/* update existing queue */
1887 		blk_mq_update_tag_set_depth(set, false);
1888 	}
1889 	mutex_unlock(&set->tag_list_lock);
1890 }
1891 
1892 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
1893 				     struct request_queue *q)
1894 {
1895 	q->tag_set = set;
1896 
1897 	mutex_lock(&set->tag_list_lock);
1898 
1899 	/* Check to see if we're transitioning to shared (from 1 to 2 queues). */
1900 	if (!list_empty(&set->tag_list) && !(set->flags & BLK_MQ_F_TAG_SHARED)) {
1901 		set->flags |= BLK_MQ_F_TAG_SHARED;
1902 		/* update existing queue */
1903 		blk_mq_update_tag_set_depth(set, true);
1904 	}
1905 	if (set->flags & BLK_MQ_F_TAG_SHARED)
1906 		queue_set_hctx_shared(q, true);
1907 	list_add_tail(&q->tag_set_list, &set->tag_list);
1908 
1909 	mutex_unlock(&set->tag_list_lock);
1910 }
1911 
1912 /*
1913  * It is the actual release handler for mq, but we do it from
1914  * request queue's release handler for avoiding use-after-free
1915  * and headache because q->mq_kobj shouldn't have been introduced,
1916  * but we can't group ctx/kctx kobj without it.
1917  */
1918 void blk_mq_release(struct request_queue *q)
1919 {
1920 	struct blk_mq_hw_ctx *hctx;
1921 	unsigned int i;
1922 
1923 	/* hctx kobj stays in hctx */
1924 	queue_for_each_hw_ctx(q, hctx, i) {
1925 		if (!hctx)
1926 			continue;
1927 		kfree(hctx->ctxs);
1928 		kfree(hctx);
1929 	}
1930 
1931 	kfree(q->mq_map);
1932 	q->mq_map = NULL;
1933 
1934 	kfree(q->queue_hw_ctx);
1935 
1936 	/* ctx kobj stays in queue_ctx */
1937 	free_percpu(q->queue_ctx);
1938 }
1939 
1940 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
1941 {
1942 	struct request_queue *uninit_q, *q;
1943 
1944 	uninit_q = blk_alloc_queue_node(GFP_KERNEL, set->numa_node);
1945 	if (!uninit_q)
1946 		return ERR_PTR(-ENOMEM);
1947 
1948 	q = blk_mq_init_allocated_queue(set, uninit_q);
1949 	if (IS_ERR(q))
1950 		blk_cleanup_queue(uninit_q);
1951 
1952 	return q;
1953 }
1954 EXPORT_SYMBOL(blk_mq_init_queue);
1955 
1956 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
1957 						struct request_queue *q)
1958 {
1959 	int i, j;
1960 	struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
1961 
1962 	blk_mq_sysfs_unregister(q);
1963 	for (i = 0; i < set->nr_hw_queues; i++) {
1964 		int node;
1965 
1966 		if (hctxs[i])
1967 			continue;
1968 
1969 		node = blk_mq_hw_queue_to_node(q->mq_map, i);
1970 		hctxs[i] = kzalloc_node(sizeof(struct blk_mq_hw_ctx),
1971 					GFP_KERNEL, node);
1972 		if (!hctxs[i])
1973 			break;
1974 
1975 		if (!zalloc_cpumask_var_node(&hctxs[i]->cpumask, GFP_KERNEL,
1976 						node)) {
1977 			kfree(hctxs[i]);
1978 			hctxs[i] = NULL;
1979 			break;
1980 		}
1981 
1982 		atomic_set(&hctxs[i]->nr_active, 0);
1983 		hctxs[i]->numa_node = node;
1984 		hctxs[i]->queue_num = i;
1985 
1986 		if (blk_mq_init_hctx(q, set, hctxs[i], i)) {
1987 			free_cpumask_var(hctxs[i]->cpumask);
1988 			kfree(hctxs[i]);
1989 			hctxs[i] = NULL;
1990 			break;
1991 		}
1992 		blk_mq_hctx_kobj_init(hctxs[i]);
1993 	}
1994 	for (j = i; j < q->nr_hw_queues; j++) {
1995 		struct blk_mq_hw_ctx *hctx = hctxs[j];
1996 
1997 		if (hctx) {
1998 			if (hctx->tags) {
1999 				blk_mq_free_rq_map(set, hctx->tags, j);
2000 				set->tags[j] = NULL;
2001 			}
2002 			blk_mq_exit_hctx(q, set, hctx, j);
2003 			free_cpumask_var(hctx->cpumask);
2004 			kobject_put(&hctx->kobj);
2005 			kfree(hctx->ctxs);
2006 			kfree(hctx);
2007 			hctxs[j] = NULL;
2008 
2009 		}
2010 	}
2011 	q->nr_hw_queues = i;
2012 	blk_mq_sysfs_register(q);
2013 }
2014 
2015 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
2016 						  struct request_queue *q)
2017 {
2018 	/* mark the queue as mq asap */
2019 	q->mq_ops = set->ops;
2020 
2021 	q->queue_ctx = alloc_percpu(struct blk_mq_ctx);
2022 	if (!q->queue_ctx)
2023 		goto err_exit;
2024 
2025 	q->queue_hw_ctx = kzalloc_node(nr_cpu_ids * sizeof(*(q->queue_hw_ctx)),
2026 						GFP_KERNEL, set->numa_node);
2027 	if (!q->queue_hw_ctx)
2028 		goto err_percpu;
2029 
2030 	q->mq_map = blk_mq_make_queue_map(set);
2031 	if (!q->mq_map)
2032 		goto err_map;
2033 
2034 	blk_mq_realloc_hw_ctxs(set, q);
2035 	if (!q->nr_hw_queues)
2036 		goto err_hctxs;
2037 
2038 	INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
2039 	blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
2040 
2041 	q->nr_queues = nr_cpu_ids;
2042 
2043 	q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
2044 
2045 	if (!(set->flags & BLK_MQ_F_SG_MERGE))
2046 		q->queue_flags |= 1 << QUEUE_FLAG_NO_SG_MERGE;
2047 
2048 	q->sg_reserved_size = INT_MAX;
2049 
2050 	INIT_WORK(&q->requeue_work, blk_mq_requeue_work);
2051 	INIT_LIST_HEAD(&q->requeue_list);
2052 	spin_lock_init(&q->requeue_lock);
2053 
2054 	if (q->nr_hw_queues > 1)
2055 		blk_queue_make_request(q, blk_mq_make_request);
2056 	else
2057 		blk_queue_make_request(q, blk_sq_make_request);
2058 
2059 	/*
2060 	 * Do this after blk_queue_make_request() overrides it...
2061 	 */
2062 	q->nr_requests = set->queue_depth;
2063 
2064 	if (set->ops->complete)
2065 		blk_queue_softirq_done(q, set->ops->complete);
2066 
2067 	blk_mq_init_cpu_queues(q, set->nr_hw_queues);
2068 
2069 	get_online_cpus();
2070 	mutex_lock(&all_q_mutex);
2071 
2072 	list_add_tail(&q->all_q_node, &all_q_list);
2073 	blk_mq_add_queue_tag_set(set, q);
2074 	blk_mq_map_swqueue(q, cpu_online_mask);
2075 
2076 	mutex_unlock(&all_q_mutex);
2077 	put_online_cpus();
2078 
2079 	return q;
2080 
2081 err_hctxs:
2082 	kfree(q->mq_map);
2083 err_map:
2084 	kfree(q->queue_hw_ctx);
2085 err_percpu:
2086 	free_percpu(q->queue_ctx);
2087 err_exit:
2088 	q->mq_ops = NULL;
2089 	return ERR_PTR(-ENOMEM);
2090 }
2091 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
2092 
2093 void blk_mq_free_queue(struct request_queue *q)
2094 {
2095 	struct blk_mq_tag_set	*set = q->tag_set;
2096 
2097 	mutex_lock(&all_q_mutex);
2098 	list_del_init(&q->all_q_node);
2099 	mutex_unlock(&all_q_mutex);
2100 
2101 	blk_mq_del_queue_tag_set(q);
2102 
2103 	blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
2104 	blk_mq_free_hw_queues(q, set);
2105 }
2106 
2107 /* Basically redo blk_mq_init_queue with queue frozen */
2108 static void blk_mq_queue_reinit(struct request_queue *q,
2109 				const struct cpumask *online_mask)
2110 {
2111 	WARN_ON_ONCE(!atomic_read(&q->mq_freeze_depth));
2112 
2113 	blk_mq_sysfs_unregister(q);
2114 
2115 	blk_mq_update_queue_map(q->mq_map, q->nr_hw_queues, online_mask);
2116 
2117 	/*
2118 	 * redo blk_mq_init_cpu_queues and blk_mq_init_hw_queues. FIXME: maybe
2119 	 * we should change hctx numa_node according to new topology (this
2120 	 * involves free and re-allocate memory, worthy doing?)
2121 	 */
2122 
2123 	blk_mq_map_swqueue(q, online_mask);
2124 
2125 	blk_mq_sysfs_register(q);
2126 }
2127 
2128 static int blk_mq_queue_reinit_notify(struct notifier_block *nb,
2129 				      unsigned long action, void *hcpu)
2130 {
2131 	struct request_queue *q;
2132 	int cpu = (unsigned long)hcpu;
2133 	/*
2134 	 * New online cpumask which is going to be set in this hotplug event.
2135 	 * Declare this cpumasks as global as cpu-hotplug operation is invoked
2136 	 * one-by-one and dynamically allocating this could result in a failure.
2137 	 */
2138 	static struct cpumask online_new;
2139 
2140 	/*
2141 	 * Before hotadded cpu starts handling requests, new mappings must
2142 	 * be established.  Otherwise, these requests in hw queue might
2143 	 * never be dispatched.
2144 	 *
2145 	 * For example, there is a single hw queue (hctx) and two CPU queues
2146 	 * (ctx0 for CPU0, and ctx1 for CPU1).
2147 	 *
2148 	 * Now CPU1 is just onlined and a request is inserted into
2149 	 * ctx1->rq_list and set bit0 in pending bitmap as ctx1->index_hw is
2150 	 * still zero.
2151 	 *
2152 	 * And then while running hw queue, flush_busy_ctxs() finds bit0 is
2153 	 * set in pending bitmap and tries to retrieve requests in
2154 	 * hctx->ctxs[0]->rq_list.  But htx->ctxs[0] is a pointer to ctx0,
2155 	 * so the request in ctx1->rq_list is ignored.
2156 	 */
2157 	switch (action & ~CPU_TASKS_FROZEN) {
2158 	case CPU_DEAD:
2159 	case CPU_UP_CANCELED:
2160 		cpumask_copy(&online_new, cpu_online_mask);
2161 		break;
2162 	case CPU_UP_PREPARE:
2163 		cpumask_copy(&online_new, cpu_online_mask);
2164 		cpumask_set_cpu(cpu, &online_new);
2165 		break;
2166 	default:
2167 		return NOTIFY_OK;
2168 	}
2169 
2170 	mutex_lock(&all_q_mutex);
2171 
2172 	/*
2173 	 * We need to freeze and reinit all existing queues.  Freezing
2174 	 * involves synchronous wait for an RCU grace period and doing it
2175 	 * one by one may take a long time.  Start freezing all queues in
2176 	 * one swoop and then wait for the completions so that freezing can
2177 	 * take place in parallel.
2178 	 */
2179 	list_for_each_entry(q, &all_q_list, all_q_node)
2180 		blk_mq_freeze_queue_start(q);
2181 	list_for_each_entry(q, &all_q_list, all_q_node) {
2182 		blk_mq_freeze_queue_wait(q);
2183 
2184 		/*
2185 		 * timeout handler can't touch hw queue during the
2186 		 * reinitialization
2187 		 */
2188 		del_timer_sync(&q->timeout);
2189 	}
2190 
2191 	list_for_each_entry(q, &all_q_list, all_q_node)
2192 		blk_mq_queue_reinit(q, &online_new);
2193 
2194 	list_for_each_entry(q, &all_q_list, all_q_node)
2195 		blk_mq_unfreeze_queue(q);
2196 
2197 	mutex_unlock(&all_q_mutex);
2198 	return NOTIFY_OK;
2199 }
2200 
2201 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2202 {
2203 	int i;
2204 
2205 	for (i = 0; i < set->nr_hw_queues; i++) {
2206 		set->tags[i] = blk_mq_init_rq_map(set, i);
2207 		if (!set->tags[i])
2208 			goto out_unwind;
2209 	}
2210 
2211 	return 0;
2212 
2213 out_unwind:
2214 	while (--i >= 0)
2215 		blk_mq_free_rq_map(set, set->tags[i], i);
2216 
2217 	return -ENOMEM;
2218 }
2219 
2220 /*
2221  * Allocate the request maps associated with this tag_set. Note that this
2222  * may reduce the depth asked for, if memory is tight. set->queue_depth
2223  * will be updated to reflect the allocated depth.
2224  */
2225 static int blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2226 {
2227 	unsigned int depth;
2228 	int err;
2229 
2230 	depth = set->queue_depth;
2231 	do {
2232 		err = __blk_mq_alloc_rq_maps(set);
2233 		if (!err)
2234 			break;
2235 
2236 		set->queue_depth >>= 1;
2237 		if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
2238 			err = -ENOMEM;
2239 			break;
2240 		}
2241 	} while (set->queue_depth);
2242 
2243 	if (!set->queue_depth || err) {
2244 		pr_err("blk-mq: failed to allocate request map\n");
2245 		return -ENOMEM;
2246 	}
2247 
2248 	if (depth != set->queue_depth)
2249 		pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
2250 						depth, set->queue_depth);
2251 
2252 	return 0;
2253 }
2254 
2255 struct cpumask *blk_mq_tags_cpumask(struct blk_mq_tags *tags)
2256 {
2257 	return tags->cpumask;
2258 }
2259 EXPORT_SYMBOL_GPL(blk_mq_tags_cpumask);
2260 
2261 /*
2262  * Alloc a tag set to be associated with one or more request queues.
2263  * May fail with EINVAL for various error conditions. May adjust the
2264  * requested depth down, if if it too large. In that case, the set
2265  * value will be stored in set->queue_depth.
2266  */
2267 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
2268 {
2269 	BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
2270 
2271 	if (!set->nr_hw_queues)
2272 		return -EINVAL;
2273 	if (!set->queue_depth)
2274 		return -EINVAL;
2275 	if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
2276 		return -EINVAL;
2277 
2278 	if (!set->ops->queue_rq || !set->ops->map_queue)
2279 		return -EINVAL;
2280 
2281 	if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
2282 		pr_info("blk-mq: reduced tag depth to %u\n",
2283 			BLK_MQ_MAX_DEPTH);
2284 		set->queue_depth = BLK_MQ_MAX_DEPTH;
2285 	}
2286 
2287 	/*
2288 	 * If a crashdump is active, then we are potentially in a very
2289 	 * memory constrained environment. Limit us to 1 queue and
2290 	 * 64 tags to prevent using too much memory.
2291 	 */
2292 	if (is_kdump_kernel()) {
2293 		set->nr_hw_queues = 1;
2294 		set->queue_depth = min(64U, set->queue_depth);
2295 	}
2296 	/*
2297 	 * There is no use for more h/w queues than cpus.
2298 	 */
2299 	if (set->nr_hw_queues > nr_cpu_ids)
2300 		set->nr_hw_queues = nr_cpu_ids;
2301 
2302 	set->tags = kzalloc_node(nr_cpu_ids * sizeof(struct blk_mq_tags *),
2303 				 GFP_KERNEL, set->numa_node);
2304 	if (!set->tags)
2305 		return -ENOMEM;
2306 
2307 	if (blk_mq_alloc_rq_maps(set))
2308 		goto enomem;
2309 
2310 	mutex_init(&set->tag_list_lock);
2311 	INIT_LIST_HEAD(&set->tag_list);
2312 
2313 	return 0;
2314 enomem:
2315 	kfree(set->tags);
2316 	set->tags = NULL;
2317 	return -ENOMEM;
2318 }
2319 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
2320 
2321 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
2322 {
2323 	int i;
2324 
2325 	for (i = 0; i < nr_cpu_ids; i++) {
2326 		if (set->tags[i])
2327 			blk_mq_free_rq_map(set, set->tags[i], i);
2328 	}
2329 
2330 	kfree(set->tags);
2331 	set->tags = NULL;
2332 }
2333 EXPORT_SYMBOL(blk_mq_free_tag_set);
2334 
2335 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
2336 {
2337 	struct blk_mq_tag_set *set = q->tag_set;
2338 	struct blk_mq_hw_ctx *hctx;
2339 	int i, ret;
2340 
2341 	if (!set || nr > set->queue_depth)
2342 		return -EINVAL;
2343 
2344 	ret = 0;
2345 	queue_for_each_hw_ctx(q, hctx, i) {
2346 		if (!hctx->tags)
2347 			continue;
2348 		ret = blk_mq_tag_update_depth(hctx->tags, nr);
2349 		if (ret)
2350 			break;
2351 	}
2352 
2353 	if (!ret)
2354 		q->nr_requests = nr;
2355 
2356 	return ret;
2357 }
2358 
2359 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
2360 {
2361 	struct request_queue *q;
2362 
2363 	if (nr_hw_queues > nr_cpu_ids)
2364 		nr_hw_queues = nr_cpu_ids;
2365 	if (nr_hw_queues < 1 || nr_hw_queues == set->nr_hw_queues)
2366 		return;
2367 
2368 	list_for_each_entry(q, &set->tag_list, tag_set_list)
2369 		blk_mq_freeze_queue(q);
2370 
2371 	set->nr_hw_queues = nr_hw_queues;
2372 	list_for_each_entry(q, &set->tag_list, tag_set_list) {
2373 		blk_mq_realloc_hw_ctxs(set, q);
2374 
2375 		if (q->nr_hw_queues > 1)
2376 			blk_queue_make_request(q, blk_mq_make_request);
2377 		else
2378 			blk_queue_make_request(q, blk_sq_make_request);
2379 
2380 		blk_mq_queue_reinit(q, cpu_online_mask);
2381 	}
2382 
2383 	list_for_each_entry(q, &set->tag_list, tag_set_list)
2384 		blk_mq_unfreeze_queue(q);
2385 }
2386 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
2387 
2388 void blk_mq_disable_hotplug(void)
2389 {
2390 	mutex_lock(&all_q_mutex);
2391 }
2392 
2393 void blk_mq_enable_hotplug(void)
2394 {
2395 	mutex_unlock(&all_q_mutex);
2396 }
2397 
2398 static int __init blk_mq_init(void)
2399 {
2400 	blk_mq_cpu_init();
2401 
2402 	hotcpu_notifier(blk_mq_queue_reinit_notify, 0);
2403 
2404 	return 0;
2405 }
2406 subsys_initcall(blk_mq_init);
2407