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

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

Version: ~ [ linux-5.2-rc1 ] ~ [ linux-5.1.2 ] ~ [ linux-5.0.16 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.43 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.119 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.176 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.179 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.139 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.67 ] ~ [ 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.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ 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 bool blk_mq_poll(struct request_queue *q, blk_qc_t cookie);
 41 static void blk_mq_poll_stats_start(struct request_queue *q);
 42 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
 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 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
 65 {
 66         return !list_empty_careful(&hctx->dispatch) ||
 67                 sbitmap_any_bit_set(&hctx->ctx_map) ||
 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 struct mq_inflight {
 88         struct hd_struct *part;
 89         unsigned int *inflight;
 90 };
 91 
 92 static void blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
 93                                   struct request *rq, void *priv,
 94                                   bool reserved)
 95 {
 96         struct mq_inflight *mi = priv;
 97 
 98         if (blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT) {
 99                 /*
100                  * index[0] counts the specific partition that was asked
101                  * for. index[1] counts the ones that are active on the
102                  * whole device, so increment that if mi->part is indeed
103                  * a partition, and not a whole device.
104                  */
105                 if (rq->part == mi->part)
106                         mi->inflight[0]++;
107                 if (mi->part->partno)
108                         mi->inflight[1]++;
109         }
110 }
111 
112 void blk_mq_in_flight(struct request_queue *q, struct hd_struct *part,
113                       unsigned int inflight[2])
114 {
115         struct mq_inflight mi = { .part = part, .inflight = inflight, };
116 
117         inflight[0] = inflight[1] = 0;
118         blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
119 }
120 
121 static void blk_mq_check_inflight_rw(struct blk_mq_hw_ctx *hctx,
122                                      struct request *rq, void *priv,
123                                      bool reserved)
124 {
125         struct mq_inflight *mi = priv;
126 
127         if (rq->part == mi->part)
128                 mi->inflight[rq_data_dir(rq)]++;
129 }
130 
131 void blk_mq_in_flight_rw(struct request_queue *q, struct hd_struct *part,
132                          unsigned int inflight[2])
133 {
134         struct mq_inflight mi = { .part = part, .inflight = inflight, };
135 
136         inflight[0] = inflight[1] = 0;
137         blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight_rw, &mi);
138 }
139 
140 void blk_freeze_queue_start(struct request_queue *q)
141 {
142         int freeze_depth;
143 
144         freeze_depth = atomic_inc_return(&q->mq_freeze_depth);
145         if (freeze_depth == 1) {
146                 percpu_ref_kill(&q->q_usage_counter);
147                 if (q->mq_ops)
148                         blk_mq_run_hw_queues(q, false);
149         }
150 }
151 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
152 
153 void blk_mq_freeze_queue_wait(struct request_queue *q)
154 {
155         wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
156 }
157 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
158 
159 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
160                                      unsigned long timeout)
161 {
162         return wait_event_timeout(q->mq_freeze_wq,
163                                         percpu_ref_is_zero(&q->q_usage_counter),
164                                         timeout);
165 }
166 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
167 
168 /*
169  * Guarantee no request is in use, so we can change any data structure of
170  * the queue afterward.
171  */
172 void blk_freeze_queue(struct request_queue *q)
173 {
174         /*
175          * In the !blk_mq case we are only calling this to kill the
176          * q_usage_counter, otherwise this increases the freeze depth
177          * and waits for it to return to zero.  For this reason there is
178          * no blk_unfreeze_queue(), and blk_freeze_queue() is not
179          * exported to drivers as the only user for unfreeze is blk_mq.
180          */
181         blk_freeze_queue_start(q);
182         if (!q->mq_ops)
183                 blk_drain_queue(q);
184         blk_mq_freeze_queue_wait(q);
185 }
186 
187 void blk_mq_freeze_queue(struct request_queue *q)
188 {
189         /*
190          * ...just an alias to keep freeze and unfreeze actions balanced
191          * in the blk_mq_* namespace
192          */
193         blk_freeze_queue(q);
194 }
195 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
196 
197 void blk_mq_unfreeze_queue(struct request_queue *q)
198 {
199         int freeze_depth;
200 
201         freeze_depth = atomic_dec_return(&q->mq_freeze_depth);
202         WARN_ON_ONCE(freeze_depth < 0);
203         if (!freeze_depth) {
204                 percpu_ref_reinit(&q->q_usage_counter);
205                 wake_up_all(&q->mq_freeze_wq);
206         }
207 }
208 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
209 
210 /*
211  * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
212  * mpt3sas driver such that this function can be removed.
213  */
214 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
215 {
216         unsigned long flags;
217 
218         spin_lock_irqsave(q->queue_lock, flags);
219         queue_flag_set(QUEUE_FLAG_QUIESCED, q);
220         spin_unlock_irqrestore(q->queue_lock, flags);
221 }
222 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
223 
224 /**
225  * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
226  * @q: request queue.
227  *
228  * Note: this function does not prevent that the struct request end_io()
229  * callback function is invoked. Once this function is returned, we make
230  * sure no dispatch can happen until the queue is unquiesced via
231  * blk_mq_unquiesce_queue().
232  */
233 void blk_mq_quiesce_queue(struct request_queue *q)
234 {
235         struct blk_mq_hw_ctx *hctx;
236         unsigned int i;
237         bool rcu = false;
238 
239         blk_mq_quiesce_queue_nowait(q);
240 
241         queue_for_each_hw_ctx(q, hctx, i) {
242                 if (hctx->flags & BLK_MQ_F_BLOCKING)
243                         synchronize_srcu(hctx->srcu);
244                 else
245                         rcu = true;
246         }
247         if (rcu)
248                 synchronize_rcu();
249 }
250 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
251 
252 /*
253  * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
254  * @q: request queue.
255  *
256  * This function recovers queue into the state before quiescing
257  * which is done by blk_mq_quiesce_queue.
258  */
259 void blk_mq_unquiesce_queue(struct request_queue *q)
260 {
261         unsigned long flags;
262 
263         spin_lock_irqsave(q->queue_lock, flags);
264         queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
265         spin_unlock_irqrestore(q->queue_lock, flags);
266 
267         /* dispatch requests which are inserted during quiescing */
268         blk_mq_run_hw_queues(q, true);
269 }
270 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
271 
272 void blk_mq_wake_waiters(struct request_queue *q)
273 {
274         struct blk_mq_hw_ctx *hctx;
275         unsigned int i;
276 
277         queue_for_each_hw_ctx(q, hctx, i)
278                 if (blk_mq_hw_queue_mapped(hctx))
279                         blk_mq_tag_wakeup_all(hctx->tags, true);
280 }
281 
282 bool blk_mq_can_queue(struct blk_mq_hw_ctx *hctx)
283 {
284         return blk_mq_has_free_tags(hctx->tags);
285 }
286 EXPORT_SYMBOL(blk_mq_can_queue);
287 
288 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
289                 unsigned int tag, unsigned int op)
290 {
291         struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
292         struct request *rq = tags->static_rqs[tag];
293         req_flags_t rq_flags = 0;
294 
295         if (data->flags & BLK_MQ_REQ_INTERNAL) {
296                 rq->tag = -1;
297                 rq->internal_tag = tag;
298         } else {
299                 if (blk_mq_tag_busy(data->hctx)) {
300                         rq_flags = RQF_MQ_INFLIGHT;
301                         atomic_inc(&data->hctx->nr_active);
302                 }
303                 rq->tag = tag;
304                 rq->internal_tag = -1;
305                 data->hctx->tags->rqs[rq->tag] = rq;
306         }
307 
308         /* csd/requeue_work/fifo_time is initialized before use */
309         rq->q = data->q;
310         rq->mq_ctx = data->ctx;
311         rq->rq_flags = rq_flags;
312         rq->cpu = -1;
313         rq->cmd_flags = op;
314         if (data->flags & BLK_MQ_REQ_PREEMPT)
315                 rq->rq_flags |= RQF_PREEMPT;
316         if (blk_queue_io_stat(data->q))
317                 rq->rq_flags |= RQF_IO_STAT;
318         INIT_LIST_HEAD(&rq->queuelist);
319         INIT_HLIST_NODE(&rq->hash);
320         RB_CLEAR_NODE(&rq->rb_node);
321         rq->rq_disk = NULL;
322         rq->part = NULL;
323         rq->start_time = jiffies;
324         rq->nr_phys_segments = 0;
325 #if defined(CONFIG_BLK_DEV_INTEGRITY)
326         rq->nr_integrity_segments = 0;
327 #endif
328         rq->special = NULL;
329         /* tag was already set */
330         rq->extra_len = 0;
331         rq->__deadline = 0;
332 
333         INIT_LIST_HEAD(&rq->timeout_list);
334         rq->timeout = 0;
335 
336         rq->end_io = NULL;
337         rq->end_io_data = NULL;
338         rq->next_rq = NULL;
339 
340 #ifdef CONFIG_BLK_CGROUP
341         rq->rl = NULL;
342         set_start_time_ns(rq);
343         rq->io_start_time_ns = 0;
344 #endif
345 
346         data->ctx->rq_dispatched[op_is_sync(op)]++;
347         return rq;
348 }
349 
350 static struct request *blk_mq_get_request(struct request_queue *q,
351                 struct bio *bio, unsigned int op,
352                 struct blk_mq_alloc_data *data)
353 {
354         struct elevator_queue *e = q->elevator;
355         struct request *rq;
356         unsigned int tag;
357         bool put_ctx_on_error = false;
358 
359         blk_queue_enter_live(q);
360         data->q = q;
361         if (likely(!data->ctx)) {
362                 data->ctx = blk_mq_get_ctx(q);
363                 put_ctx_on_error = true;
364         }
365         if (likely(!data->hctx))
366                 data->hctx = blk_mq_map_queue(q, data->ctx->cpu);
367         if (op & REQ_NOWAIT)
368                 data->flags |= BLK_MQ_REQ_NOWAIT;
369 
370         if (e) {
371                 data->flags |= BLK_MQ_REQ_INTERNAL;
372 
373                 /*
374                  * Flush requests are special and go directly to the
375                  * dispatch list.
376                  */
377                 if (!op_is_flush(op) && e->type->ops.mq.limit_depth)
378                         e->type->ops.mq.limit_depth(op, data);
379         }
380 
381         tag = blk_mq_get_tag(data);
382         if (tag == BLK_MQ_TAG_FAIL) {
383                 if (put_ctx_on_error) {
384                         blk_mq_put_ctx(data->ctx);
385                         data->ctx = NULL;
386                 }
387                 blk_queue_exit(q);
388                 return NULL;
389         }
390 
391         rq = blk_mq_rq_ctx_init(data, tag, op);
392         if (!op_is_flush(op)) {
393                 rq->elv.icq = NULL;
394                 if (e && e->type->ops.mq.prepare_request) {
395                         if (e->type->icq_cache && rq_ioc(bio))
396                                 blk_mq_sched_assign_ioc(rq, bio);
397 
398                         e->type->ops.mq.prepare_request(rq, bio);
399                         rq->rq_flags |= RQF_ELVPRIV;
400                 }
401         }
402         data->hctx->queued++;
403         return rq;
404 }
405 
406 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
407                 blk_mq_req_flags_t flags)
408 {
409         struct blk_mq_alloc_data alloc_data = { .flags = flags };
410         struct request *rq;
411         int ret;
412 
413         ret = blk_queue_enter(q, flags);
414         if (ret)
415                 return ERR_PTR(ret);
416 
417         rq = blk_mq_get_request(q, NULL, op, &alloc_data);
418         blk_queue_exit(q);
419 
420         if (!rq)
421                 return ERR_PTR(-EWOULDBLOCK);
422 
423         blk_mq_put_ctx(alloc_data.ctx);
424 
425         rq->__data_len = 0;
426         rq->__sector = (sector_t) -1;
427         rq->bio = rq->biotail = NULL;
428         return rq;
429 }
430 EXPORT_SYMBOL(blk_mq_alloc_request);
431 
432 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
433         unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
434 {
435         struct blk_mq_alloc_data alloc_data = { .flags = flags };
436         struct request *rq;
437         unsigned int cpu;
438         int ret;
439 
440         /*
441          * If the tag allocator sleeps we could get an allocation for a
442          * different hardware context.  No need to complicate the low level
443          * allocator for this for the rare use case of a command tied to
444          * a specific queue.
445          */
446         if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)))
447                 return ERR_PTR(-EINVAL);
448 
449         if (hctx_idx >= q->nr_hw_queues)
450                 return ERR_PTR(-EIO);
451 
452         ret = blk_queue_enter(q, flags);
453         if (ret)
454                 return ERR_PTR(ret);
455 
456         /*
457          * Check if the hardware context is actually mapped to anything.
458          * If not tell the caller that it should skip this queue.
459          */
460         alloc_data.hctx = q->queue_hw_ctx[hctx_idx];
461         if (!blk_mq_hw_queue_mapped(alloc_data.hctx)) {
462                 blk_queue_exit(q);
463                 return ERR_PTR(-EXDEV);
464         }
465         cpu = cpumask_first_and(alloc_data.hctx->cpumask, cpu_online_mask);
466         alloc_data.ctx = __blk_mq_get_ctx(q, cpu);
467 
468         rq = blk_mq_get_request(q, NULL, op, &alloc_data);
469         blk_queue_exit(q);
470 
471         if (!rq)
472                 return ERR_PTR(-EWOULDBLOCK);
473 
474         return rq;
475 }
476 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
477 
478 void blk_mq_free_request(struct request *rq)
479 {
480         struct request_queue *q = rq->q;
481         struct elevator_queue *e = q->elevator;
482         struct blk_mq_ctx *ctx = rq->mq_ctx;
483         struct blk_mq_hw_ctx *hctx = blk_mq_map_queue(q, ctx->cpu);
484         const int sched_tag = rq->internal_tag;
485 
486         if (rq->rq_flags & RQF_ELVPRIV) {
487                 if (e && e->type->ops.mq.finish_request)
488                         e->type->ops.mq.finish_request(rq);
489                 if (rq->elv.icq) {
490                         put_io_context(rq->elv.icq->ioc);
491                         rq->elv.icq = NULL;
492                 }
493         }
494 
495         ctx->rq_completed[rq_is_sync(rq)]++;
496         if (rq->rq_flags & RQF_MQ_INFLIGHT)
497                 atomic_dec(&hctx->nr_active);
498 
499         if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
500                 laptop_io_completion(q->backing_dev_info);
501 
502         wbt_done(q->rq_wb, &rq->issue_stat);
503 
504         if (blk_rq_rl(rq))
505                 blk_put_rl(blk_rq_rl(rq));
506 
507         blk_mq_rq_update_state(rq, MQ_RQ_IDLE);
508         if (rq->tag != -1)
509                 blk_mq_put_tag(hctx, hctx->tags, ctx, rq->tag);
510         if (sched_tag != -1)
511                 blk_mq_put_tag(hctx, hctx->sched_tags, ctx, sched_tag);
512         blk_mq_sched_restart(hctx);
513         blk_queue_exit(q);
514 }
515 EXPORT_SYMBOL_GPL(blk_mq_free_request);
516 
517 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
518 {
519         blk_account_io_done(rq);
520 
521         if (rq->end_io) {
522                 wbt_done(rq->q->rq_wb, &rq->issue_stat);
523                 rq->end_io(rq, error);
524         } else {
525                 if (unlikely(blk_bidi_rq(rq)))
526                         blk_mq_free_request(rq->next_rq);
527                 blk_mq_free_request(rq);
528         }
529 }
530 EXPORT_SYMBOL(__blk_mq_end_request);
531 
532 void blk_mq_end_request(struct request *rq, blk_status_t error)
533 {
534         if (blk_update_request(rq, error, blk_rq_bytes(rq)))
535                 BUG();
536         __blk_mq_end_request(rq, error);
537 }
538 EXPORT_SYMBOL(blk_mq_end_request);
539 
540 static void __blk_mq_complete_request_remote(void *data)
541 {
542         struct request *rq = data;
543 
544         rq->q->softirq_done_fn(rq);
545 }
546 
547 static void __blk_mq_complete_request(struct request *rq)
548 {
549         struct blk_mq_ctx *ctx = rq->mq_ctx;
550         bool shared = false;
551         int cpu;
552 
553         WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT);
554         blk_mq_rq_update_state(rq, MQ_RQ_COMPLETE);
555 
556         if (rq->internal_tag != -1)
557                 blk_mq_sched_completed_request(rq);
558         if (rq->rq_flags & RQF_STATS) {
559                 blk_mq_poll_stats_start(rq->q);
560                 blk_stat_add(rq);
561         }
562 
563         if (!test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags)) {
564                 rq->q->softirq_done_fn(rq);
565                 return;
566         }
567 
568         cpu = get_cpu();
569         if (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags))
570                 shared = cpus_share_cache(cpu, ctx->cpu);
571 
572         if (cpu != ctx->cpu && !shared && cpu_online(ctx->cpu)) {
573                 rq->csd.func = __blk_mq_complete_request_remote;
574                 rq->csd.info = rq;
575                 rq->csd.flags = 0;
576                 smp_call_function_single_async(ctx->cpu, &rq->csd);
577         } else {
578                 rq->q->softirq_done_fn(rq);
579         }
580         put_cpu();
581 }
582 
583 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
584         __releases(hctx->srcu)
585 {
586         if (!(hctx->flags & BLK_MQ_F_BLOCKING))
587                 rcu_read_unlock();
588         else
589                 srcu_read_unlock(hctx->srcu, srcu_idx);
590 }
591 
592 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
593         __acquires(hctx->srcu)
594 {
595         if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
596                 /* shut up gcc false positive */
597                 *srcu_idx = 0;
598                 rcu_read_lock();
599         } else
600                 *srcu_idx = srcu_read_lock(hctx->srcu);
601 }
602 
603 static void blk_mq_rq_update_aborted_gstate(struct request *rq, u64 gstate)
604 {
605         unsigned long flags;
606 
607         /*
608          * blk_mq_rq_aborted_gstate() is used from the completion path and
609          * can thus be called from irq context.  u64_stats_fetch in the
610          * middle of update on the same CPU leads to lockup.  Disable irq
611          * while updating.
612          */
613         local_irq_save(flags);
614         u64_stats_update_begin(&rq->aborted_gstate_sync);
615         rq->aborted_gstate = gstate;
616         u64_stats_update_end(&rq->aborted_gstate_sync);
617         local_irq_restore(flags);
618 }
619 
620 static u64 blk_mq_rq_aborted_gstate(struct request *rq)
621 {
622         unsigned int start;
623         u64 aborted_gstate;
624 
625         do {
626                 start = u64_stats_fetch_begin(&rq->aborted_gstate_sync);
627                 aborted_gstate = rq->aborted_gstate;
628         } while (u64_stats_fetch_retry(&rq->aborted_gstate_sync, start));
629 
630         return aborted_gstate;
631 }
632 
633 /**
634  * blk_mq_complete_request - end I/O on a request
635  * @rq:         the request being processed
636  *
637  * Description:
638  *      Ends all I/O on a request. It does not handle partial completions.
639  *      The actual completion happens out-of-order, through a IPI handler.
640  **/
641 void blk_mq_complete_request(struct request *rq)
642 {
643         struct request_queue *q = rq->q;
644         struct blk_mq_hw_ctx *hctx = blk_mq_map_queue(q, rq->mq_ctx->cpu);
645         int srcu_idx;
646 
647         if (unlikely(blk_should_fake_timeout(q)))
648                 return;
649 
650         /*
651          * If @rq->aborted_gstate equals the current instance, timeout is
652          * claiming @rq and we lost.  This is synchronized through
653          * hctx_lock().  See blk_mq_timeout_work() for details.
654          *
655          * Completion path never blocks and we can directly use RCU here
656          * instead of hctx_lock() which can be either RCU or SRCU.
657          * However, that would complicate paths which want to synchronize
658          * against us.  Let stay in sync with the issue path so that
659          * hctx_lock() covers both issue and completion paths.
660          */
661         hctx_lock(hctx, &srcu_idx);
662         if (blk_mq_rq_aborted_gstate(rq) != rq->gstate)
663                 __blk_mq_complete_request(rq);
664         hctx_unlock(hctx, srcu_idx);
665 }
666 EXPORT_SYMBOL(blk_mq_complete_request);
667 
668 int blk_mq_request_started(struct request *rq)
669 {
670         return blk_mq_rq_state(rq) != MQ_RQ_IDLE;
671 }
672 EXPORT_SYMBOL_GPL(blk_mq_request_started);
673 
674 void blk_mq_start_request(struct request *rq)
675 {
676         struct request_queue *q = rq->q;
677 
678         blk_mq_sched_started_request(rq);
679 
680         trace_block_rq_issue(q, rq);
681 
682         if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
683                 blk_stat_set_issue(&rq->issue_stat, blk_rq_sectors(rq));
684                 rq->rq_flags |= RQF_STATS;
685                 wbt_issue(q->rq_wb, &rq->issue_stat);
686         }
687 
688         WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
689 
690         /*
691          * Mark @rq in-flight which also advances the generation number,
692          * and register for timeout.  Protect with a seqcount to allow the
693          * timeout path to read both @rq->gstate and @rq->deadline
694          * coherently.
695          *
696          * This is the only place where a request is marked in-flight.  If
697          * the timeout path reads an in-flight @rq->gstate, the
698          * @rq->deadline it reads together under @rq->gstate_seq is
699          * guaranteed to be the matching one.
700          */
701         preempt_disable();
702         write_seqcount_begin(&rq->gstate_seq);
703 
704         blk_mq_rq_update_state(rq, MQ_RQ_IN_FLIGHT);
705         blk_add_timer(rq);
706 
707         write_seqcount_end(&rq->gstate_seq);
708         preempt_enable();
709 
710         if (q->dma_drain_size && blk_rq_bytes(rq)) {
711                 /*
712                  * Make sure space for the drain appears.  We know we can do
713                  * this because max_hw_segments has been adjusted to be one
714                  * fewer than the device can handle.
715                  */
716                 rq->nr_phys_segments++;
717         }
718 }
719 EXPORT_SYMBOL(blk_mq_start_request);
720 
721 /*
722  * When we reach here because queue is busy, it's safe to change the state
723  * to IDLE without checking @rq->aborted_gstate because we should still be
724  * holding the RCU read lock and thus protected against timeout.
725  */
726 static void __blk_mq_requeue_request(struct request *rq)
727 {
728         struct request_queue *q = rq->q;
729 
730         blk_mq_put_driver_tag(rq);
731 
732         trace_block_rq_requeue(q, rq);
733         wbt_requeue(q->rq_wb, &rq->issue_stat);
734 
735         if (blk_mq_rq_state(rq) != MQ_RQ_IDLE) {
736                 blk_mq_rq_update_state(rq, MQ_RQ_IDLE);
737                 if (q->dma_drain_size && blk_rq_bytes(rq))
738                         rq->nr_phys_segments--;
739         }
740 }
741 
742 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
743 {
744         __blk_mq_requeue_request(rq);
745 
746         /* this request will be re-inserted to io scheduler queue */
747         blk_mq_sched_requeue_request(rq);
748 
749         BUG_ON(blk_queued_rq(rq));
750         blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
751 }
752 EXPORT_SYMBOL(blk_mq_requeue_request);
753 
754 static void blk_mq_requeue_work(struct work_struct *work)
755 {
756         struct request_queue *q =
757                 container_of(work, struct request_queue, requeue_work.work);
758         LIST_HEAD(rq_list);
759         struct request *rq, *next;
760 
761         spin_lock_irq(&q->requeue_lock);
762         list_splice_init(&q->requeue_list, &rq_list);
763         spin_unlock_irq(&q->requeue_lock);
764 
765         list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
766                 if (!(rq->rq_flags & RQF_SOFTBARRIER))
767                         continue;
768 
769                 rq->rq_flags &= ~RQF_SOFTBARRIER;
770                 list_del_init(&rq->queuelist);
771                 blk_mq_sched_insert_request(rq, true, false, false);
772         }
773 
774         while (!list_empty(&rq_list)) {
775                 rq = list_entry(rq_list.next, struct request, queuelist);
776                 list_del_init(&rq->queuelist);
777                 blk_mq_sched_insert_request(rq, false, false, false);
778         }
779 
780         blk_mq_run_hw_queues(q, false);
781 }
782 
783 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
784                                 bool kick_requeue_list)
785 {
786         struct request_queue *q = rq->q;
787         unsigned long flags;
788 
789         /*
790          * We abuse this flag that is otherwise used by the I/O scheduler to
791          * request head insertion from the workqueue.
792          */
793         BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
794 
795         spin_lock_irqsave(&q->requeue_lock, flags);
796         if (at_head) {
797                 rq->rq_flags |= RQF_SOFTBARRIER;
798                 list_add(&rq->queuelist, &q->requeue_list);
799         } else {
800                 list_add_tail(&rq->queuelist, &q->requeue_list);
801         }
802         spin_unlock_irqrestore(&q->requeue_lock, flags);
803 
804         if (kick_requeue_list)
805                 blk_mq_kick_requeue_list(q);
806 }
807 EXPORT_SYMBOL(blk_mq_add_to_requeue_list);
808 
809 void blk_mq_kick_requeue_list(struct request_queue *q)
810 {
811         kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
812 }
813 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
814 
815 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
816                                     unsigned long msecs)
817 {
818         kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
819                                     msecs_to_jiffies(msecs));
820 }
821 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
822 
823 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
824 {
825         if (tag < tags->nr_tags) {
826                 prefetch(tags->rqs[tag]);
827                 return tags->rqs[tag];
828         }
829 
830         return NULL;
831 }
832 EXPORT_SYMBOL(blk_mq_tag_to_rq);
833 
834 struct blk_mq_timeout_data {
835         unsigned long next;
836         unsigned int next_set;
837         unsigned int nr_expired;
838 };
839 
840 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
841 {
842         const struct blk_mq_ops *ops = req->q->mq_ops;
843         enum blk_eh_timer_return ret = BLK_EH_RESET_TIMER;
844 
845         req->rq_flags |= RQF_MQ_TIMEOUT_EXPIRED;
846 
847         if (ops->timeout)
848                 ret = ops->timeout(req, reserved);
849 
850         switch (ret) {
851         case BLK_EH_HANDLED:
852                 __blk_mq_complete_request(req);
853                 break;
854         case BLK_EH_RESET_TIMER:
855                 /*
856                  * As nothing prevents from completion happening while
857                  * ->aborted_gstate is set, this may lead to ignored
858                  * completions and further spurious timeouts.
859                  */
860                 blk_mq_rq_update_aborted_gstate(req, 0);
861                 blk_add_timer(req);
862                 break;
863         case BLK_EH_NOT_HANDLED:
864                 break;
865         default:
866                 printk(KERN_ERR "block: bad eh return: %d\n", ret);
867                 break;
868         }
869 }
870 
871 static void blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
872                 struct request *rq, void *priv, bool reserved)
873 {
874         struct blk_mq_timeout_data *data = priv;
875         unsigned long gstate, deadline;
876         int start;
877 
878         might_sleep();
879 
880         if (rq->rq_flags & RQF_MQ_TIMEOUT_EXPIRED)
881                 return;
882 
883         /* read coherent snapshots of @rq->state_gen and @rq->deadline */
884         while (true) {
885                 start = read_seqcount_begin(&rq->gstate_seq);
886                 gstate = READ_ONCE(rq->gstate);
887                 deadline = blk_rq_deadline(rq);
888                 if (!read_seqcount_retry(&rq->gstate_seq, start))
889                         break;
890                 cond_resched();
891         }
892 
893         /* if in-flight && overdue, mark for abortion */
894         if ((gstate & MQ_RQ_STATE_MASK) == MQ_RQ_IN_FLIGHT &&
895             time_after_eq(jiffies, deadline)) {
896                 blk_mq_rq_update_aborted_gstate(rq, gstate);
897                 data->nr_expired++;
898                 hctx->nr_expired++;
899         } else if (!data->next_set || time_after(data->next, deadline)) {
900                 data->next = deadline;
901                 data->next_set = 1;
902         }
903 }
904 
905 static void blk_mq_terminate_expired(struct blk_mq_hw_ctx *hctx,
906                 struct request *rq, void *priv, bool reserved)
907 {
908         /*
909          * We marked @rq->aborted_gstate and waited for RCU.  If there were
910          * completions that we lost to, they would have finished and
911          * updated @rq->gstate by now; otherwise, the completion path is
912          * now guaranteed to see @rq->aborted_gstate and yield.  If
913          * @rq->aborted_gstate still matches @rq->gstate, @rq is ours.
914          */
915         if (!(rq->rq_flags & RQF_MQ_TIMEOUT_EXPIRED) &&
916             READ_ONCE(rq->gstate) == rq->aborted_gstate)
917                 blk_mq_rq_timed_out(rq, reserved);
918 }
919 
920 static void blk_mq_timeout_work(struct work_struct *work)
921 {
922         struct request_queue *q =
923                 container_of(work, struct request_queue, timeout_work);
924         struct blk_mq_timeout_data data = {
925                 .next           = 0,
926                 .next_set       = 0,
927                 .nr_expired     = 0,
928         };
929         struct blk_mq_hw_ctx *hctx;
930         int i;
931 
932         /* A deadlock might occur if a request is stuck requiring a
933          * timeout at the same time a queue freeze is waiting
934          * completion, since the timeout code would not be able to
935          * acquire the queue reference here.
936          *
937          * That's why we don't use blk_queue_enter here; instead, we use
938          * percpu_ref_tryget directly, because we need to be able to
939          * obtain a reference even in the short window between the queue
940          * starting to freeze, by dropping the first reference in
941          * blk_freeze_queue_start, and the moment the last request is
942          * consumed, marked by the instant q_usage_counter reaches
943          * zero.
944          */
945         if (!percpu_ref_tryget(&q->q_usage_counter))
946                 return;
947 
948         /* scan for the expired ones and set their ->aborted_gstate */
949         blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &data);
950 
951         if (data.nr_expired) {
952                 bool has_rcu = false;
953 
954                 /*
955                  * Wait till everyone sees ->aborted_gstate.  The
956                  * sequential waits for SRCUs aren't ideal.  If this ever
957                  * becomes a problem, we can add per-hw_ctx rcu_head and
958                  * wait in parallel.
959                  */
960                 queue_for_each_hw_ctx(q, hctx, i) {
961                         if (!hctx->nr_expired)
962                                 continue;
963 
964                         if (!(hctx->flags & BLK_MQ_F_BLOCKING))
965                                 has_rcu = true;
966                         else
967                                 synchronize_srcu(hctx->srcu);
968 
969                         hctx->nr_expired = 0;
970                 }
971                 if (has_rcu)
972                         synchronize_rcu();
973 
974                 /* terminate the ones we won */
975                 blk_mq_queue_tag_busy_iter(q, blk_mq_terminate_expired, NULL);
976         }
977 
978         if (data.next_set) {
979                 data.next = blk_rq_timeout(round_jiffies_up(data.next));
980                 mod_timer(&q->timeout, data.next);
981         } else {
982                 /*
983                  * Request timeouts are handled as a forward rolling timer. If
984                  * we end up here it means that no requests are pending and
985                  * also that no request has been pending for a while. Mark
986                  * each hctx as idle.
987                  */
988                 queue_for_each_hw_ctx(q, hctx, i) {
989                         /* the hctx may be unmapped, so check it here */
990                         if (blk_mq_hw_queue_mapped(hctx))
991                                 blk_mq_tag_idle(hctx);
992                 }
993         }
994         blk_queue_exit(q);
995 }
996 
997 struct flush_busy_ctx_data {
998         struct blk_mq_hw_ctx *hctx;
999         struct list_head *list;
1000 };
1001 
1002 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1003 {
1004         struct flush_busy_ctx_data *flush_data = data;
1005         struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1006         struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1007 
1008         sbitmap_clear_bit(sb, bitnr);
1009         spin_lock(&ctx->lock);
1010         list_splice_tail_init(&ctx->rq_list, flush_data->list);
1011         spin_unlock(&ctx->lock);
1012         return true;
1013 }
1014 
1015 /*
1016  * Process software queues that have been marked busy, splicing them
1017  * to the for-dispatch
1018  */
1019 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1020 {
1021         struct flush_busy_ctx_data data = {
1022                 .hctx = hctx,
1023                 .list = list,
1024         };
1025 
1026         sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1027 }
1028 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1029 
1030 struct dispatch_rq_data {
1031         struct blk_mq_hw_ctx *hctx;
1032         struct request *rq;
1033 };
1034 
1035 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1036                 void *data)
1037 {
1038         struct dispatch_rq_data *dispatch_data = data;
1039         struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1040         struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1041 
1042         spin_lock(&ctx->lock);
1043         if (unlikely(!list_empty(&ctx->rq_list))) {
1044                 dispatch_data->rq = list_entry_rq(ctx->rq_list.next);
1045                 list_del_init(&dispatch_data->rq->queuelist);
1046                 if (list_empty(&ctx->rq_list))
1047                         sbitmap_clear_bit(sb, bitnr);
1048         }
1049         spin_unlock(&ctx->lock);
1050 
1051         return !dispatch_data->rq;
1052 }
1053 
1054 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1055                                         struct blk_mq_ctx *start)
1056 {
1057         unsigned off = start ? start->index_hw : 0;
1058         struct dispatch_rq_data data = {
1059                 .hctx = hctx,
1060                 .rq   = NULL,
1061         };
1062 
1063         __sbitmap_for_each_set(&hctx->ctx_map, off,
1064                                dispatch_rq_from_ctx, &data);
1065 
1066         return data.rq;
1067 }
1068 
1069 static inline unsigned int queued_to_index(unsigned int queued)
1070 {
1071         if (!queued)
1072                 return 0;
1073 
1074         return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
1075 }
1076 
1077 bool blk_mq_get_driver_tag(struct request *rq, struct blk_mq_hw_ctx **hctx,
1078                            bool wait)
1079 {
1080         struct blk_mq_alloc_data data = {
1081                 .q = rq->q,
1082                 .hctx = blk_mq_map_queue(rq->q, rq->mq_ctx->cpu),
1083                 .flags = wait ? 0 : BLK_MQ_REQ_NOWAIT,
1084         };
1085 
1086         might_sleep_if(wait);
1087 
1088         if (rq->tag != -1)
1089                 goto done;
1090 
1091         if (blk_mq_tag_is_reserved(data.hctx->sched_tags, rq->internal_tag))
1092                 data.flags |= BLK_MQ_REQ_RESERVED;
1093 
1094         rq->tag = blk_mq_get_tag(&data);
1095         if (rq->tag >= 0) {
1096                 if (blk_mq_tag_busy(data.hctx)) {
1097                         rq->rq_flags |= RQF_MQ_INFLIGHT;
1098                         atomic_inc(&data.hctx->nr_active);
1099                 }
1100                 data.hctx->tags->rqs[rq->tag] = rq;
1101         }
1102 
1103 done:
1104         if (hctx)
1105                 *hctx = data.hctx;
1106         return rq->tag != -1;
1107 }
1108 
1109 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1110                                 int flags, void *key)
1111 {
1112         struct blk_mq_hw_ctx *hctx;
1113 
1114         hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1115 
1116         list_del_init(&wait->entry);
1117         blk_mq_run_hw_queue(hctx, true);
1118         return 1;
1119 }
1120 
1121 /*
1122  * Mark us waiting for a tag. For shared tags, this involves hooking us into
1123  * the tag wakeups. For non-shared tags, we can simply mark us needing a
1124  * restart. For both cases, take care to check the condition again after
1125  * marking us as waiting.
1126  */
1127 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx **hctx,
1128                                  struct request *rq)
1129 {
1130         struct blk_mq_hw_ctx *this_hctx = *hctx;
1131         struct sbq_wait_state *ws;
1132         wait_queue_entry_t *wait;
1133         bool ret;
1134 
1135         if (!(this_hctx->flags & BLK_MQ_F_TAG_SHARED)) {
1136                 if (!test_bit(BLK_MQ_S_SCHED_RESTART, &this_hctx->state))
1137                         set_bit(BLK_MQ_S_SCHED_RESTART, &this_hctx->state);
1138 
1139                 /*
1140                  * It's possible that a tag was freed in the window between the
1141                  * allocation failure and adding the hardware queue to the wait
1142                  * queue.
1143                  *
1144                  * Don't clear RESTART here, someone else could have set it.
1145                  * At most this will cost an extra queue run.
1146                  */
1147                 return blk_mq_get_driver_tag(rq, hctx, false);
1148         }
1149 
1150         wait = &this_hctx->dispatch_wait;
1151         if (!list_empty_careful(&wait->entry))
1152                 return false;
1153 
1154         spin_lock(&this_hctx->lock);
1155         if (!list_empty(&wait->entry)) {
1156                 spin_unlock(&this_hctx->lock);
1157                 return false;
1158         }
1159 
1160         ws = bt_wait_ptr(&this_hctx->tags->bitmap_tags, this_hctx);
1161         add_wait_queue(&ws->wait, wait);
1162 
1163         /*
1164          * It's possible that a tag was freed in the window between the
1165          * allocation failure and adding the hardware queue to the wait
1166          * queue.
1167          */
1168         ret = blk_mq_get_driver_tag(rq, hctx, false);
1169         if (!ret) {
1170                 spin_unlock(&this_hctx->lock);
1171                 return false;
1172         }
1173 
1174         /*
1175          * We got a tag, remove ourselves from the wait queue to ensure
1176          * someone else gets the wakeup.
1177          */
1178         spin_lock_irq(&ws->wait.lock);
1179         list_del_init(&wait->entry);
1180         spin_unlock_irq(&ws->wait.lock);
1181         spin_unlock(&this_hctx->lock);
1182 
1183         return true;
1184 }
1185 
1186 #define BLK_MQ_RESOURCE_DELAY   3               /* ms units */
1187 
1188 bool blk_mq_dispatch_rq_list(struct request_queue *q, struct list_head *list,
1189                              bool got_budget)
1190 {
1191         struct blk_mq_hw_ctx *hctx;
1192         struct request *rq, *nxt;
1193         bool no_tag = false;
1194         int errors, queued;
1195         blk_status_t ret = BLK_STS_OK;
1196 
1197         if (list_empty(list))
1198                 return false;
1199 
1200         WARN_ON(!list_is_singular(list) && got_budget);
1201 
1202         /*
1203          * Now process all the entries, sending them to the driver.
1204          */
1205         errors = queued = 0;
1206         do {
1207                 struct blk_mq_queue_data bd;
1208 
1209                 rq = list_first_entry(list, struct request, queuelist);
1210 
1211                 hctx = blk_mq_map_queue(rq->q, rq->mq_ctx->cpu);
1212                 if (!got_budget && !blk_mq_get_dispatch_budget(hctx))
1213                         break;
1214 
1215                 if (!blk_mq_get_driver_tag(rq, NULL, false)) {
1216                         /*
1217                          * The initial allocation attempt failed, so we need to
1218                          * rerun the hardware queue when a tag is freed. The
1219                          * waitqueue takes care of that. If the queue is run
1220                          * before we add this entry back on the dispatch list,
1221                          * we'll re-run it below.
1222                          */
1223                         if (!blk_mq_mark_tag_wait(&hctx, rq)) {
1224                                 blk_mq_put_dispatch_budget(hctx);
1225                                 /*
1226                                  * For non-shared tags, the RESTART check
1227                                  * will suffice.
1228                                  */
1229                                 if (hctx->flags & BLK_MQ_F_TAG_SHARED)
1230                                         no_tag = true;
1231                                 break;
1232                         }
1233                 }
1234 
1235                 list_del_init(&rq->queuelist);
1236 
1237                 bd.rq = rq;
1238 
1239                 /*
1240                  * Flag last if we have no more requests, or if we have more
1241                  * but can't assign a driver tag to it.
1242                  */
1243                 if (list_empty(list))
1244                         bd.last = true;
1245                 else {
1246                         nxt = list_first_entry(list, struct request, queuelist);
1247                         bd.last = !blk_mq_get_driver_tag(nxt, NULL, false);
1248                 }
1249 
1250                 ret = q->mq_ops->queue_rq(hctx, &bd);
1251                 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE) {
1252                         /*
1253                          * If an I/O scheduler has been configured and we got a
1254                          * driver tag for the next request already, free it
1255                          * again.
1256                          */
1257                         if (!list_empty(list)) {
1258                                 nxt = list_first_entry(list, struct request, queuelist);
1259                                 blk_mq_put_driver_tag(nxt);
1260                         }
1261                         list_add(&rq->queuelist, list);
1262                         __blk_mq_requeue_request(rq);
1263                         break;
1264                 }
1265 
1266                 if (unlikely(ret != BLK_STS_OK)) {
1267                         errors++;
1268                         blk_mq_end_request(rq, BLK_STS_IOERR);
1269                         continue;
1270                 }
1271 
1272                 queued++;
1273         } while (!list_empty(list));
1274 
1275         hctx->dispatched[queued_to_index(queued)]++;
1276 
1277         /*
1278          * Any items that need requeuing? Stuff them into hctx->dispatch,
1279          * that is where we will continue on next queue run.
1280          */
1281         if (!list_empty(list)) {
1282                 bool needs_restart;
1283 
1284                 spin_lock(&hctx->lock);
1285                 list_splice_init(list, &hctx->dispatch);
1286                 spin_unlock(&hctx->lock);
1287 
1288                 /*
1289                  * If SCHED_RESTART was set by the caller of this function and
1290                  * it is no longer set that means that it was cleared by another
1291                  * thread and hence that a queue rerun is needed.
1292                  *
1293                  * If 'no_tag' is set, that means that we failed getting
1294                  * a driver tag with an I/O scheduler attached. If our dispatch
1295                  * waitqueue is no longer active, ensure that we run the queue
1296                  * AFTER adding our entries back to the list.
1297                  *
1298                  * If no I/O scheduler has been configured it is possible that
1299                  * the hardware queue got stopped and restarted before requests
1300                  * were pushed back onto the dispatch list. Rerun the queue to
1301                  * avoid starvation. Notes:
1302                  * - blk_mq_run_hw_queue() checks whether or not a queue has
1303                  *   been stopped before rerunning a queue.
1304                  * - Some but not all block drivers stop a queue before
1305                  *   returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1306                  *   and dm-rq.
1307                  *
1308                  * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1309                  * bit is set, run queue after a delay to avoid IO stalls
1310                  * that could otherwise occur if the queue is idle.
1311                  */
1312                 needs_restart = blk_mq_sched_needs_restart(hctx);
1313                 if (!needs_restart ||
1314                     (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1315                         blk_mq_run_hw_queue(hctx, true);
1316                 else if (needs_restart && (ret == BLK_STS_RESOURCE))
1317                         blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1318         }
1319 
1320         return (queued + errors) != 0;
1321 }
1322 
1323 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1324 {
1325         int srcu_idx;
1326 
1327         /*
1328          * We should be running this queue from one of the CPUs that
1329          * are mapped to it.
1330          *
1331          * There are at least two related races now between setting
1332          * hctx->next_cpu from blk_mq_hctx_next_cpu() and running
1333          * __blk_mq_run_hw_queue():
1334          *
1335          * - hctx->next_cpu is found offline in blk_mq_hctx_next_cpu(),
1336          *   but later it becomes online, then this warning is harmless
1337          *   at all
1338          *
1339          * - hctx->next_cpu is found online in blk_mq_hctx_next_cpu(),
1340          *   but later it becomes offline, then the warning can't be
1341          *   triggered, and we depend on blk-mq timeout handler to
1342          *   handle dispatched requests to this hctx
1343          */
1344         if (!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask) &&
1345                 cpu_online(hctx->next_cpu)) {
1346                 printk(KERN_WARNING "run queue from wrong CPU %d, hctx %s\n",
1347                         raw_smp_processor_id(),
1348                         cpumask_empty(hctx->cpumask) ? "inactive": "active");
1349                 dump_stack();
1350         }
1351 
1352         /*
1353          * We can't run the queue inline with ints disabled. Ensure that
1354          * we catch bad users of this early.
1355          */
1356         WARN_ON_ONCE(in_interrupt());
1357 
1358         might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1359 
1360         hctx_lock(hctx, &srcu_idx);
1361         blk_mq_sched_dispatch_requests(hctx);
1362         hctx_unlock(hctx, srcu_idx);
1363 }
1364 
1365 /*
1366  * It'd be great if the workqueue API had a way to pass
1367  * in a mask and had some smarts for more clever placement.
1368  * For now we just round-robin here, switching for every
1369  * BLK_MQ_CPU_WORK_BATCH queued items.
1370  */
1371 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1372 {
1373         bool tried = false;
1374 
1375         if (hctx->queue->nr_hw_queues == 1)
1376                 return WORK_CPU_UNBOUND;
1377 
1378         if (--hctx->next_cpu_batch <= 0) {
1379                 int next_cpu;
1380 select_cpu:
1381                 next_cpu = cpumask_next_and(hctx->next_cpu, hctx->cpumask,
1382                                 cpu_online_mask);
1383                 if (next_cpu >= nr_cpu_ids)
1384                         next_cpu = cpumask_first_and(hctx->cpumask,cpu_online_mask);
1385 
1386                 /*
1387                  * No online CPU is found, so have to make sure hctx->next_cpu
1388                  * is set correctly for not breaking workqueue.
1389                  */
1390                 if (next_cpu >= nr_cpu_ids)
1391                         hctx->next_cpu = cpumask_first(hctx->cpumask);
1392                 else
1393                         hctx->next_cpu = next_cpu;
1394                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1395         }
1396 
1397         /*
1398          * Do unbound schedule if we can't find a online CPU for this hctx,
1399          * and it should only happen in the path of handling CPU DEAD.
1400          */
1401         if (!cpu_online(hctx->next_cpu)) {
1402                 if (!tried) {
1403                         tried = true;
1404                         goto select_cpu;
1405                 }
1406 
1407                 /*
1408                  * Make sure to re-select CPU next time once after CPUs
1409                  * in hctx->cpumask become online again.
1410                  */
1411                 hctx->next_cpu_batch = 1;
1412                 return WORK_CPU_UNBOUND;
1413         }
1414         return hctx->next_cpu;
1415 }
1416 
1417 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1418                                         unsigned long msecs)
1419 {
1420         if (WARN_ON_ONCE(!blk_mq_hw_queue_mapped(hctx)))
1421                 return;
1422 
1423         if (unlikely(blk_mq_hctx_stopped(hctx)))
1424                 return;
1425 
1426         if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1427                 int cpu = get_cpu();
1428                 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1429                         __blk_mq_run_hw_queue(hctx);
1430                         put_cpu();
1431                         return;
1432                 }
1433 
1434                 put_cpu();
1435         }
1436 
1437         kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1438                                     msecs_to_jiffies(msecs));
1439 }
1440 
1441 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1442 {
1443         __blk_mq_delay_run_hw_queue(hctx, true, msecs);
1444 }
1445 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1446 
1447 bool blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1448 {
1449         int srcu_idx;
1450         bool need_run;
1451 
1452         /*
1453          * When queue is quiesced, we may be switching io scheduler, or
1454          * updating nr_hw_queues, or other things, and we can't run queue
1455          * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1456          *
1457          * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1458          * quiesced.
1459          */
1460         hctx_lock(hctx, &srcu_idx);
1461         need_run = !blk_queue_quiesced(hctx->queue) &&
1462                 blk_mq_hctx_has_pending(hctx);
1463         hctx_unlock(hctx, srcu_idx);
1464 
1465         if (need_run) {
1466                 __blk_mq_delay_run_hw_queue(hctx, async, 0);
1467                 return true;
1468         }
1469 
1470         return false;
1471 }
1472 EXPORT_SYMBOL(blk_mq_run_hw_queue);
1473 
1474 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1475 {
1476         struct blk_mq_hw_ctx *hctx;
1477         int i;
1478 
1479         queue_for_each_hw_ctx(q, hctx, i) {
1480                 if (blk_mq_hctx_stopped(hctx))
1481                         continue;
1482 
1483                 blk_mq_run_hw_queue(hctx, async);
1484         }
1485 }
1486 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1487 
1488 /**
1489  * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1490  * @q: request queue.
1491  *
1492  * The caller is responsible for serializing this function against
1493  * blk_mq_{start,stop}_hw_queue().
1494  */
1495 bool blk_mq_queue_stopped(struct request_queue *q)
1496 {
1497         struct blk_mq_hw_ctx *hctx;
1498         int i;
1499 
1500         queue_for_each_hw_ctx(q, hctx, i)
1501                 if (blk_mq_hctx_stopped(hctx))
1502                         return true;
1503 
1504         return false;
1505 }
1506 EXPORT_SYMBOL(blk_mq_queue_stopped);
1507 
1508 /*
1509  * This function is often used for pausing .queue_rq() by driver when
1510  * there isn't enough resource or some conditions aren't satisfied, and
1511  * BLK_STS_RESOURCE is usually returned.
1512  *
1513  * We do not guarantee that dispatch can be drained or blocked
1514  * after blk_mq_stop_hw_queue() returns. Please use
1515  * blk_mq_quiesce_queue() for that requirement.
1516  */
1517 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1518 {
1519         cancel_delayed_work(&hctx->run_work);
1520 
1521         set_bit(BLK_MQ_S_STOPPED, &hctx->state);
1522 }
1523 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
1524 
1525 /*
1526  * This function is often used for pausing .queue_rq() by driver when
1527  * there isn't enough resource or some conditions aren't satisfied, and
1528  * BLK_STS_RESOURCE is usually returned.
1529  *
1530  * We do not guarantee that dispatch can be drained or blocked
1531  * after blk_mq_stop_hw_queues() returns. Please use
1532  * blk_mq_quiesce_queue() for that requirement.
1533  */
1534 void blk_mq_stop_hw_queues(struct request_queue *q)
1535 {
1536         struct blk_mq_hw_ctx *hctx;
1537         int i;
1538 
1539         queue_for_each_hw_ctx(q, hctx, i)
1540                 blk_mq_stop_hw_queue(hctx);
1541 }
1542 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1543 
1544 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1545 {
1546         clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1547 
1548         blk_mq_run_hw_queue(hctx, false);
1549 }
1550 EXPORT_SYMBOL(blk_mq_start_hw_queue);
1551 
1552 void blk_mq_start_hw_queues(struct request_queue *q)
1553 {
1554         struct blk_mq_hw_ctx *hctx;
1555         int i;
1556 
1557         queue_for_each_hw_ctx(q, hctx, i)
1558                 blk_mq_start_hw_queue(hctx);
1559 }
1560 EXPORT_SYMBOL(blk_mq_start_hw_queues);
1561 
1562 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1563 {
1564         if (!blk_mq_hctx_stopped(hctx))
1565                 return;
1566 
1567         clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1568         blk_mq_run_hw_queue(hctx, async);
1569 }
1570 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1571 
1572 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
1573 {
1574         struct blk_mq_hw_ctx *hctx;
1575         int i;
1576 
1577         queue_for_each_hw_ctx(q, hctx, i)
1578                 blk_mq_start_stopped_hw_queue(hctx, async);
1579 }
1580 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1581 
1582 static void blk_mq_run_work_fn(struct work_struct *work)
1583 {
1584         struct blk_mq_hw_ctx *hctx;
1585 
1586         hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
1587 
1588         /*
1589          * If we are stopped, don't run the queue. The exception is if
1590          * BLK_MQ_S_START_ON_RUN is set. For that case, we auto-clear
1591          * the STOPPED bit and run it.
1592          */
1593         if (test_bit(BLK_MQ_S_STOPPED, &hctx->state)) {
1594                 if (!test_bit(BLK_MQ_S_START_ON_RUN, &hctx->state))
1595                         return;
1596 
1597                 clear_bit(BLK_MQ_S_START_ON_RUN, &hctx->state);
1598                 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1599         }
1600 
1601         __blk_mq_run_hw_queue(hctx);
1602 }
1603 
1604 
1605 void blk_mq_delay_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1606 {
1607         if (WARN_ON_ONCE(!blk_mq_hw_queue_mapped(hctx)))
1608                 return;
1609 
1610         /*
1611          * Stop the hw queue, then modify currently delayed work.
1612          * This should prevent us from running the queue prematurely.
1613          * Mark the queue as auto-clearing STOPPED when it runs.
1614          */
1615         blk_mq_stop_hw_queue(hctx);
1616         set_bit(BLK_MQ_S_START_ON_RUN, &hctx->state);
1617         kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx),
1618                                         &hctx->run_work,
1619                                         msecs_to_jiffies(msecs));
1620 }
1621 EXPORT_SYMBOL(blk_mq_delay_queue);
1622 
1623 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
1624                                             struct request *rq,
1625                                             bool at_head)
1626 {
1627         struct blk_mq_ctx *ctx = rq->mq_ctx;
1628 
1629         lockdep_assert_held(&ctx->lock);
1630 
1631         trace_block_rq_insert(hctx->queue, rq);
1632 
1633         if (at_head)
1634                 list_add(&rq->queuelist, &ctx->rq_list);
1635         else
1636                 list_add_tail(&rq->queuelist, &ctx->rq_list);
1637 }
1638 
1639 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1640                              bool at_head)
1641 {
1642         struct blk_mq_ctx *ctx = rq->mq_ctx;
1643 
1644         lockdep_assert_held(&ctx->lock);
1645 
1646         __blk_mq_insert_req_list(hctx, rq, at_head);
1647         blk_mq_hctx_mark_pending(hctx, ctx);
1648 }
1649 
1650 /*
1651  * Should only be used carefully, when the caller knows we want to
1652  * bypass a potential IO scheduler on the target device.
1653  */
1654 void blk_mq_request_bypass_insert(struct request *rq, bool run_queue)
1655 {
1656         struct blk_mq_ctx *ctx = rq->mq_ctx;
1657         struct blk_mq_hw_ctx *hctx = blk_mq_map_queue(rq->q, ctx->cpu);
1658 
1659         spin_lock(&hctx->lock);
1660         list_add_tail(&rq->queuelist, &hctx->dispatch);
1661         spin_unlock(&hctx->lock);
1662 
1663         if (run_queue)
1664                 blk_mq_run_hw_queue(hctx, false);
1665 }
1666 
1667 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1668                             struct list_head *list)
1669 
1670 {
1671         /*
1672          * preemption doesn't flush plug list, so it's possible ctx->cpu is
1673          * offline now
1674          */
1675         spin_lock(&ctx->lock);
1676         while (!list_empty(list)) {
1677                 struct request *rq;
1678 
1679                 rq = list_first_entry(list, struct request, queuelist);
1680                 BUG_ON(rq->mq_ctx != ctx);
1681                 list_del_init(&rq->queuelist);
1682                 __blk_mq_insert_req_list(hctx, rq, false);
1683         }
1684         blk_mq_hctx_mark_pending(hctx, ctx);
1685         spin_unlock(&ctx->lock);
1686 }
1687 
1688 static int plug_ctx_cmp(void *priv, struct list_head *a, struct list_head *b)
1689 {
1690         struct request *rqa = container_of(a, struct request, queuelist);
1691         struct request *rqb = container_of(b, struct request, queuelist);
1692 
1693         return !(rqa->mq_ctx < rqb->mq_ctx ||
1694                  (rqa->mq_ctx == rqb->mq_ctx &&
1695                   blk_rq_pos(rqa) < blk_rq_pos(rqb)));
1696 }
1697 
1698 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1699 {
1700         struct blk_mq_ctx *this_ctx;
1701         struct request_queue *this_q;
1702         struct request *rq;
1703         LIST_HEAD(list);
1704         LIST_HEAD(ctx_list);
1705         unsigned int depth;
1706 
1707         list_splice_init(&plug->mq_list, &list);
1708 
1709         list_sort(NULL, &list, plug_ctx_cmp);
1710 
1711         this_q = NULL;
1712         this_ctx = NULL;
1713         depth = 0;
1714 
1715         while (!list_empty(&list)) {
1716                 rq = list_entry_rq(list.next);
1717                 list_del_init(&rq->queuelist);
1718                 BUG_ON(!rq->q);
1719                 if (rq->mq_ctx != this_ctx) {
1720                         if (this_ctx) {
1721                                 trace_block_unplug(this_q, depth, from_schedule);
1722                                 blk_mq_sched_insert_requests(this_q, this_ctx,
1723                                                                 &ctx_list,
1724                                                                 from_schedule);
1725                         }
1726 
1727                         this_ctx = rq->mq_ctx;
1728                         this_q = rq->q;
1729                         depth = 0;
1730                 }
1731 
1732                 depth++;
1733                 list_add_tail(&rq->queuelist, &ctx_list);
1734         }
1735 
1736         /*
1737          * If 'this_ctx' is set, we know we have entries to complete
1738          * on 'ctx_list'. Do those.
1739          */
1740         if (this_ctx) {
1741                 trace_block_unplug(this_q, depth, from_schedule);
1742                 blk_mq_sched_insert_requests(this_q, this_ctx, &ctx_list,
1743                                                 from_schedule);
1744         }
1745 }
1746 
1747 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio)
1748 {
1749         blk_init_request_from_bio(rq, bio);
1750 
1751         blk_rq_set_rl(rq, blk_get_rl(rq->q, bio));
1752 
1753         blk_account_io_start(rq, true);
1754 }
1755 
1756 static inline void blk_mq_queue_io(struct blk_mq_hw_ctx *hctx,
1757                                    struct blk_mq_ctx *ctx,
1758                                    struct request *rq)
1759 {
1760         spin_lock(&ctx->lock);
1761         __blk_mq_insert_request(hctx, rq, false);
1762         spin_unlock(&ctx->lock);
1763 }
1764 
1765 static blk_qc_t request_to_qc_t(struct blk_mq_hw_ctx *hctx, struct request *rq)
1766 {
1767         if (rq->tag != -1)
1768                 return blk_tag_to_qc_t(rq->tag, hctx->queue_num, false);
1769 
1770         return blk_tag_to_qc_t(rq->internal_tag, hctx->queue_num, true);
1771 }
1772 
1773 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
1774                                             struct request *rq,
1775                                             blk_qc_t *cookie)
1776 {
1777         struct request_queue *q = rq->q;
1778         struct blk_mq_queue_data bd = {
1779                 .rq = rq,
1780                 .last = true,
1781         };
1782         blk_qc_t new_cookie;
1783         blk_status_t ret;
1784 
1785         new_cookie = request_to_qc_t(hctx, rq);
1786 
1787         /*
1788          * For OK queue, we are done. For error, caller may kill it.
1789          * Any other error (busy), just add it to our list as we
1790          * previously would have done.
1791          */
1792         ret = q->mq_ops->queue_rq(hctx, &bd);
1793         switch (ret) {
1794         case BLK_STS_OK:
1795                 *cookie = new_cookie;
1796                 break;
1797         case BLK_STS_RESOURCE:
1798         case BLK_STS_DEV_RESOURCE:
1799                 __blk_mq_requeue_request(rq);
1800                 break;
1801         default:
1802                 *cookie = BLK_QC_T_NONE;
1803                 break;
1804         }
1805 
1806         return ret;
1807 }
1808 
1809 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1810                                                 struct request *rq,
1811                                                 blk_qc_t *cookie,
1812                                                 bool bypass_insert)
1813 {
1814         struct request_queue *q = rq->q;
1815         bool run_queue = true;
1816 
1817         /*
1818          * RCU or SRCU read lock is needed before checking quiesced flag.
1819          *
1820          * When queue is stopped or quiesced, ignore 'bypass_insert' from
1821          * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
1822          * and avoid driver to try to dispatch again.
1823          */
1824         if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
1825                 run_queue = false;
1826                 bypass_insert = false;
1827                 goto insert;
1828         }
1829 
1830         if (q->elevator && !bypass_insert)
1831                 goto insert;
1832 
1833         if (!blk_mq_get_dispatch_budget(hctx))
1834                 goto insert;
1835 
1836         if (!blk_mq_get_driver_tag(rq, NULL, false)) {
1837                 blk_mq_put_dispatch_budget(hctx);
1838                 goto insert;
1839         }
1840 
1841         return __blk_mq_issue_directly(hctx, rq, cookie);
1842 insert:
1843         if (bypass_insert)
1844                 return BLK_STS_RESOURCE;
1845 
1846         blk_mq_sched_insert_request(rq, false, run_queue, false);
1847         return BLK_STS_OK;
1848 }
1849 
1850 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
1851                 struct request *rq, blk_qc_t *cookie)
1852 {
1853         blk_status_t ret;
1854         int srcu_idx;
1855 
1856         might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1857 
1858         hctx_lock(hctx, &srcu_idx);
1859 
1860         ret = __blk_mq_try_issue_directly(hctx, rq, cookie, false);
1861         if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
1862                 blk_mq_sched_insert_request(rq, false, true, false);
1863         else if (ret != BLK_STS_OK)
1864                 blk_mq_end_request(rq, ret);
1865 
1866         hctx_unlock(hctx, srcu_idx);
1867 }
1868 
1869 blk_status_t blk_mq_request_issue_directly(struct request *rq)
1870 {
1871         blk_status_t ret;
1872         int srcu_idx;
1873         blk_qc_t unused_cookie;
1874         struct blk_mq_ctx *ctx = rq->mq_ctx;
1875         struct blk_mq_hw_ctx *hctx = blk_mq_map_queue(rq->q, ctx->cpu);
1876 
1877         hctx_lock(hctx, &srcu_idx);
1878         ret = __blk_mq_try_issue_directly(hctx, rq, &unused_cookie, true);
1879         hctx_unlock(hctx, srcu_idx);
1880 
1881         return ret;
1882 }
1883 
1884 static blk_qc_t blk_mq_make_request(struct request_queue *q, struct bio *bio)
1885 {
1886         const int is_sync = op_is_sync(bio->bi_opf);
1887         const int is_flush_fua = op_is_flush(bio->bi_opf);
1888         struct blk_mq_alloc_data data = { .flags = 0 };
1889         struct request *rq;
1890         unsigned int request_count = 0;
1891         struct blk_plug *plug;
1892         struct request *same_queue_rq = NULL;
1893         blk_qc_t cookie;
1894         unsigned int wb_acct;
1895 
1896         blk_queue_bounce(q, &bio);
1897 
1898         blk_queue_split(q, &bio);
1899 
1900         if (!bio_integrity_prep(bio))
1901                 return BLK_QC_T_NONE;
1902 
1903         if (!is_flush_fua && !blk_queue_nomerges(q) &&
1904             blk_attempt_plug_merge(q, bio, &request_count, &same_queue_rq))
1905                 return BLK_QC_T_NONE;
1906 
1907         if (blk_mq_sched_bio_merge(q, bio))
1908                 return BLK_QC_T_NONE;
1909 
1910         wb_acct = wbt_wait(q->rq_wb, bio, NULL);
1911 
1912         trace_block_getrq(q, bio, bio->bi_opf);
1913 
1914         rq = blk_mq_get_request(q, bio, bio->bi_opf, &data);
1915         if (unlikely(!rq)) {
1916                 __wbt_done(q->rq_wb, wb_acct);
1917                 if (bio->bi_opf & REQ_NOWAIT)
1918                         bio_wouldblock_error(bio);
1919                 return BLK_QC_T_NONE;
1920         }
1921 
1922         wbt_track(&rq->issue_stat, wb_acct);
1923 
1924         cookie = request_to_qc_t(data.hctx, rq);
1925 
1926         plug = current->plug;
1927         if (unlikely(is_flush_fua)) {
1928                 blk_mq_put_ctx(data.ctx);
1929                 blk_mq_bio_to_request(rq, bio);
1930 
1931                 /* bypass scheduler for flush rq */
1932                 blk_insert_flush(rq);
1933                 blk_mq_run_hw_queue(data.hctx, true);
1934         } else if (plug && q->nr_hw_queues == 1) {
1935                 struct request *last = NULL;
1936 
1937                 blk_mq_put_ctx(data.ctx);
1938                 blk_mq_bio_to_request(rq, bio);
1939 
1940                 /*
1941                  * @request_count may become stale because of schedule
1942                  * out, so check the list again.
1943                  */
1944                 if (list_empty(&plug->mq_list))
1945                         request_count = 0;
1946                 else if (blk_queue_nomerges(q))
1947                         request_count = blk_plug_queued_count(q);
1948 
1949                 if (!request_count)
1950                         trace_block_plug(q);
1951                 else
1952                         last = list_entry_rq(plug->mq_list.prev);
1953 
1954                 if (request_count >= BLK_MAX_REQUEST_COUNT || (last &&
1955                     blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1956                         blk_flush_plug_list(plug, false);
1957                         trace_block_plug(q);
1958                 }
1959 
1960                 list_add_tail(&rq->queuelist, &plug->mq_list);
1961         } else if (plug && !blk_queue_nomerges(q)) {
1962                 blk_mq_bio_to_request(rq, bio);
1963 
1964                 /*
1965                  * We do limited plugging. If the bio can be merged, do that.
1966                  * Otherwise the existing request in the plug list will be
1967                  * issued. So the plug list will have one request at most
1968                  * The plug list might get flushed before this. If that happens,
1969                  * the plug list is empty, and same_queue_rq is invalid.
1970                  */
1971                 if (list_empty(&plug->mq_list))
1972                         same_queue_rq = NULL;
1973                 if (same_queue_rq)
1974                         list_del_init(&same_queue_rq->queuelist);
1975                 list_add_tail(&rq->queuelist, &plug->mq_list);
1976 
1977                 blk_mq_put_ctx(data.ctx);
1978 
1979                 if (same_queue_rq) {
1980                         data.hctx = blk_mq_map_queue(q,
1981                                         same_queue_rq->mq_ctx->cpu);
1982                         blk_mq_try_issue_directly(data.hctx, same_queue_rq,
1983                                         &cookie);
1984                 }
1985         } else if (q->nr_hw_queues > 1 && is_sync) {
1986                 blk_mq_put_ctx(data.ctx);
1987                 blk_mq_bio_to_request(rq, bio);
1988                 blk_mq_try_issue_directly(data.hctx, rq, &cookie);
1989         } else if (q->elevator) {
1990                 blk_mq_put_ctx(data.ctx);
1991                 blk_mq_bio_to_request(rq, bio);
1992                 blk_mq_sched_insert_request(rq, false, true, true);
1993         } else {
1994                 blk_mq_put_ctx(data.ctx);
1995                 blk_mq_bio_to_request(rq, bio);
1996                 blk_mq_queue_io(data.hctx, data.ctx, rq);
1997                 blk_mq_run_hw_queue(data.hctx, true);
1998         }
1999 
2000         return cookie;
2001 }
2002 
2003 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2004                      unsigned int hctx_idx)
2005 {
2006         struct page *page;
2007 
2008         if (tags->rqs && set->ops->exit_request) {
2009                 int i;
2010 
2011                 for (i = 0; i < tags->nr_tags; i++) {
2012                         struct request *rq = tags->static_rqs[i];
2013 
2014                         if (!rq)
2015                                 continue;
2016                         set->ops->exit_request(set, rq, hctx_idx);
2017                         tags->static_rqs[i] = NULL;
2018                 }
2019         }
2020 
2021         while (!list_empty(&tags->page_list)) {
2022                 page = list_first_entry(&tags->page_list, struct page, lru);
2023                 list_del_init(&page->lru);
2024                 /*
2025                  * Remove kmemleak object previously allocated in
2026                  * blk_mq_init_rq_map().
2027                  */
2028                 kmemleak_free(page_address(page));
2029                 __free_pages(page, page->private);
2030         }
2031 }
2032 
2033 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
2034 {
2035         kfree(tags->rqs);
2036         tags->rqs = NULL;
2037         kfree(tags->static_rqs);
2038         tags->static_rqs = NULL;
2039 
2040         blk_mq_free_tags(tags);
2041 }
2042 
2043 struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2044                                         unsigned int hctx_idx,
2045                                         unsigned int nr_tags,
2046                                         unsigned int reserved_tags)
2047 {
2048         struct blk_mq_tags *tags;
2049         int node;
2050 
2051         node = blk_mq_hw_queue_to_node(set->mq_map, hctx_idx);
2052         if (node == NUMA_NO_NODE)
2053                 node = set->numa_node;
2054 
2055         tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
2056                                 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
2057         if (!tags)
2058                 return NULL;
2059 
2060         tags->rqs = kzalloc_node(nr_tags * sizeof(struct request *),
2061                                  GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2062                                  node);
2063         if (!tags->rqs) {
2064                 blk_mq_free_tags(tags);
2065                 return NULL;
2066         }
2067 
2068         tags->static_rqs = kzalloc_node(nr_tags * sizeof(struct request *),
2069                                  GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2070                                  node);
2071         if (!tags->static_rqs) {
2072                 kfree(tags->rqs);
2073                 blk_mq_free_tags(tags);
2074                 return NULL;
2075         }
2076 
2077         return tags;
2078 }
2079 
2080 static size_t order_to_size(unsigned int order)
2081 {
2082         return (size_t)PAGE_SIZE << order;
2083 }
2084 
2085 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2086                                unsigned int hctx_idx, int node)
2087 {
2088         int ret;
2089 
2090         if (set->ops->init_request) {
2091                 ret = set->ops->init_request(set, rq, hctx_idx, node);
2092                 if (ret)
2093                         return ret;
2094         }
2095 
2096         seqcount_init(&rq->gstate_seq);
2097         u64_stats_init(&rq->aborted_gstate_sync);
2098         /*
2099          * start gstate with gen 1 instead of 0, otherwise it will be equal
2100          * to aborted_gstate, and be identified timed out by
2101          * blk_mq_terminate_expired.
2102          */
2103         WRITE_ONCE(rq->gstate, MQ_RQ_GEN_INC);
2104 
2105         return 0;
2106 }
2107 
2108 int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2109                      unsigned int hctx_idx, unsigned int depth)
2110 {
2111         unsigned int i, j, entries_per_page, max_order = 4;
2112         size_t rq_size, left;
2113         int node;
2114 
2115         node = blk_mq_hw_queue_to_node(set->mq_map, hctx_idx);
2116         if (node == NUMA_NO_NODE)
2117                 node = set->numa_node;
2118 
2119         INIT_LIST_HEAD(&tags->page_list);
2120 
2121         /*
2122          * rq_size is the size of the request plus driver payload, rounded
2123          * to the cacheline size
2124          */
2125         rq_size = round_up(sizeof(struct request) + set->cmd_size,
2126                                 cache_line_size());
2127         left = rq_size * depth;
2128 
2129         for (i = 0; i < depth; ) {
2130                 int this_order = max_order;
2131                 struct page *page;
2132                 int to_do;
2133                 void *p;
2134 
2135                 while (this_order && left < order_to_size(this_order - 1))
2136                         this_order--;
2137 
2138                 do {
2139                         page = alloc_pages_node(node,
2140                                 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
2141                                 this_order);
2142                         if (page)
2143                                 break;
2144                         if (!this_order--)
2145                                 break;
2146                         if (order_to_size(this_order) < rq_size)
2147                                 break;
2148                 } while (1);
2149 
2150                 if (!page)
2151                         goto fail;
2152 
2153                 page->private = this_order;
2154                 list_add_tail(&page->lru, &tags->page_list);
2155 
2156                 p = page_address(page);
2157                 /*
2158                  * Allow kmemleak to scan these pages as they contain pointers
2159                  * to additional allocations like via ops->init_request().
2160                  */
2161                 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
2162                 entries_per_page = order_to_size(this_order) / rq_size;
2163                 to_do = min(entries_per_page, depth - i);
2164                 left -= to_do * rq_size;
2165                 for (j = 0; j < to_do; j++) {
2166                         struct request *rq = p;
2167 
2168                         tags->static_rqs[i] = rq;
2169                         if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2170                                 tags->static_rqs[i] = NULL;
2171                                 goto fail;
2172                         }
2173 
2174                         p += rq_size;
2175                         i++;
2176                 }
2177         }
2178         return 0;
2179 
2180 fail:
2181         blk_mq_free_rqs(set, tags, hctx_idx);
2182         return -ENOMEM;
2183 }
2184 
2185 /*
2186  * 'cpu' is going away. splice any existing rq_list entries from this
2187  * software queue to the hw queue dispatch list, and ensure that it
2188  * gets run.
2189  */
2190 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
2191 {
2192         struct blk_mq_hw_ctx *hctx;
2193         struct blk_mq_ctx *ctx;
2194         LIST_HEAD(tmp);
2195 
2196         hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
2197         ctx = __blk_mq_get_ctx(hctx->queue, cpu);
2198 
2199         spin_lock(&ctx->lock);
2200         if (!list_empty(&ctx->rq_list)) {
2201                 list_splice_init(&ctx->rq_list, &tmp);
2202                 blk_mq_hctx_clear_pending(hctx, ctx);
2203         }
2204         spin_unlock(&ctx->lock);
2205 
2206         if (list_empty(&tmp))
2207                 return 0;
2208 
2209         spin_lock(&hctx->lock);
2210         list_splice_tail_init(&tmp, &hctx->dispatch);
2211         spin_unlock(&hctx->lock);
2212 
2213         blk_mq_run_hw_queue(hctx, true);
2214         return 0;
2215 }
2216 
2217 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
2218 {
2219         cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2220                                             &hctx->cpuhp_dead);
2221 }
2222 
2223 /* hctx->ctxs will be freed in queue's release handler */
2224 static void blk_mq_exit_hctx(struct request_queue *q,
2225                 struct blk_mq_tag_set *set,
2226                 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
2227 {
2228         blk_mq_debugfs_unregister_hctx(hctx);
2229 
2230         if (blk_mq_hw_queue_mapped(hctx))
2231                 blk_mq_tag_idle(hctx);
2232 
2233         if (set->ops->exit_request)
2234                 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
2235 
2236         blk_mq_sched_exit_hctx(q, hctx, hctx_idx);
2237 
2238         if (set->ops->exit_hctx)
2239                 set->ops->exit_hctx(hctx, hctx_idx);
2240 
2241         if (hctx->flags & BLK_MQ_F_BLOCKING)
2242                 cleanup_srcu_struct(hctx->srcu);
2243 
2244         blk_mq_remove_cpuhp(hctx);
2245         blk_free_flush_queue(hctx->fq);
2246         sbitmap_free(&hctx->ctx_map);
2247 }
2248 
2249 static void blk_mq_exit_hw_queues(struct request_queue *q,
2250                 struct blk_mq_tag_set *set, int nr_queue)
2251 {
2252         struct blk_mq_hw_ctx *hctx;
2253         unsigned int i;
2254 
2255         queue_for_each_hw_ctx(q, hctx, i) {
2256                 if (i == nr_queue)
2257                         break;
2258                 blk_mq_exit_hctx(q, set, hctx, i);
2259         }
2260 }
2261 
2262 static int blk_mq_init_hctx(struct request_queue *q,
2263                 struct blk_mq_tag_set *set,
2264                 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
2265 {
2266         int node;
2267 
2268         node = hctx->numa_node;
2269         if (node == NUMA_NO_NODE)
2270                 node = hctx->numa_node = set->numa_node;
2271 
2272         INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
2273         spin_lock_init(&hctx->lock);
2274         INIT_LIST_HEAD(&hctx->dispatch);
2275         hctx->queue = q;
2276         hctx->flags = set->flags & ~BLK_MQ_F_TAG_SHARED;
2277 
2278         cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
2279 
2280         hctx->tags = set->tags[hctx_idx];
2281 
2282         /*
2283          * Allocate space for all possible cpus to avoid allocation at
2284          * runtime
2285          */
2286         hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
2287                                         GFP_KERNEL, node);
2288         if (!hctx->ctxs)
2289                 goto unregister_cpu_notifier;
2290 
2291         if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8), GFP_KERNEL,
2292                               node))
2293                 goto free_ctxs;
2294 
2295         hctx->nr_ctx = 0;
2296 
2297         init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
2298         INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
2299 
2300         if (set->ops->init_hctx &&
2301             set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
2302                 goto free_bitmap;
2303 
2304         if (blk_mq_sched_init_hctx(q, hctx, hctx_idx))
2305                 goto exit_hctx;
2306 
2307         hctx->fq = blk_alloc_flush_queue(q, hctx->numa_node, set->cmd_size);
2308         if (!hctx->fq)
2309                 goto sched_exit_hctx;
2310 
2311         if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx, node))
2312                 goto free_fq;
2313 
2314         if (hctx->flags & BLK_MQ_F_BLOCKING)
2315                 init_srcu_struct(hctx->srcu);
2316 
2317         blk_mq_debugfs_register_hctx(q, hctx);
2318 
2319         return 0;
2320 
2321  free_fq:
2322         kfree(hctx->fq);
2323  sched_exit_hctx:
2324         blk_mq_sched_exit_hctx(q, hctx, hctx_idx);
2325  exit_hctx:
2326         if (set->ops->exit_hctx)
2327                 set->ops->exit_hctx(hctx, hctx_idx);
2328  free_bitmap:
2329         sbitmap_free(&hctx->ctx_map);
2330  free_ctxs:
2331         kfree(hctx->ctxs);
2332  unregister_cpu_notifier:
2333         blk_mq_remove_cpuhp(hctx);
2334         return -1;
2335 }
2336 
2337 static void blk_mq_init_cpu_queues(struct request_queue *q,
2338                                    unsigned int nr_hw_queues)
2339 {
2340         unsigned int i;
2341 
2342         for_each_possible_cpu(i) {
2343                 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
2344                 struct blk_mq_hw_ctx *hctx;
2345 
2346                 __ctx->cpu = i;
2347                 spin_lock_init(&__ctx->lock);
2348                 INIT_LIST_HEAD(&__ctx->rq_list);
2349                 __ctx->queue = q;
2350 
2351                 /*
2352                  * Set local node, IFF we have more than one hw queue. If
2353                  * not, we remain on the home node of the device
2354                  */
2355                 hctx = blk_mq_map_queue(q, i);
2356                 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
2357                         hctx->numa_node = local_memory_node(cpu_to_node(i));
2358         }
2359 }
2360 
2361 static bool __blk_mq_alloc_rq_map(struct blk_mq_tag_set *set, int hctx_idx)
2362 {
2363         int ret = 0;
2364 
2365         set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
2366                                         set->queue_depth, set->reserved_tags);
2367         if (!set->tags[hctx_idx])
2368                 return false;
2369 
2370         ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
2371                                 set->queue_depth);
2372         if (!ret)
2373                 return true;
2374 
2375         blk_mq_free_rq_map(set->tags[hctx_idx]);
2376         set->tags[hctx_idx] = NULL;
2377         return false;
2378 }
2379 
2380 static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2381                                          unsigned int hctx_idx)
2382 {
2383         if (set->tags[hctx_idx]) {
2384                 blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
2385                 blk_mq_free_rq_map(set->tags[hctx_idx]);
2386                 set->tags[hctx_idx] = NULL;
2387         }
2388 }
2389 
2390 static void blk_mq_map_swqueue(struct request_queue *q)
2391 {
2392         unsigned int i, hctx_idx;
2393         struct blk_mq_hw_ctx *hctx;
2394         struct blk_mq_ctx *ctx;
2395         struct blk_mq_tag_set *set = q->tag_set;
2396 
2397         /*
2398          * Avoid others reading imcomplete hctx->cpumask through sysfs
2399          */
2400         mutex_lock(&q->sysfs_lock);
2401 
2402         queue_for_each_hw_ctx(q, hctx, i) {
2403                 cpumask_clear(hctx->cpumask);
2404                 hctx->nr_ctx = 0;
2405         }
2406 
2407         /*
2408          * Map software to hardware queues.
2409          *
2410          * If the cpu isn't present, the cpu is mapped to first hctx.
2411          */
2412         for_each_possible_cpu(i) {
2413                 hctx_idx = q->mq_map[i];
2414                 /* unmapped hw queue can be remapped after CPU topo changed */
2415                 if (!set->tags[hctx_idx] &&
2416                     !__blk_mq_alloc_rq_map(set, hctx_idx)) {
2417                         /*
2418                          * If tags initialization fail for some hctx,
2419                          * that hctx won't be brought online.  In this
2420                          * case, remap the current ctx to hctx[0] which
2421                          * is guaranteed to always have tags allocated
2422                          */
2423                         q->mq_map[i] = 0;
2424                 }
2425 
2426                 ctx = per_cpu_ptr(q->queue_ctx, i);
2427                 hctx = blk_mq_map_queue(q, i);
2428 
2429                 cpumask_set_cpu(i, hctx->cpumask);
2430                 ctx->index_hw = hctx->nr_ctx;
2431                 hctx->ctxs[hctx->nr_ctx++] = ctx;
2432         }
2433 
2434         mutex_unlock(&q->sysfs_lock);
2435 
2436         queue_for_each_hw_ctx(q, hctx, i) {
2437                 /*
2438                  * If no software queues are mapped to this hardware queue,
2439                  * disable it and free the request entries.
2440                  */
2441                 if (!hctx->nr_ctx) {
2442                         /* Never unmap queue 0.  We need it as a
2443                          * fallback in case of a new remap fails
2444                          * allocation
2445                          */
2446                         if (i && set->tags[i])
2447                                 blk_mq_free_map_and_requests(set, i);
2448 
2449                         hctx->tags = NULL;
2450                         continue;
2451                 }
2452 
2453                 hctx->tags = set->tags[i];
2454                 WARN_ON(!hctx->tags);
2455 
2456                 /*
2457                  * Set the map size to the number of mapped software queues.
2458                  * This is more accurate and more efficient than looping
2459                  * over all possibly mapped software queues.
2460                  */
2461                 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
2462 
2463                 /*
2464                  * Initialize batch roundrobin counts
2465                  */
2466                 hctx->next_cpu = cpumask_first_and(hctx->cpumask,
2467                                 cpu_online_mask);
2468                 if (hctx->next_cpu >= nr_cpu_ids)
2469                         hctx->next_cpu = cpumask_first(hctx->cpumask);
2470                 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2471         }
2472 }
2473 
2474 /*
2475  * Caller needs to ensure that we're either frozen/quiesced, or that
2476  * the queue isn't live yet.
2477  */
2478 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
2479 {
2480         struct blk_mq_hw_ctx *hctx;
2481         int i;
2482 
2483         queue_for_each_hw_ctx(q, hctx, i) {
2484                 if (shared) {
2485                         if (test_bit(BLK_MQ_S_SCHED_RESTART, &hctx->state))
2486                                 atomic_inc(&q->shared_hctx_restart);
2487                         hctx->flags |= BLK_MQ_F_TAG_SHARED;
2488                 } else {
2489                         if (test_bit(BLK_MQ_S_SCHED_RESTART, &hctx->state))
2490                                 atomic_dec(&q->shared_hctx_restart);
2491                         hctx->flags &= ~BLK_MQ_F_TAG_SHARED;
2492                 }
2493         }
2494 }
2495 
2496 static void blk_mq_update_tag_set_depth(struct blk_mq_tag_set *set,
2497                                         bool shared)
2498 {
2499         struct request_queue *q;
2500 
2501         lockdep_assert_held(&set->tag_list_lock);
2502 
2503         list_for_each_entry(q, &set->tag_list, tag_set_list) {
2504                 blk_mq_freeze_queue(q);
2505                 queue_set_hctx_shared(q, shared);
2506                 blk_mq_unfreeze_queue(q);
2507         }
2508 }
2509 
2510 static void blk_mq_del_queue_tag_set(struct request_queue *q)
2511 {
2512         struct blk_mq_tag_set *set = q->tag_set;
2513 
2514         mutex_lock(&set->tag_list_lock);
2515         list_del_rcu(&q->tag_set_list);
2516         if (list_is_singular(&set->tag_list)) {
2517                 /* just transitioned to unshared */
2518                 set->flags &= ~BLK_MQ_F_TAG_SHARED;
2519                 /* update existing queue */
2520                 blk_mq_update_tag_set_depth(set, false);
2521         }
2522         mutex_unlock(&set->tag_list_lock);
2523         synchronize_rcu();
2524         INIT_LIST_HEAD(&q->tag_set_list);
2525 }
2526 
2527 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
2528                                      struct request_queue *q)
2529 {
2530         q->tag_set = set;
2531 
2532         mutex_lock(&set->tag_list_lock);
2533 
2534         /*
2535          * Check to see if we're transitioning to shared (from 1 to 2 queues).
2536          */
2537         if (!list_empty(&set->tag_list) &&
2538             !(set->flags & BLK_MQ_F_TAG_SHARED)) {
2539                 set->flags |= BLK_MQ_F_TAG_SHARED;
2540                 /* update existing queue */
2541                 blk_mq_update_tag_set_depth(set, true);
2542         }
2543         if (set->flags & BLK_MQ_F_TAG_SHARED)
2544                 queue_set_hctx_shared(q, true);
2545         list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
2546 
2547         mutex_unlock(&set->tag_list_lock);
2548 }
2549 
2550 /*
2551  * It is the actual release handler for mq, but we do it from
2552  * request queue's release handler for avoiding use-after-free
2553  * and headache because q->mq_kobj shouldn't have been introduced,
2554  * but we can't group ctx/kctx kobj without it.
2555  */
2556 void blk_mq_release(struct request_queue *q)
2557 {
2558         struct blk_mq_hw_ctx *hctx;
2559         unsigned int i;
2560 
2561         /* hctx kobj stays in hctx */
2562         queue_for_each_hw_ctx(q, hctx, i) {
2563                 if (!hctx)
2564                         continue;
2565                 kobject_put(&hctx->kobj);
2566         }
2567 
2568         q->mq_map = NULL;
2569 
2570         kfree(q->queue_hw_ctx);
2571 
2572         /*
2573          * release .mq_kobj and sw queue's kobject now because
2574          * both share lifetime with request queue.
2575          */
2576         blk_mq_sysfs_deinit(q);
2577 
2578         free_percpu(q->queue_ctx);
2579 }
2580 
2581 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
2582 {
2583         struct request_queue *uninit_q, *q;
2584 
2585         uninit_q = blk_alloc_queue_node(GFP_KERNEL, set->numa_node);
2586         if (!uninit_q)
2587                 return ERR_PTR(-ENOMEM);
2588 
2589         q = blk_mq_init_allocated_queue(set, uninit_q);
2590         if (IS_ERR(q))
2591                 blk_cleanup_queue(uninit_q);
2592 
2593         return q;
2594 }
2595 EXPORT_SYMBOL(blk_mq_init_queue);
2596 
2597 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
2598 {
2599         int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
2600 
2601         BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
2602                            __alignof__(struct blk_mq_hw_ctx)) !=
2603                      sizeof(struct blk_mq_hw_ctx));
2604 
2605         if (tag_set->flags & BLK_MQ_F_BLOCKING)
2606                 hw_ctx_size += sizeof(struct srcu_struct);
2607 
2608         return hw_ctx_size;
2609 }
2610 
2611 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
2612                                                 struct request_queue *q)
2613 {
2614         int i, j;
2615         struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
2616 
2617         blk_mq_sysfs_unregister(q);
2618 
2619         /* protect against switching io scheduler  */
2620         mutex_lock(&q->sysfs_lock);
2621         for (i = 0; i < set->nr_hw_queues; i++) {
2622                 int node;
2623 
2624                 if (hctxs[i])
2625                         continue;
2626 
2627                 node = blk_mq_hw_queue_to_node(q->mq_map, i);
2628                 hctxs[i] = kzalloc_node(blk_mq_hw_ctx_size(set),
2629                                         GFP_KERNEL, node);
2630                 if (!hctxs[i])
2631                         break;
2632 
2633                 if (!zalloc_cpumask_var_node(&hctxs[i]->cpumask, GFP_KERNEL,
2634                                                 node)) {
2635                         kfree(hctxs[i]);
2636                         hctxs[i] = NULL;
2637                         break;
2638                 }
2639 
2640                 atomic_set(&hctxs[i]->nr_active, 0);
2641                 hctxs[i]->numa_node = node;
2642                 hctxs[i]->queue_num = i;
2643 
2644                 if (blk_mq_init_hctx(q, set, hctxs[i], i)) {
2645                         free_cpumask_var(hctxs[i]->cpumask);
2646                         kfree(hctxs[i]);
2647                         hctxs[i] = NULL;
2648                         break;
2649                 }
2650                 blk_mq_hctx_kobj_init(hctxs[i]);
2651         }
2652         for (j = i; j < q->nr_hw_queues; j++) {
2653                 struct blk_mq_hw_ctx *hctx = hctxs[j];
2654 
2655                 if (hctx) {
2656                         if (hctx->tags)
2657                                 blk_mq_free_map_and_requests(set, j);
2658                         blk_mq_exit_hctx(q, set, hctx, j);
2659                         kobject_put(&hctx->kobj);
2660                         hctxs[j] = NULL;
2661 
2662                 }
2663         }
2664         q->nr_hw_queues = i;
2665         mutex_unlock(&q->sysfs_lock);
2666         blk_mq_sysfs_register(q);
2667 }
2668 
2669 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
2670                                                   struct request_queue *q)
2671 {
2672         /* mark the queue as mq asap */
2673         q->mq_ops = set->ops;
2674 
2675         q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
2676                                              blk_mq_poll_stats_bkt,
2677                                              BLK_MQ_POLL_STATS_BKTS, q);
2678         if (!q->poll_cb)
2679                 goto err_exit;
2680 
2681         q->queue_ctx = alloc_percpu(struct blk_mq_ctx);
2682         if (!q->queue_ctx)
2683                 goto err_exit;
2684 
2685         /* init q->mq_kobj and sw queues' kobjects */
2686         blk_mq_sysfs_init(q);
2687 
2688         q->queue_hw_ctx = kzalloc_node(nr_cpu_ids * sizeof(*(q->queue_hw_ctx)),
2689                                                 GFP_KERNEL, set->numa_node);
2690         if (!q->queue_hw_ctx)
2691                 goto err_percpu;
2692 
2693         q->mq_map = set->mq_map;
2694 
2695         blk_mq_realloc_hw_ctxs(set, q);
2696         if (!q->nr_hw_queues)
2697                 goto err_hctxs;
2698 
2699         INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
2700         blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
2701 
2702         q->nr_queues = nr_cpu_ids;
2703 
2704         q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
2705 
2706         if (!(set->flags & BLK_MQ_F_SG_MERGE))
2707                 q->queue_flags |= 1 << QUEUE_FLAG_NO_SG_MERGE;
2708 
2709         q->sg_reserved_size = INT_MAX;
2710 
2711         INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
2712         INIT_LIST_HEAD(&q->requeue_list);
2713         spin_lock_init(&q->requeue_lock);
2714 
2715         blk_queue_make_request(q, blk_mq_make_request);
2716         if (q->mq_ops->poll)
2717                 q->poll_fn = blk_mq_poll;
2718 
2719         /*
2720          * Do this after blk_queue_make_request() overrides it...
2721          */
2722         q->nr_requests = set->queue_depth;
2723 
2724         /*
2725          * Default to classic polling
2726          */
2727         q->poll_nsec = -1;
2728 
2729         if (set->ops->complete)
2730                 blk_queue_softirq_done(q, set->ops->complete);
2731 
2732         blk_mq_init_cpu_queues(q, set->nr_hw_queues);
2733         blk_mq_add_queue_tag_set(set, q);
2734         blk_mq_map_swqueue(q);
2735 
2736         if (!(set->flags & BLK_MQ_F_NO_SCHED)) {
2737                 int ret;
2738 
2739                 ret = blk_mq_sched_init(q);
2740                 if (ret)
2741                         return ERR_PTR(ret);
2742         }
2743 
2744         return q;
2745 
2746 err_hctxs:
2747         kfree(q->queue_hw_ctx);
2748 err_percpu:
2749         free_percpu(q->queue_ctx);
2750 err_exit:
2751         q->mq_ops = NULL;
2752         return ERR_PTR(-ENOMEM);
2753 }
2754 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
2755 
2756 void blk_mq_free_queue(struct request_queue *q)
2757 {
2758         struct blk_mq_tag_set   *set = q->tag_set;
2759 
2760         blk_mq_del_queue_tag_set(q);
2761         blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
2762 }
2763 
2764 /* Basically redo blk_mq_init_queue with queue frozen */
2765 static void blk_mq_queue_reinit(struct request_queue *q)
2766 {
2767         WARN_ON_ONCE(!atomic_read(&q->mq_freeze_depth));
2768 
2769         blk_mq_debugfs_unregister_hctxs(q);
2770         blk_mq_sysfs_unregister(q);
2771 
2772         /*
2773          * redo blk_mq_init_cpu_queues and blk_mq_init_hw_queues. FIXME: maybe
2774          * we should change hctx numa_node according to the new topology (this
2775          * involves freeing and re-allocating memory, worth doing?)
2776          */
2777         blk_mq_map_swqueue(q);
2778 
2779         blk_mq_sysfs_register(q);
2780         blk_mq_debugfs_register_hctxs(q);
2781 }
2782 
2783 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2784 {
2785         int i;
2786 
2787         for (i = 0; i < set->nr_hw_queues; i++)
2788                 if (!__blk_mq_alloc_rq_map(set, i))
2789                         goto out_unwind;
2790 
2791         return 0;
2792 
2793 out_unwind:
2794         while (--i >= 0)
2795                 blk_mq_free_rq_map(set->tags[i]);
2796 
2797         return -ENOMEM;
2798 }
2799 
2800 /*
2801  * Allocate the request maps associated with this tag_set. Note that this
2802  * may reduce the depth asked for, if memory is tight. set->queue_depth
2803  * will be updated to reflect the allocated depth.
2804  */
2805 static int blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
2806 {
2807         unsigned int depth;
2808         int err;
2809 
2810         depth = set->queue_depth;
2811         do {
2812                 err = __blk_mq_alloc_rq_maps(set);
2813                 if (!err)
2814                         break;
2815 
2816                 set->queue_depth >>= 1;
2817                 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
2818                         err = -ENOMEM;
2819                         break;
2820                 }
2821         } while (set->queue_depth);
2822 
2823         if (!set->queue_depth || err) {
2824                 pr_err("blk-mq: failed to allocate request map\n");
2825                 return -ENOMEM;
2826         }
2827 
2828         if (depth != set->queue_depth)
2829                 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
2830                                                 depth, set->queue_depth);
2831 
2832         return 0;
2833 }
2834 
2835 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
2836 {
2837         if (set->ops->map_queues) {
2838                 int cpu;
2839                 /*
2840                  * transport .map_queues is usually done in the following
2841                  * way:
2842                  *
2843                  * for (queue = 0; queue < set->nr_hw_queues; queue++) {
2844                  *      mask = get_cpu_mask(queue)
2845                  *      for_each_cpu(cpu, mask)
2846                  *              set->mq_map[cpu] = queue;
2847                  * }
2848                  *
2849                  * When we need to remap, the table has to be cleared for
2850                  * killing stale mapping since one CPU may not be mapped
2851                  * to any hw queue.
2852                  */
2853                 for_each_possible_cpu(cpu)
2854                         set->mq_map[cpu] = 0;
2855 
2856                 return set->ops->map_queues(set);
2857         } else
2858                 return blk_mq_map_queues(set);
2859 }
2860 
2861 /*
2862  * Alloc a tag set to be associated with one or more request queues.
2863  * May fail with EINVAL for various error conditions. May adjust the
2864  * requested depth down, if if it too large. In that case, the set
2865  * value will be stored in set->queue_depth.
2866  */
2867 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
2868 {
2869         int ret;
2870 
2871         BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
2872 
2873         if (!set->nr_hw_queues)
2874                 return -EINVAL;
2875         if (!set->queue_depth)
2876                 return -EINVAL;
2877         if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
2878                 return -EINVAL;
2879 
2880         if (!set->ops->queue_rq)
2881                 return -EINVAL;
2882 
2883         if (!set->ops->get_budget ^ !set->ops->put_budget)
2884                 return -EINVAL;
2885 
2886         if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
2887                 pr_info("blk-mq: reduced tag depth to %u\n",
2888                         BLK_MQ_MAX_DEPTH);
2889                 set->queue_depth = BLK_MQ_MAX_DEPTH;
2890         }
2891 
2892         /*
2893          * If a crashdump is active, then we are potentially in a very
2894          * memory constrained environment. Limit us to 1 queue and
2895          * 64 tags to prevent using too much memory.
2896          */
2897         if (is_kdump_kernel()) {
2898                 set->nr_hw_queues = 1;
2899                 set->queue_depth = min(64U, set->queue_depth);
2900         }
2901         /*
2902          * There is no use for more h/w queues than cpus.
2903          */
2904         if (set->nr_hw_queues > nr_cpu_ids)
2905                 set->nr_hw_queues = nr_cpu_ids;
2906 
2907         set->tags = kzalloc_node(nr_cpu_ids * sizeof(struct blk_mq_tags *),
2908                                  GFP_KERNEL, set->numa_node);
2909         if (!set->tags)
2910                 return -ENOMEM;
2911 
2912         ret = -ENOMEM;
2913         set->mq_map = kzalloc_node(sizeof(*set->mq_map) * nr_cpu_ids,
2914                         GFP_KERNEL, set->numa_node);
2915         if (!set->mq_map)
2916                 goto out_free_tags;
2917 
2918         ret = blk_mq_update_queue_map(set);
2919         if (ret)
2920                 goto out_free_mq_map;
2921 
2922         ret = blk_mq_alloc_rq_maps(set);
2923         if (ret)
2924                 goto out_free_mq_map;
2925 
2926         mutex_init(&set->tag_list_lock);
2927         INIT_LIST_HEAD(&set->tag_list);
2928 
2929         return 0;
2930 
2931 out_free_mq_map:
2932         kfree(set->mq_map);
2933         set->mq_map = NULL;
2934 out_free_tags:
2935         kfree(set->tags);
2936         set->tags = NULL;
2937         return ret;
2938 }
2939 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
2940 
2941 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
2942 {
2943         int i;
2944 
2945         for (i = 0; i < nr_cpu_ids; i++)
2946                 blk_mq_free_map_and_requests(set, i);
2947 
2948         kfree(set->mq_map);
2949         set->mq_map = NULL;
2950 
2951         kfree(set->tags);
2952         set->tags = NULL;
2953 }
2954 EXPORT_SYMBOL(blk_mq_free_tag_set);
2955 
2956 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
2957 {
2958         struct blk_mq_tag_set *set = q->tag_set;
2959         struct blk_mq_hw_ctx *hctx;
2960         int i, ret;
2961 
2962         if (!set)
2963                 return -EINVAL;
2964 
2965         blk_mq_freeze_queue(q);
2966         blk_mq_quiesce_queue(q);
2967 
2968         ret = 0;
2969         queue_for_each_hw_ctx(q, hctx, i) {
2970                 if (!hctx->tags)
2971                         continue;
2972                 /*
2973                  * If we're using an MQ scheduler, just update the scheduler
2974                  * queue depth. This is similar to what the old code would do.
2975                  */
2976                 if (!hctx->sched_tags) {
2977                         ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
2978                                                         false);
2979                 } else {
2980                         ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
2981                                                         nr, true);
2982                 }
2983                 if (ret)
2984                         break;
2985         }
2986 
2987         if (!ret)
2988                 q->nr_requests = nr;
2989 
2990         blk_mq_unquiesce_queue(q);
2991         blk_mq_unfreeze_queue(q);
2992 
2993         return ret;
2994 }
2995 
2996 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
2997                                                         int nr_hw_queues)
2998 {
2999         struct request_queue *q;
3000 
3001         lockdep_assert_held(&set->tag_list_lock);
3002 
3003         if (nr_hw_queues > nr_cpu_ids)
3004                 nr_hw_queues = nr_cpu_ids;
3005         if (nr_hw_queues < 1 || nr_hw_queues == set->nr_hw_queues)
3006                 return;
3007 
3008         list_for_each_entry(q, &set->tag_list, tag_set_list)
3009                 blk_mq_freeze_queue(q);
3010 
3011         set->nr_hw_queues = nr_hw_queues;
3012         blk_mq_update_queue_map(set);
3013         list_for_each_entry(q, &set->tag_list, tag_set_list) {
3014                 blk_mq_realloc_hw_ctxs(set, q);
3015                 blk_mq_queue_reinit(q);
3016         }
3017 
3018         list_for_each_entry(q, &set->tag_list, tag_set_list)
3019                 blk_mq_unfreeze_queue(q);
3020 }
3021 
3022 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
3023 {
3024         mutex_lock(&set->tag_list_lock);
3025         __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
3026         mutex_unlock(&set->tag_list_lock);
3027 }
3028 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
3029 
3030 /* Enable polling stats and return whether they were already enabled. */
3031 static bool blk_poll_stats_enable(struct request_queue *q)
3032 {
3033         if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3034             test_and_set_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags))
3035                 return true;
3036         blk_stat_add_callback(q, q->poll_cb);
3037         return false;
3038 }
3039 
3040 static void blk_mq_poll_stats_start(struct request_queue *q)
3041 {
3042         /*
3043          * We don't arm the callback if polling stats are not enabled or the
3044          * callback is already active.
3045          */
3046         if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3047             blk_stat_is_active(q->poll_cb))
3048                 return;
3049 
3050         blk_stat_activate_msecs(q->poll_cb, 100);
3051 }
3052 
3053 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
3054 {
3055         struct request_queue *q = cb->data;
3056         int bucket;
3057 
3058         for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
3059                 if (cb->stat[bucket].nr_samples)
3060                         q->poll_stat[bucket] = cb->stat[bucket];
3061         }
3062 }
3063 
3064 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
3065                                        struct blk_mq_hw_ctx *hctx,
3066                                        struct request *rq)
3067 {
3068         unsigned long ret = 0;
3069         int bucket;
3070 
3071         /*
3072          * If stats collection isn't on, don't sleep but turn it on for
3073          * future users
3074          */
3075         if (!blk_poll_stats_enable(q))
3076                 return 0;
3077 
3078         /*
3079          * As an optimistic guess, use half of the mean service time
3080          * for this type of request. We can (and should) make this smarter.
3081          * For instance, if the completion latencies are tight, we can
3082          * get closer than just half the mean. This is especially
3083          * important on devices where the completion latencies are longer
3084          * than ~10 usec. We do use the stats for the relevant IO size
3085          * if available which does lead to better estimates.
3086          */
3087         bucket = blk_mq_poll_stats_bkt(rq);
3088         if (bucket < 0)
3089                 return ret;
3090 
3091         if (q->poll_stat[bucket].nr_samples)
3092                 ret = (q->poll_stat[bucket].mean + 1) / 2;
3093 
3094         return ret;
3095 }
3096 
3097 static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
3098                                      struct blk_mq_hw_ctx *hctx,
3099                                      struct request *rq)
3100 {
3101         struct hrtimer_sleeper hs;
3102         enum hrtimer_mode mode;
3103         unsigned int nsecs;
3104         ktime_t kt;
3105 
3106         if (rq->rq_flags & RQF_MQ_POLL_SLEPT)
3107                 return false;
3108 
3109         /*
3110          * poll_nsec can be:
3111          *
3112          * -1:  don't ever hybrid sleep
3113          *  0:  use half of prev avg
3114          * >0:  use this specific value
3115          */
3116         if (q->poll_nsec == -1)
3117                 return false;
3118         else if (q->poll_nsec > 0)
3119                 nsecs = q->poll_nsec;
3120         else
3121                 nsecs = blk_mq_poll_nsecs(q, hctx, rq);
3122 
3123         if (!nsecs)
3124                 return false;
3125 
3126         rq->rq_flags |= RQF_MQ_POLL_SLEPT;
3127 
3128         /*
3129          * This will be replaced with the stats tracking code, using
3130          * 'avg_completion_time / 2' as the pre-sleep target.
3131          */
3132         kt = nsecs;
3133 
3134         mode = HRTIMER_MODE_REL;
3135         hrtimer_init_on_stack(&hs.timer, CLOCK_MONOTONIC, mode);
3136         hrtimer_set_expires(&hs.timer, kt);
3137 
3138         hrtimer_init_sleeper(&hs, current);
3139         do {
3140                 if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
3141                         break;
3142                 set_current_state(TASK_UNINTERRUPTIBLE);
3143                 hrtimer_start_expires(&hs.timer, mode);
3144                 if (hs.task)
3145                         io_schedule();
3146                 hrtimer_cancel(&hs.timer);
3147                 mode = HRTIMER_MODE_ABS;
3148         } while (hs.task && !signal_pending(current));
3149 
3150         __set_current_state(TASK_RUNNING);
3151         destroy_hrtimer_on_stack(&hs.timer);
3152         return true;
3153 }
3154 
3155 static bool __blk_mq_poll(struct blk_mq_hw_ctx *hctx, struct request *rq)
3156 {
3157         struct request_queue *q = hctx->queue;
3158         long state;
3159 
3160         /*
3161          * If we sleep, have the caller restart the poll loop to reset
3162          * the state. Like for the other success return cases, the
3163          * caller is responsible for checking if the IO completed. If
3164          * the IO isn't complete, we'll get called again and will go
3165          * straight to the busy poll loop.
3166          */
3167         if (blk_mq_poll_hybrid_sleep(q, hctx, rq))
3168                 return true;
3169 
3170         hctx->poll_considered++;
3171 
3172         state = current->state;
3173         while (!need_resched()) {
3174                 int ret;
3175 
3176                 hctx->poll_invoked++;
3177 
3178                 ret = q->mq_ops->poll(hctx, rq->tag);
3179                 if (ret > 0) {
3180                         hctx->poll_success++;
3181                         set_current_state(TASK_RUNNING);
3182                         return true;
3183                 }
3184 
3185                 if (signal_pending_state(state, current))
3186                         set_current_state(TASK_RUNNING);
3187 
3188                 if (current->state == TASK_RUNNING)
3189                         return true;
3190                 if (ret < 0)
3191                         break;
3192                 cpu_relax();
3193         }
3194 
3195         __set_current_state(TASK_RUNNING);
3196         return false;
3197 }
3198 
3199 static bool blk_mq_poll(struct request_queue *q, blk_qc_t cookie)
3200 {
3201         struct blk_mq_hw_ctx *hctx;
3202         struct request *rq;
3203 
3204         if (!test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3205                 return false;
3206 
3207         hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
3208         if (!blk_qc_t_is_internal(cookie))
3209                 rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
3210         else {
3211                 rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
3212                 /*
3213                  * With scheduling, if the request has completed, we'll
3214                  * get a NULL return here, as we clear the sched tag when
3215                  * that happens. The request still remains valid, like always,
3216                  * so we should be safe with just the NULL check.
3217                  */
3218                 if (!rq)
3219                         return false;
3220         }
3221 
3222         return __blk_mq_poll(hctx, rq);
3223 }
3224 
3225 static int __init blk_mq_init(void)
3226 {
3227         cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
3228                                 blk_mq_hctx_notify_dead);
3229         return 0;
3230 }
3231 subsys_initcall(blk_mq_init);
3232 

~ [ 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