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