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