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