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