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