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