]> git.karo-electronics.de Git - karo-tx-linux.git/blob - block/blk-mq.c
blk-mq: Make it safe to use RCU to iterate over blk_mq_tag_set.tag_list
[karo-tx-linux.git] / block / blk-mq.c
1 /*
2  * Block multiqueue core code
3  *
4  * Copyright (C) 2013-2014 Jens Axboe
5  * Copyright (C) 2013-2014 Christoph Hellwig
6  */
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/backing-dev.h>
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/kmemleak.h>
13 #include <linux/mm.h>
14 #include <linux/init.h>
15 #include <linux/slab.h>
16 #include <linux/workqueue.h>
17 #include <linux/smp.h>
18 #include <linux/llist.h>
19 #include <linux/list_sort.h>
20 #include <linux/cpu.h>
21 #include <linux/cache.h>
22 #include <linux/sched/sysctl.h>
23 #include <linux/sched/topology.h>
24 #include <linux/sched/signal.h>
25 #include <linux/delay.h>
26 #include <linux/crash_dump.h>
27 #include <linux/prefetch.h>
28
29 #include <trace/events/block.h>
30
31 #include <linux/blk-mq.h>
32 #include "blk.h"
33 #include "blk-mq.h"
34 #include "blk-mq-tag.h"
35 #include "blk-stat.h"
36 #include "blk-wbt.h"
37 #include "blk-mq-sched.h"
38
39 static DEFINE_MUTEX(all_q_mutex);
40 static LIST_HEAD(all_q_list);
41
42 static void blk_mq_poll_stats_start(struct request_queue *q);
43 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
44
45 /*
46  * Check if any of the ctx's have pending work in this hardware queue
47  */
48 bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
49 {
50         return sbitmap_any_bit_set(&hctx->ctx_map) ||
51                         !list_empty_careful(&hctx->dispatch) ||
52                         blk_mq_sched_has_work(hctx);
53 }
54
55 /*
56  * Mark this ctx as having pending work in this hardware queue
57  */
58 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
59                                      struct blk_mq_ctx *ctx)
60 {
61         if (!sbitmap_test_bit(&hctx->ctx_map, ctx->index_hw))
62                 sbitmap_set_bit(&hctx->ctx_map, ctx->index_hw);
63 }
64
65 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
66                                       struct blk_mq_ctx *ctx)
67 {
68         sbitmap_clear_bit(&hctx->ctx_map, ctx->index_hw);
69 }
70
71 void blk_freeze_queue_start(struct request_queue *q)
72 {
73         int freeze_depth;
74
75         freeze_depth = atomic_inc_return(&q->mq_freeze_depth);
76         if (freeze_depth == 1) {
77                 percpu_ref_kill(&q->q_usage_counter);
78                 blk_mq_run_hw_queues(q, false);
79         }
80 }
81 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
82
83 void blk_mq_freeze_queue_wait(struct request_queue *q)
84 {
85         wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
86 }
87 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
88
89 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
90                                      unsigned long timeout)
91 {
92         return wait_event_timeout(q->mq_freeze_wq,
93                                         percpu_ref_is_zero(&q->q_usage_counter),
94                                         timeout);
95 }
96 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
97
98 /*
99  * Guarantee no request is in use, so we can change any data structure of
100  * the queue afterward.
101  */
102 void blk_freeze_queue(struct request_queue *q)
103 {
104         /*
105          * In the !blk_mq case we are only calling this to kill the
106          * q_usage_counter, otherwise this increases the freeze depth
107          * and waits for it to return to zero.  For this reason there is
108          * no blk_unfreeze_queue(), and blk_freeze_queue() is not
109          * exported to drivers as the only user for unfreeze is blk_mq.
110          */
111         blk_freeze_queue_start(q);
112         blk_mq_freeze_queue_wait(q);
113 }
114
115 void blk_mq_freeze_queue(struct request_queue *q)
116 {
117         /*
118          * ...just an alias to keep freeze and unfreeze actions balanced
119          * in the blk_mq_* namespace
120          */
121         blk_freeze_queue(q);
122 }
123 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
124
125 void blk_mq_unfreeze_queue(struct request_queue *q)
126 {
127         int freeze_depth;
128
129         freeze_depth = atomic_dec_return(&q->mq_freeze_depth);
130         WARN_ON_ONCE(freeze_depth < 0);
131         if (!freeze_depth) {
132                 percpu_ref_reinit(&q->q_usage_counter);
133                 wake_up_all(&q->mq_freeze_wq);
134         }
135 }
136 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
137
138 /**
139  * blk_mq_quiesce_queue() - wait until all ongoing queue_rq calls have finished
140  * @q: request queue.
141  *
142  * Note: this function does not prevent that the struct request end_io()
143  * callback function is invoked. Additionally, it is not prevented that
144  * new queue_rq() calls occur unless the queue has been stopped first.
145  */
146 void blk_mq_quiesce_queue(struct request_queue *q)
147 {
148         struct blk_mq_hw_ctx *hctx;
149         unsigned int i;
150         bool rcu = false;
151
152         blk_mq_stop_hw_queues(q);
153
154         queue_for_each_hw_ctx(q, hctx, i) {
155                 if (hctx->flags & BLK_MQ_F_BLOCKING)
156                         synchronize_srcu(&hctx->queue_rq_srcu);
157                 else
158                         rcu = true;
159         }
160         if (rcu)
161                 synchronize_rcu();
162 }
163 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
164
165 void blk_mq_wake_waiters(struct request_queue *q)
166 {
167         struct blk_mq_hw_ctx *hctx;
168         unsigned int i;
169
170         queue_for_each_hw_ctx(q, hctx, i)
171                 if (blk_mq_hw_queue_mapped(hctx))
172                         blk_mq_tag_wakeup_all(hctx->tags, true);
173
174         /*
175          * If we are called because the queue has now been marked as
176          * dying, we need to ensure that processes currently waiting on
177          * the queue are notified as well.
178          */
179         wake_up_all(&q->mq_freeze_wq);
180 }
181
182 bool blk_mq_can_queue(struct blk_mq_hw_ctx *hctx)
183 {
184         return blk_mq_has_free_tags(hctx->tags);
185 }
186 EXPORT_SYMBOL(blk_mq_can_queue);
187
188 void blk_mq_rq_ctx_init(struct request_queue *q, struct blk_mq_ctx *ctx,
189                         struct request *rq, unsigned int op)
190 {
191         INIT_LIST_HEAD(&rq->queuelist);
192         /* csd/requeue_work/fifo_time is initialized before use */
193         rq->q = q;
194         rq->mq_ctx = ctx;
195         rq->cmd_flags = op;
196         if (blk_queue_io_stat(q))
197                 rq->rq_flags |= RQF_IO_STAT;
198         /* do not touch atomic flags, it needs atomic ops against the timer */
199         rq->cpu = -1;
200         INIT_HLIST_NODE(&rq->hash);
201         RB_CLEAR_NODE(&rq->rb_node);
202         rq->rq_disk = NULL;
203         rq->part = NULL;
204         rq->start_time = jiffies;
205 #ifdef CONFIG_BLK_CGROUP
206         rq->rl = NULL;
207         set_start_time_ns(rq);
208         rq->io_start_time_ns = 0;
209 #endif
210         rq->nr_phys_segments = 0;
211 #if defined(CONFIG_BLK_DEV_INTEGRITY)
212         rq->nr_integrity_segments = 0;
213 #endif
214         rq->special = NULL;
215         /* tag was already set */
216         rq->errors = 0;
217         rq->extra_len = 0;
218
219         INIT_LIST_HEAD(&rq->timeout_list);
220         rq->timeout = 0;
221
222         rq->end_io = NULL;
223         rq->end_io_data = NULL;
224         rq->next_rq = NULL;
225
226         ctx->rq_dispatched[op_is_sync(op)]++;
227 }
228 EXPORT_SYMBOL_GPL(blk_mq_rq_ctx_init);
229
230 struct request *__blk_mq_alloc_request(struct blk_mq_alloc_data *data,
231                                        unsigned int op)
232 {
233         struct request *rq;
234         unsigned int tag;
235
236         tag = blk_mq_get_tag(data);
237         if (tag != BLK_MQ_TAG_FAIL) {
238                 struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
239
240                 rq = tags->static_rqs[tag];
241
242                 if (data->flags & BLK_MQ_REQ_INTERNAL) {
243                         rq->tag = -1;
244                         rq->internal_tag = tag;
245                 } else {
246                         if (blk_mq_tag_busy(data->hctx)) {
247                                 rq->rq_flags = RQF_MQ_INFLIGHT;
248                                 atomic_inc(&data->hctx->nr_active);
249                         }
250                         rq->tag = tag;
251                         rq->internal_tag = -1;
252                         data->hctx->tags->rqs[rq->tag] = rq;
253                 }
254
255                 blk_mq_rq_ctx_init(data->q, data->ctx, rq, op);
256                 return rq;
257         }
258
259         return NULL;
260 }
261 EXPORT_SYMBOL_GPL(__blk_mq_alloc_request);
262
263 struct request *blk_mq_alloc_request(struct request_queue *q, int rw,
264                 unsigned int flags)
265 {
266         struct blk_mq_alloc_data alloc_data = { .flags = flags };
267         struct request *rq;
268         int ret;
269
270         ret = blk_queue_enter(q, flags & BLK_MQ_REQ_NOWAIT);
271         if (ret)
272                 return ERR_PTR(ret);
273
274         rq = blk_mq_sched_get_request(q, NULL, rw, &alloc_data);
275
276         blk_mq_put_ctx(alloc_data.ctx);
277         blk_queue_exit(q);
278
279         if (!rq)
280                 return ERR_PTR(-EWOULDBLOCK);
281
282         rq->__data_len = 0;
283         rq->__sector = (sector_t) -1;
284         rq->bio = rq->biotail = NULL;
285         return rq;
286 }
287 EXPORT_SYMBOL(blk_mq_alloc_request);
288
289 struct request *blk_mq_alloc_request_hctx(struct request_queue *q, int rw,
290                 unsigned int flags, unsigned int hctx_idx)
291 {
292         struct blk_mq_alloc_data alloc_data = { .flags = flags };
293         struct request *rq;
294         unsigned int cpu;
295         int ret;
296
297         /*
298          * If the tag allocator sleeps we could get an allocation for a
299          * different hardware context.  No need to complicate the low level
300          * allocator for this for the rare use case of a command tied to
301          * a specific queue.
302          */
303         if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)))
304                 return ERR_PTR(-EINVAL);
305
306         if (hctx_idx >= q->nr_hw_queues)
307                 return ERR_PTR(-EIO);
308
309         ret = blk_queue_enter(q, true);
310         if (ret)
311                 return ERR_PTR(ret);
312
313         /*
314          * Check if the hardware context is actually mapped to anything.
315          * If not tell the caller that it should skip this queue.
316          */
317         alloc_data.hctx = q->queue_hw_ctx[hctx_idx];
318         if (!blk_mq_hw_queue_mapped(alloc_data.hctx)) {
319                 blk_queue_exit(q);
320                 return ERR_PTR(-EXDEV);
321         }
322         cpu = cpumask_first(alloc_data.hctx->cpumask);
323         alloc_data.ctx = __blk_mq_get_ctx(q, cpu);
324
325         rq = blk_mq_sched_get_request(q, NULL, rw, &alloc_data);
326
327         blk_queue_exit(q);
328
329         if (!rq)
330                 return ERR_PTR(-EWOULDBLOCK);
331
332         return rq;
333 }
334 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
335
336 void __blk_mq_finish_request(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
337                              struct request *rq)
338 {
339         const int sched_tag = rq->internal_tag;
340         struct request_queue *q = rq->q;
341
342         if (rq->rq_flags & RQF_MQ_INFLIGHT)
343                 atomic_dec(&hctx->nr_active);
344
345         wbt_done(q->rq_wb, &rq->issue_stat);
346         rq->rq_flags = 0;
347
348         clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
349         clear_bit(REQ_ATOM_POLL_SLEPT, &rq->atomic_flags);
350         if (rq->tag != -1)
351                 blk_mq_put_tag(hctx, hctx->tags, ctx, rq->tag);
352         if (sched_tag != -1)
353                 blk_mq_sched_completed_request(hctx, rq);
354         blk_mq_sched_restart(hctx);
355         blk_queue_exit(q);
356 }
357
358 static void blk_mq_finish_hctx_request(struct blk_mq_hw_ctx *hctx,
359                                      struct request *rq)
360 {
361         struct blk_mq_ctx *ctx = rq->mq_ctx;
362
363         ctx->rq_completed[rq_is_sync(rq)]++;
364         __blk_mq_finish_request(hctx, ctx, rq);
365 }
366
367 void blk_mq_finish_request(struct request *rq)
368 {
369         blk_mq_finish_hctx_request(blk_mq_map_queue(rq->q, rq->mq_ctx->cpu), rq);
370 }
371
372 void blk_mq_free_request(struct request *rq)
373 {
374         blk_mq_sched_put_request(rq);
375 }
376 EXPORT_SYMBOL_GPL(blk_mq_free_request);
377
378 inline void __blk_mq_end_request(struct request *rq, int error)
379 {
380         blk_account_io_done(rq);
381
382         if (rq->end_io) {
383                 wbt_done(rq->q->rq_wb, &rq->issue_stat);
384                 rq->end_io(rq, error);
385         } else {
386                 if (unlikely(blk_bidi_rq(rq)))
387                         blk_mq_free_request(rq->next_rq);
388                 blk_mq_free_request(rq);
389         }
390 }
391 EXPORT_SYMBOL(__blk_mq_end_request);
392
393 void blk_mq_end_request(struct request *rq, int error)
394 {
395         if (blk_update_request(rq, error, blk_rq_bytes(rq)))
396                 BUG();
397         __blk_mq_end_request(rq, error);
398 }
399 EXPORT_SYMBOL(blk_mq_end_request);
400
401 static void __blk_mq_complete_request_remote(void *data)
402 {
403         struct request *rq = data;
404
405         rq->q->softirq_done_fn(rq);
406 }
407
408 static void blk_mq_ipi_complete_request(struct request *rq)
409 {
410         struct blk_mq_ctx *ctx = rq->mq_ctx;
411         bool shared = false;
412         int cpu;
413
414         if (!test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags)) {
415                 rq->q->softirq_done_fn(rq);
416                 return;
417         }
418
419         cpu = get_cpu();
420         if (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags))
421                 shared = cpus_share_cache(cpu, ctx->cpu);
422
423         if (cpu != ctx->cpu && !shared && cpu_online(ctx->cpu)) {
424                 rq->csd.func = __blk_mq_complete_request_remote;
425                 rq->csd.info = rq;
426                 rq->csd.flags = 0;
427                 smp_call_function_single_async(ctx->cpu, &rq->csd);
428         } else {
429                 rq->q->softirq_done_fn(rq);
430         }
431         put_cpu();
432 }
433
434 static void blk_mq_stat_add(struct request *rq)
435 {
436         if (rq->rq_flags & RQF_STATS) {
437                 blk_mq_poll_stats_start(rq->q);
438                 blk_stat_add(rq);
439         }
440 }
441
442 static void __blk_mq_complete_request(struct request *rq)
443 {
444         struct request_queue *q = rq->q;
445
446         blk_mq_stat_add(rq);
447
448         if (!q->softirq_done_fn)
449                 blk_mq_end_request(rq, rq->errors);
450         else
451                 blk_mq_ipi_complete_request(rq);
452 }
453
454 /**
455  * blk_mq_complete_request - end I/O on a request
456  * @rq:         the request being processed
457  *
458  * Description:
459  *      Ends all I/O on a request. It does not handle partial completions.
460  *      The actual completion happens out-of-order, through a IPI handler.
461  **/
462 void blk_mq_complete_request(struct request *rq, int error)
463 {
464         struct request_queue *q = rq->q;
465
466         if (unlikely(blk_should_fake_timeout(q)))
467                 return;
468         if (!blk_mark_rq_complete(rq)) {
469                 rq->errors = error;
470                 __blk_mq_complete_request(rq);
471         }
472 }
473 EXPORT_SYMBOL(blk_mq_complete_request);
474
475 int blk_mq_request_started(struct request *rq)
476 {
477         return test_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
478 }
479 EXPORT_SYMBOL_GPL(blk_mq_request_started);
480
481 void blk_mq_start_request(struct request *rq)
482 {
483         struct request_queue *q = rq->q;
484
485         blk_mq_sched_started_request(rq);
486
487         trace_block_rq_issue(q, rq);
488
489         if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
490                 blk_stat_set_issue(&rq->issue_stat, blk_rq_sectors(rq));
491                 rq->rq_flags |= RQF_STATS;
492                 wbt_issue(q->rq_wb, &rq->issue_stat);
493         }
494
495         blk_add_timer(rq);
496
497         /*
498          * Ensure that ->deadline is visible before set the started
499          * flag and clear the completed flag.
500          */
501         smp_mb__before_atomic();
502
503         /*
504          * Mark us as started and clear complete. Complete might have been
505          * set if requeue raced with timeout, which then marked it as
506          * complete. So be sure to clear complete again when we start
507          * the request, otherwise we'll ignore the completion event.
508          */
509         if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags))
510                 set_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
511         if (test_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags))
512                 clear_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags);
513
514         if (q->dma_drain_size && blk_rq_bytes(rq)) {
515                 /*
516                  * Make sure space for the drain appears.  We know we can do
517                  * this because max_hw_segments has been adjusted to be one
518                  * fewer than the device can handle.
519                  */
520                 rq->nr_phys_segments++;
521         }
522 }
523 EXPORT_SYMBOL(blk_mq_start_request);
524
525 /*
526  * When we reach here because queue is busy, REQ_ATOM_COMPLETE
527  * flag isn't set yet, so there may be race with timeout handler,
528  * but given rq->deadline is just set in .queue_rq() under
529  * this situation, the race won't be possible in reality because
530  * rq->timeout should be set as big enough to cover the window
531  * between blk_mq_start_request() called from .queue_rq() and
532  * clearing REQ_ATOM_STARTED here.
533  */
534 static void __blk_mq_requeue_request(struct request *rq)
535 {
536         struct request_queue *q = rq->q;
537
538         trace_block_rq_requeue(q, rq);
539         wbt_requeue(q->rq_wb, &rq->issue_stat);
540         blk_mq_sched_requeue_request(rq);
541
542         if (test_and_clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
543                 if (q->dma_drain_size && blk_rq_bytes(rq))
544                         rq->nr_phys_segments--;
545         }
546 }
547
548 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
549 {
550         __blk_mq_requeue_request(rq);
551
552         BUG_ON(blk_queued_rq(rq));
553         blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
554 }
555 EXPORT_SYMBOL(blk_mq_requeue_request);
556
557 static void blk_mq_requeue_work(struct work_struct *work)
558 {
559         struct request_queue *q =
560                 container_of(work, struct request_queue, requeue_work.work);
561         LIST_HEAD(rq_list);
562         struct request *rq, *next;
563         unsigned long flags;
564
565         spin_lock_irqsave(&q->requeue_lock, flags);
566         list_splice_init(&q->requeue_list, &rq_list);
567         spin_unlock_irqrestore(&q->requeue_lock, flags);
568
569         list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
570                 if (!(rq->rq_flags & RQF_SOFTBARRIER))
571                         continue;
572
573                 rq->rq_flags &= ~RQF_SOFTBARRIER;
574                 list_del_init(&rq->queuelist);
575                 blk_mq_sched_insert_request(rq, true, false, false, true);
576         }
577
578         while (!list_empty(&rq_list)) {
579                 rq = list_entry(rq_list.next, struct request, queuelist);
580                 list_del_init(&rq->queuelist);
581                 blk_mq_sched_insert_request(rq, false, false, false, true);
582         }
583
584         blk_mq_run_hw_queues(q, false);
585 }
586
587 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
588                                 bool kick_requeue_list)
589 {
590         struct request_queue *q = rq->q;
591         unsigned long flags;
592
593         /*
594          * We abuse this flag that is otherwise used by the I/O scheduler to
595          * request head insertation from the workqueue.
596          */
597         BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
598
599         spin_lock_irqsave(&q->requeue_lock, flags);
600         if (at_head) {
601                 rq->rq_flags |= RQF_SOFTBARRIER;
602                 list_add(&rq->queuelist, &q->requeue_list);
603         } else {
604                 list_add_tail(&rq->queuelist, &q->requeue_list);
605         }
606         spin_unlock_irqrestore(&q->requeue_lock, flags);
607
608         if (kick_requeue_list)
609                 blk_mq_kick_requeue_list(q);
610 }
611 EXPORT_SYMBOL(blk_mq_add_to_requeue_list);
612
613 void blk_mq_kick_requeue_list(struct request_queue *q)
614 {
615         kblockd_schedule_delayed_work(&q->requeue_work, 0);
616 }
617 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
618
619 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
620                                     unsigned long msecs)
621 {
622         kblockd_schedule_delayed_work(&q->requeue_work,
623                                       msecs_to_jiffies(msecs));
624 }
625 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
626
627 void blk_mq_abort_requeue_list(struct request_queue *q)
628 {
629         unsigned long flags;
630         LIST_HEAD(rq_list);
631
632         spin_lock_irqsave(&q->requeue_lock, flags);
633         list_splice_init(&q->requeue_list, &rq_list);
634         spin_unlock_irqrestore(&q->requeue_lock, flags);
635
636         while (!list_empty(&rq_list)) {
637                 struct request *rq;
638
639                 rq = list_first_entry(&rq_list, struct request, queuelist);
640                 list_del_init(&rq->queuelist);
641                 rq->errors = -EIO;
642                 blk_mq_end_request(rq, rq->errors);
643         }
644 }
645 EXPORT_SYMBOL(blk_mq_abort_requeue_list);
646
647 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
648 {
649         if (tag < tags->nr_tags) {
650                 prefetch(tags->rqs[tag]);
651                 return tags->rqs[tag];
652         }
653
654         return NULL;
655 }
656 EXPORT_SYMBOL(blk_mq_tag_to_rq);
657
658 struct blk_mq_timeout_data {
659         unsigned long next;
660         unsigned int next_set;
661 };
662
663 void blk_mq_rq_timed_out(struct request *req, bool reserved)
664 {
665         const struct blk_mq_ops *ops = req->q->mq_ops;
666         enum blk_eh_timer_return ret = BLK_EH_RESET_TIMER;
667
668         /*
669          * We know that complete is set at this point. If STARTED isn't set
670          * anymore, then the request isn't active and the "timeout" should
671          * just be ignored. This can happen due to the bitflag ordering.
672          * Timeout first checks if STARTED is set, and if it is, assumes
673          * the request is active. But if we race with completion, then
674          * both flags will get cleared. So check here again, and ignore
675          * a timeout event with a request that isn't active.
676          */
677         if (!test_bit(REQ_ATOM_STARTED, &req->atomic_flags))
678                 return;
679
680         if (ops->timeout)
681                 ret = ops->timeout(req, reserved);
682
683         switch (ret) {
684         case BLK_EH_HANDLED:
685                 __blk_mq_complete_request(req);
686                 break;
687         case BLK_EH_RESET_TIMER:
688                 blk_add_timer(req);
689                 blk_clear_rq_complete(req);
690                 break;
691         case BLK_EH_NOT_HANDLED:
692                 break;
693         default:
694                 printk(KERN_ERR "block: bad eh return: %d\n", ret);
695                 break;
696         }
697 }
698
699 static void blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
700                 struct request *rq, void *priv, bool reserved)
701 {
702         struct blk_mq_timeout_data *data = priv;
703
704         if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags))
705                 return;
706
707         /*
708          * The rq being checked may have been freed and reallocated
709          * out already here, we avoid this race by checking rq->deadline
710          * and REQ_ATOM_COMPLETE flag together:
711          *
712          * - if rq->deadline is observed as new value because of
713          *   reusing, the rq won't be timed out because of timing.
714          * - if rq->deadline is observed as previous value,
715          *   REQ_ATOM_COMPLETE flag won't be cleared in reuse path
716          *   because we put a barrier between setting rq->deadline
717          *   and clearing the flag in blk_mq_start_request(), so
718          *   this rq won't be timed out too.
719          */
720         if (time_after_eq(jiffies, rq->deadline)) {
721                 if (!blk_mark_rq_complete(rq))
722                         blk_mq_rq_timed_out(rq, reserved);
723         } else if (!data->next_set || time_after(data->next, rq->deadline)) {
724                 data->next = rq->deadline;
725                 data->next_set = 1;
726         }
727 }
728
729 static void blk_mq_timeout_work(struct work_struct *work)
730 {
731         struct request_queue *q =
732                 container_of(work, struct request_queue, timeout_work);
733         struct blk_mq_timeout_data data = {
734                 .next           = 0,
735                 .next_set       = 0,
736         };
737         int i;
738
739         /* A deadlock might occur if a request is stuck requiring a
740          * timeout at the same time a queue freeze is waiting
741          * completion, since the timeout code would not be able to
742          * acquire the queue reference here.
743          *
744          * That's why we don't use blk_queue_enter here; instead, we use
745          * percpu_ref_tryget directly, because we need to be able to
746          * obtain a reference even in the short window between the queue
747          * starting to freeze, by dropping the first reference in
748          * blk_freeze_queue_start, and the moment the last request is
749          * consumed, marked by the instant q_usage_counter reaches
750          * zero.
751          */
752         if (!percpu_ref_tryget(&q->q_usage_counter))
753                 return;
754
755         blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &data);
756
757         if (data.next_set) {
758                 data.next = blk_rq_timeout(round_jiffies_up(data.next));
759                 mod_timer(&q->timeout, data.next);
760         } else {
761                 struct blk_mq_hw_ctx *hctx;
762
763                 queue_for_each_hw_ctx(q, hctx, i) {
764                         /* the hctx may be unmapped, so check it here */
765                         if (blk_mq_hw_queue_mapped(hctx))
766                                 blk_mq_tag_idle(hctx);
767                 }
768         }
769         blk_queue_exit(q);
770 }
771
772 /*
773  * Reverse check our software queue for entries that we could potentially
774  * merge with. Currently includes a hand-wavy stop count of 8, to not spend
775  * too much time checking for merges.
776  */
777 static bool blk_mq_attempt_merge(struct request_queue *q,
778                                  struct blk_mq_ctx *ctx, struct bio *bio)
779 {
780         struct request *rq;
781         int checked = 8;
782
783         list_for_each_entry_reverse(rq, &ctx->rq_list, queuelist) {
784                 bool merged = false;
785
786                 if (!checked--)
787                         break;
788
789                 if (!blk_rq_merge_ok(rq, bio))
790                         continue;
791
792                 switch (blk_try_merge(rq, bio)) {
793                 case ELEVATOR_BACK_MERGE:
794                         if (blk_mq_sched_allow_merge(q, rq, bio))
795                                 merged = bio_attempt_back_merge(q, rq, bio);
796                         break;
797                 case ELEVATOR_FRONT_MERGE:
798                         if (blk_mq_sched_allow_merge(q, rq, bio))
799                                 merged = bio_attempt_front_merge(q, rq, bio);
800                         break;
801                 case ELEVATOR_DISCARD_MERGE:
802                         merged = bio_attempt_discard_merge(q, rq, bio);
803                         break;
804                 default:
805                         continue;
806                 }
807
808                 if (merged)
809                         ctx->rq_merged++;
810                 return merged;
811         }
812
813         return false;
814 }
815
816 struct flush_busy_ctx_data {
817         struct blk_mq_hw_ctx *hctx;
818         struct list_head *list;
819 };
820
821 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
822 {
823         struct flush_busy_ctx_data *flush_data = data;
824         struct blk_mq_hw_ctx *hctx = flush_data->hctx;
825         struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
826
827         sbitmap_clear_bit(sb, bitnr);
828         spin_lock(&ctx->lock);
829         list_splice_tail_init(&ctx->rq_list, flush_data->list);
830         spin_unlock(&ctx->lock);
831         return true;
832 }
833
834 /*
835  * Process software queues that have been marked busy, splicing them
836  * to the for-dispatch
837  */
838 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
839 {
840         struct flush_busy_ctx_data data = {
841                 .hctx = hctx,
842                 .list = list,
843         };
844
845         sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
846 }
847 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
848
849 static inline unsigned int queued_to_index(unsigned int queued)
850 {
851         if (!queued)
852                 return 0;
853
854         return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
855 }
856
857 bool blk_mq_get_driver_tag(struct request *rq, struct blk_mq_hw_ctx **hctx,
858                            bool wait)
859 {
860         struct blk_mq_alloc_data data = {
861                 .q = rq->q,
862                 .hctx = blk_mq_map_queue(rq->q, rq->mq_ctx->cpu),
863                 .flags = wait ? 0 : BLK_MQ_REQ_NOWAIT,
864         };
865
866         if (rq->tag != -1)
867                 goto done;
868
869         if (blk_mq_tag_is_reserved(data.hctx->sched_tags, rq->internal_tag))
870                 data.flags |= BLK_MQ_REQ_RESERVED;
871
872         rq->tag = blk_mq_get_tag(&data);
873         if (rq->tag >= 0) {
874                 if (blk_mq_tag_busy(data.hctx)) {
875                         rq->rq_flags |= RQF_MQ_INFLIGHT;
876                         atomic_inc(&data.hctx->nr_active);
877                 }
878                 data.hctx->tags->rqs[rq->tag] = rq;
879         }
880
881 done:
882         if (hctx)
883                 *hctx = data.hctx;
884         return rq->tag != -1;
885 }
886
887 static void __blk_mq_put_driver_tag(struct blk_mq_hw_ctx *hctx,
888                                     struct request *rq)
889 {
890         blk_mq_put_tag(hctx, hctx->tags, rq->mq_ctx, rq->tag);
891         rq->tag = -1;
892
893         if (rq->rq_flags & RQF_MQ_INFLIGHT) {
894                 rq->rq_flags &= ~RQF_MQ_INFLIGHT;
895                 atomic_dec(&hctx->nr_active);
896         }
897 }
898
899 static void blk_mq_put_driver_tag_hctx(struct blk_mq_hw_ctx *hctx,
900                                        struct request *rq)
901 {
902         if (rq->tag == -1 || rq->internal_tag == -1)
903                 return;
904
905         __blk_mq_put_driver_tag(hctx, rq);
906 }
907
908 static void blk_mq_put_driver_tag(struct request *rq)
909 {
910         struct blk_mq_hw_ctx *hctx;
911
912         if (rq->tag == -1 || rq->internal_tag == -1)
913                 return;
914
915         hctx = blk_mq_map_queue(rq->q, rq->mq_ctx->cpu);
916         __blk_mq_put_driver_tag(hctx, rq);
917 }
918
919 /*
920  * If we fail getting a driver tag because all the driver tags are already
921  * assigned and on the dispatch list, BUT the first entry does not have a
922  * tag, then we could deadlock. For that case, move entries with assigned
923  * driver tags to the front, leaving the set of tagged requests in the
924  * same order, and the untagged set in the same order.
925  */
926 static bool reorder_tags_to_front(struct list_head *list)
927 {
928         struct request *rq, *tmp, *first = NULL;
929
930         list_for_each_entry_safe_reverse(rq, tmp, list, queuelist) {
931                 if (rq == first)
932                         break;
933                 if (rq->tag != -1) {
934                         list_move(&rq->queuelist, list);
935                         if (!first)
936                                 first = rq;
937                 }
938         }
939
940         return first != NULL;
941 }
942
943 static int blk_mq_dispatch_wake(wait_queue_t *wait, unsigned mode, int flags,
944                                 void *key)
945 {
946         struct blk_mq_hw_ctx *hctx;
947
948         hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
949
950         list_del(&wait->task_list);
951         clear_bit_unlock(BLK_MQ_S_TAG_WAITING, &hctx->state);
952         blk_mq_run_hw_queue(hctx, true);
953         return 1;
954 }
955
956 static bool blk_mq_dispatch_wait_add(struct blk_mq_hw_ctx *hctx)
957 {
958         struct sbq_wait_state *ws;
959
960         /*
961          * The TAG_WAITING bit serves as a lock protecting hctx->dispatch_wait.
962          * The thread which wins the race to grab this bit adds the hardware
963          * queue to the wait queue.
964          */
965         if (test_bit(BLK_MQ_S_TAG_WAITING, &hctx->state) ||
966             test_and_set_bit_lock(BLK_MQ_S_TAG_WAITING, &hctx->state))
967                 return false;
968
969         init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
970         ws = bt_wait_ptr(&hctx->tags->bitmap_tags, hctx);
971
972         /*
973          * As soon as this returns, it's no longer safe to fiddle with
974          * hctx->dispatch_wait, since a completion can wake up the wait queue
975          * and unlock the bit.
976          */
977         add_wait_queue(&ws->wait, &hctx->dispatch_wait);
978         return true;
979 }
980
981 bool blk_mq_dispatch_rq_list(struct request_queue *q, struct list_head *list)
982 {
983         struct blk_mq_hw_ctx *hctx;
984         struct request *rq;
985         int errors, queued, ret = BLK_MQ_RQ_QUEUE_OK;
986
987         if (list_empty(list))
988                 return false;
989
990         /*
991          * Now process all the entries, sending them to the driver.
992          */
993         errors = queued = 0;
994         do {
995                 struct blk_mq_queue_data bd;
996
997                 rq = list_first_entry(list, struct request, queuelist);
998                 if (!blk_mq_get_driver_tag(rq, &hctx, false)) {
999                         if (!queued && reorder_tags_to_front(list))
1000                                 continue;
1001
1002                         /*
1003                          * The initial allocation attempt failed, so we need to
1004                          * rerun the hardware queue when a tag is freed.
1005                          */
1006                         if (!blk_mq_dispatch_wait_add(hctx))
1007                                 break;
1008
1009                         /*
1010                          * It's possible that a tag was freed in the window
1011                          * between the allocation failure and adding the
1012                          * hardware queue to the wait queue.
1013                          */
1014                         if (!blk_mq_get_driver_tag(rq, &hctx, false))
1015                                 break;
1016                 }
1017
1018                 list_del_init(&rq->queuelist);
1019
1020                 bd.rq = rq;
1021
1022                 /*
1023                  * Flag last if we have no more requests, or if we have more
1024                  * but can't assign a driver tag to it.
1025                  */
1026                 if (list_empty(list))
1027                         bd.last = true;
1028                 else {
1029                         struct request *nxt;
1030
1031                         nxt = list_first_entry(list, struct request, queuelist);
1032                         bd.last = !blk_mq_get_driver_tag(nxt, NULL, false);
1033                 }
1034
1035                 ret = q->mq_ops->queue_rq(hctx, &bd);
1036                 switch (ret) {
1037                 case BLK_MQ_RQ_QUEUE_OK:
1038                         queued++;
1039                         break;
1040                 case BLK_MQ_RQ_QUEUE_BUSY:
1041                         blk_mq_put_driver_tag_hctx(hctx, rq);
1042                         list_add(&rq->queuelist, list);
1043                         __blk_mq_requeue_request(rq);
1044                         break;
1045                 default:
1046                         pr_err("blk-mq: bad return on queue: %d\n", ret);
1047                 case BLK_MQ_RQ_QUEUE_ERROR:
1048                         errors++;
1049                         rq->errors = -EIO;
1050                         blk_mq_end_request(rq, rq->errors);
1051                         break;
1052                 }
1053
1054                 if (ret == BLK_MQ_RQ_QUEUE_BUSY)
1055                         break;
1056         } while (!list_empty(list));
1057
1058         hctx->dispatched[queued_to_index(queued)]++;
1059
1060         /*
1061          * Any items that need requeuing? Stuff them into hctx->dispatch,
1062          * that is where we will continue on next queue run.
1063          */
1064         if (!list_empty(list)) {
1065                 /*
1066                  * If we got a driver tag for the next request already,
1067                  * free it again.
1068                  */
1069                 rq = list_first_entry(list, struct request, queuelist);
1070                 blk_mq_put_driver_tag(rq);
1071
1072                 spin_lock(&hctx->lock);
1073                 list_splice_init(list, &hctx->dispatch);
1074                 spin_unlock(&hctx->lock);
1075
1076                 /*
1077                  * the queue is expected stopped with BLK_MQ_RQ_QUEUE_BUSY, but
1078                  * it's possible the queue is stopped and restarted again
1079                  * before this. Queue restart will dispatch requests. And since
1080                  * requests in rq_list aren't added into hctx->dispatch yet,
1081                  * the requests in rq_list might get lost.
1082                  *
1083                  * blk_mq_run_hw_queue() already checks the STOPPED bit
1084                  *
1085                  * If RESTART or TAG_WAITING is set, then let completion restart
1086                  * the queue instead of potentially looping here.
1087                  */
1088                 if (!blk_mq_sched_needs_restart(hctx) &&
1089                     !test_bit(BLK_MQ_S_TAG_WAITING, &hctx->state))
1090                         blk_mq_run_hw_queue(hctx, true);
1091         }
1092
1093         return (queued + errors) != 0;
1094 }
1095
1096 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1097 {
1098         int srcu_idx;
1099
1100         WARN_ON(!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask) &&
1101                 cpu_online(hctx->next_cpu));
1102
1103         if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
1104                 rcu_read_lock();
1105                 blk_mq_sched_dispatch_requests(hctx);
1106                 rcu_read_unlock();
1107         } else {
1108                 might_sleep();
1109
1110                 srcu_idx = srcu_read_lock(&hctx->queue_rq_srcu);
1111                 blk_mq_sched_dispatch_requests(hctx);
1112                 srcu_read_unlock(&hctx->queue_rq_srcu, srcu_idx);
1113         }
1114 }
1115
1116 /*
1117  * It'd be great if the workqueue API had a way to pass
1118  * in a mask and had some smarts for more clever placement.
1119  * For now we just round-robin here, switching for every
1120  * BLK_MQ_CPU_WORK_BATCH queued items.
1121  */
1122 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1123 {
1124         if (hctx->queue->nr_hw_queues == 1)
1125                 return WORK_CPU_UNBOUND;
1126
1127         if (--hctx->next_cpu_batch <= 0) {
1128                 int next_cpu;
1129
1130                 next_cpu = cpumask_next(hctx->next_cpu, hctx->cpumask);
1131                 if (next_cpu >= nr_cpu_ids)
1132                         next_cpu = cpumask_first(hctx->cpumask);
1133
1134                 hctx->next_cpu = next_cpu;
1135                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1136         }
1137
1138         return hctx->next_cpu;
1139 }
1140
1141 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1142                                         unsigned long msecs)
1143 {
1144         if (unlikely(blk_mq_hctx_stopped(hctx) ||
1145                      !blk_mq_hw_queue_mapped(hctx)))
1146                 return;
1147
1148         if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1149                 int cpu = get_cpu();
1150                 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1151                         __blk_mq_run_hw_queue(hctx);
1152                         put_cpu();
1153                         return;
1154                 }
1155
1156                 put_cpu();
1157         }
1158
1159         if (msecs == 0)
1160                 kblockd_schedule_work_on(blk_mq_hctx_next_cpu(hctx),
1161                                          &hctx->run_work);
1162         else
1163                 kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
1164                                                  &hctx->delayed_run_work,
1165                                                  msecs_to_jiffies(msecs));
1166 }
1167
1168 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1169 {
1170         __blk_mq_delay_run_hw_queue(hctx, true, msecs);
1171 }
1172 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1173
1174 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1175 {
1176         __blk_mq_delay_run_hw_queue(hctx, async, 0);
1177 }
1178
1179 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1180 {
1181         struct blk_mq_hw_ctx *hctx;
1182         int i;
1183
1184         queue_for_each_hw_ctx(q, hctx, i) {
1185                 if (!blk_mq_hctx_has_pending(hctx) ||
1186                     blk_mq_hctx_stopped(hctx))
1187                         continue;
1188
1189                 blk_mq_run_hw_queue(hctx, async);
1190         }
1191 }
1192 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1193
1194 /**
1195  * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1196  * @q: request queue.
1197  *
1198  * The caller is responsible for serializing this function against
1199  * blk_mq_{start,stop}_hw_queue().
1200  */
1201 bool blk_mq_queue_stopped(struct request_queue *q)
1202 {
1203         struct blk_mq_hw_ctx *hctx;
1204         int i;
1205
1206         queue_for_each_hw_ctx(q, hctx, i)
1207                 if (blk_mq_hctx_stopped(hctx))
1208                         return true;
1209
1210         return false;
1211 }
1212 EXPORT_SYMBOL(blk_mq_queue_stopped);
1213
1214 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1215 {
1216         cancel_work(&hctx->run_work);
1217         cancel_delayed_work(&hctx->delay_work);
1218         set_bit(BLK_MQ_S_STOPPED, &hctx->state);
1219 }
1220 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
1221
1222 void blk_mq_stop_hw_queues(struct request_queue *q)
1223 {
1224         struct blk_mq_hw_ctx *hctx;
1225         int i;
1226
1227         queue_for_each_hw_ctx(q, hctx, i)
1228                 blk_mq_stop_hw_queue(hctx);
1229 }
1230 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1231
1232 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1233 {
1234         clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1235
1236         blk_mq_run_hw_queue(hctx, false);
1237 }
1238 EXPORT_SYMBOL(blk_mq_start_hw_queue);
1239
1240 void blk_mq_start_hw_queues(struct request_queue *q)
1241 {
1242         struct blk_mq_hw_ctx *hctx;
1243         int i;
1244
1245         queue_for_each_hw_ctx(q, hctx, i)
1246                 blk_mq_start_hw_queue(hctx);
1247 }
1248 EXPORT_SYMBOL(blk_mq_start_hw_queues);
1249
1250 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1251 {
1252         if (!blk_mq_hctx_stopped(hctx))
1253                 return;
1254
1255         clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1256         blk_mq_run_hw_queue(hctx, async);
1257 }
1258 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1259
1260 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
1261 {
1262         struct blk_mq_hw_ctx *hctx;
1263         int i;
1264
1265         queue_for_each_hw_ctx(q, hctx, i)
1266                 blk_mq_start_stopped_hw_queue(hctx, async);
1267 }
1268 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1269
1270 static void blk_mq_run_work_fn(struct work_struct *work)
1271 {
1272         struct blk_mq_hw_ctx *hctx;
1273
1274         hctx = container_of(work, struct blk_mq_hw_ctx, run_work);
1275
1276         __blk_mq_run_hw_queue(hctx);
1277 }
1278
1279 static void blk_mq_delayed_run_work_fn(struct work_struct *work)
1280 {
1281         struct blk_mq_hw_ctx *hctx;
1282
1283         hctx = container_of(work, struct blk_mq_hw_ctx, delayed_run_work.work);
1284
1285         __blk_mq_run_hw_queue(hctx);
1286 }
1287
1288 static void blk_mq_delay_work_fn(struct work_struct *work)
1289 {
1290         struct blk_mq_hw_ctx *hctx;
1291
1292         hctx = container_of(work, struct blk_mq_hw_ctx, delay_work.work);
1293
1294         if (test_and_clear_bit(BLK_MQ_S_STOPPED, &hctx->state))
1295                 __blk_mq_run_hw_queue(hctx);
1296 }
1297
1298 void blk_mq_delay_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1299 {
1300         if (unlikely(!blk_mq_hw_queue_mapped(hctx)))
1301                 return;
1302
1303         blk_mq_stop_hw_queue(hctx);
1304         kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
1305                         &hctx->delay_work, msecs_to_jiffies(msecs));
1306 }
1307 EXPORT_SYMBOL(blk_mq_delay_queue);
1308
1309 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
1310                                             struct request *rq,
1311                                             bool at_head)
1312 {
1313         struct blk_mq_ctx *ctx = rq->mq_ctx;
1314
1315         trace_block_rq_insert(hctx->queue, rq);
1316
1317         if (at_head)
1318                 list_add(&rq->queuelist, &ctx->rq_list);
1319         else
1320                 list_add_tail(&rq->queuelist, &ctx->rq_list);
1321 }
1322
1323 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1324                              bool at_head)
1325 {
1326         struct blk_mq_ctx *ctx = rq->mq_ctx;
1327
1328         __blk_mq_insert_req_list(hctx, rq, at_head);
1329         blk_mq_hctx_mark_pending(hctx, ctx);
1330 }
1331
1332 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1333                             struct list_head *list)
1334
1335 {
1336         /*
1337          * preemption doesn't flush plug list, so it's possible ctx->cpu is
1338          * offline now
1339          */
1340         spin_lock(&ctx->lock);
1341         while (!list_empty(list)) {
1342                 struct request *rq;
1343
1344                 rq = list_first_entry(list, struct request, queuelist);
1345                 BUG_ON(rq->mq_ctx != ctx);
1346                 list_del_init(&rq->queuelist);
1347                 __blk_mq_insert_req_list(hctx, rq, false);
1348         }
1349         blk_mq_hctx_mark_pending(hctx, ctx);
1350         spin_unlock(&ctx->lock);
1351 }
1352
1353 static int plug_ctx_cmp(void *priv, struct list_head *a, struct list_head *b)
1354 {
1355         struct request *rqa = container_of(a, struct request, queuelist);
1356         struct request *rqb = container_of(b, struct request, queuelist);
1357
1358         return !(rqa->mq_ctx < rqb->mq_ctx ||
1359                  (rqa->mq_ctx == rqb->mq_ctx &&
1360                   blk_rq_pos(rqa) < blk_rq_pos(rqb)));
1361 }
1362
1363 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1364 {
1365         struct blk_mq_ctx *this_ctx;
1366         struct request_queue *this_q;
1367         struct request *rq;
1368         LIST_HEAD(list);
1369         LIST_HEAD(ctx_list);
1370         unsigned int depth;
1371
1372         list_splice_init(&plug->mq_list, &list);
1373
1374         list_sort(NULL, &list, plug_ctx_cmp);
1375
1376         this_q = NULL;
1377         this_ctx = NULL;
1378         depth = 0;
1379
1380         while (!list_empty(&list)) {
1381                 rq = list_entry_rq(list.next);
1382                 list_del_init(&rq->queuelist);
1383                 BUG_ON(!rq->q);
1384                 if (rq->mq_ctx != this_ctx) {
1385                         if (this_ctx) {
1386                                 trace_block_unplug(this_q, depth, from_schedule);
1387                                 blk_mq_sched_insert_requests(this_q, this_ctx,
1388                                                                 &ctx_list,
1389                                                                 from_schedule);
1390                         }
1391
1392                         this_ctx = rq->mq_ctx;
1393                         this_q = rq->q;
1394                         depth = 0;
1395                 }
1396
1397                 depth++;
1398                 list_add_tail(&rq->queuelist, &ctx_list);
1399         }
1400
1401         /*
1402          * If 'this_ctx' is set, we know we have entries to complete
1403          * on 'ctx_list'. Do those.
1404          */
1405         if (this_ctx) {
1406                 trace_block_unplug(this_q, depth, from_schedule);
1407                 blk_mq_sched_insert_requests(this_q, this_ctx, &ctx_list,
1408                                                 from_schedule);
1409         }
1410 }
1411
1412 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio)
1413 {
1414         init_request_from_bio(rq, bio);
1415
1416         blk_account_io_start(rq, true);
1417 }
1418
1419 static inline bool hctx_allow_merges(struct blk_mq_hw_ctx *hctx)
1420 {
1421         return (hctx->flags & BLK_MQ_F_SHOULD_MERGE) &&
1422                 !blk_queue_nomerges(hctx->queue);
1423 }
1424
1425 static inline bool blk_mq_merge_queue_io(struct blk_mq_hw_ctx *hctx,
1426                                          struct blk_mq_ctx *ctx,
1427                                          struct request *rq, struct bio *bio)
1428 {
1429         if (!hctx_allow_merges(hctx) || !bio_mergeable(bio)) {
1430                 blk_mq_bio_to_request(rq, bio);
1431                 spin_lock(&ctx->lock);
1432 insert_rq:
1433                 __blk_mq_insert_request(hctx, rq, false);
1434                 spin_unlock(&ctx->lock);
1435                 return false;
1436         } else {
1437                 struct request_queue *q = hctx->queue;
1438
1439                 spin_lock(&ctx->lock);
1440                 if (!blk_mq_attempt_merge(q, ctx, bio)) {
1441                         blk_mq_bio_to_request(rq, bio);
1442                         goto insert_rq;
1443                 }
1444
1445                 spin_unlock(&ctx->lock);
1446                 __blk_mq_finish_request(hctx, ctx, rq);
1447                 return true;
1448         }
1449 }
1450
1451 static blk_qc_t request_to_qc_t(struct blk_mq_hw_ctx *hctx, struct request *rq)
1452 {
1453         if (rq->tag != -1)
1454                 return blk_tag_to_qc_t(rq->tag, hctx->queue_num, false);
1455
1456         return blk_tag_to_qc_t(rq->internal_tag, hctx->queue_num, true);
1457 }
1458
1459 static void __blk_mq_try_issue_directly(struct request *rq, blk_qc_t *cookie,
1460                                       bool may_sleep)
1461 {
1462         struct request_queue *q = rq->q;
1463         struct blk_mq_queue_data bd = {
1464                 .rq = rq,
1465                 .last = true,
1466         };
1467         struct blk_mq_hw_ctx *hctx;
1468         blk_qc_t new_cookie;
1469         int ret;
1470
1471         if (q->elevator)
1472                 goto insert;
1473
1474         if (!blk_mq_get_driver_tag(rq, &hctx, false))
1475                 goto insert;
1476
1477         new_cookie = request_to_qc_t(hctx, rq);
1478
1479         /*
1480          * For OK queue, we are done. For error, kill it. Any other
1481          * error (busy), just add it to our list as we previously
1482          * would have done
1483          */
1484         ret = q->mq_ops->queue_rq(hctx, &bd);
1485         if (ret == BLK_MQ_RQ_QUEUE_OK) {
1486                 *cookie = new_cookie;
1487                 return;
1488         }
1489
1490         if (ret == BLK_MQ_RQ_QUEUE_ERROR) {
1491                 *cookie = BLK_QC_T_NONE;
1492                 rq->errors = -EIO;
1493                 blk_mq_end_request(rq, rq->errors);
1494                 return;
1495         }
1496
1497         __blk_mq_requeue_request(rq);
1498 insert:
1499         blk_mq_sched_insert_request(rq, false, true, false, may_sleep);
1500 }
1501
1502 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1503                 struct request *rq, blk_qc_t *cookie)
1504 {
1505         if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
1506                 rcu_read_lock();
1507                 __blk_mq_try_issue_directly(rq, cookie, false);
1508                 rcu_read_unlock();
1509         } else {
1510                 unsigned int srcu_idx;
1511
1512                 might_sleep();
1513
1514                 srcu_idx = srcu_read_lock(&hctx->queue_rq_srcu);
1515                 __blk_mq_try_issue_directly(rq, cookie, true);
1516                 srcu_read_unlock(&hctx->queue_rq_srcu, srcu_idx);
1517         }
1518 }
1519
1520 static blk_qc_t blk_mq_make_request(struct request_queue *q, struct bio *bio)
1521 {
1522         const int is_sync = op_is_sync(bio->bi_opf);
1523         const int is_flush_fua = op_is_flush(bio->bi_opf);
1524         struct blk_mq_alloc_data data = { .flags = 0 };
1525         struct request *rq;
1526         unsigned int request_count = 0;
1527         struct blk_plug *plug;
1528         struct request *same_queue_rq = NULL;
1529         blk_qc_t cookie;
1530         unsigned int wb_acct;
1531
1532         blk_queue_bounce(q, &bio);
1533
1534         if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1535                 bio_io_error(bio);
1536                 return BLK_QC_T_NONE;
1537         }
1538
1539         blk_queue_split(q, &bio, q->bio_split);
1540
1541         if (!is_flush_fua && !blk_queue_nomerges(q) &&
1542             blk_attempt_plug_merge(q, bio, &request_count, &same_queue_rq))
1543                 return BLK_QC_T_NONE;
1544
1545         if (blk_mq_sched_bio_merge(q, bio))
1546                 return BLK_QC_T_NONE;
1547
1548         wb_acct = wbt_wait(q->rq_wb, bio, NULL);
1549
1550         trace_block_getrq(q, bio, bio->bi_opf);
1551
1552         rq = blk_mq_sched_get_request(q, bio, bio->bi_opf, &data);
1553         if (unlikely(!rq)) {
1554                 __wbt_done(q->rq_wb, wb_acct);
1555                 return BLK_QC_T_NONE;
1556         }
1557
1558         wbt_track(&rq->issue_stat, wb_acct);
1559
1560         cookie = request_to_qc_t(data.hctx, rq);
1561
1562         plug = current->plug;
1563         if (unlikely(is_flush_fua)) {
1564                 blk_mq_bio_to_request(rq, bio);
1565                 if (q->elevator) {
1566                         blk_mq_sched_insert_request(rq, false, true, true,
1567                                         true);
1568                 } else {
1569                         blk_insert_flush(rq);
1570                         blk_mq_run_hw_queue(data.hctx, true);
1571                 }
1572         } else if (plug && q->nr_hw_queues == 1) {
1573                 struct request *last = NULL;
1574
1575                 blk_mq_bio_to_request(rq, bio);
1576
1577                 /*
1578                  * @request_count may become stale because of schedule
1579                  * out, so check the list again.
1580                  */
1581                 if (list_empty(&plug->mq_list))
1582                         request_count = 0;
1583                 else if (blk_queue_nomerges(q))
1584                         request_count = blk_plug_queued_count(q);
1585
1586                 if (!request_count)
1587                         trace_block_plug(q);
1588                 else
1589                         last = list_entry_rq(plug->mq_list.prev);
1590
1591                 if (request_count >= BLK_MAX_REQUEST_COUNT || (last &&
1592                     blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1593                         blk_flush_plug_list(plug, false);
1594                         trace_block_plug(q);
1595                 }
1596
1597                 list_add_tail(&rq->queuelist, &plug->mq_list);
1598         } else if (plug && !blk_queue_nomerges(q)) {
1599                 blk_mq_bio_to_request(rq, bio);
1600
1601                 /*
1602                  * We do limited plugging. If the bio can be merged, do that.
1603                  * Otherwise the existing request in the plug list will be
1604                  * issued. So the plug list will have one request at most
1605                  * The plug list might get flushed before this. If that happens,
1606                  * the plug list is empty, and same_queue_rq is invalid.
1607                  */
1608                 if (list_empty(&plug->mq_list))
1609                         same_queue_rq = NULL;
1610                 if (same_queue_rq)
1611                         list_del_init(&same_queue_rq->queuelist);
1612                 list_add_tail(&rq->queuelist, &plug->mq_list);
1613
1614                 blk_mq_put_ctx(data.ctx);
1615
1616                 if (same_queue_rq)
1617                         blk_mq_try_issue_directly(data.hctx, same_queue_rq,
1618                                         &cookie);
1619
1620                 return cookie;
1621         } else if (q->nr_hw_queues > 1 && is_sync) {
1622                 blk_mq_put_ctx(data.ctx);
1623                 blk_mq_bio_to_request(rq, bio);
1624                 blk_mq_try_issue_directly(data.hctx, rq, &cookie);
1625                 return cookie;
1626         } else if (q->elevator) {
1627                 blk_mq_bio_to_request(rq, bio);
1628                 blk_mq_sched_insert_request(rq, false, true, true, true);
1629         } else if (!blk_mq_merge_queue_io(data.hctx, data.ctx, rq, bio))
1630                 blk_mq_run_hw_queue(data.hctx, true);
1631
1632         blk_mq_put_ctx(data.ctx);
1633         return cookie;
1634 }
1635
1636 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
1637                      unsigned int hctx_idx)
1638 {
1639         struct page *page;
1640
1641         if (tags->rqs && set->ops->exit_request) {
1642                 int i;
1643
1644                 for (i = 0; i < tags->nr_tags; i++) {
1645                         struct request *rq = tags->static_rqs[i];
1646
1647                         if (!rq)
1648                                 continue;
1649                         set->ops->exit_request(set->driver_data, rq,
1650                                                 hctx_idx, i);
1651                         tags->static_rqs[i] = NULL;
1652                 }
1653         }
1654
1655         while (!list_empty(&tags->page_list)) {
1656                 page = list_first_entry(&tags->page_list, struct page, lru);
1657                 list_del_init(&page->lru);
1658                 /*
1659                  * Remove kmemleak object previously allocated in
1660                  * blk_mq_init_rq_map().
1661                  */
1662                 kmemleak_free(page_address(page));
1663                 __free_pages(page, page->private);
1664         }
1665 }
1666
1667 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
1668 {
1669         kfree(tags->rqs);
1670         tags->rqs = NULL;
1671         kfree(tags->static_rqs);
1672         tags->static_rqs = NULL;
1673
1674         blk_mq_free_tags(tags);
1675 }
1676
1677 struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
1678                                         unsigned int hctx_idx,
1679                                         unsigned int nr_tags,
1680                                         unsigned int reserved_tags)
1681 {
1682         struct blk_mq_tags *tags;
1683         int node;
1684
1685         node = blk_mq_hw_queue_to_node(set->mq_map, hctx_idx);
1686         if (node == NUMA_NO_NODE)
1687                 node = set->numa_node;
1688
1689         tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
1690                                 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
1691         if (!tags)
1692                 return NULL;
1693
1694         tags->rqs = kzalloc_node(nr_tags * sizeof(struct request *),
1695                                  GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
1696                                  node);
1697         if (!tags->rqs) {
1698                 blk_mq_free_tags(tags);
1699                 return NULL;
1700         }
1701
1702         tags->static_rqs = kzalloc_node(nr_tags * sizeof(struct request *),
1703                                  GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
1704                                  node);
1705         if (!tags->static_rqs) {
1706                 kfree(tags->rqs);
1707                 blk_mq_free_tags(tags);
1708                 return NULL;
1709         }
1710
1711         return tags;
1712 }
1713
1714 static size_t order_to_size(unsigned int order)
1715 {
1716         return (size_t)PAGE_SIZE << order;
1717 }
1718
1719 int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
1720                      unsigned int hctx_idx, unsigned int depth)
1721 {
1722         unsigned int i, j, entries_per_page, max_order = 4;
1723         size_t rq_size, left;
1724         int node;
1725
1726         node = blk_mq_hw_queue_to_node(set->mq_map, hctx_idx);
1727         if (node == NUMA_NO_NODE)
1728                 node = set->numa_node;
1729
1730         INIT_LIST_HEAD(&tags->page_list);
1731
1732         /*
1733          * rq_size is the size of the request plus driver payload, rounded
1734          * to the cacheline size
1735          */
1736         rq_size = round_up(sizeof(struct request) + set->cmd_size,
1737                                 cache_line_size());
1738         left = rq_size * depth;
1739
1740         for (i = 0; i < depth; ) {
1741                 int this_order = max_order;
1742                 struct page *page;
1743                 int to_do;
1744                 void *p;
1745
1746                 while (this_order && left < order_to_size(this_order - 1))
1747                         this_order--;
1748
1749                 do {
1750                         page = alloc_pages_node(node,
1751                                 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
1752                                 this_order);
1753                         if (page)
1754                                 break;
1755                         if (!this_order--)
1756                                 break;
1757                         if (order_to_size(this_order) < rq_size)
1758                                 break;
1759                 } while (1);
1760
1761                 if (!page)
1762                         goto fail;
1763
1764                 page->private = this_order;
1765                 list_add_tail(&page->lru, &tags->page_list);
1766
1767                 p = page_address(page);
1768                 /*
1769                  * Allow kmemleak to scan these pages as they contain pointers
1770                  * to additional allocations like via ops->init_request().
1771                  */
1772                 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
1773                 entries_per_page = order_to_size(this_order) / rq_size;
1774                 to_do = min(entries_per_page, depth - i);
1775                 left -= to_do * rq_size;
1776                 for (j = 0; j < to_do; j++) {
1777                         struct request *rq = p;
1778
1779                         tags->static_rqs[i] = rq;
1780                         if (set->ops->init_request) {
1781                                 if (set->ops->init_request(set->driver_data,
1782                                                 rq, hctx_idx, i,
1783                                                 node)) {
1784                                         tags->static_rqs[i] = NULL;
1785                                         goto fail;
1786                                 }
1787                         }
1788
1789                         p += rq_size;
1790                         i++;
1791                 }
1792         }
1793         return 0;
1794
1795 fail:
1796         blk_mq_free_rqs(set, tags, hctx_idx);
1797         return -ENOMEM;
1798 }
1799
1800 /*
1801  * 'cpu' is going away. splice any existing rq_list entries from this
1802  * software queue to the hw queue dispatch list, and ensure that it
1803  * gets run.
1804  */
1805 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
1806 {
1807         struct blk_mq_hw_ctx *hctx;
1808         struct blk_mq_ctx *ctx;
1809         LIST_HEAD(tmp);
1810
1811         hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
1812         ctx = __blk_mq_get_ctx(hctx->queue, cpu);
1813
1814         spin_lock(&ctx->lock);
1815         if (!list_empty(&ctx->rq_list)) {
1816                 list_splice_init(&ctx->rq_list, &tmp);
1817                 blk_mq_hctx_clear_pending(hctx, ctx);
1818         }
1819         spin_unlock(&ctx->lock);
1820
1821         if (list_empty(&tmp))
1822                 return 0;
1823
1824         spin_lock(&hctx->lock);
1825         list_splice_tail_init(&tmp, &hctx->dispatch);
1826         spin_unlock(&hctx->lock);
1827
1828         blk_mq_run_hw_queue(hctx, true);
1829         return 0;
1830 }
1831
1832 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
1833 {
1834         cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
1835                                             &hctx->cpuhp_dead);
1836 }
1837
1838 /* hctx->ctxs will be freed in queue's release handler */
1839 static void blk_mq_exit_hctx(struct request_queue *q,
1840                 struct blk_mq_tag_set *set,
1841                 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
1842 {
1843         unsigned flush_start_tag = set->queue_depth;
1844
1845         blk_mq_tag_idle(hctx);
1846
1847         if (set->ops->exit_request)
1848                 set->ops->exit_request(set->driver_data,
1849                                        hctx->fq->flush_rq, hctx_idx,
1850                                        flush_start_tag + hctx_idx);
1851
1852         blk_mq_sched_exit_hctx(q, hctx, hctx_idx);
1853
1854         if (set->ops->exit_hctx)
1855                 set->ops->exit_hctx(hctx, hctx_idx);
1856
1857         if (hctx->flags & BLK_MQ_F_BLOCKING)
1858                 cleanup_srcu_struct(&hctx->queue_rq_srcu);
1859
1860         blk_mq_remove_cpuhp(hctx);
1861         blk_free_flush_queue(hctx->fq);
1862         sbitmap_free(&hctx->ctx_map);
1863 }
1864
1865 static void blk_mq_exit_hw_queues(struct request_queue *q,
1866                 struct blk_mq_tag_set *set, int nr_queue)
1867 {
1868         struct blk_mq_hw_ctx *hctx;
1869         unsigned int i;
1870
1871         queue_for_each_hw_ctx(q, hctx, i) {
1872                 if (i == nr_queue)
1873                         break;
1874                 blk_mq_exit_hctx(q, set, hctx, i);
1875         }
1876 }
1877
1878 static int blk_mq_init_hctx(struct request_queue *q,
1879                 struct blk_mq_tag_set *set,
1880                 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
1881 {
1882         int node;
1883         unsigned flush_start_tag = set->queue_depth;
1884
1885         node = hctx->numa_node;
1886         if (node == NUMA_NO_NODE)
1887                 node = hctx->numa_node = set->numa_node;
1888
1889         INIT_WORK(&hctx->run_work, blk_mq_run_work_fn);
1890         INIT_DELAYED_WORK(&hctx->delayed_run_work, blk_mq_delayed_run_work_fn);
1891         INIT_DELAYED_WORK(&hctx->delay_work, blk_mq_delay_work_fn);
1892         spin_lock_init(&hctx->lock);
1893         INIT_LIST_HEAD(&hctx->dispatch);
1894         hctx->queue = q;
1895         hctx->queue_num = hctx_idx;
1896         hctx->flags = set->flags & ~BLK_MQ_F_TAG_SHARED;
1897
1898         cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
1899
1900         hctx->tags = set->tags[hctx_idx];
1901
1902         /*
1903          * Allocate space for all possible cpus to avoid allocation at
1904          * runtime
1905          */
1906         hctx->ctxs = kmalloc_node(nr_cpu_ids * sizeof(void *),
1907                                         GFP_KERNEL, node);
1908         if (!hctx->ctxs)
1909                 goto unregister_cpu_notifier;
1910
1911         if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8), GFP_KERNEL,
1912                               node))
1913                 goto free_ctxs;
1914
1915         hctx->nr_ctx = 0;
1916
1917         if (set->ops->init_hctx &&
1918             set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
1919                 goto free_bitmap;
1920
1921         if (blk_mq_sched_init_hctx(q, hctx, hctx_idx))
1922                 goto exit_hctx;
1923
1924         hctx->fq = blk_alloc_flush_queue(q, hctx->numa_node, set->cmd_size);
1925         if (!hctx->fq)
1926                 goto sched_exit_hctx;
1927
1928         if (set->ops->init_request &&
1929             set->ops->init_request(set->driver_data,
1930                                    hctx->fq->flush_rq, hctx_idx,
1931                                    flush_start_tag + hctx_idx, node))
1932                 goto free_fq;
1933
1934         if (hctx->flags & BLK_MQ_F_BLOCKING)
1935                 init_srcu_struct(&hctx->queue_rq_srcu);
1936
1937         return 0;
1938
1939  free_fq:
1940         kfree(hctx->fq);
1941  sched_exit_hctx:
1942         blk_mq_sched_exit_hctx(q, hctx, hctx_idx);
1943  exit_hctx:
1944         if (set->ops->exit_hctx)
1945                 set->ops->exit_hctx(hctx, hctx_idx);
1946  free_bitmap:
1947         sbitmap_free(&hctx->ctx_map);
1948  free_ctxs:
1949         kfree(hctx->ctxs);
1950  unregister_cpu_notifier:
1951         blk_mq_remove_cpuhp(hctx);
1952         return -1;
1953 }
1954
1955 static void blk_mq_init_cpu_queues(struct request_queue *q,
1956                                    unsigned int nr_hw_queues)
1957 {
1958         unsigned int i;
1959
1960         for_each_possible_cpu(i) {
1961                 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
1962                 struct blk_mq_hw_ctx *hctx;
1963
1964                 __ctx->cpu = i;
1965                 spin_lock_init(&__ctx->lock);
1966                 INIT_LIST_HEAD(&__ctx->rq_list);
1967                 __ctx->queue = q;
1968
1969                 /* If the cpu isn't online, the cpu is mapped to first hctx */
1970                 if (!cpu_online(i))
1971                         continue;
1972
1973                 hctx = blk_mq_map_queue(q, i);
1974
1975                 /*
1976                  * Set local node, IFF we have more than one hw queue. If
1977                  * not, we remain on the home node of the device
1978                  */
1979                 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
1980                         hctx->numa_node = local_memory_node(cpu_to_node(i));
1981         }
1982 }
1983
1984 static bool __blk_mq_alloc_rq_map(struct blk_mq_tag_set *set, int hctx_idx)
1985 {
1986         int ret = 0;
1987
1988         set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
1989                                         set->queue_depth, set->reserved_tags);
1990         if (!set->tags[hctx_idx])
1991                 return false;
1992
1993         ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
1994                                 set->queue_depth);
1995         if (!ret)
1996                 return true;
1997
1998         blk_mq_free_rq_map(set->tags[hctx_idx]);
1999         set->tags[hctx_idx] = NULL;
2000         return false;
2001 }
2002
2003 static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2004                                          unsigned int hctx_idx)
2005 {
2006         if (set->tags[hctx_idx]) {
2007                 blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
2008                 blk_mq_free_rq_map(set->tags[hctx_idx]);
2009                 set->tags[hctx_idx] = NULL;
2010         }
2011 }
2012
2013 static void blk_mq_map_swqueue(struct request_queue *q,
2014                                const struct cpumask *online_mask)
2015 {
2016         unsigned int i, hctx_idx;
2017         struct blk_mq_hw_ctx *hctx;
2018         struct blk_mq_ctx *ctx;
2019         struct blk_mq_tag_set *set = q->tag_set;
2020
2021         /*
2022          * Avoid others reading imcomplete hctx->cpumask through sysfs
2023          */
2024         mutex_lock(&q->sysfs_lock);
2025
2026         queue_for_each_hw_ctx(q, hctx, i) {
2027                 cpumask_clear(hctx->cpumask);
2028                 hctx->nr_ctx = 0;
2029         }
2030
2031         /*
2032          * Map software to hardware queues
2033          */
2034         for_each_possible_cpu(i) {
2035                 /* If the cpu isn't online, the cpu is mapped to first hctx */
2036                 if (!cpumask_test_cpu(i, online_mask))
2037                         continue;
2038
2039                 hctx_idx = q->mq_map[i];
2040                 /* unmapped hw queue can be remapped after CPU topo changed */
2041                 if (!set->tags[hctx_idx] &&
2042                     !__blk_mq_alloc_rq_map(set, hctx_idx)) {
2043                         /*
2044                          * If tags initialization fail for some hctx,
2045                          * that hctx won't be brought online.  In this
2046                          * case, remap the current ctx to hctx[0] which
2047                          * is guaranteed to always have tags allocated
2048                          */
2049                         q->mq_map[i] = 0;
2050                 }
2051
2052                 ctx = per_cpu_ptr(q->queue_ctx, i);
2053                 hctx = blk_mq_map_queue(q, i);
2054
2055                 cpumask_set_cpu(i, hctx->cpumask);
2056                 ctx->index_hw = hctx->nr_ctx;
2057                 hctx->ctxs[hctx->nr_ctx++] = ctx;
2058         }
2059
2060         mutex_unlock(&q->sysfs_lock);
2061
2062         queue_for_each_hw_ctx(q, hctx, i) {
2063                 /*
2064                  * If no software queues are mapped to this hardware queue,
2065                  * disable it and free the request entries.
2066                  */
2067                 if (!hctx->nr_ctx) {
2068                         /* Never unmap queue 0.  We need it as a
2069                          * fallback in case of a new remap fails
2070                          * allocation
2071                          */
2072                         if (i && set->tags[i])
2073                                 blk_mq_free_map_and_requests(set, i);
2074
2075                         hctx->tags = NULL;
2076                         continue;
2077                 }
2078
2079                 hctx->tags = set->tags[i];
2080                 WARN_ON(!hctx->tags);
2081
2082                 /*
2083                  * Set the map size to the number of mapped software queues.
2084                  * This is more accurate and more efficient than looping
2085                  * over all possibly mapped software queues.
2086                  */
2087                 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
2088
2089                 /*
2090                  * Initialize batch roundrobin counts
2091                  */
2092                 hctx->next_cpu = cpumask_first(hctx->cpumask);
2093                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2094         }
2095 }
2096
2097 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
2098 {
2099         struct blk_mq_hw_ctx *hctx;
2100         int i;
2101
2102         queue_for_each_hw_ctx(q, hctx, i) {
2103                 if (shared)
2104                         hctx->flags |= BLK_MQ_F_TAG_SHARED;
2105                 else
2106                         hctx->flags &= ~BLK_MQ_F_TAG_SHARED;
2107         }
2108 }
2109
2110 static void blk_mq_update_tag_set_depth(struct blk_mq_tag_set *set, bool shared)
2111 {
2112         struct request_queue *q;
2113
2114         lockdep_assert_held(&set->tag_list_lock);
2115
2116         list_for_each_entry(q, &set->tag_list, tag_set_list) {
2117                 blk_mq_freeze_queue(q);
2118                 queue_set_hctx_shared(q, shared);
2119                 blk_mq_unfreeze_queue(q);
2120         }
2121 }
2122
2123 static void blk_mq_del_queue_tag_set(struct request_queue *q)
2124 {
2125         struct blk_mq_tag_set *set = q->tag_set;
2126
2127         mutex_lock(&set->tag_list_lock);
2128         list_del_rcu(&q->tag_set_list);
2129         INIT_LIST_HEAD(&q->tag_set_list);
2130         if (list_is_singular(&set->tag_list)) {
2131                 /* just transitioned to unshared */
2132                 set->flags &= ~BLK_MQ_F_TAG_SHARED;
2133                 /* update existing queue */
2134                 blk_mq_update_tag_set_depth(set, false);
2135         }
2136         mutex_unlock(&set->tag_list_lock);
2137
2138         synchronize_rcu();
2139 }
2140
2141 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
2142                                      struct request_queue *q)
2143 {
2144         q->tag_set = set;
2145
2146         mutex_lock(&set->tag_list_lock);
2147
2148         /* Check to see if we're transitioning to shared (from 1 to 2 queues). */
2149         if (!list_empty(&set->tag_list) && !(set->flags & BLK_MQ_F_TAG_SHARED)) {
2150                 set->flags |= BLK_MQ_F_TAG_SHARED;
2151                 /* update existing queue */
2152                 blk_mq_update_tag_set_depth(set, true);
2153         }
2154         if (set->flags & BLK_MQ_F_TAG_SHARED)
2155                 queue_set_hctx_shared(q, true);
2156         list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
2157
2158         mutex_unlock(&set->tag_list_lock);
2159 }
2160
2161 /*
2162  * It is the actual release handler for mq, but we do it from
2163  * request queue's release handler for avoiding use-after-free
2164  * and headache because q->mq_kobj shouldn't have been introduced,
2165  * but we can't group ctx/kctx kobj without it.
2166  */
2167 void blk_mq_release(struct request_queue *q)
2168 {
2169         struct blk_mq_hw_ctx *hctx;
2170         unsigned int i;
2171
2172         /* hctx kobj stays in hctx */
2173         queue_for_each_hw_ctx(q, hctx, i) {
2174                 if (!hctx)
2175                         continue;
2176                 kobject_put(&hctx->kobj);
2177         }
2178
2179         q->mq_map = NULL;
2180
2181         kfree(q->queue_hw_ctx);
2182
2183         /*
2184          * release .mq_kobj and sw queue's kobject now because
2185          * both share lifetime with request queue.
2186          */
2187         blk_mq_sysfs_deinit(q);
2188
2189         free_percpu(q->queue_ctx);
2190 }
2191
2192 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
2193 {
2194         struct request_queue *uninit_q, *q;
2195
2196         uninit_q = blk_alloc_queue_node(GFP_KERNEL, set->numa_node);
2197         if (!uninit_q)
2198                 return ERR_PTR(-ENOMEM);
2199
2200         q = blk_mq_init_allocated_queue(set, uninit_q);
2201         if (IS_ERR(q))
2202                 blk_cleanup_queue(uninit_q);
2203
2204         return q;
2205 }
2206 EXPORT_SYMBOL(blk_mq_init_queue);
2207
2208 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
2209                                                 struct request_queue *q)
2210 {
2211         int i, j;
2212         struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
2213
2214         blk_mq_sysfs_unregister(q);
2215         for (i = 0; i < set->nr_hw_queues; i++) {
2216                 int node;
2217
2218                 if (hctxs[i])
2219                         continue;
2220
2221                 node = blk_mq_hw_queue_to_node(q->mq_map, i);
2222                 hctxs[i] = kzalloc_node(sizeof(struct blk_mq_hw_ctx),
2223                                         GFP_KERNEL, node);
2224                 if (!hctxs[i])
2225                         break;
2226
2227                 if (!zalloc_cpumask_var_node(&hctxs[i]->cpumask, GFP_KERNEL,
2228                                                 node)) {
2229                         kfree(hctxs[i]);
2230                         hctxs[i] = NULL;
2231                         break;
2232                 }
2233
2234                 atomic_set(&hctxs[i]->nr_active, 0);
2235                 hctxs[i]->numa_node = node;
2236                 hctxs[i]->queue_num = i;
2237
2238                 if (blk_mq_init_hctx(q, set, hctxs[i], i)) {
2239                         free_cpumask_var(hctxs[i]->cpumask);
2240                         kfree(hctxs[i]);
2241                         hctxs[i] = NULL;
2242                         break;
2243                 }
2244                 blk_mq_hctx_kobj_init(hctxs[i]);
2245         }
2246         for (j = i; j < q->nr_hw_queues; j++) {
2247                 struct blk_mq_hw_ctx *hctx = hctxs[j];
2248
2249                 if (hctx) {
2250                         if (hctx->tags)
2251                                 blk_mq_free_map_and_requests(set, j);
2252                         blk_mq_exit_hctx(q, set, hctx, j);
2253                         kobject_put(&hctx->kobj);
2254                         hctxs[j] = NULL;
2255
2256                 }
2257         }
2258         q->nr_hw_queues = i;
2259         blk_mq_sysfs_register(q);
2260 }
2261
2262 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
2263                                                   struct request_queue *q)
2264 {
2265         /* mark the queue as mq asap */
2266         q->mq_ops = set->ops;
2267
2268         q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
2269                                              blk_stat_rq_ddir, 2, q);
2270         if (!q->poll_cb)
2271                 goto err_exit;
2272
2273         q->queue_ctx = alloc_percpu(struct blk_mq_ctx);
2274         if (!q->queue_ctx)
2275                 goto err_exit;
2276
2277         /* init q->mq_kobj and sw queues' kobjects */
2278         blk_mq_sysfs_init(q);
2279
2280         q->queue_hw_ctx = kzalloc_node(nr_cpu_ids * sizeof(*(q->queue_hw_ctx)),
2281                                                 GFP_KERNEL, set->numa_node);
2282         if (!q->queue_hw_ctx)
2283                 goto err_percpu;
2284
2285         q->mq_map = set->mq_map;
2286
2287         blk_mq_realloc_hw_ctxs(set, q);
2288         if (!q->nr_hw_queues)
2289                 goto err_hctxs;
2290
2291         INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
2292         blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
2293
2294         q->nr_queues = nr_cpu_ids;
2295
2296         q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
2297
2298         if (!(set->flags & BLK_MQ_F_SG_MERGE))
2299                 q->queue_flags |= 1 << QUEUE_FLAG_NO_SG_MERGE;
2300
2301         q->sg_reserved_size = INT_MAX;
2302
2303         INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
2304         INIT_LIST_HEAD(&q->requeue_list);
2305         spin_lock_init(&q->requeue_lock);
2306
2307         blk_queue_make_request(q, blk_mq_make_request);
2308
2309         /*
2310          * Do this after blk_queue_make_request() overrides it...
2311          */
2312         q->nr_requests = set->queue_depth;
2313
2314         /*
2315          * Default to classic polling
2316          */
2317         q->poll_nsec = -1;
2318
2319         if (set->ops->complete)
2320                 blk_queue_softirq_done(q, set->ops->complete);
2321
2322         blk_mq_init_cpu_queues(q, set->nr_hw_queues);
2323
2324         get_online_cpus();
2325         mutex_lock(&all_q_mutex);
2326
2327         list_add_tail(&q->all_q_node, &all_q_list);
2328         blk_mq_add_queue_tag_set(set, q);
2329         blk_mq_map_swqueue(q, cpu_online_mask);
2330
2331         mutex_unlock(&all_q_mutex);
2332         put_online_cpus();
2333
2334         if (!(set->flags & BLK_MQ_F_NO_SCHED)) {
2335                 int ret;
2336
2337                 ret = blk_mq_sched_init(q);
2338                 if (ret)
2339                         return ERR_PTR(ret);
2340         }
2341
2342         return q;
2343
2344 err_hctxs:
2345         kfree(q->queue_hw_ctx);
2346 err_percpu:
2347         free_percpu(q->queue_ctx);
2348 err_exit:
2349         q->mq_ops = NULL;
2350         return ERR_PTR(-ENOMEM);
2351 }
2352 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
2353
2354 void blk_mq_free_queue(struct request_queue *q)
2355 {
2356         struct blk_mq_tag_set   *set = q->tag_set;
2357
2358         mutex_lock(&all_q_mutex);
2359         list_del_init(&q->all_q_node);
2360         mutex_unlock(&all_q_mutex);
2361
2362         blk_mq_del_queue_tag_set(q);
2363
2364         blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
2365 }
2366
2367 /* Basically redo blk_mq_init_queue with queue frozen */
2368 static void blk_mq_queue_reinit(struct request_queue *q,
2369                                 const struct cpumask *online_mask)
2370 {
2371         WARN_ON_ONCE(!atomic_read(&q->mq_freeze_depth));
2372
2373         blk_mq_sysfs_unregister(q);
2374
2375         /*
2376          * redo blk_mq_init_cpu_queues and blk_mq_init_hw_queues. FIXME: maybe
2377          * we should change hctx numa_node according to new topology (this
2378          * involves free and re-allocate memory, worthy doing?)
2379          */
2380
2381         blk_mq_map_swqueue(q, online_mask);
2382
2383         blk_mq_sysfs_register(q);
2384 }
2385
2386 /*
2387  * New online cpumask which is going to be set in this hotplug event.
2388  * Declare this cpumasks as global as cpu-hotplug operation is invoked
2389  * one-by-one and dynamically allocating this could result in a failure.
2390  */
2391 static struct cpumask cpuhp_online_new;
2392
2393 static void blk_mq_queue_reinit_work(void)
2394 {
2395         struct request_queue *q;
2396
2397         mutex_lock(&all_q_mutex);
2398         /*
2399          * We need to freeze and reinit all existing queues.  Freezing
2400          * involves synchronous wait for an RCU grace period and doing it
2401          * one by one may take a long time.  Start freezing all queues in
2402          * one swoop and then wait for the completions so that freezing can
2403          * take place in parallel.
2404          */
2405         list_for_each_entry(q, &all_q_list, all_q_node)
2406                 blk_freeze_queue_start(q);
2407         list_for_each_entry(q, &all_q_list, all_q_node)
2408                 blk_mq_freeze_queue_wait(q);
2409
2410         list_for_each_entry(q, &all_q_list, all_q_node)
2411                 blk_mq_queue_reinit(q, &cpuhp_online_new);
2412
2413         list_for_each_entry(q, &all_q_list, all_q_node)
2414                 blk_mq_unfreeze_queue(q);
2415
2416         mutex_unlock(&all_q_mutex);
2417 }
2418
2419 static int blk_mq_queue_reinit_dead(unsigned int cpu)
2420 {
2421         cpumask_copy(&cpuhp_online_new, cpu_online_mask);
2422         blk_mq_queue_reinit_work();
2423         return 0;
2424 }
2425
2426 /*
2427  * Before hotadded cpu starts handling requests, new mappings must be
2428  * established.  Otherwise, these requests in hw queue might never be
2429  * dispatched.
2430  *
2431  * For example, there is a single hw queue (hctx) and two CPU queues (ctx0
2432  * for CPU0, and ctx1 for CPU1).
2433  *
2434  * Now CPU1 is just onlined and a request is inserted into ctx1->rq_list
2435  * and set bit0 in pending bitmap as ctx1->index_hw is still zero.
2436  *
2437  * And then while running hw queue, blk_mq_flush_busy_ctxs() finds bit0 is set
2438  * in pending bitmap and tries to retrieve requests in hctx->ctxs[0]->rq_list.
2439  * But htx->ctxs[0] is a pointer to ctx0, so the request in ctx1->rq_list is
2440  * ignored.
2441  */
2442 static int blk_mq_queue_reinit_prepare(unsigned int cpu)
2443 {
2444         cpumask_copy(&cpuhp_online_new, cpu_online_mask);
2445         cpumask_set_cpu(cpu, &cpuhp_online_new);
2446         blk_mq_queue_reinit_work();
2447         return 0;
2448 }
2449
2450 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2451 {
2452         int i;
2453
2454         for (i = 0; i < set->nr_hw_queues; i++)
2455                 if (!__blk_mq_alloc_rq_map(set, i))
2456                         goto out_unwind;
2457
2458         return 0;
2459
2460 out_unwind:
2461         while (--i >= 0)
2462                 blk_mq_free_rq_map(set->tags[i]);
2463
2464         return -ENOMEM;
2465 }
2466
2467 /*
2468  * Allocate the request maps associated with this tag_set. Note that this
2469  * may reduce the depth asked for, if memory is tight. set->queue_depth
2470  * will be updated to reflect the allocated depth.
2471  */
2472 static int blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2473 {
2474         unsigned int depth;
2475         int err;
2476
2477         depth = set->queue_depth;
2478         do {
2479                 err = __blk_mq_alloc_rq_maps(set);
2480                 if (!err)
2481                         break;
2482
2483                 set->queue_depth >>= 1;
2484                 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
2485                         err = -ENOMEM;
2486                         break;
2487                 }
2488         } while (set->queue_depth);
2489
2490         if (!set->queue_depth || err) {
2491                 pr_err("blk-mq: failed to allocate request map\n");
2492                 return -ENOMEM;
2493         }
2494
2495         if (depth != set->queue_depth)
2496                 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
2497                                                 depth, set->queue_depth);
2498
2499         return 0;
2500 }
2501
2502 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
2503 {
2504         if (set->ops->map_queues)
2505                 return set->ops->map_queues(set);
2506         else
2507                 return blk_mq_map_queues(set);
2508 }
2509
2510 /*
2511  * Alloc a tag set to be associated with one or more request queues.
2512  * May fail with EINVAL for various error conditions. May adjust the
2513  * requested depth down, if if it too large. In that case, the set
2514  * value will be stored in set->queue_depth.
2515  */
2516 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
2517 {
2518         int ret;
2519
2520         BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
2521
2522         if (!set->nr_hw_queues)
2523                 return -EINVAL;
2524         if (!set->queue_depth)
2525                 return -EINVAL;
2526         if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
2527                 return -EINVAL;
2528
2529         if (!set->ops->queue_rq)
2530                 return -EINVAL;
2531
2532         if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
2533                 pr_info("blk-mq: reduced tag depth to %u\n",
2534                         BLK_MQ_MAX_DEPTH);
2535                 set->queue_depth = BLK_MQ_MAX_DEPTH;
2536         }
2537
2538         /*
2539          * If a crashdump is active, then we are potentially in a very
2540          * memory constrained environment. Limit us to 1 queue and
2541          * 64 tags to prevent using too much memory.
2542          */
2543         if (is_kdump_kernel()) {
2544                 set->nr_hw_queues = 1;
2545                 set->queue_depth = min(64U, set->queue_depth);
2546         }
2547         /*
2548          * There is no use for more h/w queues than cpus.
2549          */
2550         if (set->nr_hw_queues > nr_cpu_ids)
2551                 set->nr_hw_queues = nr_cpu_ids;
2552
2553         set->tags = kzalloc_node(nr_cpu_ids * sizeof(struct blk_mq_tags *),
2554                                  GFP_KERNEL, set->numa_node);
2555         if (!set->tags)
2556                 return -ENOMEM;
2557
2558         ret = -ENOMEM;
2559         set->mq_map = kzalloc_node(sizeof(*set->mq_map) * nr_cpu_ids,
2560                         GFP_KERNEL, set->numa_node);
2561         if (!set->mq_map)
2562                 goto out_free_tags;
2563
2564         ret = blk_mq_update_queue_map(set);
2565         if (ret)
2566                 goto out_free_mq_map;
2567
2568         ret = blk_mq_alloc_rq_maps(set);
2569         if (ret)
2570                 goto out_free_mq_map;
2571
2572         mutex_init(&set->tag_list_lock);
2573         INIT_LIST_HEAD(&set->tag_list);
2574
2575         return 0;
2576
2577 out_free_mq_map:
2578         kfree(set->mq_map);
2579         set->mq_map = NULL;
2580 out_free_tags:
2581         kfree(set->tags);
2582         set->tags = NULL;
2583         return ret;
2584 }
2585 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
2586
2587 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
2588 {
2589         int i;
2590
2591         for (i = 0; i < nr_cpu_ids; i++)
2592                 blk_mq_free_map_and_requests(set, i);
2593
2594         kfree(set->mq_map);
2595         set->mq_map = NULL;
2596
2597         kfree(set->tags);
2598         set->tags = NULL;
2599 }
2600 EXPORT_SYMBOL(blk_mq_free_tag_set);
2601
2602 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
2603 {
2604         struct blk_mq_tag_set *set = q->tag_set;
2605         struct blk_mq_hw_ctx *hctx;
2606         int i, ret;
2607
2608         if (!set)
2609                 return -EINVAL;
2610
2611         blk_mq_freeze_queue(q);
2612         blk_mq_quiesce_queue(q);
2613
2614         ret = 0;
2615         queue_for_each_hw_ctx(q, hctx, i) {
2616                 if (!hctx->tags)
2617                         continue;
2618                 /*
2619                  * If we're using an MQ scheduler, just update the scheduler
2620                  * queue depth. This is similar to what the old code would do.
2621                  */
2622                 if (!hctx->sched_tags) {
2623                         ret = blk_mq_tag_update_depth(hctx, &hctx->tags,
2624                                                         min(nr, set->queue_depth),
2625                                                         false);
2626                 } else {
2627                         ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
2628                                                         nr, true);
2629                 }
2630                 if (ret)
2631                         break;
2632         }
2633
2634         if (!ret)
2635                 q->nr_requests = nr;
2636
2637         blk_mq_unfreeze_queue(q);
2638         blk_mq_start_stopped_hw_queues(q, true);
2639
2640         return ret;
2641 }
2642
2643 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
2644 {
2645         struct request_queue *q;
2646
2647         lockdep_assert_held(&set->tag_list_lock);
2648
2649         if (nr_hw_queues > nr_cpu_ids)
2650                 nr_hw_queues = nr_cpu_ids;
2651         if (nr_hw_queues < 1 || nr_hw_queues == set->nr_hw_queues)
2652                 return;
2653
2654         list_for_each_entry(q, &set->tag_list, tag_set_list)
2655                 blk_mq_freeze_queue(q);
2656
2657         set->nr_hw_queues = nr_hw_queues;
2658         blk_mq_update_queue_map(set);
2659         list_for_each_entry(q, &set->tag_list, tag_set_list) {
2660                 blk_mq_realloc_hw_ctxs(set, q);
2661                 blk_mq_queue_reinit(q, cpu_online_mask);
2662         }
2663
2664         list_for_each_entry(q, &set->tag_list, tag_set_list)
2665                 blk_mq_unfreeze_queue(q);
2666 }
2667 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
2668
2669 /* Enable polling stats and return whether they were already enabled. */
2670 static bool blk_poll_stats_enable(struct request_queue *q)
2671 {
2672         if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
2673             test_and_set_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags))
2674                 return true;
2675         blk_stat_add_callback(q, q->poll_cb);
2676         return false;
2677 }
2678
2679 static void blk_mq_poll_stats_start(struct request_queue *q)
2680 {
2681         /*
2682          * We don't arm the callback if polling stats are not enabled or the
2683          * callback is already active.
2684          */
2685         if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
2686             blk_stat_is_active(q->poll_cb))
2687                 return;
2688
2689         blk_stat_activate_msecs(q->poll_cb, 100);
2690 }
2691
2692 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
2693 {
2694         struct request_queue *q = cb->data;
2695
2696         if (cb->stat[READ].nr_samples)
2697                 q->poll_stat[READ] = cb->stat[READ];
2698         if (cb->stat[WRITE].nr_samples)
2699                 q->poll_stat[WRITE] = cb->stat[WRITE];
2700 }
2701
2702 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
2703                                        struct blk_mq_hw_ctx *hctx,
2704                                        struct request *rq)
2705 {
2706         unsigned long ret = 0;
2707
2708         /*
2709          * If stats collection isn't on, don't sleep but turn it on for
2710          * future users
2711          */
2712         if (!blk_poll_stats_enable(q))
2713                 return 0;
2714
2715         /*
2716          * As an optimistic guess, use half of the mean service time
2717          * for this type of request. We can (and should) make this smarter.
2718          * For instance, if the completion latencies are tight, we can
2719          * get closer than just half the mean. This is especially
2720          * important on devices where the completion latencies are longer
2721          * than ~10 usec.
2722          */
2723         if (req_op(rq) == REQ_OP_READ && q->poll_stat[READ].nr_samples)
2724                 ret = (q->poll_stat[READ].mean + 1) / 2;
2725         else if (req_op(rq) == REQ_OP_WRITE && q->poll_stat[WRITE].nr_samples)
2726                 ret = (q->poll_stat[WRITE].mean + 1) / 2;
2727
2728         return ret;
2729 }
2730
2731 static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
2732                                      struct blk_mq_hw_ctx *hctx,
2733                                      struct request *rq)
2734 {
2735         struct hrtimer_sleeper hs;
2736         enum hrtimer_mode mode;
2737         unsigned int nsecs;
2738         ktime_t kt;
2739
2740         if (test_bit(REQ_ATOM_POLL_SLEPT, &rq->atomic_flags))
2741                 return false;
2742
2743         /*
2744          * poll_nsec can be:
2745          *
2746          * -1:  don't ever hybrid sleep
2747          *  0:  use half of prev avg
2748          * >0:  use this specific value
2749          */
2750         if (q->poll_nsec == -1)
2751                 return false;
2752         else if (q->poll_nsec > 0)
2753                 nsecs = q->poll_nsec;
2754         else
2755                 nsecs = blk_mq_poll_nsecs(q, hctx, rq);
2756
2757         if (!nsecs)
2758                 return false;
2759
2760         set_bit(REQ_ATOM_POLL_SLEPT, &rq->atomic_flags);
2761
2762         /*
2763          * This will be replaced with the stats tracking code, using
2764          * 'avg_completion_time / 2' as the pre-sleep target.
2765          */
2766         kt = nsecs;
2767
2768         mode = HRTIMER_MODE_REL;
2769         hrtimer_init_on_stack(&hs.timer, CLOCK_MONOTONIC, mode);
2770         hrtimer_set_expires(&hs.timer, kt);
2771
2772         hrtimer_init_sleeper(&hs, current);
2773         do {
2774                 if (test_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags))
2775                         break;
2776                 set_current_state(TASK_UNINTERRUPTIBLE);
2777                 hrtimer_start_expires(&hs.timer, mode);
2778                 if (hs.task)
2779                         io_schedule();
2780                 hrtimer_cancel(&hs.timer);
2781                 mode = HRTIMER_MODE_ABS;
2782         } while (hs.task && !signal_pending(current));
2783
2784         __set_current_state(TASK_RUNNING);
2785         destroy_hrtimer_on_stack(&hs.timer);
2786         return true;
2787 }
2788
2789 static bool __blk_mq_poll(struct blk_mq_hw_ctx *hctx, struct request *rq)
2790 {
2791         struct request_queue *q = hctx->queue;
2792         long state;
2793
2794         /*
2795          * If we sleep, have the caller restart the poll loop to reset
2796          * the state. Like for the other success return cases, the
2797          * caller is responsible for checking if the IO completed. If
2798          * the IO isn't complete, we'll get called again and will go
2799          * straight to the busy poll loop.
2800          */
2801         if (blk_mq_poll_hybrid_sleep(q, hctx, rq))
2802                 return true;
2803
2804         hctx->poll_considered++;
2805
2806         state = current->state;
2807         while (!need_resched()) {
2808                 int ret;
2809
2810                 hctx->poll_invoked++;
2811
2812                 ret = q->mq_ops->poll(hctx, rq->tag);
2813                 if (ret > 0) {
2814                         hctx->poll_success++;
2815                         set_current_state(TASK_RUNNING);
2816                         return true;
2817                 }
2818
2819                 if (signal_pending_state(state, current))
2820                         set_current_state(TASK_RUNNING);
2821
2822                 if (current->state == TASK_RUNNING)
2823                         return true;
2824                 if (ret < 0)
2825                         break;
2826                 cpu_relax();
2827         }
2828
2829         return false;
2830 }
2831
2832 bool blk_mq_poll(struct request_queue *q, blk_qc_t cookie)
2833 {
2834         struct blk_mq_hw_ctx *hctx;
2835         struct blk_plug *plug;
2836         struct request *rq;
2837
2838         if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
2839             !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
2840                 return false;
2841
2842         plug = current->plug;
2843         if (plug)
2844                 blk_flush_plug_list(plug, false);
2845
2846         hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
2847         if (!blk_qc_t_is_internal(cookie))
2848                 rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
2849         else
2850                 rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
2851
2852         return __blk_mq_poll(hctx, rq);
2853 }
2854 EXPORT_SYMBOL_GPL(blk_mq_poll);
2855
2856 void blk_mq_disable_hotplug(void)
2857 {
2858         mutex_lock(&all_q_mutex);
2859 }
2860
2861 void blk_mq_enable_hotplug(void)
2862 {
2863         mutex_unlock(&all_q_mutex);
2864 }
2865
2866 static int __init blk_mq_init(void)
2867 {
2868         cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
2869                                 blk_mq_hctx_notify_dead);
2870
2871         cpuhp_setup_state_nocalls(CPUHP_BLK_MQ_PREPARE, "block/mq:prepare",
2872                                   blk_mq_queue_reinit_prepare,
2873                                   blk_mq_queue_reinit_dead);
2874         return 0;
2875 }
2876 subsys_initcall(blk_mq_init);