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