~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/block/blk-mq.c

Version: ~ [ linux-5.4.2 ] ~ [ linux-5.3.15 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.88 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.158 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.206 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.206 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.78 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp