Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / 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/delay.h>
24 #include <linux/crash_dump.h>
25
26 #include <trace/events/block.h>
27
28 #include <linux/blk-mq.h>
29 #include "blk.h"
30 #include "blk-mq.h"
31 #include "blk-mq-tag.h"
32
33 static DEFINE_MUTEX(all_q_mutex);
34 static LIST_HEAD(all_q_list);
35
36 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx);
37
38 /*
39  * Check if any of the ctx's have pending work in this hardware queue
40  */
41 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
42 {
43         unsigned int i;
44
45         for (i = 0; i < hctx->ctx_map.size; i++)
46                 if (hctx->ctx_map.map[i].word)
47                         return true;
48
49         return false;
50 }
51
52 static inline struct blk_align_bitmap *get_bm(struct blk_mq_hw_ctx *hctx,
53                                               struct blk_mq_ctx *ctx)
54 {
55         return &hctx->ctx_map.map[ctx->index_hw / hctx->ctx_map.bits_per_word];
56 }
57
58 #define CTX_TO_BIT(hctx, ctx)   \
59         ((ctx)->index_hw & ((hctx)->ctx_map.bits_per_word - 1))
60
61 /*
62  * Mark this ctx as having pending work in this hardware queue
63  */
64 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
65                                      struct blk_mq_ctx *ctx)
66 {
67         struct blk_align_bitmap *bm = get_bm(hctx, ctx);
68
69         if (!test_bit(CTX_TO_BIT(hctx, ctx), &bm->word))
70                 set_bit(CTX_TO_BIT(hctx, ctx), &bm->word);
71 }
72
73 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
74                                       struct blk_mq_ctx *ctx)
75 {
76         struct blk_align_bitmap *bm = get_bm(hctx, ctx);
77
78         clear_bit(CTX_TO_BIT(hctx, ctx), &bm->word);
79 }
80
81 void blk_mq_freeze_queue_start(struct request_queue *q)
82 {
83         int freeze_depth;
84
85         freeze_depth = atomic_inc_return(&q->mq_freeze_depth);
86         if (freeze_depth == 1) {
87                 percpu_ref_kill(&q->q_usage_counter);
88                 blk_mq_run_hw_queues(q, false);
89         }
90 }
91 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_start);
92
93 static void blk_mq_freeze_queue_wait(struct request_queue *q)
94 {
95         swait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
96 }
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_mq_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                 swake_up_all(&q->mq_freeze_wq);
134         }
135 }
136 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
137
138 void blk_mq_wake_waiters(struct request_queue *q)
139 {
140         struct blk_mq_hw_ctx *hctx;
141         unsigned int i;
142
143         queue_for_each_hw_ctx(q, hctx, i)
144                 if (blk_mq_hw_queue_mapped(hctx))
145                         blk_mq_tag_wakeup_all(hctx->tags, true);
146
147         /*
148          * If we are called because the queue has now been marked as
149          * dying, we need to ensure that processes currently waiting on
150          * the queue are notified as well.
151          */
152         swake_up_all(&q->mq_freeze_wq);
153 }
154
155 bool blk_mq_can_queue(struct blk_mq_hw_ctx *hctx)
156 {
157         return blk_mq_has_free_tags(hctx->tags);
158 }
159 EXPORT_SYMBOL(blk_mq_can_queue);
160
161 static void blk_mq_rq_ctx_init(struct request_queue *q, struct blk_mq_ctx *ctx,
162                                struct request *rq, unsigned int rw_flags)
163 {
164         if (blk_queue_io_stat(q))
165                 rw_flags |= REQ_IO_STAT;
166
167         INIT_LIST_HEAD(&rq->queuelist);
168         /* csd/requeue_work/fifo_time is initialized before use */
169         rq->q = q;
170         rq->mq_ctx = ctx;
171         rq->cmd_flags |= rw_flags;
172         /* do not touch atomic flags, it needs atomic ops against the timer */
173         rq->cpu = -1;
174         INIT_HLIST_NODE(&rq->hash);
175         RB_CLEAR_NODE(&rq->rb_node);
176         rq->rq_disk = NULL;
177         rq->part = NULL;
178         rq->start_time = jiffies;
179 #ifdef CONFIG_BLK_CGROUP
180         rq->rl = NULL;
181         set_start_time_ns(rq);
182         rq->io_start_time_ns = 0;
183 #endif
184         rq->nr_phys_segments = 0;
185 #if defined(CONFIG_BLK_DEV_INTEGRITY)
186         rq->nr_integrity_segments = 0;
187 #endif
188         rq->special = NULL;
189         /* tag was already set */
190         rq->errors = 0;
191
192         rq->cmd = rq->__cmd;
193
194         rq->extra_len = 0;
195         rq->sense_len = 0;
196         rq->resid_len = 0;
197         rq->sense = NULL;
198
199 #ifdef CONFIG_PREEMPT_RT_FULL
200         INIT_WORK(&rq->work, __blk_mq_complete_request_remote_work);
201 #endif
202         INIT_LIST_HEAD(&rq->timeout_list);
203         rq->timeout = 0;
204
205         rq->end_io = NULL;
206         rq->end_io_data = NULL;
207         rq->next_rq = NULL;
208
209         ctx->rq_dispatched[rw_is_sync(rw_flags)]++;
210 }
211
212 static struct request *
213 __blk_mq_alloc_request(struct blk_mq_alloc_data *data, int rw)
214 {
215         struct request *rq;
216         unsigned int tag;
217
218         tag = blk_mq_get_tag(data);
219         if (tag != BLK_MQ_TAG_FAIL) {
220                 rq = data->hctx->tags->rqs[tag];
221
222                 if (blk_mq_tag_busy(data->hctx)) {
223                         rq->cmd_flags = REQ_MQ_INFLIGHT;
224                         atomic_inc(&data->hctx->nr_active);
225                 }
226
227                 rq->tag = tag;
228                 blk_mq_rq_ctx_init(data->q, data->ctx, rq, rw);
229                 return rq;
230         }
231
232         return NULL;
233 }
234
235 struct request *blk_mq_alloc_request(struct request_queue *q, int rw, gfp_t gfp,
236                 bool reserved)
237 {
238         struct blk_mq_ctx *ctx;
239         struct blk_mq_hw_ctx *hctx;
240         struct request *rq;
241         struct blk_mq_alloc_data alloc_data;
242         int ret;
243
244         ret = blk_queue_enter(q, gfp);
245         if (ret)
246                 return ERR_PTR(ret);
247
248         ctx = blk_mq_get_ctx(q);
249         hctx = q->mq_ops->map_queue(q, ctx->cpu);
250         blk_mq_set_alloc_data(&alloc_data, q, gfp & ~__GFP_DIRECT_RECLAIM,
251                         reserved, ctx, hctx);
252
253         rq = __blk_mq_alloc_request(&alloc_data, rw);
254         if (!rq && (gfp & __GFP_DIRECT_RECLAIM)) {
255                 __blk_mq_run_hw_queue(hctx);
256                 blk_mq_put_ctx(ctx);
257
258                 ctx = blk_mq_get_ctx(q);
259                 hctx = q->mq_ops->map_queue(q, ctx->cpu);
260                 blk_mq_set_alloc_data(&alloc_data, q, gfp, reserved, ctx,
261                                 hctx);
262                 rq =  __blk_mq_alloc_request(&alloc_data, rw);
263                 ctx = alloc_data.ctx;
264         }
265         blk_mq_put_ctx(ctx);
266         if (!rq) {
267                 blk_queue_exit(q);
268                 return ERR_PTR(-EWOULDBLOCK);
269         }
270         return rq;
271 }
272 EXPORT_SYMBOL(blk_mq_alloc_request);
273
274 static void __blk_mq_free_request(struct blk_mq_hw_ctx *hctx,
275                                   struct blk_mq_ctx *ctx, struct request *rq)
276 {
277         const int tag = rq->tag;
278         struct request_queue *q = rq->q;
279
280         if (rq->cmd_flags & REQ_MQ_INFLIGHT)
281                 atomic_dec(&hctx->nr_active);
282         rq->cmd_flags = 0;
283
284         clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
285         blk_mq_put_tag(hctx, tag, &ctx->last_tag);
286         blk_queue_exit(q);
287 }
288
289 void blk_mq_free_hctx_request(struct blk_mq_hw_ctx *hctx, struct request *rq)
290 {
291         struct blk_mq_ctx *ctx = rq->mq_ctx;
292
293         ctx->rq_completed[rq_is_sync(rq)]++;
294         __blk_mq_free_request(hctx, ctx, rq);
295
296 }
297 EXPORT_SYMBOL_GPL(blk_mq_free_hctx_request);
298
299 void blk_mq_free_request(struct request *rq)
300 {
301         struct blk_mq_hw_ctx *hctx;
302         struct request_queue *q = rq->q;
303
304         hctx = q->mq_ops->map_queue(q, rq->mq_ctx->cpu);
305         blk_mq_free_hctx_request(hctx, rq);
306 }
307 EXPORT_SYMBOL_GPL(blk_mq_free_request);
308
309 inline void __blk_mq_end_request(struct request *rq, int error)
310 {
311         blk_account_io_done(rq);
312
313         if (rq->end_io) {
314                 rq->end_io(rq, error);
315         } else {
316                 if (unlikely(blk_bidi_rq(rq)))
317                         blk_mq_free_request(rq->next_rq);
318                 blk_mq_free_request(rq);
319         }
320 }
321 EXPORT_SYMBOL(__blk_mq_end_request);
322
323 void blk_mq_end_request(struct request *rq, int error)
324 {
325         if (blk_update_request(rq, error, blk_rq_bytes(rq)))
326                 BUG();
327         __blk_mq_end_request(rq, error);
328 }
329 EXPORT_SYMBOL(blk_mq_end_request);
330
331 #ifdef CONFIG_PREEMPT_RT_FULL
332
333 void __blk_mq_complete_request_remote_work(struct work_struct *work)
334 {
335         struct request *rq = container_of(work, struct request, work);
336
337         rq->q->softirq_done_fn(rq);
338 }
339
340 #else
341
342 static void __blk_mq_complete_request_remote(void *data)
343 {
344         struct request *rq = data;
345
346         rq->q->softirq_done_fn(rq);
347 }
348
349 #endif
350
351 static void blk_mq_ipi_complete_request(struct request *rq)
352 {
353         struct blk_mq_ctx *ctx = rq->mq_ctx;
354         bool shared = false;
355         int cpu;
356
357         if (!test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags)) {
358                 rq->q->softirq_done_fn(rq);
359                 return;
360         }
361
362         cpu = get_cpu_light();
363         if (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags))
364                 shared = cpus_share_cache(cpu, ctx->cpu);
365
366         if (cpu != ctx->cpu && !shared && cpu_online(ctx->cpu)) {
367 #ifdef CONFIG_PREEMPT_RT_FULL
368                 schedule_work_on(ctx->cpu, &rq->work);
369 #else
370                 rq->csd.func = __blk_mq_complete_request_remote;
371                 rq->csd.info = rq;
372                 rq->csd.flags = 0;
373                 smp_call_function_single_async(ctx->cpu, &rq->csd);
374 #endif
375         } else {
376                 rq->q->softirq_done_fn(rq);
377         }
378         put_cpu_light();
379 }
380
381 static void __blk_mq_complete_request(struct request *rq)
382 {
383         struct request_queue *q = rq->q;
384
385         if (!q->softirq_done_fn)
386                 blk_mq_end_request(rq, rq->errors);
387         else
388                 blk_mq_ipi_complete_request(rq);
389 }
390
391 /**
392  * blk_mq_complete_request - end I/O on a request
393  * @rq:         the request being processed
394  *
395  * Description:
396  *      Ends all I/O on a request. It does not handle partial completions.
397  *      The actual completion happens out-of-order, through a IPI handler.
398  **/
399 void blk_mq_complete_request(struct request *rq, int error)
400 {
401         struct request_queue *q = rq->q;
402
403         if (unlikely(blk_should_fake_timeout(q)))
404                 return;
405         if (!blk_mark_rq_complete(rq)) {
406                 rq->errors = error;
407                 __blk_mq_complete_request(rq);
408         }
409 }
410 EXPORT_SYMBOL(blk_mq_complete_request);
411
412 int blk_mq_request_started(struct request *rq)
413 {
414         return test_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
415 }
416 EXPORT_SYMBOL_GPL(blk_mq_request_started);
417
418 void blk_mq_start_request(struct request *rq)
419 {
420         struct request_queue *q = rq->q;
421
422         trace_block_rq_issue(q, rq);
423
424         rq->resid_len = blk_rq_bytes(rq);
425         if (unlikely(blk_bidi_rq(rq)))
426                 rq->next_rq->resid_len = blk_rq_bytes(rq->next_rq);
427
428         blk_add_timer(rq);
429
430         /*
431          * Ensure that ->deadline is visible before set the started
432          * flag and clear the completed flag.
433          */
434         smp_mb__before_atomic();
435
436         /*
437          * Mark us as started and clear complete. Complete might have been
438          * set if requeue raced with timeout, which then marked it as
439          * complete. So be sure to clear complete again when we start
440          * the request, otherwise we'll ignore the completion event.
441          */
442         if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags))
443                 set_bit(REQ_ATOM_STARTED, &rq->atomic_flags);
444         if (test_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags))
445                 clear_bit(REQ_ATOM_COMPLETE, &rq->atomic_flags);
446
447         if (q->dma_drain_size && blk_rq_bytes(rq)) {
448                 /*
449                  * Make sure space for the drain appears.  We know we can do
450                  * this because max_hw_segments has been adjusted to be one
451                  * fewer than the device can handle.
452                  */
453                 rq->nr_phys_segments++;
454         }
455 }
456 EXPORT_SYMBOL(blk_mq_start_request);
457
458 static void __blk_mq_requeue_request(struct request *rq)
459 {
460         struct request_queue *q = rq->q;
461
462         trace_block_rq_requeue(q, rq);
463
464         if (test_and_clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
465                 if (q->dma_drain_size && blk_rq_bytes(rq))
466                         rq->nr_phys_segments--;
467         }
468 }
469
470 void blk_mq_requeue_request(struct request *rq)
471 {
472         __blk_mq_requeue_request(rq);
473
474         BUG_ON(blk_queued_rq(rq));
475         blk_mq_add_to_requeue_list(rq, true);
476 }
477 EXPORT_SYMBOL(blk_mq_requeue_request);
478
479 static void blk_mq_requeue_work(struct work_struct *work)
480 {
481         struct request_queue *q =
482                 container_of(work, struct request_queue, requeue_work);
483         LIST_HEAD(rq_list);
484         struct request *rq, *next;
485         unsigned long flags;
486
487         spin_lock_irqsave(&q->requeue_lock, flags);
488         list_splice_init(&q->requeue_list, &rq_list);
489         spin_unlock_irqrestore(&q->requeue_lock, flags);
490
491         list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
492                 if (!(rq->cmd_flags & REQ_SOFTBARRIER))
493                         continue;
494
495                 rq->cmd_flags &= ~REQ_SOFTBARRIER;
496                 list_del_init(&rq->queuelist);
497                 blk_mq_insert_request(rq, true, false, false);
498         }
499
500         while (!list_empty(&rq_list)) {
501                 rq = list_entry(rq_list.next, struct request, queuelist);
502                 list_del_init(&rq->queuelist);
503                 blk_mq_insert_request(rq, false, false, false);
504         }
505
506         /*
507          * Use the start variant of queue running here, so that running
508          * the requeue work will kick stopped queues.
509          */
510         blk_mq_start_hw_queues(q);
511 }
512
513 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head)
514 {
515         struct request_queue *q = rq->q;
516         unsigned long flags;
517
518         /*
519          * We abuse this flag that is otherwise used by the I/O scheduler to
520          * request head insertation from the workqueue.
521          */
522         BUG_ON(rq->cmd_flags & REQ_SOFTBARRIER);
523
524         spin_lock_irqsave(&q->requeue_lock, flags);
525         if (at_head) {
526                 rq->cmd_flags |= REQ_SOFTBARRIER;
527                 list_add(&rq->queuelist, &q->requeue_list);
528         } else {
529                 list_add_tail(&rq->queuelist, &q->requeue_list);
530         }
531         spin_unlock_irqrestore(&q->requeue_lock, flags);
532 }
533 EXPORT_SYMBOL(blk_mq_add_to_requeue_list);
534
535 void blk_mq_cancel_requeue_work(struct request_queue *q)
536 {
537         cancel_work_sync(&q->requeue_work);
538 }
539 EXPORT_SYMBOL_GPL(blk_mq_cancel_requeue_work);
540
541 void blk_mq_kick_requeue_list(struct request_queue *q)
542 {
543         kblockd_schedule_work(&q->requeue_work);
544 }
545 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
546
547 void blk_mq_abort_requeue_list(struct request_queue *q)
548 {
549         unsigned long flags;
550         LIST_HEAD(rq_list);
551
552         spin_lock_irqsave(&q->requeue_lock, flags);
553         list_splice_init(&q->requeue_list, &rq_list);
554         spin_unlock_irqrestore(&q->requeue_lock, flags);
555
556         while (!list_empty(&rq_list)) {
557                 struct request *rq;
558
559                 rq = list_first_entry(&rq_list, struct request, queuelist);
560                 list_del_init(&rq->queuelist);
561                 rq->errors = -EIO;
562                 blk_mq_end_request(rq, rq->errors);
563         }
564 }
565 EXPORT_SYMBOL(blk_mq_abort_requeue_list);
566
567 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
568 {
569         return tags->rqs[tag];
570 }
571 EXPORT_SYMBOL(blk_mq_tag_to_rq);
572
573 struct blk_mq_timeout_data {
574         unsigned long next;
575         unsigned int next_set;
576 };
577
578 void blk_mq_rq_timed_out(struct request *req, bool reserved)
579 {
580         struct blk_mq_ops *ops = req->q->mq_ops;
581         enum blk_eh_timer_return ret = BLK_EH_RESET_TIMER;
582
583         /*
584          * We know that complete is set at this point. If STARTED isn't set
585          * anymore, then the request isn't active and the "timeout" should
586          * just be ignored. This can happen due to the bitflag ordering.
587          * Timeout first checks if STARTED is set, and if it is, assumes
588          * the request is active. But if we race with completion, then
589          * we both flags will get cleared. So check here again, and ignore
590          * a timeout event with a request that isn't active.
591          */
592         if (!test_bit(REQ_ATOM_STARTED, &req->atomic_flags))
593                 return;
594
595         if (ops->timeout)
596                 ret = ops->timeout(req, reserved);
597
598         switch (ret) {
599         case BLK_EH_HANDLED:
600                 __blk_mq_complete_request(req);
601                 break;
602         case BLK_EH_RESET_TIMER:
603                 blk_add_timer(req);
604                 blk_clear_rq_complete(req);
605                 break;
606         case BLK_EH_NOT_HANDLED:
607                 break;
608         default:
609                 printk(KERN_ERR "block: bad eh return: %d\n", ret);
610                 break;
611         }
612 }
613
614 static void blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
615                 struct request *rq, void *priv, bool reserved)
616 {
617         struct blk_mq_timeout_data *data = priv;
618
619         if (!test_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
620                 /*
621                  * If a request wasn't started before the queue was
622                  * marked dying, kill it here or it'll go unnoticed.
623                  */
624                 if (unlikely(blk_queue_dying(rq->q))) {
625                         rq->errors = -EIO;
626                         blk_mq_end_request(rq, rq->errors);
627                 }
628                 return;
629         }
630         if (rq->cmd_flags & REQ_NO_TIMEOUT)
631                 return;
632
633         if (time_after_eq(jiffies, rq->deadline)) {
634                 if (!blk_mark_rq_complete(rq))
635                         blk_mq_rq_timed_out(rq, reserved);
636         } else if (!data->next_set || time_after(data->next, rq->deadline)) {
637                 data->next = rq->deadline;
638                 data->next_set = 1;
639         }
640 }
641
642 static void blk_mq_rq_timer(unsigned long priv)
643 {
644         struct request_queue *q = (struct request_queue *)priv;
645         struct blk_mq_timeout_data data = {
646                 .next           = 0,
647                 .next_set       = 0,
648         };
649         int i;
650
651         blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &data);
652
653         if (data.next_set) {
654                 data.next = blk_rq_timeout(round_jiffies_up(data.next));
655                 mod_timer(&q->timeout, data.next);
656         } else {
657                 struct blk_mq_hw_ctx *hctx;
658
659                 queue_for_each_hw_ctx(q, hctx, i) {
660                         /* the hctx may be unmapped, so check it here */
661                         if (blk_mq_hw_queue_mapped(hctx))
662                                 blk_mq_tag_idle(hctx);
663                 }
664         }
665 }
666
667 /*
668  * Reverse check our software queue for entries that we could potentially
669  * merge with. Currently includes a hand-wavy stop count of 8, to not spend
670  * too much time checking for merges.
671  */
672 static bool blk_mq_attempt_merge(struct request_queue *q,
673                                  struct blk_mq_ctx *ctx, struct bio *bio)
674 {
675         struct request *rq;
676         int checked = 8;
677
678         list_for_each_entry_reverse(rq, &ctx->rq_list, queuelist) {
679                 int el_ret;
680
681                 if (!checked--)
682                         break;
683
684                 if (!blk_rq_merge_ok(rq, bio))
685                         continue;
686
687                 el_ret = blk_try_merge(rq, bio);
688                 if (el_ret == ELEVATOR_BACK_MERGE) {
689                         if (bio_attempt_back_merge(q, rq, bio)) {
690                                 ctx->rq_merged++;
691                                 return true;
692                         }
693                         break;
694                 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
695                         if (bio_attempt_front_merge(q, rq, bio)) {
696                                 ctx->rq_merged++;
697                                 return true;
698                         }
699                         break;
700                 }
701         }
702
703         return false;
704 }
705
706 /*
707  * Process software queues that have been marked busy, splicing them
708  * to the for-dispatch
709  */
710 static void flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
711 {
712         struct blk_mq_ctx *ctx;
713         int i;
714
715         for (i = 0; i < hctx->ctx_map.size; i++) {
716                 struct blk_align_bitmap *bm = &hctx->ctx_map.map[i];
717                 unsigned int off, bit;
718
719                 if (!bm->word)
720                         continue;
721
722                 bit = 0;
723                 off = i * hctx->ctx_map.bits_per_word;
724                 do {
725                         bit = find_next_bit(&bm->word, bm->depth, bit);
726                         if (bit >= bm->depth)
727                                 break;
728
729                         ctx = hctx->ctxs[bit + off];
730                         clear_bit(bit, &bm->word);
731                         spin_lock(&ctx->lock);
732                         list_splice_tail_init(&ctx->rq_list, list);
733                         spin_unlock(&ctx->lock);
734
735                         bit++;
736                 } while (1);
737         }
738 }
739
740 /*
741  * Run this hardware queue, pulling any software queues mapped to it in.
742  * Note that this function currently has various problems around ordering
743  * of IO. In particular, we'd like FIFO behaviour on handling existing
744  * items on the hctx->dispatch list. Ignore that for now.
745  */
746 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
747 {
748         struct request_queue *q = hctx->queue;
749         struct request *rq;
750         LIST_HEAD(rq_list);
751         LIST_HEAD(driver_list);
752         struct list_head *dptr;
753         int queued;
754
755         WARN_ON(!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask));
756
757         if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state)))
758                 return;
759
760         hctx->run++;
761
762         /*
763          * Touch any software queue that has pending entries.
764          */
765         flush_busy_ctxs(hctx, &rq_list);
766
767         /*
768          * If we have previous entries on our dispatch list, grab them
769          * and stuff them at the front for more fair dispatch.
770          */
771         if (!list_empty_careful(&hctx->dispatch)) {
772                 spin_lock(&hctx->lock);
773                 if (!list_empty(&hctx->dispatch))
774                         list_splice_init(&hctx->dispatch, &rq_list);
775                 spin_unlock(&hctx->lock);
776         }
777
778         /*
779          * Start off with dptr being NULL, so we start the first request
780          * immediately, even if we have more pending.
781          */
782         dptr = NULL;
783
784         /*
785          * Now process all the entries, sending them to the driver.
786          */
787         queued = 0;
788         while (!list_empty(&rq_list)) {
789                 struct blk_mq_queue_data bd;
790                 int ret;
791
792                 rq = list_first_entry(&rq_list, struct request, queuelist);
793                 list_del_init(&rq->queuelist);
794
795                 bd.rq = rq;
796                 bd.list = dptr;
797                 bd.last = list_empty(&rq_list);
798
799                 ret = q->mq_ops->queue_rq(hctx, &bd);
800                 switch (ret) {
801                 case BLK_MQ_RQ_QUEUE_OK:
802                         queued++;
803                         break;
804                 case BLK_MQ_RQ_QUEUE_BUSY:
805                         list_add(&rq->queuelist, &rq_list);
806                         __blk_mq_requeue_request(rq);
807                         break;
808                 default:
809                         pr_err("blk-mq: bad return on queue: %d\n", ret);
810                 case BLK_MQ_RQ_QUEUE_ERROR:
811                         rq->errors = -EIO;
812                         blk_mq_end_request(rq, rq->errors);
813                         break;
814                 }
815
816                 if (ret == BLK_MQ_RQ_QUEUE_BUSY)
817                         break;
818
819                 /*
820                  * We've done the first request. If we have more than 1
821                  * left in the list, set dptr to defer issue.
822                  */
823                 if (!dptr && rq_list.next != rq_list.prev)
824                         dptr = &driver_list;
825         }
826
827         if (!queued)
828                 hctx->dispatched[0]++;
829         else if (queued < (1 << (BLK_MQ_MAX_DISPATCH_ORDER - 1)))
830                 hctx->dispatched[ilog2(queued) + 1]++;
831
832         /*
833          * Any items that need requeuing? Stuff them into hctx->dispatch,
834          * that is where we will continue on next queue run.
835          */
836         if (!list_empty(&rq_list)) {
837                 spin_lock(&hctx->lock);
838                 list_splice(&rq_list, &hctx->dispatch);
839                 spin_unlock(&hctx->lock);
840                 /*
841                  * the queue is expected stopped with BLK_MQ_RQ_QUEUE_BUSY, but
842                  * it's possible the queue is stopped and restarted again
843                  * before this. Queue restart will dispatch requests. And since
844                  * requests in rq_list aren't added into hctx->dispatch yet,
845                  * the requests in rq_list might get lost.
846                  *
847                  * blk_mq_run_hw_queue() already checks the STOPPED bit
848                  **/
849                 blk_mq_run_hw_queue(hctx, true);
850         }
851 }
852
853 /*
854  * It'd be great if the workqueue API had a way to pass
855  * in a mask and had some smarts for more clever placement.
856  * For now we just round-robin here, switching for every
857  * BLK_MQ_CPU_WORK_BATCH queued items.
858  */
859 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
860 {
861         if (hctx->queue->nr_hw_queues == 1)
862                 return WORK_CPU_UNBOUND;
863
864         if (--hctx->next_cpu_batch <= 0) {
865                 int next_cpu;
866
867                 next_cpu = cpumask_next(hctx->next_cpu, hctx->cpumask);
868                 if (next_cpu >= nr_cpu_ids)
869                         next_cpu = cpumask_first(hctx->cpumask);
870
871                 hctx->next_cpu = next_cpu;
872                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
873         }
874
875         return hctx->next_cpu;
876 }
877
878 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
879 {
880         if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state) ||
881             !blk_mq_hw_queue_mapped(hctx)))
882                 return;
883
884         if (!async) {
885                 int cpu = get_cpu_light();
886                 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
887                         __blk_mq_run_hw_queue(hctx);
888                         put_cpu_light();
889                         return;
890                 }
891
892                 put_cpu_light();
893         }
894
895         kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
896                         &hctx->run_work, 0);
897 }
898
899 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
900 {
901         struct blk_mq_hw_ctx *hctx;
902         int i;
903
904         queue_for_each_hw_ctx(q, hctx, i) {
905                 if ((!blk_mq_hctx_has_pending(hctx) &&
906                     list_empty_careful(&hctx->dispatch)) ||
907                     test_bit(BLK_MQ_S_STOPPED, &hctx->state))
908                         continue;
909
910                 blk_mq_run_hw_queue(hctx, async);
911         }
912 }
913 EXPORT_SYMBOL(blk_mq_run_hw_queues);
914
915 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
916 {
917         cancel_delayed_work(&hctx->run_work);
918         cancel_delayed_work(&hctx->delay_work);
919         set_bit(BLK_MQ_S_STOPPED, &hctx->state);
920 }
921 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
922
923 void blk_mq_stop_hw_queues(struct request_queue *q)
924 {
925         struct blk_mq_hw_ctx *hctx;
926         int i;
927
928         queue_for_each_hw_ctx(q, hctx, i)
929                 blk_mq_stop_hw_queue(hctx);
930 }
931 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
932
933 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
934 {
935         clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
936
937         blk_mq_run_hw_queue(hctx, false);
938 }
939 EXPORT_SYMBOL(blk_mq_start_hw_queue);
940
941 void blk_mq_start_hw_queues(struct request_queue *q)
942 {
943         struct blk_mq_hw_ctx *hctx;
944         int i;
945
946         queue_for_each_hw_ctx(q, hctx, i)
947                 blk_mq_start_hw_queue(hctx);
948 }
949 EXPORT_SYMBOL(blk_mq_start_hw_queues);
950
951 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
952 {
953         struct blk_mq_hw_ctx *hctx;
954         int i;
955
956         queue_for_each_hw_ctx(q, hctx, i) {
957                 if (!test_bit(BLK_MQ_S_STOPPED, &hctx->state))
958                         continue;
959
960                 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
961                 blk_mq_run_hw_queue(hctx, async);
962         }
963 }
964 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
965
966 static void blk_mq_run_work_fn(struct work_struct *work)
967 {
968         struct blk_mq_hw_ctx *hctx;
969
970         hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
971
972         __blk_mq_run_hw_queue(hctx);
973 }
974
975 static void blk_mq_delay_work_fn(struct work_struct *work)
976 {
977         struct blk_mq_hw_ctx *hctx;
978
979         hctx = container_of(work, struct blk_mq_hw_ctx, delay_work.work);
980
981         if (test_and_clear_bit(BLK_MQ_S_STOPPED, &hctx->state))
982                 __blk_mq_run_hw_queue(hctx);
983 }
984
985 void blk_mq_delay_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
986 {
987         if (unlikely(!blk_mq_hw_queue_mapped(hctx)))
988                 return;
989
990         kblockd_schedule_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
991                         &hctx->delay_work, msecs_to_jiffies(msecs));
992 }
993 EXPORT_SYMBOL(blk_mq_delay_queue);
994
995 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
996                                             struct blk_mq_ctx *ctx,
997                                             struct request *rq,
998                                             bool at_head)
999 {
1000         trace_block_rq_insert(hctx->queue, rq);
1001
1002         if (at_head)
1003                 list_add(&rq->queuelist, &ctx->rq_list);
1004         else
1005                 list_add_tail(&rq->queuelist, &ctx->rq_list);
1006 }
1007
1008 static void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx,
1009                                     struct request *rq, bool at_head)
1010 {
1011         struct blk_mq_ctx *ctx = rq->mq_ctx;
1012
1013         __blk_mq_insert_req_list(hctx, ctx, rq, at_head);
1014         blk_mq_hctx_mark_pending(hctx, ctx);
1015 }
1016
1017 void blk_mq_insert_request(struct request *rq, bool at_head, bool run_queue,
1018                 bool async)
1019 {
1020         struct request_queue *q = rq->q;
1021         struct blk_mq_hw_ctx *hctx;
1022         struct blk_mq_ctx *ctx = rq->mq_ctx, *current_ctx;
1023
1024         current_ctx = blk_mq_get_ctx(q);
1025         if (!cpu_online(ctx->cpu))
1026                 rq->mq_ctx = ctx = current_ctx;
1027
1028         hctx = q->mq_ops->map_queue(q, ctx->cpu);
1029
1030         spin_lock(&ctx->lock);
1031         __blk_mq_insert_request(hctx, rq, at_head);
1032         spin_unlock(&ctx->lock);
1033
1034         if (run_queue)
1035                 blk_mq_run_hw_queue(hctx, async);
1036
1037         blk_mq_put_ctx(current_ctx);
1038 }
1039
1040 static void blk_mq_insert_requests(struct request_queue *q,
1041                                      struct blk_mq_ctx *ctx,
1042                                      struct list_head *list,
1043                                      int depth,
1044                                      bool from_schedule)
1045
1046 {
1047         struct blk_mq_hw_ctx *hctx;
1048         struct blk_mq_ctx *current_ctx;
1049
1050         trace_block_unplug(q, depth, !from_schedule);
1051
1052         current_ctx = blk_mq_get_ctx(q);
1053
1054         if (!cpu_online(ctx->cpu))
1055                 ctx = current_ctx;
1056         hctx = q->mq_ops->map_queue(q, ctx->cpu);
1057
1058         /*
1059          * preemption doesn't flush plug list, so it's possible ctx->cpu is
1060          * offline now
1061          */
1062         spin_lock(&ctx->lock);
1063         while (!list_empty(list)) {
1064                 struct request *rq;
1065
1066                 rq = list_first_entry(list, struct request, queuelist);
1067                 list_del_init(&rq->queuelist);
1068                 rq->mq_ctx = ctx;
1069                 __blk_mq_insert_req_list(hctx, ctx, rq, false);
1070         }
1071         blk_mq_hctx_mark_pending(hctx, ctx);
1072         spin_unlock(&ctx->lock);
1073
1074         blk_mq_run_hw_queue(hctx, from_schedule);
1075         blk_mq_put_ctx(current_ctx);
1076 }
1077
1078 static int plug_ctx_cmp(void *priv, struct list_head *a, struct list_head *b)
1079 {
1080         struct request *rqa = container_of(a, struct request, queuelist);
1081         struct request *rqb = container_of(b, struct request, queuelist);
1082
1083         return !(rqa->mq_ctx < rqb->mq_ctx ||
1084                  (rqa->mq_ctx == rqb->mq_ctx &&
1085                   blk_rq_pos(rqa) < blk_rq_pos(rqb)));
1086 }
1087
1088 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1089 {
1090         struct blk_mq_ctx *this_ctx;
1091         struct request_queue *this_q;
1092         struct request *rq;
1093         LIST_HEAD(list);
1094         LIST_HEAD(ctx_list);
1095         unsigned int depth;
1096
1097         list_splice_init(&plug->mq_list, &list);
1098
1099         list_sort(NULL, &list, plug_ctx_cmp);
1100
1101         this_q = NULL;
1102         this_ctx = NULL;
1103         depth = 0;
1104
1105         while (!list_empty(&list)) {
1106                 rq = list_entry_rq(list.next);
1107                 list_del_init(&rq->queuelist);
1108                 BUG_ON(!rq->q);
1109                 if (rq->mq_ctx != this_ctx) {
1110                         if (this_ctx) {
1111                                 blk_mq_insert_requests(this_q, this_ctx,
1112                                                         &ctx_list, depth,
1113                                                         from_schedule);
1114                         }
1115
1116                         this_ctx = rq->mq_ctx;
1117                         this_q = rq->q;
1118                         depth = 0;
1119                 }
1120
1121                 depth++;
1122                 list_add_tail(&rq->queuelist, &ctx_list);
1123         }
1124
1125         /*
1126          * If 'this_ctx' is set, we know we have entries to complete
1127          * on 'ctx_list'. Do those.
1128          */
1129         if (this_ctx) {
1130                 blk_mq_insert_requests(this_q, this_ctx, &ctx_list, depth,
1131                                        from_schedule);
1132         }
1133 }
1134
1135 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio)
1136 {
1137         init_request_from_bio(rq, bio);
1138
1139         if (blk_do_io_stat(rq))
1140                 blk_account_io_start(rq, 1);
1141 }
1142
1143 static inline bool hctx_allow_merges(struct blk_mq_hw_ctx *hctx)
1144 {
1145         return (hctx->flags & BLK_MQ_F_SHOULD_MERGE) &&
1146                 !blk_queue_nomerges(hctx->queue);
1147 }
1148
1149 static inline bool blk_mq_merge_queue_io(struct blk_mq_hw_ctx *hctx,
1150                                          struct blk_mq_ctx *ctx,
1151                                          struct request *rq, struct bio *bio)
1152 {
1153         if (!hctx_allow_merges(hctx) || !bio_mergeable(bio)) {
1154                 blk_mq_bio_to_request(rq, bio);
1155                 spin_lock(&ctx->lock);
1156 insert_rq:
1157                 __blk_mq_insert_request(hctx, rq, false);
1158                 spin_unlock(&ctx->lock);
1159                 return false;
1160         } else {
1161                 struct request_queue *q = hctx->queue;
1162
1163                 spin_lock(&ctx->lock);
1164                 if (!blk_mq_attempt_merge(q, ctx, bio)) {
1165                         blk_mq_bio_to_request(rq, bio);
1166                         goto insert_rq;
1167                 }
1168
1169                 spin_unlock(&ctx->lock);
1170                 __blk_mq_free_request(hctx, ctx, rq);
1171                 return true;
1172         }
1173 }
1174
1175 struct blk_map_ctx {
1176         struct blk_mq_hw_ctx *hctx;
1177         struct blk_mq_ctx *ctx;
1178 };
1179
1180 static struct request *blk_mq_map_request(struct request_queue *q,
1181                                           struct bio *bio,
1182                                           struct blk_map_ctx *data)
1183 {
1184         struct blk_mq_hw_ctx *hctx;
1185         struct blk_mq_ctx *ctx;
1186         struct request *rq;
1187         int rw = bio_data_dir(bio);
1188         struct blk_mq_alloc_data alloc_data;
1189
1190         blk_queue_enter_live(q);
1191         ctx = blk_mq_get_ctx(q);
1192         hctx = q->mq_ops->map_queue(q, ctx->cpu);
1193
1194         if (rw_is_sync(bio->bi_rw))
1195                 rw |= REQ_SYNC;
1196
1197         trace_block_getrq(q, bio, rw);
1198         blk_mq_set_alloc_data(&alloc_data, q, GFP_ATOMIC, false, ctx,
1199                         hctx);
1200         rq = __blk_mq_alloc_request(&alloc_data, rw);
1201         if (unlikely(!rq)) {
1202                 __blk_mq_run_hw_queue(hctx);
1203                 blk_mq_put_ctx(ctx);
1204                 trace_block_sleeprq(q, bio, rw);
1205
1206                 ctx = blk_mq_get_ctx(q);
1207                 hctx = q->mq_ops->map_queue(q, ctx->cpu);
1208                 blk_mq_set_alloc_data(&alloc_data, q,
1209                                 __GFP_RECLAIM|__GFP_HIGH, false, ctx, hctx);
1210                 rq = __blk_mq_alloc_request(&alloc_data, rw);
1211                 ctx = alloc_data.ctx;
1212                 hctx = alloc_data.hctx;
1213         }
1214
1215         hctx->queued++;
1216         data->hctx = hctx;
1217         data->ctx = ctx;
1218         return rq;
1219 }
1220
1221 static int blk_mq_direct_issue_request(struct request *rq, blk_qc_t *cookie)
1222 {
1223         int ret;
1224         struct request_queue *q = rq->q;
1225         struct blk_mq_hw_ctx *hctx = q->mq_ops->map_queue(q,
1226                         rq->mq_ctx->cpu);
1227         struct blk_mq_queue_data bd = {
1228                 .rq = rq,
1229                 .list = NULL,
1230                 .last = 1
1231         };
1232         blk_qc_t new_cookie = blk_tag_to_qc_t(rq->tag, hctx->queue_num);
1233
1234         /*
1235          * For OK queue, we are done. For error, kill it. Any other
1236          * error (busy), just add it to our list as we previously
1237          * would have done
1238          */
1239         ret = q->mq_ops->queue_rq(hctx, &bd);
1240         if (ret == BLK_MQ_RQ_QUEUE_OK) {
1241                 *cookie = new_cookie;
1242                 return 0;
1243         }
1244
1245         __blk_mq_requeue_request(rq);
1246
1247         if (ret == BLK_MQ_RQ_QUEUE_ERROR) {
1248                 *cookie = BLK_QC_T_NONE;
1249                 rq->errors = -EIO;
1250                 blk_mq_end_request(rq, rq->errors);
1251                 return 0;
1252         }
1253
1254         return -1;
1255 }
1256
1257 /*
1258  * Multiple hardware queue variant. This will not use per-process plugs,
1259  * but will attempt to bypass the hctx queueing if we can go straight to
1260  * hardware for SYNC IO.
1261  */
1262 static blk_qc_t blk_mq_make_request(struct request_queue *q, struct bio *bio)
1263 {
1264         const int is_sync = rw_is_sync(bio->bi_rw);
1265         const int is_flush_fua = bio->bi_rw & (REQ_FLUSH | REQ_FUA);
1266         struct blk_map_ctx data;
1267         struct request *rq;
1268         unsigned int request_count = 0;
1269         struct blk_plug *plug;
1270         struct request *same_queue_rq = NULL;
1271         blk_qc_t cookie;
1272
1273         blk_queue_bounce(q, &bio);
1274
1275         if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1276                 bio_io_error(bio);
1277                 return BLK_QC_T_NONE;
1278         }
1279
1280         blk_queue_split(q, &bio, q->bio_split);
1281
1282         if (!is_flush_fua && !blk_queue_nomerges(q)) {
1283                 if (blk_attempt_plug_merge(q, bio, &request_count,
1284                                            &same_queue_rq))
1285                         return BLK_QC_T_NONE;
1286         } else
1287                 request_count = blk_plug_queued_count(q);
1288
1289         rq = blk_mq_map_request(q, bio, &data);
1290         if (unlikely(!rq))
1291                 return BLK_QC_T_NONE;
1292
1293         cookie = blk_tag_to_qc_t(rq->tag, data.hctx->queue_num);
1294
1295         if (unlikely(is_flush_fua)) {
1296                 blk_mq_bio_to_request(rq, bio);
1297                 blk_insert_flush(rq);
1298                 goto run_queue;
1299         }
1300
1301         plug = current->plug;
1302         /*
1303          * If the driver supports defer issued based on 'last', then
1304          * queue it up like normal since we can potentially save some
1305          * CPU this way.
1306          */
1307         if (((plug && !blk_queue_nomerges(q)) || is_sync) &&
1308             !(data.hctx->flags & BLK_MQ_F_DEFER_ISSUE)) {
1309                 struct request *old_rq = NULL;
1310
1311                 blk_mq_bio_to_request(rq, bio);
1312
1313                 /*
1314                  * We do limited pluging. If the bio can be merged, do that.
1315                  * Otherwise the existing request in the plug list will be
1316                  * issued. So the plug list will have one request at most
1317                  */
1318                 if (plug) {
1319                         /*
1320                          * The plug list might get flushed before this. If that
1321                          * happens, same_queue_rq is invalid and plug list is
1322                          * empty
1323                          */
1324                         if (same_queue_rq && !list_empty(&plug->mq_list)) {
1325                                 old_rq = same_queue_rq;
1326                                 list_del_init(&old_rq->queuelist);
1327                         }
1328                         list_add_tail(&rq->queuelist, &plug->mq_list);
1329                 } else /* is_sync */
1330                         old_rq = rq;
1331                 blk_mq_put_ctx(data.ctx);
1332                 if (!old_rq)
1333                         goto done;
1334                 if (test_bit(BLK_MQ_S_STOPPED, &data.hctx->state) ||
1335                     blk_mq_direct_issue_request(old_rq, &cookie) != 0)
1336                         blk_mq_insert_request(old_rq, false, true, true);
1337                 goto done;
1338         }
1339
1340         if (!blk_mq_merge_queue_io(data.hctx, data.ctx, rq, bio)) {
1341                 /*
1342                  * For a SYNC request, send it to the hardware immediately. For
1343                  * an ASYNC request, just ensure that we run it later on. The
1344                  * latter allows for merging opportunities and more efficient
1345                  * dispatching.
1346                  */
1347 run_queue:
1348                 blk_mq_run_hw_queue(data.hctx, !is_sync || is_flush_fua);
1349         }
1350         blk_mq_put_ctx(data.ctx);
1351 done:
1352         return cookie;
1353 }
1354
1355 /*
1356  * Single hardware queue variant. This will attempt to use any per-process
1357  * plug for merging and IO deferral.
1358  */
1359 static blk_qc_t blk_sq_make_request(struct request_queue *q, struct bio *bio)
1360 {
1361         const int is_sync = rw_is_sync(bio->bi_rw);
1362         const int is_flush_fua = bio->bi_rw & (REQ_FLUSH | REQ_FUA);
1363         struct blk_plug *plug;
1364         unsigned int request_count = 0;
1365         struct blk_map_ctx data;
1366         struct request *rq;
1367         blk_qc_t cookie;
1368
1369         blk_queue_bounce(q, &bio);
1370
1371         if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1372                 bio_io_error(bio);
1373                 return BLK_QC_T_NONE;
1374         }
1375
1376         blk_queue_split(q, &bio, q->bio_split);
1377
1378         if (!is_flush_fua && !blk_queue_nomerges(q) &&
1379             blk_attempt_plug_merge(q, bio, &request_count, NULL))
1380                 return BLK_QC_T_NONE;
1381
1382         rq = blk_mq_map_request(q, bio, &data);
1383         if (unlikely(!rq))
1384                 return BLK_QC_T_NONE;
1385
1386         cookie = blk_tag_to_qc_t(rq->tag, data.hctx->queue_num);
1387
1388         if (unlikely(is_flush_fua)) {
1389                 blk_mq_bio_to_request(rq, bio);
1390                 blk_insert_flush(rq);
1391                 goto run_queue;
1392         }
1393
1394         /*
1395          * A task plug currently exists. Since this is completely lockless,
1396          * utilize that to temporarily store requests until the task is
1397          * either done or scheduled away.
1398          */
1399         plug = current->plug;
1400         if (plug) {
1401                 blk_mq_bio_to_request(rq, bio);
1402                 if (!request_count)
1403                         trace_block_plug(q);
1404
1405                 blk_mq_put_ctx(data.ctx);
1406
1407                 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1408                         blk_flush_plug_list(plug, false);
1409                         trace_block_plug(q);
1410                 }
1411
1412                 list_add_tail(&rq->queuelist, &plug->mq_list);
1413                 return cookie;
1414         }
1415
1416         if (!blk_mq_merge_queue_io(data.hctx, data.ctx, rq, bio)) {
1417                 /*
1418                  * For a SYNC request, send it to the hardware immediately. For
1419                  * an ASYNC request, just ensure that we run it later on. The
1420                  * latter allows for merging opportunities and more efficient
1421                  * dispatching.
1422                  */
1423 run_queue:
1424                 blk_mq_run_hw_queue(data.hctx, !is_sync || is_flush_fua);
1425         }
1426
1427         blk_mq_put_ctx(data.ctx);
1428         return cookie;
1429 }
1430
1431 /*
1432  * Default mapping to a software queue, since we use one per CPU.
1433  */
1434 struct blk_mq_hw_ctx *blk_mq_map_queue(struct request_queue *q, const int cpu)
1435 {
1436         return q->queue_hw_ctx[q->mq_map[cpu]];
1437 }
1438 EXPORT_SYMBOL(blk_mq_map_queue);
1439
1440 static void blk_mq_free_rq_map(struct blk_mq_tag_set *set,
1441                 struct blk_mq_tags *tags, unsigned int hctx_idx)
1442 {
1443         struct page *page;
1444
1445         if (tags->rqs && set->ops->exit_request) {
1446                 int i;
1447
1448                 for (i = 0; i < tags->nr_tags; i++) {
1449                         if (!tags->rqs[i])
1450                                 continue;
1451                         set->ops->exit_request(set->driver_data, tags->rqs[i],
1452                                                 hctx_idx, i);
1453                         tags->rqs[i] = NULL;
1454                 }
1455         }
1456
1457         while (!list_empty(&tags->page_list)) {
1458                 page = list_first_entry(&tags->page_list, struct page, lru);
1459                 list_del_init(&page->lru);
1460                 /*
1461                  * Remove kmemleak object previously allocated in
1462                  * blk_mq_init_rq_map().
1463                  */
1464                 kmemleak_free(page_address(page));
1465                 __free_pages(page, page->private);
1466         }
1467
1468         kfree(tags->rqs);
1469
1470         blk_mq_free_tags(tags);
1471 }
1472
1473 static size_t order_to_size(unsigned int order)
1474 {
1475         return (size_t)PAGE_SIZE << order;
1476 }
1477
1478 static struct blk_mq_tags *blk_mq_init_rq_map(struct blk_mq_tag_set *set,
1479                 unsigned int hctx_idx)
1480 {
1481         struct blk_mq_tags *tags;
1482         unsigned int i, j, entries_per_page, max_order = 4;
1483         size_t rq_size, left;
1484
1485         tags = blk_mq_init_tags(set->queue_depth, set->reserved_tags,
1486                                 set->numa_node,
1487                                 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
1488         if (!tags)
1489                 return NULL;
1490
1491         INIT_LIST_HEAD(&tags->page_list);
1492
1493         tags->rqs = kzalloc_node(set->queue_depth * sizeof(struct request *),
1494                                  GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY,
1495                                  set->numa_node);
1496         if (!tags->rqs) {
1497                 blk_mq_free_tags(tags);
1498                 return NULL;
1499         }
1500
1501         /*
1502          * rq_size is the size of the request plus driver payload, rounded
1503          * to the cacheline size
1504          */
1505         rq_size = round_up(sizeof(struct request) + set->cmd_size,
1506                                 cache_line_size());
1507         left = rq_size * set->queue_depth;
1508
1509         for (i = 0; i < set->queue_depth; ) {
1510                 int this_order = max_order;
1511                 struct page *page;
1512                 int to_do;
1513                 void *p;
1514
1515                 while (left < order_to_size(this_order - 1) && this_order)
1516                         this_order--;
1517
1518                 do {
1519                         page = alloc_pages_node(set->numa_node,
1520                                 GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
1521                                 this_order);
1522                         if (page)
1523                                 break;
1524                         if (!this_order--)
1525                                 break;
1526                         if (order_to_size(this_order) < rq_size)
1527                                 break;
1528                 } while (1);
1529
1530                 if (!page)
1531                         goto fail;
1532
1533                 page->private = this_order;
1534                 list_add_tail(&page->lru, &tags->page_list);
1535
1536                 p = page_address(page);
1537                 /*
1538                  * Allow kmemleak to scan these pages as they contain pointers
1539                  * to additional allocations like via ops->init_request().
1540                  */
1541                 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_KERNEL);
1542                 entries_per_page = order_to_size(this_order) / rq_size;
1543                 to_do = min(entries_per_page, set->queue_depth - i);
1544                 left -= to_do * rq_size;
1545                 for (j = 0; j < to_do; j++) {
1546                         tags->rqs[i] = p;
1547                         if (set->ops->init_request) {
1548                                 if (set->ops->init_request(set->driver_data,
1549                                                 tags->rqs[i], hctx_idx, i,
1550                                                 set->numa_node)) {
1551                                         tags->rqs[i] = NULL;
1552                                         goto fail;
1553                                 }
1554                         }
1555
1556                         p += rq_size;
1557                         i++;
1558                 }
1559         }
1560         return tags;
1561
1562 fail:
1563         blk_mq_free_rq_map(set, tags, hctx_idx);
1564         return NULL;
1565 }
1566
1567 static void blk_mq_free_bitmap(struct blk_mq_ctxmap *bitmap)
1568 {
1569         kfree(bitmap->map);
1570 }
1571
1572 static int blk_mq_alloc_bitmap(struct blk_mq_ctxmap *bitmap, int node)
1573 {
1574         unsigned int bpw = 8, total, num_maps, i;
1575
1576         bitmap->bits_per_word = bpw;
1577
1578         num_maps = ALIGN(nr_cpu_ids, bpw) / bpw;
1579         bitmap->map = kzalloc_node(num_maps * sizeof(struct blk_align_bitmap),
1580                                         GFP_KERNEL, node);
1581         if (!bitmap->map)
1582                 return -ENOMEM;
1583
1584         total = nr_cpu_ids;
1585         for (i = 0; i < num_maps; i++) {
1586                 bitmap->map[i].depth = min(total, bitmap->bits_per_word);
1587                 total -= bitmap->map[i].depth;
1588         }
1589
1590         return 0;
1591 }
1592
1593 static int blk_mq_hctx_cpu_offline(struct blk_mq_hw_ctx *hctx, int cpu)
1594 {
1595         struct request_queue *q = hctx->queue;
1596         struct blk_mq_ctx *ctx;
1597         LIST_HEAD(tmp);
1598
1599         /*
1600          * Move ctx entries to new CPU, if this one is going away.
1601          */
1602         ctx = __blk_mq_get_ctx(q, cpu);
1603
1604         spin_lock(&ctx->lock);
1605         if (!list_empty(&ctx->rq_list)) {
1606                 list_splice_init(&ctx->rq_list, &tmp);
1607                 blk_mq_hctx_clear_pending(hctx, ctx);
1608         }
1609         spin_unlock(&ctx->lock);
1610
1611         if (list_empty(&tmp))
1612                 return NOTIFY_OK;
1613
1614         ctx = blk_mq_get_ctx(q);
1615         spin_lock(&ctx->lock);
1616
1617         while (!list_empty(&tmp)) {
1618                 struct request *rq;
1619
1620                 rq = list_first_entry(&tmp, struct request, queuelist);
1621                 rq->mq_ctx = ctx;
1622                 list_move_tail(&rq->queuelist, &ctx->rq_list);
1623         }
1624
1625         hctx = q->mq_ops->map_queue(q, ctx->cpu);
1626         blk_mq_hctx_mark_pending(hctx, ctx);
1627
1628         spin_unlock(&ctx->lock);
1629
1630         blk_mq_run_hw_queue(hctx, true);
1631         blk_mq_put_ctx(ctx);
1632         return NOTIFY_OK;
1633 }
1634
1635 static int blk_mq_hctx_notify(void *data, unsigned long action,
1636                               unsigned int cpu)
1637 {
1638         struct blk_mq_hw_ctx *hctx = data;
1639
1640         if (action == CPU_POST_DEAD)
1641                 return blk_mq_hctx_cpu_offline(hctx, cpu);
1642
1643         /*
1644          * In case of CPU online, tags may be reallocated
1645          * in blk_mq_map_swqueue() after mapping is updated.
1646          */
1647
1648         return NOTIFY_OK;
1649 }
1650
1651 /* hctx->ctxs will be freed in queue's release handler */
1652 static void blk_mq_exit_hctx(struct request_queue *q,
1653                 struct blk_mq_tag_set *set,
1654                 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
1655 {
1656         unsigned flush_start_tag = set->queue_depth;
1657
1658         blk_mq_tag_idle(hctx);
1659
1660         if (set->ops->exit_request)
1661                 set->ops->exit_request(set->driver_data,
1662                                        hctx->fq->flush_rq, hctx_idx,
1663                                        flush_start_tag + hctx_idx);
1664
1665         if (set->ops->exit_hctx)
1666                 set->ops->exit_hctx(hctx, hctx_idx);
1667
1668         blk_mq_unregister_cpu_notifier(&hctx->cpu_notifier);
1669         blk_free_flush_queue(hctx->fq);
1670         blk_mq_free_bitmap(&hctx->ctx_map);
1671 }
1672
1673 static void blk_mq_exit_hw_queues(struct request_queue *q,
1674                 struct blk_mq_tag_set *set, int nr_queue)
1675 {
1676         struct blk_mq_hw_ctx *hctx;
1677         unsigned int i;
1678
1679         queue_for_each_hw_ctx(q, hctx, i) {
1680                 if (i == nr_queue)
1681                         break;
1682                 blk_mq_exit_hctx(q, set, hctx, i);
1683         }
1684 }
1685
1686 static void blk_mq_free_hw_queues(struct request_queue *q,
1687                 struct blk_mq_tag_set *set)
1688 {
1689         struct blk_mq_hw_ctx *hctx;
1690         unsigned int i;
1691
1692         queue_for_each_hw_ctx(q, hctx, i)
1693                 free_cpumask_var(hctx->cpumask);
1694 }
1695
1696 static int blk_mq_init_hctx(struct request_queue *q,
1697                 struct blk_mq_tag_set *set,
1698                 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
1699 {
1700         int node;
1701         unsigned flush_start_tag = set->queue_depth;
1702
1703         node = hctx->numa_node;
1704         if (node == NUMA_NO_NODE)
1705                 node = hctx->numa_node = set->numa_node;
1706
1707         INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
1708         INIT_DELAYED_WORK(&hctx->delay_work, blk_mq_delay_work_fn);
1709         spin_lock_init(&hctx->lock);
1710         INIT_LIST_HEAD(&hctx->dispatch);
1711         hctx->queue = q;
1712         hctx->queue_num = hctx_idx;
1713         hctx->flags = set->flags & ~BLK_MQ_F_TAG_SHARED;
1714
1715         blk_mq_init_cpu_notifier(&hctx->cpu_notifier,
1716                                         blk_mq_hctx_notify, hctx);
1717         blk_mq_register_cpu_notifier(&hctx->cpu_notifier);
1718
1719         hctx->tags = set->tags[hctx_idx];
1720
1721         /*
1722          * Allocate space for all possible cpus to avoid allocation at
1723          * runtime
1724          */
1725         hctx->ctxs = kmalloc_node(nr_cpu_ids * sizeof(void *),
1726                                         GFP_KERNEL, node);
1727         if (!hctx->ctxs)
1728                 goto unregister_cpu_notifier;
1729
1730         if (blk_mq_alloc_bitmap(&hctx->ctx_map, node))
1731                 goto free_ctxs;
1732
1733         hctx->nr_ctx = 0;
1734
1735         if (set->ops->init_hctx &&
1736             set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
1737                 goto free_bitmap;
1738
1739         hctx->fq = blk_alloc_flush_queue(q, hctx->numa_node, set->cmd_size);
1740         if (!hctx->fq)
1741                 goto exit_hctx;
1742
1743         if (set->ops->init_request &&
1744             set->ops->init_request(set->driver_data,
1745                                    hctx->fq->flush_rq, hctx_idx,
1746                                    flush_start_tag + hctx_idx, node))
1747                 goto free_fq;
1748
1749         return 0;
1750
1751  free_fq:
1752         kfree(hctx->fq);
1753  exit_hctx:
1754         if (set->ops->exit_hctx)
1755                 set->ops->exit_hctx(hctx, hctx_idx);
1756  free_bitmap:
1757         blk_mq_free_bitmap(&hctx->ctx_map);
1758  free_ctxs:
1759         kfree(hctx->ctxs);
1760  unregister_cpu_notifier:
1761         blk_mq_unregister_cpu_notifier(&hctx->cpu_notifier);
1762
1763         return -1;
1764 }
1765
1766 static int blk_mq_init_hw_queues(struct request_queue *q,
1767                 struct blk_mq_tag_set *set)
1768 {
1769         struct blk_mq_hw_ctx *hctx;
1770         unsigned int i;
1771
1772         /*
1773          * Initialize hardware queues
1774          */
1775         queue_for_each_hw_ctx(q, hctx, i) {
1776                 if (blk_mq_init_hctx(q, set, hctx, i))
1777                         break;
1778         }
1779
1780         if (i == q->nr_hw_queues)
1781                 return 0;
1782
1783         /*
1784          * Init failed
1785          */
1786         blk_mq_exit_hw_queues(q, set, i);
1787
1788         return 1;
1789 }
1790
1791 static void blk_mq_init_cpu_queues(struct request_queue *q,
1792                                    unsigned int nr_hw_queues)
1793 {
1794         unsigned int i;
1795
1796         for_each_possible_cpu(i) {
1797                 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
1798                 struct blk_mq_hw_ctx *hctx;
1799
1800                 memset(__ctx, 0, sizeof(*__ctx));
1801                 __ctx->cpu = i;
1802                 spin_lock_init(&__ctx->lock);
1803                 INIT_LIST_HEAD(&__ctx->rq_list);
1804                 __ctx->queue = q;
1805
1806                 /* If the cpu isn't online, the cpu is mapped to first hctx */
1807                 if (!cpu_online(i))
1808                         continue;
1809
1810                 hctx = q->mq_ops->map_queue(q, i);
1811
1812                 /*
1813                  * Set local node, IFF we have more than one hw queue. If
1814                  * not, we remain on the home node of the device
1815                  */
1816                 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
1817                         hctx->numa_node = cpu_to_node(i);
1818         }
1819 }
1820
1821 static void blk_mq_map_swqueue(struct request_queue *q,
1822                                const struct cpumask *online_mask)
1823 {
1824         unsigned int i;
1825         struct blk_mq_hw_ctx *hctx;
1826         struct blk_mq_ctx *ctx;
1827         struct blk_mq_tag_set *set = q->tag_set;
1828
1829         /*
1830          * Avoid others reading imcomplete hctx->cpumask through sysfs
1831          */
1832         mutex_lock(&q->sysfs_lock);
1833
1834         queue_for_each_hw_ctx(q, hctx, i) {
1835                 cpumask_clear(hctx->cpumask);
1836                 hctx->nr_ctx = 0;
1837         }
1838
1839         /*
1840          * Map software to hardware queues
1841          */
1842         queue_for_each_ctx(q, ctx, i) {
1843                 /* If the cpu isn't online, the cpu is mapped to first hctx */
1844                 if (!cpumask_test_cpu(i, online_mask))
1845                         continue;
1846
1847                 hctx = q->mq_ops->map_queue(q, i);
1848                 cpumask_set_cpu(i, hctx->cpumask);
1849                 ctx->index_hw = hctx->nr_ctx;
1850                 hctx->ctxs[hctx->nr_ctx++] = ctx;
1851         }
1852
1853         mutex_unlock(&q->sysfs_lock);
1854
1855         queue_for_each_hw_ctx(q, hctx, i) {
1856                 struct blk_mq_ctxmap *map = &hctx->ctx_map;
1857
1858                 /*
1859                  * If no software queues are mapped to this hardware queue,
1860                  * disable it and free the request entries.
1861                  */
1862                 if (!hctx->nr_ctx) {
1863                         if (set->tags[i]) {
1864                                 blk_mq_free_rq_map(set, set->tags[i], i);
1865                                 set->tags[i] = NULL;
1866                         }
1867                         hctx->tags = NULL;
1868                         continue;
1869                 }
1870
1871                 /* unmapped hw queue can be remapped after CPU topo changed */
1872                 if (!set->tags[i])
1873                         set->tags[i] = blk_mq_init_rq_map(set, i);
1874                 hctx->tags = set->tags[i];
1875                 WARN_ON(!hctx->tags);
1876
1877                 /*
1878                  * Set the map size to the number of mapped software queues.
1879                  * This is more accurate and more efficient than looping
1880                  * over all possibly mapped software queues.
1881                  */
1882                 map->size = DIV_ROUND_UP(hctx->nr_ctx, map->bits_per_word);
1883
1884                 /*
1885                  * Initialize batch roundrobin counts
1886                  */
1887                 hctx->next_cpu = cpumask_first(hctx->cpumask);
1888                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1889         }
1890
1891         queue_for_each_ctx(q, ctx, i) {
1892                 if (!cpumask_test_cpu(i, online_mask))
1893                         continue;
1894
1895                 hctx = q->mq_ops->map_queue(q, i);
1896                 cpumask_set_cpu(i, hctx->tags->cpumask);
1897         }
1898 }
1899
1900 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
1901 {
1902         struct blk_mq_hw_ctx *hctx;
1903         int i;
1904
1905         queue_for_each_hw_ctx(q, hctx, i) {
1906                 if (shared)
1907                         hctx->flags |= BLK_MQ_F_TAG_SHARED;
1908                 else
1909                         hctx->flags &= ~BLK_MQ_F_TAG_SHARED;
1910         }
1911 }
1912
1913 static void blk_mq_update_tag_set_depth(struct blk_mq_tag_set *set, bool shared)
1914 {
1915         struct request_queue *q;
1916
1917         list_for_each_entry(q, &set->tag_list, tag_set_list) {
1918                 blk_mq_freeze_queue(q);
1919                 queue_set_hctx_shared(q, shared);
1920                 blk_mq_unfreeze_queue(q);
1921         }
1922 }
1923
1924 static void blk_mq_del_queue_tag_set(struct request_queue *q)
1925 {
1926         struct blk_mq_tag_set *set = q->tag_set;
1927
1928         mutex_lock(&set->tag_list_lock);
1929         list_del_init(&q->tag_set_list);
1930         if (list_is_singular(&set->tag_list)) {
1931                 /* just transitioned to unshared */
1932                 set->flags &= ~BLK_MQ_F_TAG_SHARED;
1933                 /* update existing queue */
1934                 blk_mq_update_tag_set_depth(set, false);
1935         }
1936         mutex_unlock(&set->tag_list_lock);
1937 }
1938
1939 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
1940                                      struct request_queue *q)
1941 {
1942         q->tag_set = set;
1943
1944         mutex_lock(&set->tag_list_lock);
1945
1946         /* Check to see if we're transitioning to shared (from 1 to 2 queues). */
1947         if (!list_empty(&set->tag_list) && !(set->flags & BLK_MQ_F_TAG_SHARED)) {
1948                 set->flags |= BLK_MQ_F_TAG_SHARED;
1949                 /* update existing queue */
1950                 blk_mq_update_tag_set_depth(set, true);
1951         }
1952         if (set->flags & BLK_MQ_F_TAG_SHARED)
1953                 queue_set_hctx_shared(q, true);
1954         list_add_tail(&q->tag_set_list, &set->tag_list);
1955
1956         mutex_unlock(&set->tag_list_lock);
1957 }
1958
1959 /*
1960  * It is the actual release handler for mq, but we do it from
1961  * request queue's release handler for avoiding use-after-free
1962  * and headache because q->mq_kobj shouldn't have been introduced,
1963  * but we can't group ctx/kctx kobj without it.
1964  */
1965 void blk_mq_release(struct request_queue *q)
1966 {
1967         struct blk_mq_hw_ctx *hctx;
1968         unsigned int i;
1969
1970         /* hctx kobj stays in hctx */
1971         queue_for_each_hw_ctx(q, hctx, i) {
1972                 if (!hctx)
1973                         continue;
1974                 kfree(hctx->ctxs);
1975                 kfree(hctx);
1976         }
1977
1978         kfree(q->mq_map);
1979         q->mq_map = NULL;
1980
1981         kfree(q->queue_hw_ctx);
1982
1983         /* ctx kobj stays in queue_ctx */
1984         free_percpu(q->queue_ctx);
1985 }
1986
1987 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
1988 {
1989         struct request_queue *uninit_q, *q;
1990
1991         uninit_q = blk_alloc_queue_node(GFP_KERNEL, set->numa_node);
1992         if (!uninit_q)
1993                 return ERR_PTR(-ENOMEM);
1994
1995         q = blk_mq_init_allocated_queue(set, uninit_q);
1996         if (IS_ERR(q))
1997                 blk_cleanup_queue(uninit_q);
1998
1999         return q;
2000 }
2001 EXPORT_SYMBOL(blk_mq_init_queue);
2002
2003 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
2004                                                   struct request_queue *q)
2005 {
2006         struct blk_mq_hw_ctx **hctxs;
2007         struct blk_mq_ctx __percpu *ctx;
2008         unsigned int *map;
2009         int i;
2010
2011         ctx = alloc_percpu(struct blk_mq_ctx);
2012         if (!ctx)
2013                 return ERR_PTR(-ENOMEM);
2014
2015         hctxs = kmalloc_node(set->nr_hw_queues * sizeof(*hctxs), GFP_KERNEL,
2016                         set->numa_node);
2017
2018         if (!hctxs)
2019                 goto err_percpu;
2020
2021         map = blk_mq_make_queue_map(set);
2022         if (!map)
2023                 goto err_map;
2024
2025         for (i = 0; i < set->nr_hw_queues; i++) {
2026                 int node = blk_mq_hw_queue_to_node(map, i);
2027
2028                 hctxs[i] = kzalloc_node(sizeof(struct blk_mq_hw_ctx),
2029                                         GFP_KERNEL, node);
2030                 if (!hctxs[i])
2031                         goto err_hctxs;
2032
2033                 if (!zalloc_cpumask_var_node(&hctxs[i]->cpumask, GFP_KERNEL,
2034                                                 node))
2035                         goto err_hctxs;
2036
2037                 atomic_set(&hctxs[i]->nr_active, 0);
2038                 hctxs[i]->numa_node = node;
2039                 hctxs[i]->queue_num = i;
2040         }
2041
2042         setup_timer(&q->timeout, blk_mq_rq_timer, (unsigned long) q);
2043         blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
2044
2045         q->nr_queues = nr_cpu_ids;
2046         q->nr_hw_queues = set->nr_hw_queues;
2047         q->mq_map = map;
2048
2049         q->queue_ctx = ctx;
2050         q->queue_hw_ctx = hctxs;
2051
2052         q->mq_ops = set->ops;
2053         q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
2054
2055         if (!(set->flags & BLK_MQ_F_SG_MERGE))
2056                 q->queue_flags |= 1 << QUEUE_FLAG_NO_SG_MERGE;
2057
2058         q->sg_reserved_size = INT_MAX;
2059
2060         INIT_WORK(&q->requeue_work, blk_mq_requeue_work);
2061         INIT_LIST_HEAD(&q->requeue_list);
2062         spin_lock_init(&q->requeue_lock);
2063
2064         if (q->nr_hw_queues > 1)
2065                 blk_queue_make_request(q, blk_mq_make_request);
2066         else
2067                 blk_queue_make_request(q, blk_sq_make_request);
2068
2069         /*
2070          * Do this after blk_queue_make_request() overrides it...
2071          */
2072         q->nr_requests = set->queue_depth;
2073
2074         if (set->ops->complete)
2075                 blk_queue_softirq_done(q, set->ops->complete);
2076
2077         blk_mq_init_cpu_queues(q, set->nr_hw_queues);
2078
2079         if (blk_mq_init_hw_queues(q, set))
2080                 goto err_hctxs;
2081
2082         get_online_cpus();
2083         mutex_lock(&all_q_mutex);
2084
2085         list_add_tail(&q->all_q_node, &all_q_list);
2086         blk_mq_add_queue_tag_set(set, q);
2087         blk_mq_map_swqueue(q, cpu_online_mask);
2088
2089         mutex_unlock(&all_q_mutex);
2090         put_online_cpus();
2091
2092         return q;
2093
2094 err_hctxs:
2095         kfree(map);
2096         for (i = 0; i < set->nr_hw_queues; i++) {
2097                 if (!hctxs[i])
2098                         break;
2099                 free_cpumask_var(hctxs[i]->cpumask);
2100                 kfree(hctxs[i]);
2101         }
2102 err_map:
2103         kfree(hctxs);
2104 err_percpu:
2105         free_percpu(ctx);
2106         return ERR_PTR(-ENOMEM);
2107 }
2108 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
2109
2110 void blk_mq_free_queue(struct request_queue *q)
2111 {
2112         struct blk_mq_tag_set   *set = q->tag_set;
2113
2114         mutex_lock(&all_q_mutex);
2115         list_del_init(&q->all_q_node);
2116         mutex_unlock(&all_q_mutex);
2117
2118         blk_mq_del_queue_tag_set(q);
2119
2120         blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
2121         blk_mq_free_hw_queues(q, set);
2122 }
2123
2124 /* Basically redo blk_mq_init_queue with queue frozen */
2125 static void blk_mq_queue_reinit(struct request_queue *q,
2126                                 const struct cpumask *online_mask)
2127 {
2128         WARN_ON_ONCE(!atomic_read(&q->mq_freeze_depth));
2129
2130         blk_mq_sysfs_unregister(q);
2131
2132         blk_mq_update_queue_map(q->mq_map, q->nr_hw_queues, online_mask);
2133
2134         /*
2135          * redo blk_mq_init_cpu_queues and blk_mq_init_hw_queues. FIXME: maybe
2136          * we should change hctx numa_node according to new topology (this
2137          * involves free and re-allocate memory, worthy doing?)
2138          */
2139
2140         blk_mq_map_swqueue(q, online_mask);
2141
2142         blk_mq_sysfs_register(q);
2143 }
2144
2145 static int blk_mq_queue_reinit_notify(struct notifier_block *nb,
2146                                       unsigned long action, void *hcpu)
2147 {
2148         struct request_queue *q;
2149         int cpu = (unsigned long)hcpu;
2150         /*
2151          * New online cpumask which is going to be set in this hotplug event.
2152          * Declare this cpumasks as global as cpu-hotplug operation is invoked
2153          * one-by-one and dynamically allocating this could result in a failure.
2154          */
2155         static struct cpumask online_new;
2156
2157         /*
2158          * Before hotadded cpu starts handling requests, new mappings must
2159          * be established.  Otherwise, these requests in hw queue might
2160          * never be dispatched.
2161          *
2162          * For example, there is a single hw queue (hctx) and two CPU queues
2163          * (ctx0 for CPU0, and ctx1 for CPU1).
2164          *
2165          * Now CPU1 is just onlined and a request is inserted into
2166          * ctx1->rq_list and set bit0 in pending bitmap as ctx1->index_hw is
2167          * still zero.
2168          *
2169          * And then while running hw queue, flush_busy_ctxs() finds bit0 is
2170          * set in pending bitmap and tries to retrieve requests in
2171          * hctx->ctxs[0]->rq_list.  But htx->ctxs[0] is a pointer to ctx0,
2172          * so the request in ctx1->rq_list is ignored.
2173          */
2174         switch (action & ~CPU_TASKS_FROZEN) {
2175         case CPU_DEAD:
2176         case CPU_UP_CANCELED:
2177                 cpumask_copy(&online_new, cpu_online_mask);
2178                 break;
2179         case CPU_UP_PREPARE:
2180                 cpumask_copy(&online_new, cpu_online_mask);
2181                 cpumask_set_cpu(cpu, &online_new);
2182                 break;
2183         default:
2184                 return NOTIFY_OK;
2185         }
2186
2187         mutex_lock(&all_q_mutex);
2188
2189         /*
2190          * We need to freeze and reinit all existing queues.  Freezing
2191          * involves synchronous wait for an RCU grace period and doing it
2192          * one by one may take a long time.  Start freezing all queues in
2193          * one swoop and then wait for the completions so that freezing can
2194          * take place in parallel.
2195          */
2196         list_for_each_entry(q, &all_q_list, all_q_node)
2197                 blk_mq_freeze_queue_start(q);
2198         list_for_each_entry(q, &all_q_list, all_q_node) {
2199                 blk_mq_freeze_queue_wait(q);
2200
2201                 /*
2202                  * timeout handler can't touch hw queue during the
2203                  * reinitialization
2204                  */
2205                 del_timer_sync(&q->timeout);
2206         }
2207
2208         list_for_each_entry(q, &all_q_list, all_q_node)
2209                 blk_mq_queue_reinit(q, &online_new);
2210
2211         list_for_each_entry(q, &all_q_list, all_q_node)
2212                 blk_mq_unfreeze_queue(q);
2213
2214         mutex_unlock(&all_q_mutex);
2215         return NOTIFY_OK;
2216 }
2217
2218 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2219 {
2220         int i;
2221
2222         for (i = 0; i < set->nr_hw_queues; i++) {
2223                 set->tags[i] = blk_mq_init_rq_map(set, i);
2224                 if (!set->tags[i])
2225                         goto out_unwind;
2226         }
2227
2228         return 0;
2229
2230 out_unwind:
2231         while (--i >= 0)
2232                 blk_mq_free_rq_map(set, set->tags[i], i);
2233
2234         return -ENOMEM;
2235 }
2236
2237 /*
2238  * Allocate the request maps associated with this tag_set. Note that this
2239  * may reduce the depth asked for, if memory is tight. set->queue_depth
2240  * will be updated to reflect the allocated depth.
2241  */
2242 static int blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2243 {
2244         unsigned int depth;
2245         int err;
2246
2247         depth = set->queue_depth;
2248         do {
2249                 err = __blk_mq_alloc_rq_maps(set);
2250                 if (!err)
2251                         break;
2252
2253                 set->queue_depth >>= 1;
2254                 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
2255                         err = -ENOMEM;
2256                         break;
2257                 }
2258         } while (set->queue_depth);
2259
2260         if (!set->queue_depth || err) {
2261                 pr_err("blk-mq: failed to allocate request map\n");
2262                 return -ENOMEM;
2263         }
2264
2265         if (depth != set->queue_depth)
2266                 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
2267                                                 depth, set->queue_depth);
2268
2269         return 0;
2270 }
2271
2272 struct cpumask *blk_mq_tags_cpumask(struct blk_mq_tags *tags)
2273 {
2274         return tags->cpumask;
2275 }
2276 EXPORT_SYMBOL_GPL(blk_mq_tags_cpumask);
2277
2278 /*
2279  * Alloc a tag set to be associated with one or more request queues.
2280  * May fail with EINVAL for various error conditions. May adjust the
2281  * requested depth down, if if it too large. In that case, the set
2282  * value will be stored in set->queue_depth.
2283  */
2284 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
2285 {
2286         BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
2287
2288         if (!set->nr_hw_queues)
2289                 return -EINVAL;
2290         if (!set->queue_depth)
2291                 return -EINVAL;
2292         if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
2293                 return -EINVAL;
2294
2295         if (!set->ops->queue_rq || !set->ops->map_queue)
2296                 return -EINVAL;
2297
2298         if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
2299                 pr_info("blk-mq: reduced tag depth to %u\n",
2300                         BLK_MQ_MAX_DEPTH);
2301                 set->queue_depth = BLK_MQ_MAX_DEPTH;
2302         }
2303
2304         /*
2305          * If a crashdump is active, then we are potentially in a very
2306          * memory constrained environment. Limit us to 1 queue and
2307          * 64 tags to prevent using too much memory.
2308          */
2309         if (is_kdump_kernel()) {
2310                 set->nr_hw_queues = 1;
2311                 set->queue_depth = min(64U, set->queue_depth);
2312         }
2313
2314         set->tags = kmalloc_node(set->nr_hw_queues *
2315                                  sizeof(struct blk_mq_tags *),
2316                                  GFP_KERNEL, set->numa_node);
2317         if (!set->tags)
2318                 return -ENOMEM;
2319
2320         if (blk_mq_alloc_rq_maps(set))
2321                 goto enomem;
2322
2323         mutex_init(&set->tag_list_lock);
2324         INIT_LIST_HEAD(&set->tag_list);
2325
2326         return 0;
2327 enomem:
2328         kfree(set->tags);
2329         set->tags = NULL;
2330         return -ENOMEM;
2331 }
2332 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
2333
2334 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
2335 {
2336         int i;
2337
2338         for (i = 0; i < set->nr_hw_queues; i++) {
2339                 if (set->tags[i])
2340                         blk_mq_free_rq_map(set, set->tags[i], i);
2341         }
2342
2343         kfree(set->tags);
2344         set->tags = NULL;
2345 }
2346 EXPORT_SYMBOL(blk_mq_free_tag_set);
2347
2348 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
2349 {
2350         struct blk_mq_tag_set *set = q->tag_set;
2351         struct blk_mq_hw_ctx *hctx;
2352         int i, ret;
2353
2354         if (!set || nr > set->queue_depth)
2355                 return -EINVAL;
2356
2357         ret = 0;
2358         queue_for_each_hw_ctx(q, hctx, i) {
2359                 ret = blk_mq_tag_update_depth(hctx->tags, nr);
2360                 if (ret)
2361                         break;
2362         }
2363
2364         if (!ret)
2365                 q->nr_requests = nr;
2366
2367         return ret;
2368 }
2369
2370 void blk_mq_disable_hotplug(void)
2371 {
2372         mutex_lock(&all_q_mutex);
2373 }
2374
2375 void blk_mq_enable_hotplug(void)
2376 {
2377         mutex_unlock(&all_q_mutex);
2378 }
2379
2380 static int __init blk_mq_init(void)
2381 {
2382         blk_mq_cpu_init();
2383
2384         hotcpu_notifier(blk_mq_queue_reinit_notify, 0);
2385
2386         return 0;
2387 }
2388 subsys_initcall(blk_mq_init);