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