1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Block multiqueue core code
4 *
5 * Copyright (C) 2013-2014 Jens Axboe
6 * Copyright (C) 2013-2014 Christoph Hellwig
7 */
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/backing-dev.h>
11 #include <linux/bio.h>
12 #include <linux/blkdev.h>
13 #include <linux/kmemleak.h>
14 #include <linux/mm.h>
15 #include <linux/init.h>
16 #include <linux/slab.h>
17 #include <linux/workqueue.h>
18 #include <linux/smp.h>
19 #include <linux/llist.h>
20 #include <linux/list_sort.h>
21 #include <linux/cpu.h>
22 #include <linux/cache.h>
23 #include <linux/sched/sysctl.h>
24 #include <linux/sched/topology.h>
25 #include <linux/sched/signal.h>
26 #include <linux/delay.h>
27 #include <linux/crash_dump.h>
28 #include <linux/prefetch.h>
29 #include <linux/blk-crypto.h>
30
31 #include <trace/events/block.h>
32
33 #include <linux/blk-mq.h>
34 #include <linux/t10-pi.h>
35 #include "blk.h"
36 #include "blk-mq.h"
37 #include "blk-mq-debugfs.h"
38 #include "blk-mq-tag.h"
39 #include "blk-pm.h"
40 #include "blk-stat.h"
41 #include "blk-mq-sched.h"
42 #include "blk-rq-qos.h"
43
44 static DEFINE_PER_CPU(struct list_head, blk_cpu_done);
45
46 static void blk_mq_poll_stats_start(struct request_queue *q);
47 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb);
48
blk_mq_poll_stats_bkt(const struct request * rq)49 static int blk_mq_poll_stats_bkt(const struct request *rq)
50 {
51 int ddir, sectors, bucket;
52
53 ddir = rq_data_dir(rq);
54 sectors = blk_rq_stats_sectors(rq);
55
56 bucket = ddir + 2 * ilog2(sectors);
57
58 if (bucket < 0)
59 return -1;
60 else if (bucket >= BLK_MQ_POLL_STATS_BKTS)
61 return ddir + BLK_MQ_POLL_STATS_BKTS - 2;
62
63 return bucket;
64 }
65
66 /*
67 * Check if any of the ctx, dispatch list or elevator
68 * have pending work in this hardware queue.
69 */
blk_mq_hctx_has_pending(struct blk_mq_hw_ctx * hctx)70 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
71 {
72 return !list_empty_careful(&hctx->dispatch) ||
73 sbitmap_any_bit_set(&hctx->ctx_map) ||
74 blk_mq_sched_has_work(hctx);
75 }
76
77 /*
78 * Mark this ctx as having pending work in this hardware queue
79 */
blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)80 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
81 struct blk_mq_ctx *ctx)
82 {
83 const int bit = ctx->index_hw[hctx->type];
84
85 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
86 sbitmap_set_bit(&hctx->ctx_map, bit);
87 }
88
blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)89 static void blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx *hctx,
90 struct blk_mq_ctx *ctx)
91 {
92 const int bit = ctx->index_hw[hctx->type];
93
94 sbitmap_clear_bit(&hctx->ctx_map, bit);
95 }
96
97 struct mq_inflight {
98 struct hd_struct *part;
99 unsigned int inflight[2];
100 };
101
blk_mq_check_inflight(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)102 static bool blk_mq_check_inflight(struct blk_mq_hw_ctx *hctx,
103 struct request *rq, void *priv,
104 bool reserved)
105 {
106 struct mq_inflight *mi = priv;
107
108 if ((!mi->part->partno || rq->part == mi->part) &&
109 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
110 mi->inflight[rq_data_dir(rq)]++;
111
112 return true;
113 }
114
blk_mq_in_flight(struct request_queue * q,struct hd_struct * part)115 unsigned int blk_mq_in_flight(struct request_queue *q, struct hd_struct *part)
116 {
117 struct mq_inflight mi = { .part = part };
118
119 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
120
121 return mi.inflight[0] + mi.inflight[1];
122 }
123
blk_mq_in_flight_rw(struct request_queue * q,struct hd_struct * part,unsigned int inflight[2])124 void blk_mq_in_flight_rw(struct request_queue *q, struct hd_struct *part,
125 unsigned int inflight[2])
126 {
127 struct mq_inflight mi = { .part = part };
128
129 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
130 inflight[0] = mi.inflight[0];
131 inflight[1] = mi.inflight[1];
132 }
133
blk_freeze_queue_start(struct request_queue * q)134 void blk_freeze_queue_start(struct request_queue *q)
135 {
136 mutex_lock(&q->mq_freeze_lock);
137 if (++q->mq_freeze_depth == 1) {
138 percpu_ref_kill(&q->q_usage_counter);
139 mutex_unlock(&q->mq_freeze_lock);
140 if (queue_is_mq(q))
141 blk_mq_run_hw_queues(q, false);
142 } else {
143 mutex_unlock(&q->mq_freeze_lock);
144 }
145 }
146 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
147
blk_mq_freeze_queue_wait(struct request_queue * q)148 void blk_mq_freeze_queue_wait(struct request_queue *q)
149 {
150 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
151 }
152 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
153
blk_mq_freeze_queue_wait_timeout(struct request_queue * q,unsigned long timeout)154 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
155 unsigned long timeout)
156 {
157 return wait_event_timeout(q->mq_freeze_wq,
158 percpu_ref_is_zero(&q->q_usage_counter),
159 timeout);
160 }
161 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
162
163 /*
164 * Guarantee no request is in use, so we can change any data structure of
165 * the queue afterward.
166 */
blk_freeze_queue(struct request_queue * q)167 void blk_freeze_queue(struct request_queue *q)
168 {
169 /*
170 * In the !blk_mq case we are only calling this to kill the
171 * q_usage_counter, otherwise this increases the freeze depth
172 * and waits for it to return to zero. For this reason there is
173 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
174 * exported to drivers as the only user for unfreeze is blk_mq.
175 */
176 blk_freeze_queue_start(q);
177 blk_mq_freeze_queue_wait(q);
178 }
179
blk_mq_freeze_queue(struct request_queue * q)180 void blk_mq_freeze_queue(struct request_queue *q)
181 {
182 /*
183 * ...just an alias to keep freeze and unfreeze actions balanced
184 * in the blk_mq_* namespace
185 */
186 blk_freeze_queue(q);
187 }
188 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
189
blk_mq_unfreeze_queue(struct request_queue * q)190 void blk_mq_unfreeze_queue(struct request_queue *q)
191 {
192 mutex_lock(&q->mq_freeze_lock);
193 q->mq_freeze_depth--;
194 WARN_ON_ONCE(q->mq_freeze_depth < 0);
195 if (!q->mq_freeze_depth) {
196 percpu_ref_resurrect(&q->q_usage_counter);
197 wake_up_all(&q->mq_freeze_wq);
198 }
199 mutex_unlock(&q->mq_freeze_lock);
200 }
201 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
202
203 /*
204 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
205 * mpt3sas driver such that this function can be removed.
206 */
blk_mq_quiesce_queue_nowait(struct request_queue * q)207 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
208 {
209 unsigned long flags;
210
211 spin_lock_irqsave(&q->queue_lock, flags);
212 if (!q->quiesce_depth++)
213 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
214 spin_unlock_irqrestore(&q->queue_lock, flags);
215 }
216 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
217
218 /**
219 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
220 * @q: request queue.
221 *
222 * Note: this function does not prevent that the struct request end_io()
223 * callback function is invoked. Once this function is returned, we make
224 * sure no dispatch can happen until the queue is unquiesced via
225 * blk_mq_unquiesce_queue().
226 */
blk_mq_quiesce_queue(struct request_queue * q)227 void blk_mq_quiesce_queue(struct request_queue *q)
228 {
229 struct blk_mq_hw_ctx *hctx;
230 unsigned int i;
231 bool rcu = false;
232
233 blk_mq_quiesce_queue_nowait(q);
234
235 queue_for_each_hw_ctx(q, hctx, i) {
236 if (hctx->flags & BLK_MQ_F_BLOCKING)
237 synchronize_srcu(hctx->srcu);
238 else
239 rcu = true;
240 }
241 if (rcu)
242 synchronize_rcu();
243 }
244 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
245
246 /*
247 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
248 * @q: request queue.
249 *
250 * This function recovers queue into the state before quiescing
251 * which is done by blk_mq_quiesce_queue.
252 */
blk_mq_unquiesce_queue(struct request_queue * q)253 void blk_mq_unquiesce_queue(struct request_queue *q)
254 {
255 unsigned long flags;
256 bool run_queue = false;
257
258 spin_lock_irqsave(&q->queue_lock, flags);
259 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
260 ;
261 } else if (!--q->quiesce_depth) {
262 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
263 run_queue = true;
264 }
265 spin_unlock_irqrestore(&q->queue_lock, flags);
266
267 /* dispatch requests which are inserted during quiescing */
268 if (run_queue)
269 blk_mq_run_hw_queues(q, true);
270 }
271 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
272
blk_mq_wake_waiters(struct request_queue * q)273 void blk_mq_wake_waiters(struct request_queue *q)
274 {
275 struct blk_mq_hw_ctx *hctx;
276 unsigned int i;
277
278 queue_for_each_hw_ctx(q, hctx, i)
279 if (blk_mq_hw_queue_mapped(hctx))
280 blk_mq_tag_wakeup_all(hctx->tags, true);
281 }
282
283 /*
284 * Only need start/end time stamping if we have iostat or
285 * blk stats enabled, or using an IO scheduler.
286 */
blk_mq_need_time_stamp(struct request * rq)287 static inline bool blk_mq_need_time_stamp(struct request *rq)
288 {
289 return (rq->rq_flags & (RQF_IO_STAT | RQF_STATS)) || rq->q->elevator;
290 }
291
blk_mq_rq_ctx_init(struct blk_mq_alloc_data * data,unsigned int tag,u64 alloc_time_ns)292 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
293 unsigned int tag, u64 alloc_time_ns)
294 {
295 struct blk_mq_tags *tags = blk_mq_tags_from_data(data);
296 struct request *rq = tags->static_rqs[tag];
297
298 if (data->q->elevator) {
299 rq->tag = BLK_MQ_NO_TAG;
300 rq->internal_tag = tag;
301 } else {
302 rq->tag = tag;
303 rq->internal_tag = BLK_MQ_NO_TAG;
304 }
305
306 /* csd/requeue_work/fifo_time is initialized before use */
307 rq->q = data->q;
308 rq->mq_ctx = data->ctx;
309 rq->mq_hctx = data->hctx;
310 rq->rq_flags = 0;
311 rq->cmd_flags = data->cmd_flags;
312 if (data->flags & BLK_MQ_REQ_PM)
313 rq->rq_flags |= RQF_PM;
314 if (blk_queue_io_stat(data->q))
315 rq->rq_flags |= RQF_IO_STAT;
316 INIT_LIST_HEAD(&rq->queuelist);
317 INIT_HLIST_NODE(&rq->hash);
318 RB_CLEAR_NODE(&rq->rb_node);
319 rq->rq_disk = NULL;
320 rq->part = NULL;
321 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
322 rq->alloc_time_ns = alloc_time_ns;
323 #endif
324 if (blk_mq_need_time_stamp(rq))
325 rq->start_time_ns = ktime_get_ns();
326 else
327 rq->start_time_ns = 0;
328 rq->io_start_time_ns = 0;
329 rq->stats_sectors = 0;
330 rq->nr_phys_segments = 0;
331 #if defined(CONFIG_BLK_DEV_INTEGRITY)
332 rq->nr_integrity_segments = 0;
333 #endif
334 blk_crypto_rq_set_defaults(rq);
335 /* tag was already set */
336 WRITE_ONCE(rq->deadline, 0);
337
338 rq->timeout = 0;
339
340 rq->end_io = NULL;
341 rq->end_io_data = NULL;
342
343 data->ctx->rq_dispatched[op_is_sync(data->cmd_flags)]++;
344 refcount_set(&rq->ref, 1);
345
346 if (!op_is_flush(data->cmd_flags)) {
347 struct elevator_queue *e = data->q->elevator;
348
349 rq->elv.icq = NULL;
350 if (e && e->type->ops.prepare_request) {
351 if (e->type->icq_cache)
352 blk_mq_sched_assign_ioc(rq);
353
354 e->type->ops.prepare_request(rq);
355 rq->rq_flags |= RQF_ELVPRIV;
356 }
357 }
358
359 data->hctx->queued++;
360 return rq;
361 }
362
__blk_mq_alloc_request(struct blk_mq_alloc_data * data)363 static struct request *__blk_mq_alloc_request(struct blk_mq_alloc_data *data)
364 {
365 struct request_queue *q = data->q;
366 struct elevator_queue *e = q->elevator;
367 u64 alloc_time_ns = 0;
368 unsigned int tag;
369
370 /* alloc_time includes depth and tag waits */
371 if (blk_queue_rq_alloc_time(q))
372 alloc_time_ns = ktime_get_ns();
373
374 if (data->cmd_flags & REQ_NOWAIT)
375 data->flags |= BLK_MQ_REQ_NOWAIT;
376
377 if (e) {
378 /*
379 * Flush requests are special and go directly to the
380 * dispatch list. Don't include reserved tags in the
381 * limiting, as it isn't useful.
382 */
383 if (!op_is_flush(data->cmd_flags) &&
384 e->type->ops.limit_depth &&
385 !(data->flags & BLK_MQ_REQ_RESERVED))
386 e->type->ops.limit_depth(data->cmd_flags, data);
387 }
388
389 retry:
390 data->ctx = blk_mq_get_ctx(q);
391 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
392 if (!e)
393 blk_mq_tag_busy(data->hctx);
394
395 /*
396 * Waiting allocations only fail because of an inactive hctx. In that
397 * case just retry the hctx assignment and tag allocation as CPU hotplug
398 * should have migrated us to an online CPU by now.
399 */
400 tag = blk_mq_get_tag(data);
401 if (tag == BLK_MQ_NO_TAG) {
402 if (data->flags & BLK_MQ_REQ_NOWAIT)
403 return NULL;
404
405 /*
406 * Give up the CPU and sleep for a random short time to ensure
407 * that thread using a realtime scheduling class are migrated
408 * off the CPU, and thus off the hctx that is going away.
409 */
410 msleep(3);
411 goto retry;
412 }
413 return blk_mq_rq_ctx_init(data, tag, alloc_time_ns);
414 }
415
blk_mq_alloc_request(struct request_queue * q,unsigned int op,blk_mq_req_flags_t flags)416 struct request *blk_mq_alloc_request(struct request_queue *q, unsigned int op,
417 blk_mq_req_flags_t flags)
418 {
419 struct blk_mq_alloc_data data = {
420 .q = q,
421 .flags = flags,
422 .cmd_flags = op,
423 };
424 struct request *rq;
425 int ret;
426
427 ret = blk_queue_enter(q, flags);
428 if (ret)
429 return ERR_PTR(ret);
430
431 rq = __blk_mq_alloc_request(&data);
432 if (!rq)
433 goto out_queue_exit;
434 rq->__data_len = 0;
435 rq->__sector = (sector_t) -1;
436 rq->bio = rq->biotail = NULL;
437 return rq;
438 out_queue_exit:
439 blk_queue_exit(q);
440 return ERR_PTR(-EWOULDBLOCK);
441 }
442 EXPORT_SYMBOL(blk_mq_alloc_request);
443
blk_mq_alloc_request_hctx(struct request_queue * q,unsigned int op,blk_mq_req_flags_t flags,unsigned int hctx_idx)444 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
445 unsigned int op, blk_mq_req_flags_t flags, unsigned int hctx_idx)
446 {
447 struct blk_mq_alloc_data data = {
448 .q = q,
449 .flags = flags,
450 .cmd_flags = op,
451 };
452 u64 alloc_time_ns = 0;
453 unsigned int cpu;
454 unsigned int tag;
455 int ret;
456
457 /* alloc_time includes depth and tag waits */
458 if (blk_queue_rq_alloc_time(q))
459 alloc_time_ns = ktime_get_ns();
460
461 /*
462 * If the tag allocator sleeps we could get an allocation for a
463 * different hardware context. No need to complicate the low level
464 * allocator for this for the rare use case of a command tied to
465 * a specific queue.
466 */
467 if (WARN_ON_ONCE(!(flags & (BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED))))
468 return ERR_PTR(-EINVAL);
469
470 if (hctx_idx >= q->nr_hw_queues)
471 return ERR_PTR(-EIO);
472
473 ret = blk_queue_enter(q, flags);
474 if (ret)
475 return ERR_PTR(ret);
476
477 /*
478 * Check if the hardware context is actually mapped to anything.
479 * If not tell the caller that it should skip this queue.
480 */
481 ret = -EXDEV;
482 data.hctx = q->queue_hw_ctx[hctx_idx];
483 if (!blk_mq_hw_queue_mapped(data.hctx))
484 goto out_queue_exit;
485 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
486 if (cpu >= nr_cpu_ids)
487 goto out_queue_exit;
488 data.ctx = __blk_mq_get_ctx(q, cpu);
489
490 if (!q->elevator)
491 blk_mq_tag_busy(data.hctx);
492
493 ret = -EWOULDBLOCK;
494 tag = blk_mq_get_tag(&data);
495 if (tag == BLK_MQ_NO_TAG)
496 goto out_queue_exit;
497 return blk_mq_rq_ctx_init(&data, tag, alloc_time_ns);
498
499 out_queue_exit:
500 blk_queue_exit(q);
501 return ERR_PTR(ret);
502 }
503 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
504
__blk_mq_free_request(struct request * rq)505 static void __blk_mq_free_request(struct request *rq)
506 {
507 struct request_queue *q = rq->q;
508 struct blk_mq_ctx *ctx = rq->mq_ctx;
509 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
510 const int sched_tag = rq->internal_tag;
511
512 blk_crypto_free_request(rq);
513 blk_pm_mark_last_busy(rq);
514 rq->mq_hctx = NULL;
515 if (rq->tag != BLK_MQ_NO_TAG)
516 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
517 if (sched_tag != BLK_MQ_NO_TAG)
518 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
519 blk_mq_sched_restart(hctx);
520 blk_queue_exit(q);
521 }
522
blk_mq_free_request(struct request * rq)523 void blk_mq_free_request(struct request *rq)
524 {
525 struct request_queue *q = rq->q;
526 struct elevator_queue *e = q->elevator;
527 struct blk_mq_ctx *ctx = rq->mq_ctx;
528 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
529
530 if (rq->rq_flags & RQF_ELVPRIV) {
531 if (e && e->type->ops.finish_request)
532 e->type->ops.finish_request(rq);
533 if (rq->elv.icq) {
534 put_io_context(rq->elv.icq->ioc);
535 rq->elv.icq = NULL;
536 }
537 }
538
539 ctx->rq_completed[rq_is_sync(rq)]++;
540 if (rq->rq_flags & RQF_MQ_INFLIGHT)
541 __blk_mq_dec_active_requests(hctx);
542
543 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
544 laptop_io_completion(q->backing_dev_info);
545
546 rq_qos_done(q, rq);
547
548 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
549 if (refcount_dec_and_test(&rq->ref))
550 __blk_mq_free_request(rq);
551 }
552 EXPORT_SYMBOL_GPL(blk_mq_free_request);
553
__blk_mq_end_request(struct request * rq,blk_status_t error)554 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
555 {
556 u64 now = 0;
557
558 if (blk_mq_need_time_stamp(rq))
559 now = ktime_get_ns();
560
561 if (rq->rq_flags & RQF_STATS) {
562 blk_mq_poll_stats_start(rq->q);
563 blk_stat_add(rq, now);
564 }
565
566 blk_mq_sched_completed_request(rq, now);
567
568 blk_account_io_done(rq, now);
569
570 if (rq->end_io) {
571 rq_qos_done(rq->q, rq);
572 rq->end_io(rq, error);
573 } else {
574 blk_mq_free_request(rq);
575 }
576 }
577 EXPORT_SYMBOL(__blk_mq_end_request);
578
blk_mq_end_request(struct request * rq,blk_status_t error)579 void blk_mq_end_request(struct request *rq, blk_status_t error)
580 {
581 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
582 BUG();
583 __blk_mq_end_request(rq, error);
584 }
585 EXPORT_SYMBOL(blk_mq_end_request);
586
587 /*
588 * Softirq action handler - move entries to local list and loop over them
589 * while passing them to the queue registered handler.
590 */
blk_done_softirq(struct softirq_action * h)591 static __latent_entropy void blk_done_softirq(struct softirq_action *h)
592 {
593 struct list_head *cpu_list, local_list;
594
595 local_irq_disable();
596 cpu_list = this_cpu_ptr(&blk_cpu_done);
597 list_replace_init(cpu_list, &local_list);
598 local_irq_enable();
599
600 while (!list_empty(&local_list)) {
601 struct request *rq;
602
603 rq = list_entry(local_list.next, struct request, ipi_list);
604 list_del_init(&rq->ipi_list);
605 rq->q->mq_ops->complete(rq);
606 }
607 }
608
blk_mq_trigger_softirq(struct request * rq)609 static void blk_mq_trigger_softirq(struct request *rq)
610 {
611 struct list_head *list;
612 unsigned long flags;
613
614 local_irq_save(flags);
615 list = this_cpu_ptr(&blk_cpu_done);
616 list_add_tail(&rq->ipi_list, list);
617
618 /*
619 * If the list only contains our just added request, signal a raise of
620 * the softirq. If there are already entries there, someone already
621 * raised the irq but it hasn't run yet.
622 */
623 if (list->next == &rq->ipi_list)
624 raise_softirq_irqoff(BLOCK_SOFTIRQ);
625 local_irq_restore(flags);
626 }
627
blk_softirq_cpu_dead(unsigned int cpu)628 static int blk_softirq_cpu_dead(unsigned int cpu)
629 {
630 /*
631 * If a CPU goes away, splice its entries to the current CPU
632 * and trigger a run of the softirq
633 */
634 local_irq_disable();
635 list_splice_init(&per_cpu(blk_cpu_done, cpu),
636 this_cpu_ptr(&blk_cpu_done));
637 raise_softirq_irqoff(BLOCK_SOFTIRQ);
638 local_irq_enable();
639
640 return 0;
641 }
642
643
__blk_mq_complete_request_remote(void * data)644 static void __blk_mq_complete_request_remote(void *data)
645 {
646 struct request *rq = data;
647
648 /*
649 * For most of single queue controllers, there is only one irq vector
650 * for handling I/O completion, and the only irq's affinity is set
651 * to all possible CPUs. On most of ARCHs, this affinity means the irq
652 * is handled on one specific CPU.
653 *
654 * So complete I/O requests in softirq context in case of single queue
655 * devices to avoid degrading I/O performance due to irqsoff latency.
656 */
657 if (rq->q->nr_hw_queues == 1)
658 blk_mq_trigger_softirq(rq);
659 else
660 rq->q->mq_ops->complete(rq);
661 }
662
blk_mq_complete_need_ipi(struct request * rq)663 static inline bool blk_mq_complete_need_ipi(struct request *rq)
664 {
665 int cpu = raw_smp_processor_id();
666
667 if (!IS_ENABLED(CONFIG_SMP) ||
668 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
669 return false;
670
671 /* same CPU or cache domain? Complete locally */
672 if (cpu == rq->mq_ctx->cpu ||
673 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
674 cpus_share_cache(cpu, rq->mq_ctx->cpu)))
675 return false;
676
677 /* don't try to IPI to an offline CPU */
678 return cpu_online(rq->mq_ctx->cpu);
679 }
680
blk_mq_complete_request_remote(struct request * rq)681 bool blk_mq_complete_request_remote(struct request *rq)
682 {
683 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
684
685 /*
686 * For a polled request, always complete locallly, it's pointless
687 * to redirect the completion.
688 */
689 if (rq->cmd_flags & REQ_HIPRI)
690 return false;
691
692 if (blk_mq_complete_need_ipi(rq)) {
693 rq->csd.func = __blk_mq_complete_request_remote;
694 rq->csd.info = rq;
695 rq->csd.flags = 0;
696 smp_call_function_single_async(rq->mq_ctx->cpu, &rq->csd);
697 } else {
698 if (rq->q->nr_hw_queues > 1)
699 return false;
700 blk_mq_trigger_softirq(rq);
701 }
702
703 return true;
704 }
705 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
706
707 /**
708 * blk_mq_complete_request - end I/O on a request
709 * @rq: the request being processed
710 *
711 * Description:
712 * Complete a request by scheduling the ->complete_rq operation.
713 **/
blk_mq_complete_request(struct request * rq)714 void blk_mq_complete_request(struct request *rq)
715 {
716 if (!blk_mq_complete_request_remote(rq))
717 rq->q->mq_ops->complete(rq);
718 }
719 EXPORT_SYMBOL(blk_mq_complete_request);
720
hctx_unlock(struct blk_mq_hw_ctx * hctx,int srcu_idx)721 static void hctx_unlock(struct blk_mq_hw_ctx *hctx, int srcu_idx)
722 __releases(hctx->srcu)
723 {
724 if (!(hctx->flags & BLK_MQ_F_BLOCKING))
725 rcu_read_unlock();
726 else
727 srcu_read_unlock(hctx->srcu, srcu_idx);
728 }
729
hctx_lock(struct blk_mq_hw_ctx * hctx,int * srcu_idx)730 static void hctx_lock(struct blk_mq_hw_ctx *hctx, int *srcu_idx)
731 __acquires(hctx->srcu)
732 {
733 if (!(hctx->flags & BLK_MQ_F_BLOCKING)) {
734 /* shut up gcc false positive */
735 *srcu_idx = 0;
736 rcu_read_lock();
737 } else
738 *srcu_idx = srcu_read_lock(hctx->srcu);
739 }
740
741 /**
742 * blk_mq_start_request - Start processing a request
743 * @rq: Pointer to request to be started
744 *
745 * Function used by device drivers to notify the block layer that a request
746 * is going to be processed now, so blk layer can do proper initializations
747 * such as starting the timeout timer.
748 */
blk_mq_start_request(struct request * rq)749 void blk_mq_start_request(struct request *rq)
750 {
751 struct request_queue *q = rq->q;
752
753 trace_block_rq_issue(rq);
754
755 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags)) {
756 rq->io_start_time_ns = ktime_get_ns();
757 rq->stats_sectors = blk_rq_sectors(rq);
758 rq->rq_flags |= RQF_STATS;
759 rq_qos_issue(q, rq);
760 }
761
762 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
763
764 blk_add_timer(rq);
765 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
766
767 #ifdef CONFIG_BLK_DEV_INTEGRITY
768 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
769 q->integrity.profile->prepare_fn(rq);
770 #endif
771 }
772 EXPORT_SYMBOL(blk_mq_start_request);
773
__blk_mq_requeue_request(struct request * rq)774 static void __blk_mq_requeue_request(struct request *rq)
775 {
776 struct request_queue *q = rq->q;
777
778 blk_mq_put_driver_tag(rq);
779
780 trace_block_rq_requeue(rq);
781 rq_qos_requeue(q, rq);
782
783 if (blk_mq_request_started(rq)) {
784 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
785 rq->rq_flags &= ~RQF_TIMED_OUT;
786 }
787 }
788
blk_mq_requeue_request(struct request * rq,bool kick_requeue_list)789 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
790 {
791 __blk_mq_requeue_request(rq);
792
793 /* this request will be re-inserted to io scheduler queue */
794 blk_mq_sched_requeue_request(rq);
795
796 blk_mq_add_to_requeue_list(rq, true, kick_requeue_list);
797 }
798 EXPORT_SYMBOL(blk_mq_requeue_request);
799
blk_mq_requeue_work(struct work_struct * work)800 static void blk_mq_requeue_work(struct work_struct *work)
801 {
802 struct request_queue *q =
803 container_of(work, struct request_queue, requeue_work.work);
804 LIST_HEAD(rq_list);
805 struct request *rq, *next;
806
807 spin_lock_irq(&q->requeue_lock);
808 list_splice_init(&q->requeue_list, &rq_list);
809 spin_unlock_irq(&q->requeue_lock);
810
811 list_for_each_entry_safe(rq, next, &rq_list, queuelist) {
812 if (!(rq->rq_flags & (RQF_SOFTBARRIER | RQF_DONTPREP)))
813 continue;
814
815 rq->rq_flags &= ~RQF_SOFTBARRIER;
816 list_del_init(&rq->queuelist);
817 /*
818 * If RQF_DONTPREP, rq has contained some driver specific
819 * data, so insert it to hctx dispatch list to avoid any
820 * merge.
821 */
822 if (rq->rq_flags & RQF_DONTPREP)
823 blk_mq_request_bypass_insert(rq, false, false);
824 else
825 blk_mq_sched_insert_request(rq, true, false, false);
826 }
827
828 while (!list_empty(&rq_list)) {
829 rq = list_entry(rq_list.next, struct request, queuelist);
830 list_del_init(&rq->queuelist);
831 blk_mq_sched_insert_request(rq, false, false, false);
832 }
833
834 blk_mq_run_hw_queues(q, false);
835 }
836
blk_mq_add_to_requeue_list(struct request * rq,bool at_head,bool kick_requeue_list)837 void blk_mq_add_to_requeue_list(struct request *rq, bool at_head,
838 bool kick_requeue_list)
839 {
840 struct request_queue *q = rq->q;
841 unsigned long flags;
842
843 /*
844 * We abuse this flag that is otherwise used by the I/O scheduler to
845 * request head insertion from the workqueue.
846 */
847 BUG_ON(rq->rq_flags & RQF_SOFTBARRIER);
848
849 spin_lock_irqsave(&q->requeue_lock, flags);
850 if (at_head) {
851 rq->rq_flags |= RQF_SOFTBARRIER;
852 list_add(&rq->queuelist, &q->requeue_list);
853 } else {
854 list_add_tail(&rq->queuelist, &q->requeue_list);
855 }
856 spin_unlock_irqrestore(&q->requeue_lock, flags);
857
858 if (kick_requeue_list)
859 blk_mq_kick_requeue_list(q);
860 }
861
blk_mq_kick_requeue_list(struct request_queue * q)862 void blk_mq_kick_requeue_list(struct request_queue *q)
863 {
864 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
865 }
866 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
867
blk_mq_delay_kick_requeue_list(struct request_queue * q,unsigned long msecs)868 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
869 unsigned long msecs)
870 {
871 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
872 msecs_to_jiffies(msecs));
873 }
874 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
875
blk_mq_tag_to_rq(struct blk_mq_tags * tags,unsigned int tag)876 struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag)
877 {
878 if (tag < tags->nr_tags) {
879 prefetch(tags->rqs[tag]);
880 return tags->rqs[tag];
881 }
882
883 return NULL;
884 }
885 EXPORT_SYMBOL(blk_mq_tag_to_rq);
886
blk_mq_rq_inflight(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)887 static bool blk_mq_rq_inflight(struct blk_mq_hw_ctx *hctx, struct request *rq,
888 void *priv, bool reserved)
889 {
890 /*
891 * If we find a request that isn't idle and the queue matches,
892 * we know the queue is busy. Return false to stop the iteration.
893 */
894 if (blk_mq_request_started(rq) && rq->q == hctx->queue) {
895 bool *busy = priv;
896
897 *busy = true;
898 return false;
899 }
900
901 return true;
902 }
903
blk_mq_queue_inflight(struct request_queue * q)904 bool blk_mq_queue_inflight(struct request_queue *q)
905 {
906 bool busy = false;
907
908 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
909 return busy;
910 }
911 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
912
blk_mq_rq_timed_out(struct request * req,bool reserved)913 static void blk_mq_rq_timed_out(struct request *req, bool reserved)
914 {
915 req->rq_flags |= RQF_TIMED_OUT;
916 if (req->q->mq_ops->timeout) {
917 enum blk_eh_timer_return ret;
918
919 ret = req->q->mq_ops->timeout(req, reserved);
920 if (ret == BLK_EH_DONE)
921 return;
922 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
923 }
924
925 blk_add_timer(req);
926 }
927
blk_mq_req_expired(struct request * rq,unsigned long * next)928 static bool blk_mq_req_expired(struct request *rq, unsigned long *next)
929 {
930 unsigned long deadline;
931
932 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
933 return false;
934 if (rq->rq_flags & RQF_TIMED_OUT)
935 return false;
936
937 deadline = READ_ONCE(rq->deadline);
938 if (time_after_eq(jiffies, deadline))
939 return true;
940
941 if (*next == 0)
942 *next = deadline;
943 else if (time_after(*next, deadline))
944 *next = deadline;
945 return false;
946 }
947
blk_mq_put_rq_ref(struct request * rq)948 void blk_mq_put_rq_ref(struct request *rq)
949 {
950 if (is_flush_rq(rq))
951 rq->end_io(rq, 0);
952 else if (refcount_dec_and_test(&rq->ref))
953 __blk_mq_free_request(rq);
954 }
955
blk_mq_check_expired(struct blk_mq_hw_ctx * hctx,struct request * rq,void * priv,bool reserved)956 static bool blk_mq_check_expired(struct blk_mq_hw_ctx *hctx,
957 struct request *rq, void *priv, bool reserved)
958 {
959 unsigned long *next = priv;
960
961 /*
962 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
963 * be reallocated underneath the timeout handler's processing, then
964 * the expire check is reliable. If the request is not expired, then
965 * it was completed and reallocated as a new request after returning
966 * from blk_mq_check_expired().
967 */
968 if (blk_mq_req_expired(rq, next))
969 blk_mq_rq_timed_out(rq, reserved);
970 return true;
971 }
972
blk_mq_timeout_work(struct work_struct * work)973 static void blk_mq_timeout_work(struct work_struct *work)
974 {
975 struct request_queue *q =
976 container_of(work, struct request_queue, timeout_work);
977 unsigned long next = 0;
978 struct blk_mq_hw_ctx *hctx;
979 int i;
980
981 /* A deadlock might occur if a request is stuck requiring a
982 * timeout at the same time a queue freeze is waiting
983 * completion, since the timeout code would not be able to
984 * acquire the queue reference here.
985 *
986 * That's why we don't use blk_queue_enter here; instead, we use
987 * percpu_ref_tryget directly, because we need to be able to
988 * obtain a reference even in the short window between the queue
989 * starting to freeze, by dropping the first reference in
990 * blk_freeze_queue_start, and the moment the last request is
991 * consumed, marked by the instant q_usage_counter reaches
992 * zero.
993 */
994 if (!percpu_ref_tryget(&q->q_usage_counter))
995 return;
996
997 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &next);
998
999 if (next != 0) {
1000 mod_timer(&q->timeout, next);
1001 } else {
1002 /*
1003 * Request timeouts are handled as a forward rolling timer. If
1004 * we end up here it means that no requests are pending and
1005 * also that no request has been pending for a while. Mark
1006 * each hctx as idle.
1007 */
1008 queue_for_each_hw_ctx(q, hctx, i) {
1009 /* the hctx may be unmapped, so check it here */
1010 if (blk_mq_hw_queue_mapped(hctx))
1011 blk_mq_tag_idle(hctx);
1012 }
1013 }
1014 blk_queue_exit(q);
1015 }
1016
1017 struct flush_busy_ctx_data {
1018 struct blk_mq_hw_ctx *hctx;
1019 struct list_head *list;
1020 };
1021
flush_busy_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1022 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1023 {
1024 struct flush_busy_ctx_data *flush_data = data;
1025 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1026 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1027 enum hctx_type type = hctx->type;
1028
1029 spin_lock(&ctx->lock);
1030 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1031 sbitmap_clear_bit(sb, bitnr);
1032 spin_unlock(&ctx->lock);
1033 return true;
1034 }
1035
1036 /*
1037 * Process software queues that have been marked busy, splicing them
1038 * to the for-dispatch
1039 */
blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx * hctx,struct list_head * list)1040 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1041 {
1042 struct flush_busy_ctx_data data = {
1043 .hctx = hctx,
1044 .list = list,
1045 };
1046
1047 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1048 }
1049 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1050
1051 struct dispatch_rq_data {
1052 struct blk_mq_hw_ctx *hctx;
1053 struct request *rq;
1054 };
1055
dispatch_rq_from_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1056 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1057 void *data)
1058 {
1059 struct dispatch_rq_data *dispatch_data = data;
1060 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1061 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1062 enum hctx_type type = hctx->type;
1063
1064 spin_lock(&ctx->lock);
1065 if (!list_empty(&ctx->rq_lists[type])) {
1066 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1067 list_del_init(&dispatch_data->rq->queuelist);
1068 if (list_empty(&ctx->rq_lists[type]))
1069 sbitmap_clear_bit(sb, bitnr);
1070 }
1071 spin_unlock(&ctx->lock);
1072
1073 return !dispatch_data->rq;
1074 }
1075
blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * start)1076 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1077 struct blk_mq_ctx *start)
1078 {
1079 unsigned off = start ? start->index_hw[hctx->type] : 0;
1080 struct dispatch_rq_data data = {
1081 .hctx = hctx,
1082 .rq = NULL,
1083 };
1084
1085 __sbitmap_for_each_set(&hctx->ctx_map, off,
1086 dispatch_rq_from_ctx, &data);
1087
1088 return data.rq;
1089 }
1090
queued_to_index(unsigned int queued)1091 static inline unsigned int queued_to_index(unsigned int queued)
1092 {
1093 if (!queued)
1094 return 0;
1095
1096 return min(BLK_MQ_MAX_DISPATCH_ORDER - 1, ilog2(queued) + 1);
1097 }
1098
__blk_mq_get_driver_tag(struct request * rq)1099 static bool __blk_mq_get_driver_tag(struct request *rq)
1100 {
1101 struct sbitmap_queue *bt = rq->mq_hctx->tags->bitmap_tags;
1102 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1103 int tag;
1104
1105 blk_mq_tag_busy(rq->mq_hctx);
1106
1107 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1108 bt = rq->mq_hctx->tags->breserved_tags;
1109 tag_offset = 0;
1110 } else {
1111 if (!hctx_may_queue(rq->mq_hctx, bt))
1112 return false;
1113 }
1114
1115 tag = __sbitmap_queue_get(bt);
1116 if (tag == BLK_MQ_NO_TAG)
1117 return false;
1118
1119 rq->tag = tag + tag_offset;
1120 return true;
1121 }
1122
blk_mq_get_driver_tag(struct request * rq)1123 static bool blk_mq_get_driver_tag(struct request *rq)
1124 {
1125 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1126
1127 if (rq->tag == BLK_MQ_NO_TAG && !__blk_mq_get_driver_tag(rq))
1128 return false;
1129
1130 if ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1131 !(rq->rq_flags & RQF_MQ_INFLIGHT)) {
1132 rq->rq_flags |= RQF_MQ_INFLIGHT;
1133 __blk_mq_inc_active_requests(hctx);
1134 }
1135 hctx->tags->rqs[rq->tag] = rq;
1136 return true;
1137 }
1138
blk_mq_dispatch_wake(wait_queue_entry_t * wait,unsigned mode,int flags,void * key)1139 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1140 int flags, void *key)
1141 {
1142 struct blk_mq_hw_ctx *hctx;
1143
1144 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1145
1146 spin_lock(&hctx->dispatch_wait_lock);
1147 if (!list_empty(&wait->entry)) {
1148 struct sbitmap_queue *sbq;
1149
1150 list_del_init(&wait->entry);
1151 sbq = hctx->tags->bitmap_tags;
1152 atomic_dec(&sbq->ws_active);
1153 }
1154 spin_unlock(&hctx->dispatch_wait_lock);
1155
1156 blk_mq_run_hw_queue(hctx, true);
1157 return 1;
1158 }
1159
1160 /*
1161 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1162 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1163 * restart. For both cases, take care to check the condition again after
1164 * marking us as waiting.
1165 */
blk_mq_mark_tag_wait(struct blk_mq_hw_ctx * hctx,struct request * rq)1166 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1167 struct request *rq)
1168 {
1169 struct sbitmap_queue *sbq = hctx->tags->bitmap_tags;
1170 struct wait_queue_head *wq;
1171 wait_queue_entry_t *wait;
1172 bool ret;
1173
1174 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
1175 blk_mq_sched_mark_restart_hctx(hctx);
1176
1177 /*
1178 * It's possible that a tag was freed in the window between the
1179 * allocation failure and adding the hardware queue to the wait
1180 * queue.
1181 *
1182 * Don't clear RESTART here, someone else could have set it.
1183 * At most this will cost an extra queue run.
1184 */
1185 return blk_mq_get_driver_tag(rq);
1186 }
1187
1188 wait = &hctx->dispatch_wait;
1189 if (!list_empty_careful(&wait->entry))
1190 return false;
1191
1192 wq = &bt_wait_ptr(sbq, hctx)->wait;
1193
1194 spin_lock_irq(&wq->lock);
1195 spin_lock(&hctx->dispatch_wait_lock);
1196 if (!list_empty(&wait->entry)) {
1197 spin_unlock(&hctx->dispatch_wait_lock);
1198 spin_unlock_irq(&wq->lock);
1199 return false;
1200 }
1201
1202 atomic_inc(&sbq->ws_active);
1203 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1204 __add_wait_queue(wq, wait);
1205
1206 /*
1207 * It's possible that a tag was freed in the window between the
1208 * allocation failure and adding the hardware queue to the wait
1209 * queue.
1210 */
1211 ret = blk_mq_get_driver_tag(rq);
1212 if (!ret) {
1213 spin_unlock(&hctx->dispatch_wait_lock);
1214 spin_unlock_irq(&wq->lock);
1215 return false;
1216 }
1217
1218 /*
1219 * We got a tag, remove ourselves from the wait queue to ensure
1220 * someone else gets the wakeup.
1221 */
1222 list_del_init(&wait->entry);
1223 atomic_dec(&sbq->ws_active);
1224 spin_unlock(&hctx->dispatch_wait_lock);
1225 spin_unlock_irq(&wq->lock);
1226
1227 return true;
1228 }
1229
1230 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1231 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1232 /*
1233 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1234 * - EWMA is one simple way to compute running average value
1235 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1236 * - take 4 as factor for avoiding to get too small(0) result, and this
1237 * factor doesn't matter because EWMA decreases exponentially
1238 */
blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx * hctx,bool busy)1239 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1240 {
1241 unsigned int ewma;
1242
1243 ewma = hctx->dispatch_busy;
1244
1245 if (!ewma && !busy)
1246 return;
1247
1248 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
1249 if (busy)
1250 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
1251 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
1252
1253 hctx->dispatch_busy = ewma;
1254 }
1255
1256 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
1257
blk_mq_handle_dev_resource(struct request * rq,struct list_head * list)1258 static void blk_mq_handle_dev_resource(struct request *rq,
1259 struct list_head *list)
1260 {
1261 struct request *next =
1262 list_first_entry_or_null(list, struct request, queuelist);
1263
1264 /*
1265 * If an I/O scheduler has been configured and we got a driver tag for
1266 * the next request already, free it.
1267 */
1268 if (next)
1269 blk_mq_put_driver_tag(next);
1270
1271 list_add(&rq->queuelist, list);
1272 __blk_mq_requeue_request(rq);
1273 }
1274
blk_mq_handle_zone_resource(struct request * rq,struct list_head * zone_list)1275 static void blk_mq_handle_zone_resource(struct request *rq,
1276 struct list_head *zone_list)
1277 {
1278 /*
1279 * If we end up here it is because we cannot dispatch a request to a
1280 * specific zone due to LLD level zone-write locking or other zone
1281 * related resource not being available. In this case, set the request
1282 * aside in zone_list for retrying it later.
1283 */
1284 list_add(&rq->queuelist, zone_list);
1285 __blk_mq_requeue_request(rq);
1286 }
1287
1288 enum prep_dispatch {
1289 PREP_DISPATCH_OK,
1290 PREP_DISPATCH_NO_TAG,
1291 PREP_DISPATCH_NO_BUDGET,
1292 };
1293
blk_mq_prep_dispatch_rq(struct request * rq,bool need_budget)1294 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
1295 bool need_budget)
1296 {
1297 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1298
1299 if (need_budget && !blk_mq_get_dispatch_budget(rq->q)) {
1300 blk_mq_put_driver_tag(rq);
1301 return PREP_DISPATCH_NO_BUDGET;
1302 }
1303
1304 if (!blk_mq_get_driver_tag(rq)) {
1305 /*
1306 * The initial allocation attempt failed, so we need to
1307 * rerun the hardware queue when a tag is freed. The
1308 * waitqueue takes care of that. If the queue is run
1309 * before we add this entry back on the dispatch list,
1310 * we'll re-run it below.
1311 */
1312 if (!blk_mq_mark_tag_wait(hctx, rq)) {
1313 /*
1314 * All budgets not got from this function will be put
1315 * together during handling partial dispatch
1316 */
1317 if (need_budget)
1318 blk_mq_put_dispatch_budget(rq->q);
1319 return PREP_DISPATCH_NO_TAG;
1320 }
1321 }
1322
1323 return PREP_DISPATCH_OK;
1324 }
1325
1326 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
blk_mq_release_budgets(struct request_queue * q,unsigned int nr_budgets)1327 static void blk_mq_release_budgets(struct request_queue *q,
1328 unsigned int nr_budgets)
1329 {
1330 int i;
1331
1332 for (i = 0; i < nr_budgets; i++)
1333 blk_mq_put_dispatch_budget(q);
1334 }
1335
1336 /*
1337 * Returns true if we did some work AND can potentially do more.
1338 */
blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx * hctx,struct list_head * list,unsigned int nr_budgets)1339 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
1340 unsigned int nr_budgets)
1341 {
1342 enum prep_dispatch prep;
1343 struct request_queue *q = hctx->queue;
1344 struct request *rq, *nxt;
1345 int errors, queued;
1346 blk_status_t ret = BLK_STS_OK;
1347 LIST_HEAD(zone_list);
1348 bool needs_resource = false;
1349
1350 if (list_empty(list))
1351 return false;
1352
1353 /*
1354 * Now process all the entries, sending them to the driver.
1355 */
1356 errors = queued = 0;
1357 do {
1358 struct blk_mq_queue_data bd;
1359
1360 rq = list_first_entry(list, struct request, queuelist);
1361
1362 WARN_ON_ONCE(hctx != rq->mq_hctx);
1363 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
1364 if (prep != PREP_DISPATCH_OK)
1365 break;
1366
1367 list_del_init(&rq->queuelist);
1368
1369 bd.rq = rq;
1370
1371 /*
1372 * Flag last if we have no more requests, or if we have more
1373 * but can't assign a driver tag to it.
1374 */
1375 if (list_empty(list))
1376 bd.last = true;
1377 else {
1378 nxt = list_first_entry(list, struct request, queuelist);
1379 bd.last = !blk_mq_get_driver_tag(nxt);
1380 }
1381
1382 /*
1383 * once the request is queued to lld, no need to cover the
1384 * budget any more
1385 */
1386 if (nr_budgets)
1387 nr_budgets--;
1388 ret = q->mq_ops->queue_rq(hctx, &bd);
1389 switch (ret) {
1390 case BLK_STS_OK:
1391 queued++;
1392 break;
1393 case BLK_STS_RESOURCE:
1394 needs_resource = true;
1395 fallthrough;
1396 case BLK_STS_DEV_RESOURCE:
1397 blk_mq_handle_dev_resource(rq, list);
1398 goto out;
1399 case BLK_STS_ZONE_RESOURCE:
1400 /*
1401 * Move the request to zone_list and keep going through
1402 * the dispatch list to find more requests the drive can
1403 * accept.
1404 */
1405 blk_mq_handle_zone_resource(rq, &zone_list);
1406 needs_resource = true;
1407 break;
1408 default:
1409 errors++;
1410 blk_mq_end_request(rq, BLK_STS_IOERR);
1411 }
1412 } while (!list_empty(list));
1413 out:
1414 if (!list_empty(&zone_list))
1415 list_splice_tail_init(&zone_list, list);
1416
1417 hctx->dispatched[queued_to_index(queued)]++;
1418
1419 /* If we didn't flush the entire list, we could have told the driver
1420 * there was more coming, but that turned out to be a lie.
1421 */
1422 if ((!list_empty(list) || errors || needs_resource ||
1423 ret == BLK_STS_DEV_RESOURCE) && q->mq_ops->commit_rqs && queued)
1424 q->mq_ops->commit_rqs(hctx);
1425 /*
1426 * Any items that need requeuing? Stuff them into hctx->dispatch,
1427 * that is where we will continue on next queue run.
1428 */
1429 if (!list_empty(list)) {
1430 bool needs_restart;
1431 /* For non-shared tags, the RESTART check will suffice */
1432 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
1433 (hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED);
1434
1435 blk_mq_release_budgets(q, nr_budgets);
1436
1437 spin_lock(&hctx->lock);
1438 list_splice_tail_init(list, &hctx->dispatch);
1439 spin_unlock(&hctx->lock);
1440
1441 /*
1442 * Order adding requests to hctx->dispatch and checking
1443 * SCHED_RESTART flag. The pair of this smp_mb() is the one
1444 * in blk_mq_sched_restart(). Avoid restart code path to
1445 * miss the new added requests to hctx->dispatch, meantime
1446 * SCHED_RESTART is observed here.
1447 */
1448 smp_mb();
1449
1450 /*
1451 * If SCHED_RESTART was set by the caller of this function and
1452 * it is no longer set that means that it was cleared by another
1453 * thread and hence that a queue rerun is needed.
1454 *
1455 * If 'no_tag' is set, that means that we failed getting
1456 * a driver tag with an I/O scheduler attached. If our dispatch
1457 * waitqueue is no longer active, ensure that we run the queue
1458 * AFTER adding our entries back to the list.
1459 *
1460 * If no I/O scheduler has been configured it is possible that
1461 * the hardware queue got stopped and restarted before requests
1462 * were pushed back onto the dispatch list. Rerun the queue to
1463 * avoid starvation. Notes:
1464 * - blk_mq_run_hw_queue() checks whether or not a queue has
1465 * been stopped before rerunning a queue.
1466 * - Some but not all block drivers stop a queue before
1467 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
1468 * and dm-rq.
1469 *
1470 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
1471 * bit is set, run queue after a delay to avoid IO stalls
1472 * that could otherwise occur if the queue is idle. We'll do
1473 * similar if we couldn't get budget or couldn't lock a zone
1474 * and SCHED_RESTART is set.
1475 */
1476 needs_restart = blk_mq_sched_needs_restart(hctx);
1477 if (prep == PREP_DISPATCH_NO_BUDGET)
1478 needs_resource = true;
1479 if (!needs_restart ||
1480 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
1481 blk_mq_run_hw_queue(hctx, true);
1482 else if (needs_restart && needs_resource)
1483 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
1484
1485 blk_mq_update_dispatch_busy(hctx, true);
1486 return false;
1487 } else
1488 blk_mq_update_dispatch_busy(hctx, false);
1489
1490 return (queued + errors) != 0;
1491 }
1492
1493 /**
1494 * __blk_mq_run_hw_queue - Run a hardware queue.
1495 * @hctx: Pointer to the hardware queue to run.
1496 *
1497 * Send pending requests to the hardware.
1498 */
__blk_mq_run_hw_queue(struct blk_mq_hw_ctx * hctx)1499 static void __blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx)
1500 {
1501 int srcu_idx;
1502
1503 /*
1504 * We should be running this queue from one of the CPUs that
1505 * are mapped to it.
1506 *
1507 * There are at least two related races now between setting
1508 * hctx->next_cpu from blk_mq_hctx_next_cpu() and running
1509 * __blk_mq_run_hw_queue():
1510 *
1511 * - hctx->next_cpu is found offline in blk_mq_hctx_next_cpu(),
1512 * but later it becomes online, then this warning is harmless
1513 * at all
1514 *
1515 * - hctx->next_cpu is found online in blk_mq_hctx_next_cpu(),
1516 * but later it becomes offline, then the warning can't be
1517 * triggered, and we depend on blk-mq timeout handler to
1518 * handle dispatched requests to this hctx
1519 */
1520 if (!cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask) &&
1521 cpu_online(hctx->next_cpu)) {
1522 printk(KERN_WARNING "run queue from wrong CPU %d, hctx %s\n",
1523 raw_smp_processor_id(),
1524 cpumask_empty(hctx->cpumask) ? "inactive": "active");
1525 dump_stack();
1526 }
1527
1528 /*
1529 * We can't run the queue inline with ints disabled. Ensure that
1530 * we catch bad users of this early.
1531 */
1532 WARN_ON_ONCE(in_interrupt());
1533
1534 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1535
1536 hctx_lock(hctx, &srcu_idx);
1537 blk_mq_sched_dispatch_requests(hctx);
1538 hctx_unlock(hctx, srcu_idx);
1539 }
1540
blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx * hctx)1541 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
1542 {
1543 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
1544
1545 if (cpu >= nr_cpu_ids)
1546 cpu = cpumask_first(hctx->cpumask);
1547 return cpu;
1548 }
1549
1550 /*
1551 * It'd be great if the workqueue API had a way to pass
1552 * in a mask and had some smarts for more clever placement.
1553 * For now we just round-robin here, switching for every
1554 * BLK_MQ_CPU_WORK_BATCH queued items.
1555 */
blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx * hctx)1556 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
1557 {
1558 bool tried = false;
1559 int next_cpu = hctx->next_cpu;
1560
1561 if (hctx->queue->nr_hw_queues == 1)
1562 return WORK_CPU_UNBOUND;
1563
1564 if (--hctx->next_cpu_batch <= 0) {
1565 select_cpu:
1566 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
1567 cpu_online_mask);
1568 if (next_cpu >= nr_cpu_ids)
1569 next_cpu = blk_mq_first_mapped_cpu(hctx);
1570 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
1571 }
1572
1573 /*
1574 * Do unbound schedule if we can't find a online CPU for this hctx,
1575 * and it should only happen in the path of handling CPU DEAD.
1576 */
1577 if (!cpu_online(next_cpu)) {
1578 if (!tried) {
1579 tried = true;
1580 goto select_cpu;
1581 }
1582
1583 /*
1584 * Make sure to re-select CPU next time once after CPUs
1585 * in hctx->cpumask become online again.
1586 */
1587 hctx->next_cpu = next_cpu;
1588 hctx->next_cpu_batch = 1;
1589 return WORK_CPU_UNBOUND;
1590 }
1591
1592 hctx->next_cpu = next_cpu;
1593 return next_cpu;
1594 }
1595
1596 /**
1597 * __blk_mq_delay_run_hw_queue - Run (or schedule to run) a hardware queue.
1598 * @hctx: Pointer to the hardware queue to run.
1599 * @async: If we want to run the queue asynchronously.
1600 * @msecs: Microseconds of delay to wait before running the queue.
1601 *
1602 * If !@async, try to run the queue now. Else, run the queue asynchronously and
1603 * with a delay of @msecs.
1604 */
__blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx * hctx,bool async,unsigned long msecs)1605 static void __blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async,
1606 unsigned long msecs)
1607 {
1608 if (unlikely(blk_mq_hctx_stopped(hctx)))
1609 return;
1610
1611 if (!async && !(hctx->flags & BLK_MQ_F_BLOCKING)) {
1612 int cpu = get_cpu();
1613 if (cpumask_test_cpu(cpu, hctx->cpumask)) {
1614 __blk_mq_run_hw_queue(hctx);
1615 put_cpu();
1616 return;
1617 }
1618
1619 put_cpu();
1620 }
1621
1622 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
1623 msecs_to_jiffies(msecs));
1624 }
1625
1626 /**
1627 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
1628 * @hctx: Pointer to the hardware queue to run.
1629 * @msecs: Microseconds of delay to wait before running the queue.
1630 *
1631 * Run a hardware queue asynchronously with a delay of @msecs.
1632 */
blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx * hctx,unsigned long msecs)1633 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
1634 {
1635 __blk_mq_delay_run_hw_queue(hctx, true, msecs);
1636 }
1637 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
1638
1639 /**
1640 * blk_mq_run_hw_queue - Start to run a hardware queue.
1641 * @hctx: Pointer to the hardware queue to run.
1642 * @async: If we want to run the queue asynchronously.
1643 *
1644 * Check if the request queue is not in a quiesced state and if there are
1645 * pending requests to be sent. If this is true, run the queue to send requests
1646 * to hardware.
1647 */
blk_mq_run_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)1648 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1649 {
1650 int srcu_idx;
1651 bool need_run;
1652
1653 /*
1654 * When queue is quiesced, we may be switching io scheduler, or
1655 * updating nr_hw_queues, or other things, and we can't run queue
1656 * any more, even __blk_mq_hctx_has_pending() can't be called safely.
1657 *
1658 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
1659 * quiesced.
1660 */
1661 hctx_lock(hctx, &srcu_idx);
1662 need_run = !blk_queue_quiesced(hctx->queue) &&
1663 blk_mq_hctx_has_pending(hctx);
1664 hctx_unlock(hctx, srcu_idx);
1665
1666 if (need_run)
1667 __blk_mq_delay_run_hw_queue(hctx, async, 0);
1668 }
1669 EXPORT_SYMBOL(blk_mq_run_hw_queue);
1670
1671 /**
1672 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
1673 * @q: Pointer to the request queue to run.
1674 * @async: If we want to run the queue asynchronously.
1675 */
blk_mq_run_hw_queues(struct request_queue * q,bool async)1676 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
1677 {
1678 struct blk_mq_hw_ctx *hctx;
1679 int i;
1680
1681 queue_for_each_hw_ctx(q, hctx, i) {
1682 if (blk_mq_hctx_stopped(hctx))
1683 continue;
1684
1685 blk_mq_run_hw_queue(hctx, async);
1686 }
1687 }
1688 EXPORT_SYMBOL(blk_mq_run_hw_queues);
1689
1690 /**
1691 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
1692 * @q: Pointer to the request queue to run.
1693 * @msecs: Microseconds of delay to wait before running the queues.
1694 */
blk_mq_delay_run_hw_queues(struct request_queue * q,unsigned long msecs)1695 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
1696 {
1697 struct blk_mq_hw_ctx *hctx;
1698 int i;
1699
1700 queue_for_each_hw_ctx(q, hctx, i) {
1701 if (blk_mq_hctx_stopped(hctx))
1702 continue;
1703
1704 blk_mq_delay_run_hw_queue(hctx, msecs);
1705 }
1706 }
1707 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
1708
1709 /**
1710 * blk_mq_queue_stopped() - check whether one or more hctxs have been stopped
1711 * @q: request queue.
1712 *
1713 * The caller is responsible for serializing this function against
1714 * blk_mq_{start,stop}_hw_queue().
1715 */
blk_mq_queue_stopped(struct request_queue * q)1716 bool blk_mq_queue_stopped(struct request_queue *q)
1717 {
1718 struct blk_mq_hw_ctx *hctx;
1719 int i;
1720
1721 queue_for_each_hw_ctx(q, hctx, i)
1722 if (blk_mq_hctx_stopped(hctx))
1723 return true;
1724
1725 return false;
1726 }
1727 EXPORT_SYMBOL(blk_mq_queue_stopped);
1728
1729 /*
1730 * This function is often used for pausing .queue_rq() by driver when
1731 * there isn't enough resource or some conditions aren't satisfied, and
1732 * BLK_STS_RESOURCE is usually returned.
1733 *
1734 * We do not guarantee that dispatch can be drained or blocked
1735 * after blk_mq_stop_hw_queue() returns. Please use
1736 * blk_mq_quiesce_queue() for that requirement.
1737 */
blk_mq_stop_hw_queue(struct blk_mq_hw_ctx * hctx)1738 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
1739 {
1740 cancel_delayed_work(&hctx->run_work);
1741
1742 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
1743 }
1744 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
1745
1746 /*
1747 * This function is often used for pausing .queue_rq() by driver when
1748 * there isn't enough resource or some conditions aren't satisfied, and
1749 * BLK_STS_RESOURCE is usually returned.
1750 *
1751 * We do not guarantee that dispatch can be drained or blocked
1752 * after blk_mq_stop_hw_queues() returns. Please use
1753 * blk_mq_quiesce_queue() for that requirement.
1754 */
blk_mq_stop_hw_queues(struct request_queue * q)1755 void blk_mq_stop_hw_queues(struct request_queue *q)
1756 {
1757 struct blk_mq_hw_ctx *hctx;
1758 int i;
1759
1760 queue_for_each_hw_ctx(q, hctx, i)
1761 blk_mq_stop_hw_queue(hctx);
1762 }
1763 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
1764
blk_mq_start_hw_queue(struct blk_mq_hw_ctx * hctx)1765 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
1766 {
1767 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1768
1769 blk_mq_run_hw_queue(hctx, false);
1770 }
1771 EXPORT_SYMBOL(blk_mq_start_hw_queue);
1772
blk_mq_start_hw_queues(struct request_queue * q)1773 void blk_mq_start_hw_queues(struct request_queue *q)
1774 {
1775 struct blk_mq_hw_ctx *hctx;
1776 int i;
1777
1778 queue_for_each_hw_ctx(q, hctx, i)
1779 blk_mq_start_hw_queue(hctx);
1780 }
1781 EXPORT_SYMBOL(blk_mq_start_hw_queues);
1782
blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)1783 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
1784 {
1785 if (!blk_mq_hctx_stopped(hctx))
1786 return;
1787
1788 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
1789 blk_mq_run_hw_queue(hctx, async);
1790 }
1791 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
1792
blk_mq_start_stopped_hw_queues(struct request_queue * q,bool async)1793 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
1794 {
1795 struct blk_mq_hw_ctx *hctx;
1796 int i;
1797
1798 queue_for_each_hw_ctx(q, hctx, i)
1799 blk_mq_start_stopped_hw_queue(hctx, async);
1800 }
1801 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
1802
blk_mq_run_work_fn(struct work_struct * work)1803 static void blk_mq_run_work_fn(struct work_struct *work)
1804 {
1805 struct blk_mq_hw_ctx *hctx;
1806
1807 hctx = container_of(work, struct blk_mq_hw_ctx, run_work.work);
1808
1809 /*
1810 * If we are stopped, don't run the queue.
1811 */
1812 if (blk_mq_hctx_stopped(hctx))
1813 return;
1814
1815 __blk_mq_run_hw_queue(hctx);
1816 }
1817
__blk_mq_insert_req_list(struct blk_mq_hw_ctx * hctx,struct request * rq,bool at_head)1818 static inline void __blk_mq_insert_req_list(struct blk_mq_hw_ctx *hctx,
1819 struct request *rq,
1820 bool at_head)
1821 {
1822 struct blk_mq_ctx *ctx = rq->mq_ctx;
1823 enum hctx_type type = hctx->type;
1824
1825 lockdep_assert_held(&ctx->lock);
1826
1827 trace_block_rq_insert(rq);
1828
1829 if (at_head)
1830 list_add(&rq->queuelist, &ctx->rq_lists[type]);
1831 else
1832 list_add_tail(&rq->queuelist, &ctx->rq_lists[type]);
1833 }
1834
__blk_mq_insert_request(struct blk_mq_hw_ctx * hctx,struct request * rq,bool at_head)1835 void __blk_mq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
1836 bool at_head)
1837 {
1838 struct blk_mq_ctx *ctx = rq->mq_ctx;
1839
1840 lockdep_assert_held(&ctx->lock);
1841
1842 __blk_mq_insert_req_list(hctx, rq, at_head);
1843 blk_mq_hctx_mark_pending(hctx, ctx);
1844 }
1845
1846 /**
1847 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
1848 * @rq: Pointer to request to be inserted.
1849 * @at_head: true if the request should be inserted at the head of the list.
1850 * @run_queue: If we should run the hardware queue after inserting the request.
1851 *
1852 * Should only be used carefully, when the caller knows we want to
1853 * bypass a potential IO scheduler on the target device.
1854 */
blk_mq_request_bypass_insert(struct request * rq,bool at_head,bool run_queue)1855 void blk_mq_request_bypass_insert(struct request *rq, bool at_head,
1856 bool run_queue)
1857 {
1858 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1859
1860 spin_lock(&hctx->lock);
1861 if (at_head)
1862 list_add(&rq->queuelist, &hctx->dispatch);
1863 else
1864 list_add_tail(&rq->queuelist, &hctx->dispatch);
1865 spin_unlock(&hctx->lock);
1866
1867 if (run_queue)
1868 blk_mq_run_hw_queue(hctx, false);
1869 }
1870
blk_mq_insert_requests(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx,struct list_head * list)1871 void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx, struct blk_mq_ctx *ctx,
1872 struct list_head *list)
1873
1874 {
1875 struct request *rq;
1876 enum hctx_type type = hctx->type;
1877
1878 /*
1879 * preemption doesn't flush plug list, so it's possible ctx->cpu is
1880 * offline now
1881 */
1882 list_for_each_entry(rq, list, queuelist) {
1883 BUG_ON(rq->mq_ctx != ctx);
1884 trace_block_rq_insert(rq);
1885 }
1886
1887 spin_lock(&ctx->lock);
1888 list_splice_tail_init(list, &ctx->rq_lists[type]);
1889 blk_mq_hctx_mark_pending(hctx, ctx);
1890 spin_unlock(&ctx->lock);
1891 }
1892
plug_rq_cmp(void * priv,const struct list_head * a,const struct list_head * b)1893 static int plug_rq_cmp(void *priv, const struct list_head *a,
1894 const struct list_head *b)
1895 {
1896 struct request *rqa = container_of(a, struct request, queuelist);
1897 struct request *rqb = container_of(b, struct request, queuelist);
1898
1899 if (rqa->mq_ctx != rqb->mq_ctx)
1900 return rqa->mq_ctx > rqb->mq_ctx;
1901 if (rqa->mq_hctx != rqb->mq_hctx)
1902 return rqa->mq_hctx > rqb->mq_hctx;
1903
1904 return blk_rq_pos(rqa) > blk_rq_pos(rqb);
1905 }
1906
blk_mq_flush_plug_list(struct blk_plug * plug,bool from_schedule)1907 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1908 {
1909 LIST_HEAD(list);
1910
1911 if (list_empty(&plug->mq_list))
1912 return;
1913 list_splice_init(&plug->mq_list, &list);
1914
1915 if (plug->rq_count > 2 && plug->multiple_queues)
1916 list_sort(NULL, &list, plug_rq_cmp);
1917
1918 plug->rq_count = 0;
1919
1920 do {
1921 struct list_head rq_list;
1922 struct request *rq, *head_rq = list_entry_rq(list.next);
1923 struct list_head *pos = &head_rq->queuelist; /* skip first */
1924 struct blk_mq_hw_ctx *this_hctx = head_rq->mq_hctx;
1925 struct blk_mq_ctx *this_ctx = head_rq->mq_ctx;
1926 unsigned int depth = 1;
1927
1928 list_for_each_continue(pos, &list) {
1929 rq = list_entry_rq(pos);
1930 BUG_ON(!rq->q);
1931 if (rq->mq_hctx != this_hctx || rq->mq_ctx != this_ctx)
1932 break;
1933 depth++;
1934 }
1935
1936 list_cut_before(&rq_list, &list, pos);
1937 trace_block_unplug(head_rq->q, depth, !from_schedule);
1938 blk_mq_sched_insert_requests(this_hctx, this_ctx, &rq_list,
1939 from_schedule);
1940 } while(!list_empty(&list));
1941 }
1942
blk_mq_bio_to_request(struct request * rq,struct bio * bio,unsigned int nr_segs)1943 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
1944 unsigned int nr_segs)
1945 {
1946 int err;
1947
1948 if (bio->bi_opf & REQ_RAHEAD)
1949 rq->cmd_flags |= REQ_FAILFAST_MASK;
1950
1951 rq->__sector = bio->bi_iter.bi_sector;
1952 rq->write_hint = bio->bi_write_hint;
1953 blk_rq_bio_prep(rq, bio, nr_segs);
1954
1955 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
1956 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
1957 WARN_ON_ONCE(err);
1958
1959 blk_account_io_start(rq);
1960 }
1961
__blk_mq_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie,bool last)1962 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
1963 struct request *rq,
1964 blk_qc_t *cookie, bool last)
1965 {
1966 struct request_queue *q = rq->q;
1967 struct blk_mq_queue_data bd = {
1968 .rq = rq,
1969 .last = last,
1970 };
1971 blk_qc_t new_cookie;
1972 blk_status_t ret;
1973
1974 new_cookie = request_to_qc_t(hctx, rq);
1975
1976 /*
1977 * For OK queue, we are done. For error, caller may kill it.
1978 * Any other error (busy), just add it to our list as we
1979 * previously would have done.
1980 */
1981 ret = q->mq_ops->queue_rq(hctx, &bd);
1982 switch (ret) {
1983 case BLK_STS_OK:
1984 blk_mq_update_dispatch_busy(hctx, false);
1985 *cookie = new_cookie;
1986 break;
1987 case BLK_STS_RESOURCE:
1988 case BLK_STS_DEV_RESOURCE:
1989 blk_mq_update_dispatch_busy(hctx, true);
1990 __blk_mq_requeue_request(rq);
1991 break;
1992 default:
1993 blk_mq_update_dispatch_busy(hctx, false);
1994 *cookie = BLK_QC_T_NONE;
1995 break;
1996 }
1997
1998 return ret;
1999 }
2000
__blk_mq_try_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie,bool bypass_insert,bool last)2001 static blk_status_t __blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2002 struct request *rq,
2003 blk_qc_t *cookie,
2004 bool bypass_insert, bool last)
2005 {
2006 struct request_queue *q = rq->q;
2007 bool run_queue = true;
2008
2009 /*
2010 * RCU or SRCU read lock is needed before checking quiesced flag.
2011 *
2012 * When queue is stopped or quiesced, ignore 'bypass_insert' from
2013 * blk_mq_request_issue_directly(), and return BLK_STS_OK to caller,
2014 * and avoid driver to try to dispatch again.
2015 */
2016 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(q)) {
2017 run_queue = false;
2018 bypass_insert = false;
2019 goto insert;
2020 }
2021
2022 if (q->elevator && !bypass_insert)
2023 goto insert;
2024
2025 if (!blk_mq_get_dispatch_budget(q))
2026 goto insert;
2027
2028 if (!blk_mq_get_driver_tag(rq)) {
2029 blk_mq_put_dispatch_budget(q);
2030 goto insert;
2031 }
2032
2033 return __blk_mq_issue_directly(hctx, rq, cookie, last);
2034 insert:
2035 if (bypass_insert)
2036 return BLK_STS_RESOURCE;
2037
2038 blk_mq_sched_insert_request(rq, false, run_queue, false);
2039
2040 return BLK_STS_OK;
2041 }
2042
2043 /**
2044 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2045 * @hctx: Pointer of the associated hardware queue.
2046 * @rq: Pointer to request to be sent.
2047 * @cookie: Request queue cookie.
2048 *
2049 * If the device has enough resources to accept a new request now, send the
2050 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2051 * we can try send it another time in the future. Requests inserted at this
2052 * queue have higher priority.
2053 */
blk_mq_try_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,blk_qc_t * cookie)2054 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2055 struct request *rq, blk_qc_t *cookie)
2056 {
2057 blk_status_t ret;
2058 int srcu_idx;
2059
2060 might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
2061
2062 hctx_lock(hctx, &srcu_idx);
2063
2064 ret = __blk_mq_try_issue_directly(hctx, rq, cookie, false, true);
2065 if (ret == BLK_STS_RESOURCE || ret == BLK_STS_DEV_RESOURCE)
2066 blk_mq_request_bypass_insert(rq, false, true);
2067 else if (ret != BLK_STS_OK)
2068 blk_mq_end_request(rq, ret);
2069
2070 hctx_unlock(hctx, srcu_idx);
2071 }
2072
blk_mq_request_issue_directly(struct request * rq,bool last)2073 blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2074 {
2075 blk_status_t ret;
2076 int srcu_idx;
2077 blk_qc_t unused_cookie;
2078 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2079
2080 hctx_lock(hctx, &srcu_idx);
2081 ret = __blk_mq_try_issue_directly(hctx, rq, &unused_cookie, true, last);
2082 hctx_unlock(hctx, srcu_idx);
2083
2084 return ret;
2085 }
2086
blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx * hctx,struct list_head * list)2087 void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2088 struct list_head *list)
2089 {
2090 int queued = 0;
2091 int errors = 0;
2092
2093 while (!list_empty(list)) {
2094 blk_status_t ret;
2095 struct request *rq = list_first_entry(list, struct request,
2096 queuelist);
2097
2098 list_del_init(&rq->queuelist);
2099 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2100 if (ret != BLK_STS_OK) {
2101 errors++;
2102 if (ret == BLK_STS_RESOURCE ||
2103 ret == BLK_STS_DEV_RESOURCE) {
2104 blk_mq_request_bypass_insert(rq, false,
2105 list_empty(list));
2106 break;
2107 }
2108 blk_mq_end_request(rq, ret);
2109 } else
2110 queued++;
2111 }
2112
2113 /*
2114 * If we didn't flush the entire list, we could have told
2115 * the driver there was more coming, but that turned out to
2116 * be a lie.
2117 */
2118 if ((!list_empty(list) || errors) &&
2119 hctx->queue->mq_ops->commit_rqs && queued)
2120 hctx->queue->mq_ops->commit_rqs(hctx);
2121 }
2122
blk_add_rq_to_plug(struct blk_plug * plug,struct request * rq)2123 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
2124 {
2125 list_add_tail(&rq->queuelist, &plug->mq_list);
2126 plug->rq_count++;
2127 if (!plug->multiple_queues && !list_is_singular(&plug->mq_list)) {
2128 struct request *tmp;
2129
2130 tmp = list_first_entry(&plug->mq_list, struct request,
2131 queuelist);
2132 if (tmp->q != rq->q)
2133 plug->multiple_queues = true;
2134 }
2135 }
2136
2137 /*
2138 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
2139 * queues. This is important for md arrays to benefit from merging
2140 * requests.
2141 */
blk_plug_max_rq_count(struct blk_plug * plug)2142 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
2143 {
2144 if (plug->multiple_queues)
2145 return BLK_MAX_REQUEST_COUNT * 2;
2146 return BLK_MAX_REQUEST_COUNT;
2147 }
2148
2149 /**
2150 * blk_mq_submit_bio - Create and send a request to block device.
2151 * @bio: Bio pointer.
2152 *
2153 * Builds up a request structure from @q and @bio and send to the device. The
2154 * request may not be queued directly to hardware if:
2155 * * This request can be merged with another one
2156 * * We want to place request at plug queue for possible future merging
2157 * * There is an IO scheduler active at this queue
2158 *
2159 * It will not queue the request if there is an error with the bio, or at the
2160 * request creation.
2161 *
2162 * Returns: Request queue cookie.
2163 */
blk_mq_submit_bio(struct bio * bio)2164 blk_qc_t blk_mq_submit_bio(struct bio *bio)
2165 {
2166 struct request_queue *q = bio->bi_disk->queue;
2167 const int is_sync = op_is_sync(bio->bi_opf);
2168 const int is_flush_fua = op_is_flush(bio->bi_opf);
2169 struct blk_mq_alloc_data data = {
2170 .q = q,
2171 };
2172 struct request *rq;
2173 struct blk_plug *plug;
2174 struct request *same_queue_rq = NULL;
2175 unsigned int nr_segs;
2176 blk_qc_t cookie;
2177 blk_status_t ret;
2178
2179 blk_queue_bounce(q, &bio);
2180 __blk_queue_split(&bio, &nr_segs);
2181
2182 if (!bio_integrity_prep(bio))
2183 goto queue_exit;
2184
2185 if (!is_flush_fua && !blk_queue_nomerges(q) &&
2186 blk_attempt_plug_merge(q, bio, nr_segs, &same_queue_rq))
2187 goto queue_exit;
2188
2189 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2190 goto queue_exit;
2191
2192 rq_qos_throttle(q, bio);
2193
2194 data.cmd_flags = bio->bi_opf;
2195 rq = __blk_mq_alloc_request(&data);
2196 if (unlikely(!rq)) {
2197 rq_qos_cleanup(q, bio);
2198 if (bio->bi_opf & REQ_NOWAIT)
2199 bio_wouldblock_error(bio);
2200 goto queue_exit;
2201 }
2202
2203 trace_block_getrq(q, bio, bio->bi_opf);
2204
2205 rq_qos_track(q, rq, bio);
2206
2207 cookie = request_to_qc_t(data.hctx, rq);
2208
2209 blk_mq_bio_to_request(rq, bio, nr_segs);
2210
2211 ret = blk_crypto_init_request(rq);
2212 if (ret != BLK_STS_OK) {
2213 bio->bi_status = ret;
2214 bio_endio(bio);
2215 blk_mq_free_request(rq);
2216 return BLK_QC_T_NONE;
2217 }
2218
2219 plug = blk_mq_plug(q, bio);
2220 if (unlikely(is_flush_fua)) {
2221 /* Bypass scheduler for flush requests */
2222 blk_insert_flush(rq);
2223 blk_mq_run_hw_queue(data.hctx, true);
2224 } else if (plug && (q->nr_hw_queues == 1 ||
2225 blk_mq_is_sbitmap_shared(rq->mq_hctx->flags) ||
2226 q->mq_ops->commit_rqs || !blk_queue_nonrot(q))) {
2227 /*
2228 * Use plugging if we have a ->commit_rqs() hook as well, as
2229 * we know the driver uses bd->last in a smart fashion.
2230 *
2231 * Use normal plugging if this disk is slow HDD, as sequential
2232 * IO may benefit a lot from plug merging.
2233 */
2234 unsigned int request_count = plug->rq_count;
2235 struct request *last = NULL;
2236
2237 if (!request_count)
2238 trace_block_plug(q);
2239 else
2240 last = list_entry_rq(plug->mq_list.prev);
2241
2242 if (request_count >= blk_plug_max_rq_count(plug) || (last &&
2243 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
2244 blk_flush_plug_list(plug, false);
2245 trace_block_plug(q);
2246 }
2247
2248 blk_add_rq_to_plug(plug, rq);
2249 } else if (q->elevator) {
2250 /* Insert the request at the IO scheduler queue */
2251 blk_mq_sched_insert_request(rq, false, true, true);
2252 } else if (plug && !blk_queue_nomerges(q)) {
2253 /*
2254 * We do limited plugging. If the bio can be merged, do that.
2255 * Otherwise the existing request in the plug list will be
2256 * issued. So the plug list will have one request at most
2257 * The plug list might get flushed before this. If that happens,
2258 * the plug list is empty, and same_queue_rq is invalid.
2259 */
2260 if (list_empty(&plug->mq_list))
2261 same_queue_rq = NULL;
2262 if (same_queue_rq) {
2263 list_del_init(&same_queue_rq->queuelist);
2264 plug->rq_count--;
2265 }
2266 blk_add_rq_to_plug(plug, rq);
2267 trace_block_plug(q);
2268
2269 if (same_queue_rq) {
2270 data.hctx = same_queue_rq->mq_hctx;
2271 trace_block_unplug(q, 1, true);
2272 blk_mq_try_issue_directly(data.hctx, same_queue_rq,
2273 &cookie);
2274 }
2275 } else if ((q->nr_hw_queues > 1 && is_sync) ||
2276 !data.hctx->dispatch_busy) {
2277 /*
2278 * There is no scheduler and we can try to send directly
2279 * to the hardware.
2280 */
2281 blk_mq_try_issue_directly(data.hctx, rq, &cookie);
2282 } else {
2283 /* Default case. */
2284 blk_mq_sched_insert_request(rq, false, true, true);
2285 }
2286
2287 return cookie;
2288 queue_exit:
2289 blk_queue_exit(q);
2290 return BLK_QC_T_NONE;
2291 }
2292
order_to_size(unsigned int order)2293 static size_t order_to_size(unsigned int order)
2294 {
2295 return (size_t)PAGE_SIZE << order;
2296 }
2297
2298 /* called before freeing request pool in @tags */
blk_mq_clear_rq_mapping(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)2299 static void blk_mq_clear_rq_mapping(struct blk_mq_tag_set *set,
2300 struct blk_mq_tags *tags, unsigned int hctx_idx)
2301 {
2302 struct blk_mq_tags *drv_tags = set->tags[hctx_idx];
2303 struct page *page;
2304 unsigned long flags;
2305
2306 list_for_each_entry(page, &tags->page_list, lru) {
2307 unsigned long start = (unsigned long)page_address(page);
2308 unsigned long end = start + order_to_size(page->private);
2309 int i;
2310
2311 for (i = 0; i < set->queue_depth; i++) {
2312 struct request *rq = drv_tags->rqs[i];
2313 unsigned long rq_addr = (unsigned long)rq;
2314
2315 if (rq_addr >= start && rq_addr < end) {
2316 WARN_ON_ONCE(refcount_read(&rq->ref) != 0);
2317 cmpxchg(&drv_tags->rqs[i], rq, NULL);
2318 }
2319 }
2320 }
2321
2322 /*
2323 * Wait until all pending iteration is done.
2324 *
2325 * Request reference is cleared and it is guaranteed to be observed
2326 * after the ->lock is released.
2327 */
2328 spin_lock_irqsave(&drv_tags->lock, flags);
2329 spin_unlock_irqrestore(&drv_tags->lock, flags);
2330 }
2331
blk_mq_free_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)2332 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2333 unsigned int hctx_idx)
2334 {
2335 struct page *page;
2336
2337 if (tags->rqs && set->ops->exit_request) {
2338 int i;
2339
2340 for (i = 0; i < tags->nr_tags; i++) {
2341 struct request *rq = tags->static_rqs[i];
2342
2343 if (!rq)
2344 continue;
2345 set->ops->exit_request(set, rq, hctx_idx);
2346 tags->static_rqs[i] = NULL;
2347 }
2348 }
2349
2350 blk_mq_clear_rq_mapping(set, tags, hctx_idx);
2351
2352 while (!list_empty(&tags->page_list)) {
2353 page = list_first_entry(&tags->page_list, struct page, lru);
2354 list_del_init(&page->lru);
2355 /*
2356 * Remove kmemleak object previously allocated in
2357 * blk_mq_alloc_rqs().
2358 */
2359 kmemleak_free(page_address(page));
2360 __free_pages(page, page->private);
2361 }
2362 }
2363
blk_mq_free_rq_map(struct blk_mq_tags * tags,unsigned int flags)2364 void blk_mq_free_rq_map(struct blk_mq_tags *tags, unsigned int flags)
2365 {
2366 kfree(tags->rqs);
2367 tags->rqs = NULL;
2368 kfree(tags->static_rqs);
2369 tags->static_rqs = NULL;
2370
2371 blk_mq_free_tags(tags, flags);
2372 }
2373
blk_mq_alloc_rq_map(struct blk_mq_tag_set * set,unsigned int hctx_idx,unsigned int nr_tags,unsigned int reserved_tags,unsigned int flags)2374 struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
2375 unsigned int hctx_idx,
2376 unsigned int nr_tags,
2377 unsigned int reserved_tags,
2378 unsigned int flags)
2379 {
2380 struct blk_mq_tags *tags;
2381 int node;
2382
2383 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2384 if (node == NUMA_NO_NODE)
2385 node = set->numa_node;
2386
2387 tags = blk_mq_init_tags(nr_tags, reserved_tags, node, flags);
2388 if (!tags)
2389 return NULL;
2390
2391 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2392 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2393 node);
2394 if (!tags->rqs) {
2395 blk_mq_free_tags(tags, flags);
2396 return NULL;
2397 }
2398
2399 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
2400 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
2401 node);
2402 if (!tags->static_rqs) {
2403 kfree(tags->rqs);
2404 blk_mq_free_tags(tags, flags);
2405 return NULL;
2406 }
2407
2408 return tags;
2409 }
2410
blk_mq_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,int node)2411 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
2412 unsigned int hctx_idx, int node)
2413 {
2414 int ret;
2415
2416 if (set->ops->init_request) {
2417 ret = set->ops->init_request(set, rq, hctx_idx, node);
2418 if (ret)
2419 return ret;
2420 }
2421
2422 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
2423 return 0;
2424 }
2425
blk_mq_alloc_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx,unsigned int depth)2426 int blk_mq_alloc_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
2427 unsigned int hctx_idx, unsigned int depth)
2428 {
2429 unsigned int i, j, entries_per_page, max_order = 4;
2430 size_t rq_size, left;
2431 int node;
2432
2433 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], hctx_idx);
2434 if (node == NUMA_NO_NODE)
2435 node = set->numa_node;
2436
2437 INIT_LIST_HEAD(&tags->page_list);
2438
2439 /*
2440 * rq_size is the size of the request plus driver payload, rounded
2441 * to the cacheline size
2442 */
2443 rq_size = round_up(sizeof(struct request) + set->cmd_size,
2444 cache_line_size());
2445 left = rq_size * depth;
2446
2447 for (i = 0; i < depth; ) {
2448 int this_order = max_order;
2449 struct page *page;
2450 int to_do;
2451 void *p;
2452
2453 while (this_order && left < order_to_size(this_order - 1))
2454 this_order--;
2455
2456 do {
2457 page = alloc_pages_node(node,
2458 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
2459 this_order);
2460 if (page)
2461 break;
2462 if (!this_order--)
2463 break;
2464 if (order_to_size(this_order) < rq_size)
2465 break;
2466 } while (1);
2467
2468 if (!page)
2469 goto fail;
2470
2471 page->private = this_order;
2472 list_add_tail(&page->lru, &tags->page_list);
2473
2474 p = page_address(page);
2475 /*
2476 * Allow kmemleak to scan these pages as they contain pointers
2477 * to additional allocations like via ops->init_request().
2478 */
2479 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
2480 entries_per_page = order_to_size(this_order) / rq_size;
2481 to_do = min(entries_per_page, depth - i);
2482 left -= to_do * rq_size;
2483 for (j = 0; j < to_do; j++) {
2484 struct request *rq = p;
2485
2486 tags->static_rqs[i] = rq;
2487 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
2488 tags->static_rqs[i] = NULL;
2489 goto fail;
2490 }
2491
2492 p += rq_size;
2493 i++;
2494 }
2495 }
2496 return 0;
2497
2498 fail:
2499 blk_mq_free_rqs(set, tags, hctx_idx);
2500 return -ENOMEM;
2501 }
2502
2503 struct rq_iter_data {
2504 struct blk_mq_hw_ctx *hctx;
2505 bool has_rq;
2506 };
2507
blk_mq_has_request(struct request * rq,void * data,bool reserved)2508 static bool blk_mq_has_request(struct request *rq, void *data, bool reserved)
2509 {
2510 struct rq_iter_data *iter_data = data;
2511
2512 if (rq->mq_hctx != iter_data->hctx)
2513 return true;
2514 iter_data->has_rq = true;
2515 return false;
2516 }
2517
blk_mq_hctx_has_requests(struct blk_mq_hw_ctx * hctx)2518 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
2519 {
2520 struct blk_mq_tags *tags = hctx->sched_tags ?
2521 hctx->sched_tags : hctx->tags;
2522 struct rq_iter_data data = {
2523 .hctx = hctx,
2524 };
2525
2526 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
2527 return data.has_rq;
2528 }
2529
blk_mq_last_cpu_in_hctx(unsigned int cpu,struct blk_mq_hw_ctx * hctx)2530 static inline bool blk_mq_last_cpu_in_hctx(unsigned int cpu,
2531 struct blk_mq_hw_ctx *hctx)
2532 {
2533 if (cpumask_next_and(-1, hctx->cpumask, cpu_online_mask) != cpu)
2534 return false;
2535 if (cpumask_next_and(cpu, hctx->cpumask, cpu_online_mask) < nr_cpu_ids)
2536 return false;
2537 return true;
2538 }
2539
blk_mq_hctx_notify_offline(unsigned int cpu,struct hlist_node * node)2540 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
2541 {
2542 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2543 struct blk_mq_hw_ctx, cpuhp_online);
2544
2545 if (!cpumask_test_cpu(cpu, hctx->cpumask) ||
2546 !blk_mq_last_cpu_in_hctx(cpu, hctx))
2547 return 0;
2548
2549 /*
2550 * Prevent new request from being allocated on the current hctx.
2551 *
2552 * The smp_mb__after_atomic() Pairs with the implied barrier in
2553 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
2554 * seen once we return from the tag allocator.
2555 */
2556 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2557 smp_mb__after_atomic();
2558
2559 /*
2560 * Try to grab a reference to the queue and wait for any outstanding
2561 * requests. If we could not grab a reference the queue has been
2562 * frozen and there are no requests.
2563 */
2564 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
2565 while (blk_mq_hctx_has_requests(hctx))
2566 msleep(5);
2567 percpu_ref_put(&hctx->queue->q_usage_counter);
2568 }
2569
2570 return 0;
2571 }
2572
blk_mq_hctx_notify_online(unsigned int cpu,struct hlist_node * node)2573 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
2574 {
2575 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
2576 struct blk_mq_hw_ctx, cpuhp_online);
2577
2578 if (cpumask_test_cpu(cpu, hctx->cpumask))
2579 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
2580 return 0;
2581 }
2582
2583 /*
2584 * 'cpu' is going away. splice any existing rq_list entries from this
2585 * software queue to the hw queue dispatch list, and ensure that it
2586 * gets run.
2587 */
blk_mq_hctx_notify_dead(unsigned int cpu,struct hlist_node * node)2588 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
2589 {
2590 struct blk_mq_hw_ctx *hctx;
2591 struct blk_mq_ctx *ctx;
2592 LIST_HEAD(tmp);
2593 enum hctx_type type;
2594
2595 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
2596 if (!cpumask_test_cpu(cpu, hctx->cpumask))
2597 return 0;
2598
2599 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
2600 type = hctx->type;
2601
2602 spin_lock(&ctx->lock);
2603 if (!list_empty(&ctx->rq_lists[type])) {
2604 list_splice_init(&ctx->rq_lists[type], &tmp);
2605 blk_mq_hctx_clear_pending(hctx, ctx);
2606 }
2607 spin_unlock(&ctx->lock);
2608
2609 if (list_empty(&tmp))
2610 return 0;
2611
2612 spin_lock(&hctx->lock);
2613 list_splice_tail_init(&tmp, &hctx->dispatch);
2614 spin_unlock(&hctx->lock);
2615
2616 blk_mq_run_hw_queue(hctx, true);
2617 return 0;
2618 }
2619
blk_mq_remove_cpuhp(struct blk_mq_hw_ctx * hctx)2620 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
2621 {
2622 if (!(hctx->flags & BLK_MQ_F_STACKING))
2623 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2624 &hctx->cpuhp_online);
2625 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
2626 &hctx->cpuhp_dead);
2627 }
2628
2629 /*
2630 * Before freeing hw queue, clearing the flush request reference in
2631 * tags->rqs[] for avoiding potential UAF.
2632 */
blk_mq_clear_flush_rq_mapping(struct blk_mq_tags * tags,unsigned int queue_depth,struct request * flush_rq)2633 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
2634 unsigned int queue_depth, struct request *flush_rq)
2635 {
2636 int i;
2637 unsigned long flags;
2638
2639 /* The hw queue may not be mapped yet */
2640 if (!tags)
2641 return;
2642
2643 WARN_ON_ONCE(refcount_read(&flush_rq->ref) != 0);
2644
2645 for (i = 0; i < queue_depth; i++)
2646 cmpxchg(&tags->rqs[i], flush_rq, NULL);
2647
2648 /*
2649 * Wait until all pending iteration is done.
2650 *
2651 * Request reference is cleared and it is guaranteed to be observed
2652 * after the ->lock is released.
2653 */
2654 spin_lock_irqsave(&tags->lock, flags);
2655 spin_unlock_irqrestore(&tags->lock, flags);
2656 }
2657
2658 /* hctx->ctxs will be freed in queue's release handler */
blk_mq_exit_hctx(struct request_queue * q,struct blk_mq_tag_set * set,struct blk_mq_hw_ctx * hctx,unsigned int hctx_idx)2659 static void blk_mq_exit_hctx(struct request_queue *q,
2660 struct blk_mq_tag_set *set,
2661 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
2662 {
2663 struct request *flush_rq = hctx->fq->flush_rq;
2664
2665 if (blk_mq_hw_queue_mapped(hctx))
2666 blk_mq_tag_idle(hctx);
2667
2668 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
2669 set->queue_depth, flush_rq);
2670 if (set->ops->exit_request)
2671 set->ops->exit_request(set, flush_rq, hctx_idx);
2672
2673 if (set->ops->exit_hctx)
2674 set->ops->exit_hctx(hctx, hctx_idx);
2675
2676 blk_mq_remove_cpuhp(hctx);
2677
2678 spin_lock(&q->unused_hctx_lock);
2679 list_add(&hctx->hctx_list, &q->unused_hctx_list);
2680 spin_unlock(&q->unused_hctx_lock);
2681 }
2682
blk_mq_exit_hw_queues(struct request_queue * q,struct blk_mq_tag_set * set,int nr_queue)2683 static void blk_mq_exit_hw_queues(struct request_queue *q,
2684 struct blk_mq_tag_set *set, int nr_queue)
2685 {
2686 struct blk_mq_hw_ctx *hctx;
2687 unsigned int i;
2688
2689 queue_for_each_hw_ctx(q, hctx, i) {
2690 if (i == nr_queue)
2691 break;
2692 blk_mq_debugfs_unregister_hctx(hctx);
2693 blk_mq_exit_hctx(q, set, hctx, i);
2694 }
2695 }
2696
blk_mq_hw_ctx_size(struct blk_mq_tag_set * tag_set)2697 static int blk_mq_hw_ctx_size(struct blk_mq_tag_set *tag_set)
2698 {
2699 int hw_ctx_size = sizeof(struct blk_mq_hw_ctx);
2700
2701 BUILD_BUG_ON(ALIGN(offsetof(struct blk_mq_hw_ctx, srcu),
2702 __alignof__(struct blk_mq_hw_ctx)) !=
2703 sizeof(struct blk_mq_hw_ctx));
2704
2705 if (tag_set->flags & BLK_MQ_F_BLOCKING)
2706 hw_ctx_size += sizeof(struct srcu_struct);
2707
2708 return hw_ctx_size;
2709 }
2710
blk_mq_init_hctx(struct request_queue * q,struct blk_mq_tag_set * set,struct blk_mq_hw_ctx * hctx,unsigned hctx_idx)2711 static int blk_mq_init_hctx(struct request_queue *q,
2712 struct blk_mq_tag_set *set,
2713 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
2714 {
2715 hctx->queue_num = hctx_idx;
2716
2717 if (!(hctx->flags & BLK_MQ_F_STACKING))
2718 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
2719 &hctx->cpuhp_online);
2720 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
2721
2722 hctx->tags = set->tags[hctx_idx];
2723
2724 if (set->ops->init_hctx &&
2725 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
2726 goto unregister_cpu_notifier;
2727
2728 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
2729 hctx->numa_node))
2730 goto exit_hctx;
2731 return 0;
2732
2733 exit_hctx:
2734 if (set->ops->exit_hctx)
2735 set->ops->exit_hctx(hctx, hctx_idx);
2736 unregister_cpu_notifier:
2737 blk_mq_remove_cpuhp(hctx);
2738 return -1;
2739 }
2740
2741 static struct blk_mq_hw_ctx *
blk_mq_alloc_hctx(struct request_queue * q,struct blk_mq_tag_set * set,int node)2742 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
2743 int node)
2744 {
2745 struct blk_mq_hw_ctx *hctx;
2746 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
2747
2748 hctx = kzalloc_node(blk_mq_hw_ctx_size(set), gfp, node);
2749 if (!hctx)
2750 goto fail_alloc_hctx;
2751
2752 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
2753 goto free_hctx;
2754
2755 atomic_set(&hctx->nr_active, 0);
2756 atomic_set(&hctx->elevator_queued, 0);
2757 if (node == NUMA_NO_NODE)
2758 node = set->numa_node;
2759 hctx->numa_node = node;
2760
2761 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
2762 spin_lock_init(&hctx->lock);
2763 INIT_LIST_HEAD(&hctx->dispatch);
2764 hctx->queue = q;
2765 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
2766
2767 INIT_LIST_HEAD(&hctx->hctx_list);
2768
2769 /*
2770 * Allocate space for all possible cpus to avoid allocation at
2771 * runtime
2772 */
2773 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
2774 gfp, node);
2775 if (!hctx->ctxs)
2776 goto free_cpumask;
2777
2778 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
2779 gfp, node))
2780 goto free_ctxs;
2781 hctx->nr_ctx = 0;
2782
2783 spin_lock_init(&hctx->dispatch_wait_lock);
2784 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
2785 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
2786
2787 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
2788 if (!hctx->fq)
2789 goto free_bitmap;
2790
2791 if (hctx->flags & BLK_MQ_F_BLOCKING)
2792 init_srcu_struct(hctx->srcu);
2793 blk_mq_hctx_kobj_init(hctx);
2794
2795 return hctx;
2796
2797 free_bitmap:
2798 sbitmap_free(&hctx->ctx_map);
2799 free_ctxs:
2800 kfree(hctx->ctxs);
2801 free_cpumask:
2802 free_cpumask_var(hctx->cpumask);
2803 free_hctx:
2804 kfree(hctx);
2805 fail_alloc_hctx:
2806 return NULL;
2807 }
2808
blk_mq_init_cpu_queues(struct request_queue * q,unsigned int nr_hw_queues)2809 static void blk_mq_init_cpu_queues(struct request_queue *q,
2810 unsigned int nr_hw_queues)
2811 {
2812 struct blk_mq_tag_set *set = q->tag_set;
2813 unsigned int i, j;
2814
2815 for_each_possible_cpu(i) {
2816 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
2817 struct blk_mq_hw_ctx *hctx;
2818 int k;
2819
2820 __ctx->cpu = i;
2821 spin_lock_init(&__ctx->lock);
2822 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
2823 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
2824
2825 __ctx->queue = q;
2826
2827 /*
2828 * Set local node, IFF we have more than one hw queue. If
2829 * not, we remain on the home node of the device
2830 */
2831 for (j = 0; j < set->nr_maps; j++) {
2832 hctx = blk_mq_map_queue_type(q, j, i);
2833 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
2834 hctx->numa_node = cpu_to_node(i);
2835 }
2836 }
2837 }
2838
__blk_mq_alloc_map_and_request(struct blk_mq_tag_set * set,int hctx_idx)2839 static bool __blk_mq_alloc_map_and_request(struct blk_mq_tag_set *set,
2840 int hctx_idx)
2841 {
2842 unsigned int flags = set->flags;
2843 int ret = 0;
2844
2845 set->tags[hctx_idx] = blk_mq_alloc_rq_map(set, hctx_idx,
2846 set->queue_depth, set->reserved_tags, flags);
2847 if (!set->tags[hctx_idx])
2848 return false;
2849
2850 ret = blk_mq_alloc_rqs(set, set->tags[hctx_idx], hctx_idx,
2851 set->queue_depth);
2852 if (!ret)
2853 return true;
2854
2855 blk_mq_free_rq_map(set->tags[hctx_idx], flags);
2856 set->tags[hctx_idx] = NULL;
2857 return false;
2858 }
2859
blk_mq_free_map_and_requests(struct blk_mq_tag_set * set,unsigned int hctx_idx)2860 static void blk_mq_free_map_and_requests(struct blk_mq_tag_set *set,
2861 unsigned int hctx_idx)
2862 {
2863 unsigned int flags = set->flags;
2864
2865 if (set->tags && set->tags[hctx_idx]) {
2866 blk_mq_free_rqs(set, set->tags[hctx_idx], hctx_idx);
2867 blk_mq_free_rq_map(set->tags[hctx_idx], flags);
2868 set->tags[hctx_idx] = NULL;
2869 }
2870 }
2871
blk_mq_map_swqueue(struct request_queue * q)2872 static void blk_mq_map_swqueue(struct request_queue *q)
2873 {
2874 unsigned int i, j, hctx_idx;
2875 struct blk_mq_hw_ctx *hctx;
2876 struct blk_mq_ctx *ctx;
2877 struct blk_mq_tag_set *set = q->tag_set;
2878
2879 queue_for_each_hw_ctx(q, hctx, i) {
2880 cpumask_clear(hctx->cpumask);
2881 hctx->nr_ctx = 0;
2882 hctx->dispatch_from = NULL;
2883 }
2884
2885 /*
2886 * Map software to hardware queues.
2887 *
2888 * If the cpu isn't present, the cpu is mapped to first hctx.
2889 */
2890 for_each_possible_cpu(i) {
2891
2892 ctx = per_cpu_ptr(q->queue_ctx, i);
2893 for (j = 0; j < set->nr_maps; j++) {
2894 if (!set->map[j].nr_queues) {
2895 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2896 HCTX_TYPE_DEFAULT, i);
2897 continue;
2898 }
2899 hctx_idx = set->map[j].mq_map[i];
2900 /* unmapped hw queue can be remapped after CPU topo changed */
2901 if (!set->tags[hctx_idx] &&
2902 !__blk_mq_alloc_map_and_request(set, hctx_idx)) {
2903 /*
2904 * If tags initialization fail for some hctx,
2905 * that hctx won't be brought online. In this
2906 * case, remap the current ctx to hctx[0] which
2907 * is guaranteed to always have tags allocated
2908 */
2909 set->map[j].mq_map[i] = 0;
2910 }
2911
2912 hctx = blk_mq_map_queue_type(q, j, i);
2913 ctx->hctxs[j] = hctx;
2914 /*
2915 * If the CPU is already set in the mask, then we've
2916 * mapped this one already. This can happen if
2917 * devices share queues across queue maps.
2918 */
2919 if (cpumask_test_cpu(i, hctx->cpumask))
2920 continue;
2921
2922 cpumask_set_cpu(i, hctx->cpumask);
2923 hctx->type = j;
2924 ctx->index_hw[hctx->type] = hctx->nr_ctx;
2925 hctx->ctxs[hctx->nr_ctx++] = ctx;
2926
2927 /*
2928 * If the nr_ctx type overflows, we have exceeded the
2929 * amount of sw queues we can support.
2930 */
2931 BUG_ON(!hctx->nr_ctx);
2932 }
2933
2934 for (; j < HCTX_MAX_TYPES; j++)
2935 ctx->hctxs[j] = blk_mq_map_queue_type(q,
2936 HCTX_TYPE_DEFAULT, i);
2937 }
2938
2939 queue_for_each_hw_ctx(q, hctx, i) {
2940 /*
2941 * If no software queues are mapped to this hardware queue,
2942 * disable it and free the request entries.
2943 */
2944 if (!hctx->nr_ctx) {
2945 /* Never unmap queue 0. We need it as a
2946 * fallback in case of a new remap fails
2947 * allocation
2948 */
2949 if (i && set->tags[i])
2950 blk_mq_free_map_and_requests(set, i);
2951
2952 hctx->tags = NULL;
2953 continue;
2954 }
2955
2956 hctx->tags = set->tags[i];
2957 WARN_ON(!hctx->tags);
2958
2959 /*
2960 * Set the map size to the number of mapped software queues.
2961 * This is more accurate and more efficient than looping
2962 * over all possibly mapped software queues.
2963 */
2964 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
2965
2966 /*
2967 * Initialize batch roundrobin counts
2968 */
2969 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
2970 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2971 }
2972 }
2973
2974 /*
2975 * Caller needs to ensure that we're either frozen/quiesced, or that
2976 * the queue isn't live yet.
2977 */
queue_set_hctx_shared(struct request_queue * q,bool shared)2978 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
2979 {
2980 struct blk_mq_hw_ctx *hctx;
2981 int i;
2982
2983 queue_for_each_hw_ctx(q, hctx, i) {
2984 if (shared) {
2985 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
2986 } else {
2987 blk_mq_tag_idle(hctx);
2988 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
2989 }
2990 }
2991 }
2992
blk_mq_update_tag_set_shared(struct blk_mq_tag_set * set,bool shared)2993 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
2994 bool shared)
2995 {
2996 struct request_queue *q;
2997
2998 lockdep_assert_held(&set->tag_list_lock);
2999
3000 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3001 blk_mq_freeze_queue(q);
3002 queue_set_hctx_shared(q, shared);
3003 blk_mq_unfreeze_queue(q);
3004 }
3005 }
3006
blk_mq_del_queue_tag_set(struct request_queue * q)3007 static void blk_mq_del_queue_tag_set(struct request_queue *q)
3008 {
3009 struct blk_mq_tag_set *set = q->tag_set;
3010
3011 mutex_lock(&set->tag_list_lock);
3012 list_del(&q->tag_set_list);
3013 if (list_is_singular(&set->tag_list)) {
3014 /* just transitioned to unshared */
3015 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
3016 /* update existing queue */
3017 blk_mq_update_tag_set_shared(set, false);
3018 }
3019 mutex_unlock(&set->tag_list_lock);
3020 INIT_LIST_HEAD(&q->tag_set_list);
3021 }
3022
blk_mq_add_queue_tag_set(struct blk_mq_tag_set * set,struct request_queue * q)3023 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
3024 struct request_queue *q)
3025 {
3026 mutex_lock(&set->tag_list_lock);
3027
3028 /*
3029 * Check to see if we're transitioning to shared (from 1 to 2 queues).
3030 */
3031 if (!list_empty(&set->tag_list) &&
3032 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
3033 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
3034 /* update existing queue */
3035 blk_mq_update_tag_set_shared(set, true);
3036 }
3037 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
3038 queue_set_hctx_shared(q, true);
3039 list_add_tail(&q->tag_set_list, &set->tag_list);
3040
3041 mutex_unlock(&set->tag_list_lock);
3042 }
3043
3044 /* All allocations will be freed in release handler of q->mq_kobj */
blk_mq_alloc_ctxs(struct request_queue * q)3045 static int blk_mq_alloc_ctxs(struct request_queue *q)
3046 {
3047 struct blk_mq_ctxs *ctxs;
3048 int cpu;
3049
3050 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
3051 if (!ctxs)
3052 return -ENOMEM;
3053
3054 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
3055 if (!ctxs->queue_ctx)
3056 goto fail;
3057
3058 for_each_possible_cpu(cpu) {
3059 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
3060 ctx->ctxs = ctxs;
3061 }
3062
3063 q->mq_kobj = &ctxs->kobj;
3064 q->queue_ctx = ctxs->queue_ctx;
3065
3066 return 0;
3067 fail:
3068 kfree(ctxs);
3069 return -ENOMEM;
3070 }
3071
3072 /*
3073 * It is the actual release handler for mq, but we do it from
3074 * request queue's release handler for avoiding use-after-free
3075 * and headache because q->mq_kobj shouldn't have been introduced,
3076 * but we can't group ctx/kctx kobj without it.
3077 */
blk_mq_release(struct request_queue * q)3078 void blk_mq_release(struct request_queue *q)
3079 {
3080 struct blk_mq_hw_ctx *hctx, *next;
3081 int i;
3082
3083 queue_for_each_hw_ctx(q, hctx, i)
3084 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
3085
3086 /* all hctx are in .unused_hctx_list now */
3087 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
3088 list_del_init(&hctx->hctx_list);
3089 kobject_put(&hctx->kobj);
3090 }
3091
3092 kfree(q->queue_hw_ctx);
3093
3094 /*
3095 * release .mq_kobj and sw queue's kobject now because
3096 * both share lifetime with request queue.
3097 */
3098 blk_mq_sysfs_deinit(q);
3099 }
3100
blk_mq_init_queue_data(struct blk_mq_tag_set * set,void * queuedata)3101 struct request_queue *blk_mq_init_queue_data(struct blk_mq_tag_set *set,
3102 void *queuedata)
3103 {
3104 struct request_queue *uninit_q, *q;
3105
3106 uninit_q = blk_alloc_queue(set->numa_node);
3107 if (!uninit_q)
3108 return ERR_PTR(-ENOMEM);
3109 uninit_q->queuedata = queuedata;
3110
3111 /*
3112 * Initialize the queue without an elevator. device_add_disk() will do
3113 * the initialization.
3114 */
3115 q = blk_mq_init_allocated_queue(set, uninit_q, false);
3116 if (IS_ERR(q))
3117 blk_cleanup_queue(uninit_q);
3118
3119 return q;
3120 }
3121 EXPORT_SYMBOL_GPL(blk_mq_init_queue_data);
3122
blk_mq_init_queue(struct blk_mq_tag_set * set)3123 struct request_queue *blk_mq_init_queue(struct blk_mq_tag_set *set)
3124 {
3125 return blk_mq_init_queue_data(set, NULL);
3126 }
3127 EXPORT_SYMBOL(blk_mq_init_queue);
3128
3129 /*
3130 * Helper for setting up a queue with mq ops, given queue depth, and
3131 * the passed in mq ops flags.
3132 */
blk_mq_init_sq_queue(struct blk_mq_tag_set * set,const struct blk_mq_ops * ops,unsigned int queue_depth,unsigned int set_flags)3133 struct request_queue *blk_mq_init_sq_queue(struct blk_mq_tag_set *set,
3134 const struct blk_mq_ops *ops,
3135 unsigned int queue_depth,
3136 unsigned int set_flags)
3137 {
3138 struct request_queue *q;
3139 int ret;
3140
3141 memset(set, 0, sizeof(*set));
3142 set->ops = ops;
3143 set->nr_hw_queues = 1;
3144 set->nr_maps = 1;
3145 set->queue_depth = queue_depth;
3146 set->numa_node = NUMA_NO_NODE;
3147 set->flags = set_flags;
3148
3149 ret = blk_mq_alloc_tag_set(set);
3150 if (ret)
3151 return ERR_PTR(ret);
3152
3153 q = blk_mq_init_queue(set);
3154 if (IS_ERR(q)) {
3155 blk_mq_free_tag_set(set);
3156 return q;
3157 }
3158
3159 return q;
3160 }
3161 EXPORT_SYMBOL(blk_mq_init_sq_queue);
3162
blk_mq_alloc_and_init_hctx(struct blk_mq_tag_set * set,struct request_queue * q,int hctx_idx,int node)3163 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
3164 struct blk_mq_tag_set *set, struct request_queue *q,
3165 int hctx_idx, int node)
3166 {
3167 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
3168
3169 /* reuse dead hctx first */
3170 spin_lock(&q->unused_hctx_lock);
3171 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
3172 if (tmp->numa_node == node) {
3173 hctx = tmp;
3174 break;
3175 }
3176 }
3177 if (hctx)
3178 list_del_init(&hctx->hctx_list);
3179 spin_unlock(&q->unused_hctx_lock);
3180
3181 if (!hctx)
3182 hctx = blk_mq_alloc_hctx(q, set, node);
3183 if (!hctx)
3184 goto fail;
3185
3186 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
3187 goto free_hctx;
3188
3189 return hctx;
3190
3191 free_hctx:
3192 kobject_put(&hctx->kobj);
3193 fail:
3194 return NULL;
3195 }
3196
blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set * set,struct request_queue * q)3197 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
3198 struct request_queue *q)
3199 {
3200 int i, j, end;
3201 struct blk_mq_hw_ctx **hctxs = q->queue_hw_ctx;
3202
3203 if (q->nr_hw_queues < set->nr_hw_queues) {
3204 struct blk_mq_hw_ctx **new_hctxs;
3205
3206 new_hctxs = kcalloc_node(set->nr_hw_queues,
3207 sizeof(*new_hctxs), GFP_KERNEL,
3208 set->numa_node);
3209 if (!new_hctxs)
3210 return;
3211 if (hctxs)
3212 memcpy(new_hctxs, hctxs, q->nr_hw_queues *
3213 sizeof(*hctxs));
3214 q->queue_hw_ctx = new_hctxs;
3215 kfree(hctxs);
3216 hctxs = new_hctxs;
3217 }
3218
3219 /* protect against switching io scheduler */
3220 mutex_lock(&q->sysfs_lock);
3221 for (i = 0; i < set->nr_hw_queues; i++) {
3222 int node;
3223 struct blk_mq_hw_ctx *hctx;
3224
3225 node = blk_mq_hw_queue_to_node(&set->map[HCTX_TYPE_DEFAULT], i);
3226 /*
3227 * If the hw queue has been mapped to another numa node,
3228 * we need to realloc the hctx. If allocation fails, fallback
3229 * to use the previous one.
3230 */
3231 if (hctxs[i] && (hctxs[i]->numa_node == node))
3232 continue;
3233
3234 hctx = blk_mq_alloc_and_init_hctx(set, q, i, node);
3235 if (hctx) {
3236 if (hctxs[i])
3237 blk_mq_exit_hctx(q, set, hctxs[i], i);
3238 hctxs[i] = hctx;
3239 } else {
3240 if (hctxs[i])
3241 pr_warn("Allocate new hctx on node %d fails,\
3242 fallback to previous one on node %d\n",
3243 node, hctxs[i]->numa_node);
3244 else
3245 break;
3246 }
3247 }
3248 /*
3249 * Increasing nr_hw_queues fails. Free the newly allocated
3250 * hctxs and keep the previous q->nr_hw_queues.
3251 */
3252 if (i != set->nr_hw_queues) {
3253 j = q->nr_hw_queues;
3254 end = i;
3255 } else {
3256 j = i;
3257 end = q->nr_hw_queues;
3258 q->nr_hw_queues = set->nr_hw_queues;
3259 }
3260
3261 for (; j < end; j++) {
3262 struct blk_mq_hw_ctx *hctx = hctxs[j];
3263
3264 if (hctx) {
3265 blk_mq_exit_hctx(q, set, hctx, j);
3266 hctxs[j] = NULL;
3267 }
3268 }
3269 mutex_unlock(&q->sysfs_lock);
3270 }
3271
blk_mq_init_allocated_queue(struct blk_mq_tag_set * set,struct request_queue * q,bool elevator_init)3272 struct request_queue *blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
3273 struct request_queue *q,
3274 bool elevator_init)
3275 {
3276 /* mark the queue as mq asap */
3277 q->mq_ops = set->ops;
3278
3279 q->poll_cb = blk_stat_alloc_callback(blk_mq_poll_stats_fn,
3280 blk_mq_poll_stats_bkt,
3281 BLK_MQ_POLL_STATS_BKTS, q);
3282 if (!q->poll_cb)
3283 goto err_exit;
3284
3285 if (blk_mq_alloc_ctxs(q))
3286 goto err_poll;
3287
3288 /* init q->mq_kobj and sw queues' kobjects */
3289 blk_mq_sysfs_init(q);
3290
3291 INIT_LIST_HEAD(&q->unused_hctx_list);
3292 spin_lock_init(&q->unused_hctx_lock);
3293
3294 blk_mq_realloc_hw_ctxs(set, q);
3295 if (!q->nr_hw_queues)
3296 goto err_hctxs;
3297
3298 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
3299 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
3300
3301 q->tag_set = set;
3302
3303 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
3304 if (set->nr_maps > HCTX_TYPE_POLL &&
3305 set->map[HCTX_TYPE_POLL].nr_queues)
3306 blk_queue_flag_set(QUEUE_FLAG_POLL, q);
3307
3308 q->sg_reserved_size = INT_MAX;
3309
3310 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
3311 INIT_LIST_HEAD(&q->requeue_list);
3312 spin_lock_init(&q->requeue_lock);
3313
3314 q->nr_requests = set->queue_depth;
3315
3316 /*
3317 * Default to classic polling
3318 */
3319 q->poll_nsec = BLK_MQ_POLL_CLASSIC;
3320
3321 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
3322 blk_mq_add_queue_tag_set(set, q);
3323 blk_mq_map_swqueue(q);
3324
3325 if (elevator_init)
3326 elevator_init_mq(q);
3327
3328 return q;
3329
3330 err_hctxs:
3331 kfree(q->queue_hw_ctx);
3332 q->nr_hw_queues = 0;
3333 blk_mq_sysfs_deinit(q);
3334 err_poll:
3335 blk_stat_free_callback(q->poll_cb);
3336 q->poll_cb = NULL;
3337 err_exit:
3338 q->mq_ops = NULL;
3339 return ERR_PTR(-ENOMEM);
3340 }
3341 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
3342
3343 /* tags can _not_ be used after returning from blk_mq_exit_queue */
blk_mq_exit_queue(struct request_queue * q)3344 void blk_mq_exit_queue(struct request_queue *q)
3345 {
3346 struct blk_mq_tag_set *set = q->tag_set;
3347
3348 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
3349 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
3350 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
3351 blk_mq_del_queue_tag_set(q);
3352 }
3353
__blk_mq_alloc_rq_maps(struct blk_mq_tag_set * set)3354 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
3355 {
3356 int i;
3357
3358 for (i = 0; i < set->nr_hw_queues; i++) {
3359 if (!__blk_mq_alloc_map_and_request(set, i))
3360 goto out_unwind;
3361 cond_resched();
3362 }
3363
3364 return 0;
3365
3366 out_unwind:
3367 while (--i >= 0)
3368 blk_mq_free_map_and_requests(set, i);
3369
3370 return -ENOMEM;
3371 }
3372
3373 /*
3374 * Allocate the request maps associated with this tag_set. Note that this
3375 * may reduce the depth asked for, if memory is tight. set->queue_depth
3376 * will be updated to reflect the allocated depth.
3377 */
blk_mq_alloc_map_and_requests(struct blk_mq_tag_set * set)3378 static int blk_mq_alloc_map_and_requests(struct blk_mq_tag_set *set)
3379 {
3380 unsigned int depth;
3381 int err;
3382
3383 depth = set->queue_depth;
3384 do {
3385 err = __blk_mq_alloc_rq_maps(set);
3386 if (!err)
3387 break;
3388
3389 set->queue_depth >>= 1;
3390 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
3391 err = -ENOMEM;
3392 break;
3393 }
3394 } while (set->queue_depth);
3395
3396 if (!set->queue_depth || err) {
3397 pr_err("blk-mq: failed to allocate request map\n");
3398 return -ENOMEM;
3399 }
3400
3401 if (depth != set->queue_depth)
3402 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
3403 depth, set->queue_depth);
3404
3405 return 0;
3406 }
3407
blk_mq_update_queue_map(struct blk_mq_tag_set * set)3408 static int blk_mq_update_queue_map(struct blk_mq_tag_set *set)
3409 {
3410 /*
3411 * blk_mq_map_queues() and multiple .map_queues() implementations
3412 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
3413 * number of hardware queues.
3414 */
3415 if (set->nr_maps == 1)
3416 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
3417
3418 if (set->ops->map_queues && !is_kdump_kernel()) {
3419 int i;
3420
3421 /*
3422 * transport .map_queues is usually done in the following
3423 * way:
3424 *
3425 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
3426 * mask = get_cpu_mask(queue)
3427 * for_each_cpu(cpu, mask)
3428 * set->map[x].mq_map[cpu] = queue;
3429 * }
3430 *
3431 * When we need to remap, the table has to be cleared for
3432 * killing stale mapping since one CPU may not be mapped
3433 * to any hw queue.
3434 */
3435 for (i = 0; i < set->nr_maps; i++)
3436 blk_mq_clear_mq_map(&set->map[i]);
3437
3438 return set->ops->map_queues(set);
3439 } else {
3440 BUG_ON(set->nr_maps > 1);
3441 return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3442 }
3443 }
3444
blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set * set,int cur_nr_hw_queues,int new_nr_hw_queues)3445 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
3446 int cur_nr_hw_queues, int new_nr_hw_queues)
3447 {
3448 struct blk_mq_tags **new_tags;
3449
3450 if (cur_nr_hw_queues >= new_nr_hw_queues)
3451 return 0;
3452
3453 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
3454 GFP_KERNEL, set->numa_node);
3455 if (!new_tags)
3456 return -ENOMEM;
3457
3458 if (set->tags)
3459 memcpy(new_tags, set->tags, cur_nr_hw_queues *
3460 sizeof(*set->tags));
3461 kfree(set->tags);
3462 set->tags = new_tags;
3463 set->nr_hw_queues = new_nr_hw_queues;
3464
3465 return 0;
3466 }
3467
3468 /*
3469 * Alloc a tag set to be associated with one or more request queues.
3470 * May fail with EINVAL for various error conditions. May adjust the
3471 * requested depth down, if it's too large. In that case, the set
3472 * value will be stored in set->queue_depth.
3473 */
blk_mq_alloc_tag_set(struct blk_mq_tag_set * set)3474 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
3475 {
3476 int i, ret;
3477
3478 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
3479
3480 if (!set->nr_hw_queues)
3481 return -EINVAL;
3482 if (!set->queue_depth)
3483 return -EINVAL;
3484 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
3485 return -EINVAL;
3486
3487 if (!set->ops->queue_rq)
3488 return -EINVAL;
3489
3490 if (!set->ops->get_budget ^ !set->ops->put_budget)
3491 return -EINVAL;
3492
3493 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
3494 pr_info("blk-mq: reduced tag depth to %u\n",
3495 BLK_MQ_MAX_DEPTH);
3496 set->queue_depth = BLK_MQ_MAX_DEPTH;
3497 }
3498
3499 if (!set->nr_maps)
3500 set->nr_maps = 1;
3501 else if (set->nr_maps > HCTX_MAX_TYPES)
3502 return -EINVAL;
3503
3504 /*
3505 * If a crashdump is active, then we are potentially in a very
3506 * memory constrained environment. Limit us to 1 queue and
3507 * 64 tags to prevent using too much memory.
3508 */
3509 if (is_kdump_kernel()) {
3510 set->nr_hw_queues = 1;
3511 set->nr_maps = 1;
3512 set->queue_depth = min(64U, set->queue_depth);
3513 }
3514 /*
3515 * There is no use for more h/w queues than cpus if we just have
3516 * a single map
3517 */
3518 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
3519 set->nr_hw_queues = nr_cpu_ids;
3520
3521 if (blk_mq_realloc_tag_set_tags(set, 0, set->nr_hw_queues) < 0)
3522 return -ENOMEM;
3523
3524 ret = -ENOMEM;
3525 for (i = 0; i < set->nr_maps; i++) {
3526 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
3527 sizeof(set->map[i].mq_map[0]),
3528 GFP_KERNEL, set->numa_node);
3529 if (!set->map[i].mq_map)
3530 goto out_free_mq_map;
3531 set->map[i].nr_queues = is_kdump_kernel() ? 1 : set->nr_hw_queues;
3532 }
3533
3534 ret = blk_mq_update_queue_map(set);
3535 if (ret)
3536 goto out_free_mq_map;
3537
3538 ret = blk_mq_alloc_map_and_requests(set);
3539 if (ret)
3540 goto out_free_mq_map;
3541
3542 if (blk_mq_is_sbitmap_shared(set->flags)) {
3543 atomic_set(&set->active_queues_shared_sbitmap, 0);
3544
3545 if (blk_mq_init_shared_sbitmap(set, set->flags)) {
3546 ret = -ENOMEM;
3547 goto out_free_mq_rq_maps;
3548 }
3549 }
3550
3551 mutex_init(&set->tag_list_lock);
3552 INIT_LIST_HEAD(&set->tag_list);
3553
3554 return 0;
3555
3556 out_free_mq_rq_maps:
3557 for (i = 0; i < set->nr_hw_queues; i++)
3558 blk_mq_free_map_and_requests(set, i);
3559 out_free_mq_map:
3560 for (i = 0; i < set->nr_maps; i++) {
3561 kfree(set->map[i].mq_map);
3562 set->map[i].mq_map = NULL;
3563 }
3564 kfree(set->tags);
3565 set->tags = NULL;
3566 return ret;
3567 }
3568 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
3569
blk_mq_free_tag_set(struct blk_mq_tag_set * set)3570 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
3571 {
3572 int i, j;
3573
3574 for (i = 0; i < set->nr_hw_queues; i++)
3575 blk_mq_free_map_and_requests(set, i);
3576
3577 if (blk_mq_is_sbitmap_shared(set->flags))
3578 blk_mq_exit_shared_sbitmap(set);
3579
3580 for (j = 0; j < set->nr_maps; j++) {
3581 kfree(set->map[j].mq_map);
3582 set->map[j].mq_map = NULL;
3583 }
3584
3585 kfree(set->tags);
3586 set->tags = NULL;
3587 }
3588 EXPORT_SYMBOL(blk_mq_free_tag_set);
3589
blk_mq_update_nr_requests(struct request_queue * q,unsigned int nr)3590 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
3591 {
3592 struct blk_mq_tag_set *set = q->tag_set;
3593 struct blk_mq_hw_ctx *hctx;
3594 int i, ret;
3595
3596 if (!set)
3597 return -EINVAL;
3598
3599 if (q->nr_requests == nr)
3600 return 0;
3601
3602 blk_mq_freeze_queue(q);
3603 blk_mq_quiesce_queue(q);
3604
3605 ret = 0;
3606 queue_for_each_hw_ctx(q, hctx, i) {
3607 if (!hctx->tags)
3608 continue;
3609 /*
3610 * If we're using an MQ scheduler, just update the scheduler
3611 * queue depth. This is similar to what the old code would do.
3612 */
3613 if (!hctx->sched_tags) {
3614 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
3615 false);
3616 if (!ret && blk_mq_is_sbitmap_shared(set->flags))
3617 blk_mq_tag_resize_shared_sbitmap(set, nr);
3618 } else {
3619 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
3620 nr, true);
3621 }
3622 if (ret)
3623 break;
3624 if (q->elevator && q->elevator->type->ops.depth_updated)
3625 q->elevator->type->ops.depth_updated(hctx);
3626 }
3627
3628 if (!ret)
3629 q->nr_requests = nr;
3630
3631 blk_mq_unquiesce_queue(q);
3632 blk_mq_unfreeze_queue(q);
3633
3634 return ret;
3635 }
3636
3637 /*
3638 * request_queue and elevator_type pair.
3639 * It is just used by __blk_mq_update_nr_hw_queues to cache
3640 * the elevator_type associated with a request_queue.
3641 */
3642 struct blk_mq_qe_pair {
3643 struct list_head node;
3644 struct request_queue *q;
3645 struct elevator_type *type;
3646 };
3647
3648 /*
3649 * Cache the elevator_type in qe pair list and switch the
3650 * io scheduler to 'none'
3651 */
blk_mq_elv_switch_none(struct list_head * head,struct request_queue * q)3652 static bool blk_mq_elv_switch_none(struct list_head *head,
3653 struct request_queue *q)
3654 {
3655 struct blk_mq_qe_pair *qe;
3656
3657 if (!q->elevator)
3658 return true;
3659
3660 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
3661 if (!qe)
3662 return false;
3663
3664 INIT_LIST_HEAD(&qe->node);
3665 qe->q = q;
3666 qe->type = q->elevator->type;
3667 list_add(&qe->node, head);
3668
3669 mutex_lock(&q->sysfs_lock);
3670 /*
3671 * After elevator_switch_mq, the previous elevator_queue will be
3672 * released by elevator_release. The reference of the io scheduler
3673 * module get by elevator_get will also be put. So we need to get
3674 * a reference of the io scheduler module here to prevent it to be
3675 * removed.
3676 */
3677 __module_get(qe->type->elevator_owner);
3678 elevator_switch_mq(q, NULL);
3679 mutex_unlock(&q->sysfs_lock);
3680
3681 return true;
3682 }
3683
blk_mq_elv_switch_back(struct list_head * head,struct request_queue * q)3684 static void blk_mq_elv_switch_back(struct list_head *head,
3685 struct request_queue *q)
3686 {
3687 struct blk_mq_qe_pair *qe;
3688 struct elevator_type *t = NULL;
3689
3690 list_for_each_entry(qe, head, node)
3691 if (qe->q == q) {
3692 t = qe->type;
3693 break;
3694 }
3695
3696 if (!t)
3697 return;
3698
3699 list_del(&qe->node);
3700 kfree(qe);
3701
3702 mutex_lock(&q->sysfs_lock);
3703 elevator_switch_mq(q, t);
3704 mutex_unlock(&q->sysfs_lock);
3705 }
3706
__blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)3707 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
3708 int nr_hw_queues)
3709 {
3710 struct request_queue *q;
3711 LIST_HEAD(head);
3712 int prev_nr_hw_queues;
3713
3714 lockdep_assert_held(&set->tag_list_lock);
3715
3716 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
3717 nr_hw_queues = nr_cpu_ids;
3718 if (nr_hw_queues < 1)
3719 return;
3720 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
3721 return;
3722
3723 list_for_each_entry(q, &set->tag_list, tag_set_list)
3724 blk_mq_freeze_queue(q);
3725 /*
3726 * Switch IO scheduler to 'none', cleaning up the data associated
3727 * with the previous scheduler. We will switch back once we are done
3728 * updating the new sw to hw queue mappings.
3729 */
3730 list_for_each_entry(q, &set->tag_list, tag_set_list)
3731 if (!blk_mq_elv_switch_none(&head, q))
3732 goto switch_back;
3733
3734 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3735 blk_mq_debugfs_unregister_hctxs(q);
3736 blk_mq_sysfs_unregister(q);
3737 }
3738
3739 prev_nr_hw_queues = set->nr_hw_queues;
3740 if (blk_mq_realloc_tag_set_tags(set, set->nr_hw_queues, nr_hw_queues) <
3741 0)
3742 goto reregister;
3743
3744 set->nr_hw_queues = nr_hw_queues;
3745 fallback:
3746 blk_mq_update_queue_map(set);
3747 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3748 blk_mq_realloc_hw_ctxs(set, q);
3749 if (q->nr_hw_queues != set->nr_hw_queues) {
3750 int i = prev_nr_hw_queues;
3751
3752 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
3753 nr_hw_queues, prev_nr_hw_queues);
3754 for (; i < set->nr_hw_queues; i++)
3755 blk_mq_free_map_and_requests(set, i);
3756
3757 set->nr_hw_queues = prev_nr_hw_queues;
3758 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
3759 goto fallback;
3760 }
3761 blk_mq_map_swqueue(q);
3762 }
3763
3764 reregister:
3765 list_for_each_entry(q, &set->tag_list, tag_set_list) {
3766 blk_mq_sysfs_register(q);
3767 blk_mq_debugfs_register_hctxs(q);
3768 }
3769
3770 switch_back:
3771 list_for_each_entry(q, &set->tag_list, tag_set_list)
3772 blk_mq_elv_switch_back(&head, q);
3773
3774 list_for_each_entry(q, &set->tag_list, tag_set_list)
3775 blk_mq_unfreeze_queue(q);
3776 }
3777
blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)3778 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
3779 {
3780 mutex_lock(&set->tag_list_lock);
3781 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
3782 mutex_unlock(&set->tag_list_lock);
3783 }
3784 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
3785
3786 /* Enable polling stats and return whether they were already enabled. */
blk_poll_stats_enable(struct request_queue * q)3787 static bool blk_poll_stats_enable(struct request_queue *q)
3788 {
3789 if (test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3790 blk_queue_flag_test_and_set(QUEUE_FLAG_POLL_STATS, q))
3791 return true;
3792 blk_stat_add_callback(q, q->poll_cb);
3793 return false;
3794 }
3795
blk_mq_poll_stats_start(struct request_queue * q)3796 static void blk_mq_poll_stats_start(struct request_queue *q)
3797 {
3798 /*
3799 * We don't arm the callback if polling stats are not enabled or the
3800 * callback is already active.
3801 */
3802 if (!test_bit(QUEUE_FLAG_POLL_STATS, &q->queue_flags) ||
3803 blk_stat_is_active(q->poll_cb))
3804 return;
3805
3806 blk_stat_activate_msecs(q->poll_cb, 100);
3807 }
3808
blk_mq_poll_stats_fn(struct blk_stat_callback * cb)3809 static void blk_mq_poll_stats_fn(struct blk_stat_callback *cb)
3810 {
3811 struct request_queue *q = cb->data;
3812 int bucket;
3813
3814 for (bucket = 0; bucket < BLK_MQ_POLL_STATS_BKTS; bucket++) {
3815 if (cb->stat[bucket].nr_samples)
3816 q->poll_stat[bucket] = cb->stat[bucket];
3817 }
3818 }
3819
blk_mq_poll_nsecs(struct request_queue * q,struct request * rq)3820 static unsigned long blk_mq_poll_nsecs(struct request_queue *q,
3821 struct request *rq)
3822 {
3823 unsigned long ret = 0;
3824 int bucket;
3825
3826 /*
3827 * If stats collection isn't on, don't sleep but turn it on for
3828 * future users
3829 */
3830 if (!blk_poll_stats_enable(q))
3831 return 0;
3832
3833 /*
3834 * As an optimistic guess, use half of the mean service time
3835 * for this type of request. We can (and should) make this smarter.
3836 * For instance, if the completion latencies are tight, we can
3837 * get closer than just half the mean. This is especially
3838 * important on devices where the completion latencies are longer
3839 * than ~10 usec. We do use the stats for the relevant IO size
3840 * if available which does lead to better estimates.
3841 */
3842 bucket = blk_mq_poll_stats_bkt(rq);
3843 if (bucket < 0)
3844 return ret;
3845
3846 if (q->poll_stat[bucket].nr_samples)
3847 ret = (q->poll_stat[bucket].mean + 1) / 2;
3848
3849 return ret;
3850 }
3851
blk_mq_poll_hybrid_sleep(struct request_queue * q,struct request * rq)3852 static bool blk_mq_poll_hybrid_sleep(struct request_queue *q,
3853 struct request *rq)
3854 {
3855 struct hrtimer_sleeper hs;
3856 enum hrtimer_mode mode;
3857 unsigned int nsecs;
3858 ktime_t kt;
3859
3860 if (rq->rq_flags & RQF_MQ_POLL_SLEPT)
3861 return false;
3862
3863 /*
3864 * If we get here, hybrid polling is enabled. Hence poll_nsec can be:
3865 *
3866 * 0: use half of prev avg
3867 * >0: use this specific value
3868 */
3869 if (q->poll_nsec > 0)
3870 nsecs = q->poll_nsec;
3871 else
3872 nsecs = blk_mq_poll_nsecs(q, rq);
3873
3874 if (!nsecs)
3875 return false;
3876
3877 rq->rq_flags |= RQF_MQ_POLL_SLEPT;
3878
3879 /*
3880 * This will be replaced with the stats tracking code, using
3881 * 'avg_completion_time / 2' as the pre-sleep target.
3882 */
3883 kt = nsecs;
3884
3885 mode = HRTIMER_MODE_REL;
3886 hrtimer_init_sleeper_on_stack(&hs, CLOCK_MONOTONIC, mode);
3887 hrtimer_set_expires(&hs.timer, kt);
3888
3889 do {
3890 if (blk_mq_rq_state(rq) == MQ_RQ_COMPLETE)
3891 break;
3892 set_current_state(TASK_UNINTERRUPTIBLE);
3893 hrtimer_sleeper_start_expires(&hs, mode);
3894 if (hs.task)
3895 io_schedule();
3896 hrtimer_cancel(&hs.timer);
3897 mode = HRTIMER_MODE_ABS;
3898 } while (hs.task && !signal_pending(current));
3899
3900 __set_current_state(TASK_RUNNING);
3901 destroy_hrtimer_on_stack(&hs.timer);
3902 return true;
3903 }
3904
blk_mq_poll_hybrid(struct request_queue * q,struct blk_mq_hw_ctx * hctx,blk_qc_t cookie)3905 static bool blk_mq_poll_hybrid(struct request_queue *q,
3906 struct blk_mq_hw_ctx *hctx, blk_qc_t cookie)
3907 {
3908 struct request *rq;
3909
3910 if (q->poll_nsec == BLK_MQ_POLL_CLASSIC)
3911 return false;
3912
3913 if (!blk_qc_t_is_internal(cookie))
3914 rq = blk_mq_tag_to_rq(hctx->tags, blk_qc_t_to_tag(cookie));
3915 else {
3916 rq = blk_mq_tag_to_rq(hctx->sched_tags, blk_qc_t_to_tag(cookie));
3917 /*
3918 * With scheduling, if the request has completed, we'll
3919 * get a NULL return here, as we clear the sched tag when
3920 * that happens. The request still remains valid, like always,
3921 * so we should be safe with just the NULL check.
3922 */
3923 if (!rq)
3924 return false;
3925 }
3926
3927 return blk_mq_poll_hybrid_sleep(q, rq);
3928 }
3929
3930 /**
3931 * blk_poll - poll for IO completions
3932 * @q: the queue
3933 * @cookie: cookie passed back at IO submission time
3934 * @spin: whether to spin for completions
3935 *
3936 * Description:
3937 * Poll for completions on the passed in queue. Returns number of
3938 * completed entries found. If @spin is true, then blk_poll will continue
3939 * looping until at least one completion is found, unless the task is
3940 * otherwise marked running (or we need to reschedule).
3941 */
blk_poll(struct request_queue * q,blk_qc_t cookie,bool spin)3942 int blk_poll(struct request_queue *q, blk_qc_t cookie, bool spin)
3943 {
3944 struct blk_mq_hw_ctx *hctx;
3945 long state;
3946
3947 if (!blk_qc_t_valid(cookie) ||
3948 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3949 return 0;
3950
3951 if (current->plug)
3952 blk_flush_plug_list(current->plug, false);
3953
3954 hctx = q->queue_hw_ctx[blk_qc_t_to_queue_num(cookie)];
3955
3956 /*
3957 * If we sleep, have the caller restart the poll loop to reset
3958 * the state. Like for the other success return cases, the
3959 * caller is responsible for checking if the IO completed. If
3960 * the IO isn't complete, we'll get called again and will go
3961 * straight to the busy poll loop.
3962 */
3963 if (blk_mq_poll_hybrid(q, hctx, cookie))
3964 return 1;
3965
3966 hctx->poll_considered++;
3967
3968 state = current->state;
3969 do {
3970 int ret;
3971
3972 hctx->poll_invoked++;
3973
3974 ret = q->mq_ops->poll(hctx);
3975 if (ret > 0) {
3976 hctx->poll_success++;
3977 __set_current_state(TASK_RUNNING);
3978 return ret;
3979 }
3980
3981 if (signal_pending_state(state, current))
3982 __set_current_state(TASK_RUNNING);
3983
3984 if (current->state == TASK_RUNNING)
3985 return 1;
3986 if (ret < 0 || !spin)
3987 break;
3988 cpu_relax();
3989 } while (!need_resched());
3990
3991 __set_current_state(TASK_RUNNING);
3992 return 0;
3993 }
3994 EXPORT_SYMBOL_GPL(blk_poll);
3995
blk_mq_rq_cpu(struct request * rq)3996 unsigned int blk_mq_rq_cpu(struct request *rq)
3997 {
3998 return rq->mq_ctx->cpu;
3999 }
4000 EXPORT_SYMBOL(blk_mq_rq_cpu);
4001
blk_mq_cancel_work_sync(struct request_queue * q)4002 void blk_mq_cancel_work_sync(struct request_queue *q)
4003 {
4004 if (queue_is_mq(q)) {
4005 struct blk_mq_hw_ctx *hctx;
4006 int i;
4007
4008 cancel_delayed_work_sync(&q->requeue_work);
4009
4010 queue_for_each_hw_ctx(q, hctx, i)
4011 cancel_delayed_work_sync(&hctx->run_work);
4012 }
4013 }
4014
blk_mq_init(void)4015 static int __init blk_mq_init(void)
4016 {
4017 int i;
4018
4019 for_each_possible_cpu(i)
4020 INIT_LIST_HEAD(&per_cpu(blk_cpu_done, i));
4021 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
4022
4023 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
4024 "block/softirq:dead", NULL,
4025 blk_softirq_cpu_dead);
4026 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
4027 blk_mq_hctx_notify_dead);
4028 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
4029 blk_mq_hctx_notify_online,
4030 blk_mq_hctx_notify_offline);
4031 return 0;
4032 }
4033 subsys_initcall(blk_mq_init);
4034