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