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