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/blk-integrity.h>
14 #include <linux/kmemleak.h>
15 #include <linux/mm.h>
16 #include <linux/init.h>
17 #include <linux/slab.h>
18 #include <linux/workqueue.h>
19 #include <linux/smp.h>
20 #include <linux/interrupt.h>
21 #include <linux/llist.h>
22 #include <linux/cpu.h>
23 #include <linux/cache.h>
24 #include <linux/sched/topology.h>
25 #include <linux/sched/signal.h>
26 #include <linux/delay.h>
27 #include <linux/crash_dump.h>
28 #include <linux/prefetch.h>
29 #include <linux/blk-crypto.h>
30 #include <linux/part_stat.h>
31 #include <linux/sched/isolation.h>
32
33 #include <trace/events/block.h>
34
35 #include <trace/hooks/blk.h>
36
37 #include <linux/t10-pi.h>
38 #include "blk.h"
39 #include "blk-mq.h"
40 #include "blk-mq-debugfs.h"
41 #include "blk-pm.h"
42 #include "blk-stat.h"
43 #include "blk-mq-sched.h"
44 #include "blk-rq-qos.h"
45
46 static DEFINE_PER_CPU(struct llist_head, blk_cpu_done);
47 static DEFINE_PER_CPU(call_single_data_t, blk_cpu_csd);
48 static DEFINE_MUTEX(blk_mq_cpuhp_lock);
49
50 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags);
51 static void blk_mq_request_bypass_insert(struct request *rq,
52 blk_insert_t flags);
53 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
54 struct list_head *list);
55 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
56 struct io_comp_batch *iob, unsigned int flags);
57
58 /*
59 * Check if any of the ctx, dispatch list or elevator
60 * have pending work in this hardware queue.
61 */
blk_mq_hctx_has_pending(struct blk_mq_hw_ctx * hctx)62 static bool blk_mq_hctx_has_pending(struct blk_mq_hw_ctx *hctx)
63 {
64 return !list_empty_careful(&hctx->dispatch) ||
65 sbitmap_any_bit_set(&hctx->ctx_map) ||
66 blk_mq_sched_has_work(hctx);
67 }
68
69 /*
70 * Mark this ctx as having pending work in this hardware queue
71 */
blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)72 static void blk_mq_hctx_mark_pending(struct blk_mq_hw_ctx *hctx,
73 struct blk_mq_ctx *ctx)
74 {
75 const int bit = ctx->index_hw[hctx->type];
76
77 if (!sbitmap_test_bit(&hctx->ctx_map, bit))
78 sbitmap_set_bit(&hctx->ctx_map, bit);
79 }
80
blk_mq_hctx_clear_pending(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx)81 static void blk_mq_hctx_clear_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 sbitmap_clear_bit(&hctx->ctx_map, bit);
87 }
88
89 struct mq_inflight {
90 struct block_device *part;
91 unsigned int inflight[2];
92 };
93
blk_mq_check_inflight(struct request * rq,void * priv)94 static bool blk_mq_check_inflight(struct request *rq, void *priv)
95 {
96 struct mq_inflight *mi = priv;
97
98 if (rq->part && blk_do_io_stat(rq) &&
99 (!bdev_is_partition(mi->part) || rq->part == mi->part) &&
100 blk_mq_rq_state(rq) == MQ_RQ_IN_FLIGHT)
101 mi->inflight[rq_data_dir(rq)]++;
102
103 return true;
104 }
105
blk_mq_in_flight(struct request_queue * q,struct block_device * part)106 unsigned int blk_mq_in_flight(struct request_queue *q,
107 struct block_device *part)
108 {
109 struct mq_inflight mi = { .part = part };
110
111 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
112
113 return mi.inflight[0] + mi.inflight[1];
114 }
115
blk_mq_in_flight_rw(struct request_queue * q,struct block_device * part,unsigned int inflight[2])116 void blk_mq_in_flight_rw(struct request_queue *q, struct block_device *part,
117 unsigned int inflight[2])
118 {
119 struct mq_inflight mi = { .part = part };
120
121 blk_mq_queue_tag_busy_iter(q, blk_mq_check_inflight, &mi);
122 inflight[0] = mi.inflight[0];
123 inflight[1] = mi.inflight[1];
124 }
125
126 #ifdef CONFIG_LOCKDEP
blk_freeze_set_owner(struct request_queue * q,struct task_struct * owner)127 static bool blk_freeze_set_owner(struct request_queue *q,
128 struct task_struct *owner)
129 {
130 if (!owner)
131 return false;
132
133 if (!q->mq_freeze_depth) {
134 q->mq_freeze_owner = owner;
135 q->mq_freeze_owner_depth = 1;
136 q->mq_freeze_disk_dead = !q->disk ||
137 test_bit(GD_DEAD, &q->disk->state) ||
138 !blk_queue_registered(q);
139 q->mq_freeze_queue_dying = blk_queue_dying(q);
140 return true;
141 }
142
143 if (owner == q->mq_freeze_owner)
144 q->mq_freeze_owner_depth += 1;
145 return false;
146 }
147
148 /* verify the last unfreeze in owner context */
blk_unfreeze_check_owner(struct request_queue * q)149 static bool blk_unfreeze_check_owner(struct request_queue *q)
150 {
151 if (!q->mq_freeze_owner)
152 return false;
153 if (q->mq_freeze_owner != current)
154 return false;
155 if (--q->mq_freeze_owner_depth == 0) {
156 q->mq_freeze_owner = NULL;
157 return true;
158 }
159 return false;
160 }
161
162 #else
163
blk_freeze_set_owner(struct request_queue * q,struct task_struct * owner)164 static bool blk_freeze_set_owner(struct request_queue *q,
165 struct task_struct *owner)
166 {
167 return false;
168 }
169
blk_unfreeze_check_owner(struct request_queue * q)170 static bool blk_unfreeze_check_owner(struct request_queue *q)
171 {
172 return false;
173 }
174 #endif
175
__blk_freeze_queue_start(struct request_queue * q,struct task_struct * owner)176 bool __blk_freeze_queue_start(struct request_queue *q,
177 struct task_struct *owner)
178 {
179 bool freeze;
180
181 mutex_lock(&q->mq_freeze_lock);
182 freeze = blk_freeze_set_owner(q, owner);
183 if (++q->mq_freeze_depth == 1) {
184 percpu_ref_kill(&q->q_usage_counter);
185 mutex_unlock(&q->mq_freeze_lock);
186 if (queue_is_mq(q))
187 blk_mq_run_hw_queues(q, false);
188 } else {
189 mutex_unlock(&q->mq_freeze_lock);
190 }
191
192 return freeze;
193 }
194
blk_freeze_queue_start(struct request_queue * q)195 void blk_freeze_queue_start(struct request_queue *q)
196 {
197 if (__blk_freeze_queue_start(q, current))
198 blk_freeze_acquire_lock(q);
199 }
200 EXPORT_SYMBOL_GPL(blk_freeze_queue_start);
201
blk_mq_freeze_queue_wait(struct request_queue * q)202 void blk_mq_freeze_queue_wait(struct request_queue *q)
203 {
204 wait_event(q->mq_freeze_wq, percpu_ref_is_zero(&q->q_usage_counter));
205 }
206 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait);
207
blk_mq_freeze_queue_wait_timeout(struct request_queue * q,unsigned long timeout)208 int blk_mq_freeze_queue_wait_timeout(struct request_queue *q,
209 unsigned long timeout)
210 {
211 return wait_event_timeout(q->mq_freeze_wq,
212 percpu_ref_is_zero(&q->q_usage_counter),
213 timeout);
214 }
215 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue_wait_timeout);
216
217 /*
218 * Guarantee no request is in use, so we can change any data structure of
219 * the queue afterward.
220 */
blk_freeze_queue(struct request_queue * q)221 void blk_freeze_queue(struct request_queue *q)
222 {
223 /*
224 * In the !blk_mq case we are only calling this to kill the
225 * q_usage_counter, otherwise this increases the freeze depth
226 * and waits for it to return to zero. For this reason there is
227 * no blk_unfreeze_queue(), and blk_freeze_queue() is not
228 * exported to drivers as the only user for unfreeze is blk_mq.
229 */
230 blk_freeze_queue_start(q);
231 blk_mq_freeze_queue_wait(q);
232 }
233
blk_mq_freeze_queue(struct request_queue * q)234 void blk_mq_freeze_queue(struct request_queue *q)
235 {
236 /*
237 * ...just an alias to keep freeze and unfreeze actions balanced
238 * in the blk_mq_* namespace
239 */
240 blk_freeze_queue(q);
241 }
242 EXPORT_SYMBOL_GPL(blk_mq_freeze_queue);
243
__blk_mq_unfreeze_queue(struct request_queue * q,bool force_atomic)244 bool __blk_mq_unfreeze_queue(struct request_queue *q, bool force_atomic)
245 {
246 bool unfreeze;
247
248 mutex_lock(&q->mq_freeze_lock);
249 if (force_atomic)
250 q->q_usage_counter.data->force_atomic = true;
251 q->mq_freeze_depth--;
252 WARN_ON_ONCE(q->mq_freeze_depth < 0);
253 if (!q->mq_freeze_depth) {
254 percpu_ref_resurrect(&q->q_usage_counter);
255 wake_up_all(&q->mq_freeze_wq);
256 }
257 unfreeze = blk_unfreeze_check_owner(q);
258 mutex_unlock(&q->mq_freeze_lock);
259
260 return unfreeze;
261 }
262
blk_mq_unfreeze_queue(struct request_queue * q)263 void blk_mq_unfreeze_queue(struct request_queue *q)
264 {
265 if (__blk_mq_unfreeze_queue(q, false))
266 blk_unfreeze_release_lock(q);
267 }
268 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue);
269
270 /*
271 * non_owner variant of blk_freeze_queue_start
272 *
273 * Unlike blk_freeze_queue_start, the queue doesn't need to be unfrozen
274 * by the same task. This is fragile and should not be used if at all
275 * possible.
276 */
blk_freeze_queue_start_non_owner(struct request_queue * q)277 void blk_freeze_queue_start_non_owner(struct request_queue *q)
278 {
279 __blk_freeze_queue_start(q, NULL);
280 }
281 EXPORT_SYMBOL_GPL(blk_freeze_queue_start_non_owner);
282
283 /* non_owner variant of blk_mq_unfreeze_queue */
blk_mq_unfreeze_queue_non_owner(struct request_queue * q)284 void blk_mq_unfreeze_queue_non_owner(struct request_queue *q)
285 {
286 __blk_mq_unfreeze_queue(q, false);
287 }
288 EXPORT_SYMBOL_GPL(blk_mq_unfreeze_queue_non_owner);
289
290 /*
291 * FIXME: replace the scsi_internal_device_*block_nowait() calls in the
292 * mpt3sas driver such that this function can be removed.
293 */
blk_mq_quiesce_queue_nowait(struct request_queue * q)294 void blk_mq_quiesce_queue_nowait(struct request_queue *q)
295 {
296 unsigned long flags;
297
298 spin_lock_irqsave(&q->queue_lock, flags);
299 if (!q->quiesce_depth++)
300 blk_queue_flag_set(QUEUE_FLAG_QUIESCED, q);
301 spin_unlock_irqrestore(&q->queue_lock, flags);
302 }
303 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue_nowait);
304
305 /**
306 * blk_mq_wait_quiesce_done() - wait until in-progress quiesce is done
307 * @set: tag_set to wait on
308 *
309 * Note: it is driver's responsibility for making sure that quiesce has
310 * been started on or more of the request_queues of the tag_set. This
311 * function only waits for the quiesce on those request_queues that had
312 * the quiesce flag set using blk_mq_quiesce_queue_nowait.
313 */
blk_mq_wait_quiesce_done(struct blk_mq_tag_set * set)314 void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
315 {
316 if (set->flags & BLK_MQ_F_BLOCKING)
317 synchronize_srcu(set->srcu);
318 else
319 synchronize_rcu();
320 }
321 EXPORT_SYMBOL_GPL(blk_mq_wait_quiesce_done);
322
323 /**
324 * blk_mq_quiesce_queue() - wait until all ongoing dispatches have finished
325 * @q: request queue.
326 *
327 * Note: this function does not prevent that the struct request end_io()
328 * callback function is invoked. Once this function is returned, we make
329 * sure no dispatch can happen until the queue is unquiesced via
330 * blk_mq_unquiesce_queue().
331 */
blk_mq_quiesce_queue(struct request_queue * q)332 void blk_mq_quiesce_queue(struct request_queue *q)
333 {
334 blk_mq_quiesce_queue_nowait(q);
335 /* nothing to wait for non-mq queues */
336 if (queue_is_mq(q))
337 blk_mq_wait_quiesce_done(q->tag_set);
338 }
339 EXPORT_SYMBOL_GPL(blk_mq_quiesce_queue);
340
341 /*
342 * blk_mq_unquiesce_queue() - counterpart of blk_mq_quiesce_queue()
343 * @q: request queue.
344 *
345 * This function recovers queue into the state before quiescing
346 * which is done by blk_mq_quiesce_queue.
347 */
blk_mq_unquiesce_queue(struct request_queue * q)348 void blk_mq_unquiesce_queue(struct request_queue *q)
349 {
350 unsigned long flags;
351 bool run_queue = false;
352
353 spin_lock_irqsave(&q->queue_lock, flags);
354 if (WARN_ON_ONCE(q->quiesce_depth <= 0)) {
355 ;
356 } else if (!--q->quiesce_depth) {
357 blk_queue_flag_clear(QUEUE_FLAG_QUIESCED, q);
358 run_queue = true;
359 }
360 spin_unlock_irqrestore(&q->queue_lock, flags);
361
362 /* dispatch requests which are inserted during quiescing */
363 if (run_queue)
364 blk_mq_run_hw_queues(q, true);
365 }
366 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_queue);
367
blk_mq_quiesce_tagset(struct blk_mq_tag_set * set)368 void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
369 {
370 struct request_queue *q;
371
372 mutex_lock(&set->tag_list_lock);
373 list_for_each_entry(q, &set->tag_list, tag_set_list) {
374 if (!blk_queue_skip_tagset_quiesce(q))
375 blk_mq_quiesce_queue_nowait(q);
376 }
377 mutex_unlock(&set->tag_list_lock);
378
379 blk_mq_wait_quiesce_done(set);
380 }
381 EXPORT_SYMBOL_GPL(blk_mq_quiesce_tagset);
382
blk_mq_unquiesce_tagset(struct blk_mq_tag_set * set)383 void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
384 {
385 struct request_queue *q;
386
387 mutex_lock(&set->tag_list_lock);
388 list_for_each_entry(q, &set->tag_list, tag_set_list) {
389 if (!blk_queue_skip_tagset_quiesce(q))
390 blk_mq_unquiesce_queue(q);
391 }
392 mutex_unlock(&set->tag_list_lock);
393 }
394 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
395
blk_mq_wake_waiters(struct request_queue * q)396 void blk_mq_wake_waiters(struct request_queue *q)
397 {
398 struct blk_mq_hw_ctx *hctx;
399 unsigned long i;
400
401 queue_for_each_hw_ctx(q, hctx, i)
402 if (blk_mq_hw_queue_mapped(hctx))
403 blk_mq_tag_wakeup_all(hctx->tags, true);
404 }
405
blk_rq_init(struct request_queue * q,struct request * rq)406 void blk_rq_init(struct request_queue *q, struct request *rq)
407 {
408 memset(rq, 0, sizeof(*rq));
409
410 INIT_LIST_HEAD(&rq->queuelist);
411 rq->q = q;
412 rq->__sector = (sector_t) -1;
413 INIT_HLIST_NODE(&rq->hash);
414 RB_CLEAR_NODE(&rq->rb_node);
415 rq->tag = BLK_MQ_NO_TAG;
416 rq->internal_tag = BLK_MQ_NO_TAG;
417 rq->start_time_ns = blk_time_get_ns();
418 rq->part = NULL;
419 blk_crypto_rq_set_defaults(rq);
420 }
421 EXPORT_SYMBOL(blk_rq_init);
422
423 /* Set start and alloc time when the allocated request is actually used */
blk_mq_rq_time_init(struct request * rq,u64 alloc_time_ns)424 static inline void blk_mq_rq_time_init(struct request *rq, u64 alloc_time_ns)
425 {
426 if (blk_mq_need_time_stamp(rq))
427 rq->start_time_ns = blk_time_get_ns();
428 else
429 rq->start_time_ns = 0;
430
431 #ifdef CONFIG_BLK_RQ_ALLOC_TIME
432 if (blk_queue_rq_alloc_time(rq->q))
433 rq->alloc_time_ns = alloc_time_ns ?: rq->start_time_ns;
434 else
435 rq->alloc_time_ns = 0;
436 #endif
437 }
438
blk_mq_rq_ctx_init(struct blk_mq_alloc_data * data,struct blk_mq_tags * tags,unsigned int tag)439 static struct request *blk_mq_rq_ctx_init(struct blk_mq_alloc_data *data,
440 struct blk_mq_tags *tags, unsigned int tag)
441 {
442 struct blk_mq_ctx *ctx = data->ctx;
443 struct blk_mq_hw_ctx *hctx = data->hctx;
444 struct request_queue *q = data->q;
445 struct request *rq = tags->static_rqs[tag];
446
447 rq->q = q;
448 rq->mq_ctx = ctx;
449 rq->mq_hctx = hctx;
450 rq->cmd_flags = data->cmd_flags;
451
452 if (data->flags & BLK_MQ_REQ_PM)
453 data->rq_flags |= RQF_PM;
454 if (blk_queue_io_stat(q))
455 data->rq_flags |= RQF_IO_STAT;
456 rq->rq_flags = data->rq_flags;
457
458 if (data->rq_flags & RQF_SCHED_TAGS) {
459 rq->tag = BLK_MQ_NO_TAG;
460 rq->internal_tag = tag;
461 } else {
462 rq->tag = tag;
463 rq->internal_tag = BLK_MQ_NO_TAG;
464 }
465 rq->timeout = 0;
466
467 rq->part = NULL;
468 rq->io_start_time_ns = 0;
469 rq->stats_sectors = 0;
470 rq->nr_phys_segments = 0;
471 rq->nr_integrity_segments = 0;
472 rq->end_io = NULL;
473 rq->end_io_data = NULL;
474
475 blk_crypto_rq_set_defaults(rq);
476 INIT_LIST_HEAD(&rq->queuelist);
477 /* tag was already set */
478 WRITE_ONCE(rq->deadline, 0);
479 req_ref_set(rq, 1);
480
481 if (rq->rq_flags & RQF_USE_SCHED) {
482 struct elevator_queue *e = data->q->elevator;
483
484 INIT_HLIST_NODE(&rq->hash);
485 RB_CLEAR_NODE(&rq->rb_node);
486
487 if (e->type->ops.prepare_request)
488 e->type->ops.prepare_request(rq);
489 }
490
491 return rq;
492 }
493
494 static inline struct request *
__blk_mq_alloc_requests_batch(struct blk_mq_alloc_data * data)495 __blk_mq_alloc_requests_batch(struct blk_mq_alloc_data *data)
496 {
497 unsigned int tag, tag_offset;
498 struct blk_mq_tags *tags;
499 struct request *rq;
500 unsigned long tag_mask;
501 int i, nr = 0;
502
503 tag_mask = blk_mq_get_tags(data, data->nr_tags, &tag_offset);
504 if (unlikely(!tag_mask))
505 return NULL;
506
507 tags = blk_mq_tags_from_data(data);
508 for (i = 0; tag_mask; i++) {
509 if (!(tag_mask & (1UL << i)))
510 continue;
511 tag = tag_offset + i;
512 prefetch(tags->static_rqs[tag]);
513 tag_mask &= ~(1UL << i);
514 rq = blk_mq_rq_ctx_init(data, tags, tag);
515 rq_list_add_head(data->cached_rqs, rq);
516 nr++;
517 }
518 if (!(data->rq_flags & RQF_SCHED_TAGS))
519 blk_mq_add_active_requests(data->hctx, nr);
520 /* caller already holds a reference, add for remainder */
521 percpu_ref_get_many(&data->q->q_usage_counter, nr - 1);
522 data->nr_tags -= nr;
523
524 return rq_list_pop(data->cached_rqs);
525 }
526
__blk_mq_alloc_requests(struct blk_mq_alloc_data * data)527 static struct request *__blk_mq_alloc_requests(struct blk_mq_alloc_data *data)
528 {
529 struct request_queue *q = data->q;
530 u64 alloc_time_ns = 0;
531 struct request *rq;
532 unsigned int tag;
533
534 /* alloc_time includes depth and tag waits */
535 if (blk_queue_rq_alloc_time(q))
536 alloc_time_ns = blk_time_get_ns();
537
538 if (data->cmd_flags & REQ_NOWAIT)
539 data->flags |= BLK_MQ_REQ_NOWAIT;
540
541 retry:
542 data->ctx = blk_mq_get_ctx(q);
543 data->hctx = blk_mq_map_queue(q, data->cmd_flags, data->ctx);
544
545 if (q->elevator) {
546 /*
547 * All requests use scheduler tags when an I/O scheduler is
548 * enabled for the queue.
549 */
550 data->rq_flags |= RQF_SCHED_TAGS;
551
552 /*
553 * Flush/passthrough requests are special and go directly to the
554 * dispatch list.
555 */
556 if ((data->cmd_flags & REQ_OP_MASK) != REQ_OP_FLUSH &&
557 !blk_op_is_passthrough(data->cmd_flags)) {
558 struct elevator_mq_ops *ops = &q->elevator->type->ops;
559
560 WARN_ON_ONCE(data->flags & BLK_MQ_REQ_RESERVED);
561
562 data->rq_flags |= RQF_USE_SCHED;
563 if (ops->limit_depth)
564 ops->limit_depth(data->cmd_flags, data);
565 }
566 } else {
567 blk_mq_tag_busy(data->hctx);
568 }
569
570 if (data->flags & BLK_MQ_REQ_RESERVED)
571 data->rq_flags |= RQF_RESV;
572
573 /*
574 * Try batched alloc if we want more than 1 tag.
575 */
576 if (data->nr_tags > 1) {
577 rq = __blk_mq_alloc_requests_batch(data);
578 if (rq) {
579 blk_mq_rq_time_init(rq, alloc_time_ns);
580 return rq;
581 }
582 data->nr_tags = 1;
583 }
584
585 /*
586 * Waiting allocations only fail because of an inactive hctx. In that
587 * case just retry the hctx assignment and tag allocation as CPU hotplug
588 * should have migrated us to an online CPU by now.
589 */
590 tag = blk_mq_get_tag(data);
591 if (tag == BLK_MQ_NO_TAG) {
592 if (data->flags & BLK_MQ_REQ_NOWAIT)
593 return NULL;
594 /*
595 * Give up the CPU and sleep for a random short time to
596 * ensure that thread using a realtime scheduling class
597 * are migrated off the CPU, and thus off the hctx that
598 * is going away.
599 */
600 msleep(3);
601 goto retry;
602 }
603
604 if (!(data->rq_flags & RQF_SCHED_TAGS))
605 blk_mq_inc_active_requests(data->hctx);
606 rq = blk_mq_rq_ctx_init(data, blk_mq_tags_from_data(data), tag);
607 blk_mq_rq_time_init(rq, alloc_time_ns);
608 return rq;
609 }
610
blk_mq_rq_cache_fill(struct request_queue * q,struct blk_plug * plug,blk_opf_t opf,blk_mq_req_flags_t flags)611 static struct request *blk_mq_rq_cache_fill(struct request_queue *q,
612 struct blk_plug *plug,
613 blk_opf_t opf,
614 blk_mq_req_flags_t flags)
615 {
616 struct blk_mq_alloc_data data = {
617 .q = q,
618 .flags = flags,
619 .cmd_flags = opf,
620 .nr_tags = plug->nr_ios,
621 .cached_rqs = &plug->cached_rqs,
622 };
623 struct request *rq;
624
625 if (blk_queue_enter(q, flags))
626 return NULL;
627
628 plug->nr_ios = 1;
629
630 rq = __blk_mq_alloc_requests(&data);
631 if (unlikely(!rq))
632 blk_queue_exit(q);
633 return rq;
634 }
635
blk_mq_alloc_cached_request(struct request_queue * q,blk_opf_t opf,blk_mq_req_flags_t flags)636 static struct request *blk_mq_alloc_cached_request(struct request_queue *q,
637 blk_opf_t opf,
638 blk_mq_req_flags_t flags)
639 {
640 struct blk_plug *plug = current->plug;
641 struct request *rq;
642
643 if (!plug)
644 return NULL;
645
646 if (rq_list_empty(&plug->cached_rqs)) {
647 if (plug->nr_ios == 1)
648 return NULL;
649 rq = blk_mq_rq_cache_fill(q, plug, opf, flags);
650 if (!rq)
651 return NULL;
652 } else {
653 rq = rq_list_peek(&plug->cached_rqs);
654 if (!rq || rq->q != q)
655 return NULL;
656
657 if (blk_mq_get_hctx_type(opf) != rq->mq_hctx->type)
658 return NULL;
659 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
660 return NULL;
661
662 rq_list_pop(&plug->cached_rqs);
663 blk_mq_rq_time_init(rq, 0);
664 }
665
666 rq->cmd_flags = opf;
667 INIT_LIST_HEAD(&rq->queuelist);
668 return rq;
669 }
670
blk_mq_alloc_request(struct request_queue * q,blk_opf_t opf,blk_mq_req_flags_t flags)671 struct request *blk_mq_alloc_request(struct request_queue *q, blk_opf_t opf,
672 blk_mq_req_flags_t flags)
673 {
674 struct request *rq;
675
676 rq = blk_mq_alloc_cached_request(q, opf, flags);
677 if (!rq) {
678 struct blk_mq_alloc_data data = {
679 .q = q,
680 .flags = flags,
681 .cmd_flags = opf,
682 .nr_tags = 1,
683 };
684 int ret;
685
686 ret = blk_queue_enter(q, flags);
687 if (ret)
688 return ERR_PTR(ret);
689
690 rq = __blk_mq_alloc_requests(&data);
691 if (!rq)
692 goto out_queue_exit;
693 }
694 rq->__data_len = 0;
695 rq->__sector = (sector_t) -1;
696 rq->bio = rq->biotail = NULL;
697 return rq;
698 out_queue_exit:
699 blk_queue_exit(q);
700 return ERR_PTR(-EWOULDBLOCK);
701 }
702 EXPORT_SYMBOL(blk_mq_alloc_request);
703
blk_mq_alloc_request_hctx(struct request_queue * q,blk_opf_t opf,blk_mq_req_flags_t flags,unsigned int hctx_idx)704 struct request *blk_mq_alloc_request_hctx(struct request_queue *q,
705 blk_opf_t opf, blk_mq_req_flags_t flags, unsigned int hctx_idx)
706 {
707 struct blk_mq_alloc_data data = {
708 .q = q,
709 .flags = flags,
710 .cmd_flags = opf,
711 .nr_tags = 1,
712 };
713 u64 alloc_time_ns = 0;
714 struct request *rq;
715 unsigned int cpu;
716 unsigned int tag;
717 int ret;
718
719 /* alloc_time includes depth and tag waits */
720 if (blk_queue_rq_alloc_time(q))
721 alloc_time_ns = blk_time_get_ns();
722
723 /*
724 * If the tag allocator sleeps we could get an allocation for a
725 * different hardware context. No need to complicate the low level
726 * allocator for this for the rare use case of a command tied to
727 * a specific queue.
728 */
729 if (WARN_ON_ONCE(!(flags & BLK_MQ_REQ_NOWAIT)) ||
730 WARN_ON_ONCE(!(flags & BLK_MQ_REQ_RESERVED)))
731 return ERR_PTR(-EINVAL);
732
733 if (hctx_idx >= q->nr_hw_queues)
734 return ERR_PTR(-EIO);
735
736 ret = blk_queue_enter(q, flags);
737 if (ret)
738 return ERR_PTR(ret);
739
740 /*
741 * Check if the hardware context is actually mapped to anything.
742 * If not tell the caller that it should skip this queue.
743 */
744 ret = -EXDEV;
745 data.hctx = xa_load(&q->hctx_table, hctx_idx);
746 if (!blk_mq_hw_queue_mapped(data.hctx))
747 goto out_queue_exit;
748 cpu = cpumask_first_and(data.hctx->cpumask, cpu_online_mask);
749 if (cpu >= nr_cpu_ids)
750 goto out_queue_exit;
751 data.ctx = __blk_mq_get_ctx(q, cpu);
752
753 if (q->elevator)
754 data.rq_flags |= RQF_SCHED_TAGS;
755 else
756 blk_mq_tag_busy(data.hctx);
757
758 if (flags & BLK_MQ_REQ_RESERVED)
759 data.rq_flags |= RQF_RESV;
760
761 ret = -EWOULDBLOCK;
762 tag = blk_mq_get_tag(&data);
763 if (tag == BLK_MQ_NO_TAG)
764 goto out_queue_exit;
765 if (!(data.rq_flags & RQF_SCHED_TAGS))
766 blk_mq_inc_active_requests(data.hctx);
767 rq = blk_mq_rq_ctx_init(&data, blk_mq_tags_from_data(&data), tag);
768 blk_mq_rq_time_init(rq, alloc_time_ns);
769 rq->__data_len = 0;
770 rq->__sector = (sector_t) -1;
771 rq->bio = rq->biotail = NULL;
772 return rq;
773
774 out_queue_exit:
775 blk_queue_exit(q);
776 return ERR_PTR(ret);
777 }
778 EXPORT_SYMBOL_GPL(blk_mq_alloc_request_hctx);
779
blk_mq_finish_request(struct request * rq)780 static void blk_mq_finish_request(struct request *rq)
781 {
782 struct request_queue *q = rq->q;
783
784 blk_zone_finish_request(rq);
785
786 if (rq->rq_flags & RQF_USE_SCHED) {
787 q->elevator->type->ops.finish_request(rq);
788 /*
789 * For postflush request that may need to be
790 * completed twice, we should clear this flag
791 * to avoid double finish_request() on the rq.
792 */
793 rq->rq_flags &= ~RQF_USE_SCHED;
794 }
795 }
796
__blk_mq_free_request(struct request * rq)797 static void __blk_mq_free_request(struct request *rq)
798 {
799 struct request_queue *q = rq->q;
800 struct blk_mq_ctx *ctx = rq->mq_ctx;
801 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
802 const int sched_tag = rq->internal_tag;
803
804 blk_crypto_free_request(rq);
805 blk_pm_mark_last_busy(rq);
806 rq->mq_hctx = NULL;
807
808 if (rq->tag != BLK_MQ_NO_TAG) {
809 blk_mq_dec_active_requests(hctx);
810 blk_mq_put_tag(hctx->tags, ctx, rq->tag);
811 }
812 if (sched_tag != BLK_MQ_NO_TAG)
813 blk_mq_put_tag(hctx->sched_tags, ctx, sched_tag);
814 blk_mq_sched_restart(hctx);
815 blk_queue_exit(q);
816 }
817
blk_mq_free_request(struct request * rq)818 void blk_mq_free_request(struct request *rq)
819 {
820 struct request_queue *q = rq->q;
821
822 blk_mq_finish_request(rq);
823
824 if (unlikely(laptop_mode && !blk_rq_is_passthrough(rq)))
825 laptop_io_completion(q->disk->bdi);
826
827 rq_qos_done(q, rq);
828
829 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
830 if (req_ref_put_and_test(rq))
831 __blk_mq_free_request(rq);
832 }
833 EXPORT_SYMBOL_GPL(blk_mq_free_request);
834
blk_mq_free_plug_rqs(struct blk_plug * plug)835 void blk_mq_free_plug_rqs(struct blk_plug *plug)
836 {
837 struct request *rq;
838
839 while ((rq = rq_list_pop(&plug->cached_rqs)) != NULL)
840 blk_mq_free_request(rq);
841 }
842
blk_dump_rq_flags(struct request * rq,char * msg)843 void blk_dump_rq_flags(struct request *rq, char *msg)
844 {
845 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
846 rq->q->disk ? rq->q->disk->disk_name : "?",
847 (__force unsigned long long) rq->cmd_flags);
848
849 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
850 (unsigned long long)blk_rq_pos(rq),
851 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
852 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
853 rq->bio, rq->biotail, blk_rq_bytes(rq));
854 }
855 EXPORT_SYMBOL(blk_dump_rq_flags);
856
blk_account_io_completion(struct request * req,unsigned int bytes)857 static void blk_account_io_completion(struct request *req, unsigned int bytes)
858 {
859 if (req->part && blk_do_io_stat(req)) {
860 const int sgrp = op_stat_group(req_op(req));
861
862 part_stat_lock();
863 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
864 part_stat_unlock();
865 }
866 }
867
blk_print_req_error(struct request * req,blk_status_t status)868 static void blk_print_req_error(struct request *req, blk_status_t status)
869 {
870 printk_ratelimited(KERN_ERR
871 "%s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
872 "phys_seg %u prio class %u\n",
873 blk_status_to_str(status),
874 req->q->disk ? req->q->disk->disk_name : "?",
875 blk_rq_pos(req), (__force u32)req_op(req),
876 blk_op_str(req_op(req)),
877 (__force u32)(req->cmd_flags & ~REQ_OP_MASK),
878 req->nr_phys_segments,
879 IOPRIO_PRIO_CLASS(req->ioprio));
880 }
881
882 /*
883 * Fully end IO on a request. Does not support partial completions, or
884 * errors.
885 */
blk_complete_request(struct request * req)886 static void blk_complete_request(struct request *req)
887 {
888 const bool is_flush = (req->rq_flags & RQF_FLUSH_SEQ) != 0;
889 int total_bytes = blk_rq_bytes(req);
890 struct bio *bio = req->bio;
891
892 trace_block_rq_complete(req, BLK_STS_OK, total_bytes);
893
894 if (!bio)
895 return;
896
897 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ)
898 blk_integrity_complete(req, total_bytes);
899
900 /*
901 * Upper layers may call blk_crypto_evict_key() anytime after the last
902 * bio_endio(). Therefore, the keyslot must be released before that.
903 */
904 blk_crypto_rq_put_keyslot(req);
905
906 blk_account_io_completion(req, total_bytes);
907
908 do {
909 struct bio *next = bio->bi_next;
910
911 /* Completion has already been traced */
912 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
913
914 if (blk_req_bio_is_zone_append(req, bio))
915 blk_zone_append_update_request_bio(req, bio);
916
917 if (!is_flush)
918 bio_endio(bio);
919 bio = next;
920 } while (bio);
921
922 /*
923 * Reset counters so that the request stacking driver
924 * can find how many bytes remain in the request
925 * later.
926 */
927 if (!req->end_io) {
928 req->bio = NULL;
929 req->__data_len = 0;
930 }
931 }
932
933 /**
934 * blk_update_request - Complete multiple bytes without completing the request
935 * @req: the request being processed
936 * @error: block status code
937 * @nr_bytes: number of bytes to complete for @req
938 *
939 * Description:
940 * Ends I/O on a number of bytes attached to @req, but doesn't complete
941 * the request structure even if @req doesn't have leftover.
942 * If @req has leftover, sets it up for the next range of segments.
943 *
944 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
945 * %false return from this function.
946 *
947 * Note:
948 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
949 * except in the consistency check at the end of this function.
950 *
951 * Return:
952 * %false - this request doesn't have any more data
953 * %true - this request has more data
954 **/
blk_update_request(struct request * req,blk_status_t error,unsigned int nr_bytes)955 bool blk_update_request(struct request *req, blk_status_t error,
956 unsigned int nr_bytes)
957 {
958 bool is_flush = req->rq_flags & RQF_FLUSH_SEQ;
959 bool quiet = req->rq_flags & RQF_QUIET;
960 int total_bytes;
961
962 trace_block_rq_complete(req, error, nr_bytes);
963
964 if (!req->bio)
965 return false;
966
967 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
968 error == BLK_STS_OK)
969 blk_integrity_complete(req, nr_bytes);
970
971 /*
972 * Upper layers may call blk_crypto_evict_key() anytime after the last
973 * bio_endio(). Therefore, the keyslot must be released before that.
974 */
975 if (blk_crypto_rq_has_keyslot(req) && nr_bytes >= blk_rq_bytes(req))
976 __blk_crypto_rq_put_keyslot(req);
977
978 if (unlikely(error && !blk_rq_is_passthrough(req) && !quiet) &&
979 !test_bit(GD_DEAD, &req->q->disk->state)) {
980 blk_print_req_error(req, error);
981 trace_block_rq_error(req, error, nr_bytes);
982 }
983
984 blk_account_io_completion(req, nr_bytes);
985
986 total_bytes = 0;
987 while (req->bio) {
988 struct bio *bio = req->bio;
989 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
990
991 if (unlikely(error))
992 bio->bi_status = error;
993
994 if (bio_bytes == bio->bi_iter.bi_size) {
995 req->bio = bio->bi_next;
996 } else if (bio_is_zone_append(bio) && error == BLK_STS_OK) {
997 /*
998 * Partial zone append completions cannot be supported
999 * as the BIO fragments may end up not being written
1000 * sequentially.
1001 */
1002 bio->bi_status = BLK_STS_IOERR;
1003 }
1004
1005 /* Completion has already been traced */
1006 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
1007 if (unlikely(quiet))
1008 bio_set_flag(bio, BIO_QUIET);
1009
1010 bio_advance(bio, bio_bytes);
1011
1012 /* Don't actually finish bio if it's part of flush sequence */
1013 if (!bio->bi_iter.bi_size) {
1014 if (blk_req_bio_is_zone_append(req, bio))
1015 blk_zone_append_update_request_bio(req, bio);
1016 if (!is_flush)
1017 bio_endio(bio);
1018 }
1019
1020 total_bytes += bio_bytes;
1021 nr_bytes -= bio_bytes;
1022
1023 if (!nr_bytes)
1024 break;
1025 }
1026
1027 /*
1028 * completely done
1029 */
1030 if (!req->bio) {
1031 /*
1032 * Reset counters so that the request stacking driver
1033 * can find how many bytes remain in the request
1034 * later.
1035 */
1036 req->__data_len = 0;
1037 return false;
1038 }
1039
1040 req->__data_len -= total_bytes;
1041
1042 /* update sector only for requests with clear definition of sector */
1043 if (!blk_rq_is_passthrough(req))
1044 req->__sector += total_bytes >> 9;
1045
1046 /* mixed attributes always follow the first bio */
1047 if (req->rq_flags & RQF_MIXED_MERGE) {
1048 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1049 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1050 }
1051
1052 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1053 /*
1054 * If total number of sectors is less than the first segment
1055 * size, something has gone terribly wrong.
1056 */
1057 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1058 blk_dump_rq_flags(req, "request botched");
1059 req->__data_len = blk_rq_cur_bytes(req);
1060 }
1061
1062 /* recalculate the number of segments */
1063 req->nr_phys_segments = blk_recalc_rq_segments(req);
1064 }
1065
1066 return true;
1067 }
1068 EXPORT_SYMBOL_GPL(blk_update_request);
1069
blk_account_io_done(struct request * req,u64 now)1070 static inline void blk_account_io_done(struct request *req, u64 now)
1071 {
1072 trace_block_io_done(req);
1073
1074 /*
1075 * Account IO completion. flush_rq isn't accounted as a
1076 * normal IO on queueing nor completion. Accounting the
1077 * containing request is enough.
1078 */
1079 if (blk_do_io_stat(req) && req->part &&
1080 !(req->rq_flags & RQF_FLUSH_SEQ)) {
1081 const int sgrp = op_stat_group(req_op(req));
1082
1083 part_stat_lock();
1084 update_io_ticks(req->part, jiffies, true);
1085 part_stat_inc(req->part, ios[sgrp]);
1086 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1087 part_stat_local_dec(req->part,
1088 in_flight[op_is_write(req_op(req))]);
1089 part_stat_unlock();
1090 }
1091 }
1092
blk_account_io_start(struct request * req)1093 static inline void blk_account_io_start(struct request *req)
1094 {
1095 trace_block_io_start(req);
1096
1097 if (blk_do_io_stat(req)) {
1098 /*
1099 * All non-passthrough requests are created from a bio with one
1100 * exception: when a flush command that is part of a flush sequence
1101 * generated by the state machine in blk-flush.c is cloned onto the
1102 * lower device by dm-multipath we can get here without a bio.
1103 */
1104 if (req->bio)
1105 req->part = req->bio->bi_bdev;
1106 else
1107 req->part = req->q->disk->part0;
1108
1109 part_stat_lock();
1110 update_io_ticks(req->part, jiffies, false);
1111 part_stat_local_inc(req->part,
1112 in_flight[op_is_write(req_op(req))]);
1113 part_stat_unlock();
1114 }
1115 }
1116
__blk_mq_end_request_acct(struct request * rq,u64 now)1117 static inline void __blk_mq_end_request_acct(struct request *rq, u64 now)
1118 {
1119 if (rq->rq_flags & RQF_STATS)
1120 blk_stat_add(rq, now);
1121
1122 blk_mq_sched_completed_request(rq, now);
1123 blk_account_io_done(rq, now);
1124 }
1125
__blk_mq_end_request(struct request * rq,blk_status_t error)1126 inline void __blk_mq_end_request(struct request *rq, blk_status_t error)
1127 {
1128 if (blk_mq_need_time_stamp(rq))
1129 __blk_mq_end_request_acct(rq, blk_time_get_ns());
1130
1131 blk_mq_finish_request(rq);
1132
1133 if (rq->end_io) {
1134 rq_qos_done(rq->q, rq);
1135 if (rq->end_io(rq, error) == RQ_END_IO_FREE)
1136 blk_mq_free_request(rq);
1137 } else {
1138 blk_mq_free_request(rq);
1139 }
1140 }
1141 EXPORT_SYMBOL(__blk_mq_end_request);
1142
blk_mq_end_request(struct request * rq,blk_status_t error)1143 void blk_mq_end_request(struct request *rq, blk_status_t error)
1144 {
1145 if (blk_update_request(rq, error, blk_rq_bytes(rq)))
1146 BUG();
1147 __blk_mq_end_request(rq, error);
1148 }
1149 EXPORT_SYMBOL(blk_mq_end_request);
1150
1151 #define TAG_COMP_BATCH 32
1152
blk_mq_flush_tag_batch(struct blk_mq_hw_ctx * hctx,int * tag_array,int nr_tags)1153 static inline void blk_mq_flush_tag_batch(struct blk_mq_hw_ctx *hctx,
1154 int *tag_array, int nr_tags)
1155 {
1156 struct request_queue *q = hctx->queue;
1157
1158 blk_mq_sub_active_requests(hctx, nr_tags);
1159
1160 blk_mq_put_tags(hctx->tags, tag_array, nr_tags);
1161 percpu_ref_put_many(&q->q_usage_counter, nr_tags);
1162 }
1163
blk_mq_end_request_batch(struct io_comp_batch * iob)1164 void blk_mq_end_request_batch(struct io_comp_batch *iob)
1165 {
1166 int tags[TAG_COMP_BATCH], nr_tags = 0;
1167 struct blk_mq_hw_ctx *cur_hctx = NULL;
1168 struct request *rq;
1169 u64 now = 0;
1170
1171 if (iob->need_ts)
1172 now = blk_time_get_ns();
1173
1174 while ((rq = rq_list_pop(&iob->req_list)) != NULL) {
1175 prefetch(rq->bio);
1176 prefetch(rq->rq_next);
1177
1178 blk_complete_request(rq);
1179 if (iob->need_ts)
1180 __blk_mq_end_request_acct(rq, now);
1181
1182 blk_mq_finish_request(rq);
1183
1184 rq_qos_done(rq->q, rq);
1185
1186 /*
1187 * If end_io handler returns NONE, then it still has
1188 * ownership of the request.
1189 */
1190 if (rq->end_io && rq->end_io(rq, 0) == RQ_END_IO_NONE)
1191 continue;
1192
1193 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1194 if (!req_ref_put_and_test(rq))
1195 continue;
1196
1197 blk_crypto_free_request(rq);
1198 blk_pm_mark_last_busy(rq);
1199
1200 if (nr_tags == TAG_COMP_BATCH || cur_hctx != rq->mq_hctx) {
1201 if (cur_hctx)
1202 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1203 nr_tags = 0;
1204 cur_hctx = rq->mq_hctx;
1205 }
1206 tags[nr_tags++] = rq->tag;
1207 }
1208
1209 if (nr_tags)
1210 blk_mq_flush_tag_batch(cur_hctx, tags, nr_tags);
1211 }
1212 EXPORT_SYMBOL_GPL(blk_mq_end_request_batch);
1213
blk_complete_reqs(struct llist_head * list)1214 static void blk_complete_reqs(struct llist_head *list)
1215 {
1216 struct llist_node *entry = llist_reverse_order(llist_del_all(list));
1217 struct request *rq, *next;
1218
1219 llist_for_each_entry_safe(rq, next, entry, ipi_list)
1220 rq->q->mq_ops->complete(rq);
1221 }
1222
blk_done_softirq(void)1223 static __latent_entropy void blk_done_softirq(void)
1224 {
1225 blk_complete_reqs(this_cpu_ptr(&blk_cpu_done));
1226 }
1227
blk_softirq_cpu_dead(unsigned int cpu)1228 static int blk_softirq_cpu_dead(unsigned int cpu)
1229 {
1230 blk_complete_reqs(&per_cpu(blk_cpu_done, cpu));
1231 return 0;
1232 }
1233
__blk_mq_complete_request_remote(void * data)1234 static void __blk_mq_complete_request_remote(void *data)
1235 {
1236 __raise_softirq_irqoff(BLOCK_SOFTIRQ);
1237 }
1238
blk_mq_complete_need_ipi(struct request * rq)1239 static inline bool blk_mq_complete_need_ipi(struct request *rq)
1240 {
1241 int cpu = raw_smp_processor_id();
1242
1243 if (!IS_ENABLED(CONFIG_SMP) ||
1244 !test_bit(QUEUE_FLAG_SAME_COMP, &rq->q->queue_flags))
1245 return false;
1246 /*
1247 * With force threaded interrupts enabled, raising softirq from an SMP
1248 * function call will always result in waking the ksoftirqd thread.
1249 * This is probably worse than completing the request on a different
1250 * cache domain.
1251 */
1252 if (force_irqthreads())
1253 return false;
1254
1255 /* same CPU or cache domain and capacity? Complete locally */
1256 if (cpu == rq->mq_ctx->cpu ||
1257 (!test_bit(QUEUE_FLAG_SAME_FORCE, &rq->q->queue_flags) &&
1258 cpus_share_cache(cpu, rq->mq_ctx->cpu) &&
1259 cpus_equal_capacity(cpu, rq->mq_ctx->cpu)))
1260 return false;
1261
1262 /* don't try to IPI to an offline CPU */
1263 return cpu_online(rq->mq_ctx->cpu);
1264 }
1265
blk_mq_complete_send_ipi(struct request * rq)1266 static void blk_mq_complete_send_ipi(struct request *rq)
1267 {
1268 unsigned int cpu;
1269
1270 cpu = rq->mq_ctx->cpu;
1271 if (llist_add(&rq->ipi_list, &per_cpu(blk_cpu_done, cpu)))
1272 smp_call_function_single_async(cpu, &per_cpu(blk_cpu_csd, cpu));
1273 }
1274
blk_mq_raise_softirq(struct request * rq)1275 static void blk_mq_raise_softirq(struct request *rq)
1276 {
1277 struct llist_head *list;
1278
1279 preempt_disable();
1280 list = this_cpu_ptr(&blk_cpu_done);
1281 if (llist_add(&rq->ipi_list, list))
1282 raise_softirq(BLOCK_SOFTIRQ);
1283 preempt_enable();
1284 }
1285
blk_mq_complete_request_remote(struct request * rq)1286 bool blk_mq_complete_request_remote(struct request *rq)
1287 {
1288 WRITE_ONCE(rq->state, MQ_RQ_COMPLETE);
1289
1290 /*
1291 * For request which hctx has only one ctx mapping,
1292 * or a polled request, always complete locally,
1293 * it's pointless to redirect the completion.
1294 */
1295 if ((rq->mq_hctx->nr_ctx == 1 &&
1296 rq->mq_ctx->cpu == raw_smp_processor_id()) ||
1297 rq->cmd_flags & REQ_POLLED)
1298 return false;
1299
1300 if (blk_mq_complete_need_ipi(rq)) {
1301 blk_mq_complete_send_ipi(rq);
1302 return true;
1303 }
1304
1305 if (rq->q->nr_hw_queues == 1) {
1306 blk_mq_raise_softirq(rq);
1307 return true;
1308 }
1309 return false;
1310 }
1311 EXPORT_SYMBOL_GPL(blk_mq_complete_request_remote);
1312
1313 /**
1314 * blk_mq_complete_request - end I/O on a request
1315 * @rq: the request being processed
1316 *
1317 * Description:
1318 * Complete a request by scheduling the ->complete_rq operation.
1319 **/
blk_mq_complete_request(struct request * rq)1320 void blk_mq_complete_request(struct request *rq)
1321 {
1322 if (!blk_mq_complete_request_remote(rq))
1323 rq->q->mq_ops->complete(rq);
1324 }
1325 EXPORT_SYMBOL(blk_mq_complete_request);
1326
1327 /**
1328 * blk_mq_start_request - Start processing a request
1329 * @rq: Pointer to request to be started
1330 *
1331 * Function used by device drivers to notify the block layer that a request
1332 * is going to be processed now, so blk layer can do proper initializations
1333 * such as starting the timeout timer.
1334 */
blk_mq_start_request(struct request * rq)1335 void blk_mq_start_request(struct request *rq)
1336 {
1337 struct request_queue *q = rq->q;
1338
1339 trace_block_rq_issue(rq);
1340
1341 if (test_bit(QUEUE_FLAG_STATS, &q->queue_flags) &&
1342 !blk_rq_is_passthrough(rq)) {
1343 rq->io_start_time_ns = blk_time_get_ns();
1344 rq->stats_sectors = blk_rq_sectors(rq);
1345 rq->rq_flags |= RQF_STATS;
1346 rq_qos_issue(q, rq);
1347 }
1348
1349 WARN_ON_ONCE(blk_mq_rq_state(rq) != MQ_RQ_IDLE);
1350
1351 blk_add_timer(rq);
1352 WRITE_ONCE(rq->state, MQ_RQ_IN_FLIGHT);
1353 rq->mq_hctx->tags->rqs[rq->tag] = rq;
1354
1355 if (blk_integrity_rq(rq) && req_op(rq) == REQ_OP_WRITE)
1356 blk_integrity_prepare(rq);
1357
1358 if (rq->bio && rq->bio->bi_opf & REQ_POLLED)
1359 WRITE_ONCE(rq->bio->bi_cookie, rq->mq_hctx->queue_num);
1360 }
1361 EXPORT_SYMBOL(blk_mq_start_request);
1362
1363 /*
1364 * Allow 2x BLK_MAX_REQUEST_COUNT requests on plug queue for multiple
1365 * queues. This is important for md arrays to benefit from merging
1366 * requests.
1367 */
blk_plug_max_rq_count(struct blk_plug * plug)1368 static inline unsigned short blk_plug_max_rq_count(struct blk_plug *plug)
1369 {
1370 if (plug->multiple_queues)
1371 return BLK_MAX_REQUEST_COUNT * 2;
1372 return BLK_MAX_REQUEST_COUNT;
1373 }
1374
blk_add_rq_to_plug(struct blk_plug * plug,struct request * rq)1375 static void blk_add_rq_to_plug(struct blk_plug *plug, struct request *rq)
1376 {
1377 struct request *last = rq_list_peek(&plug->mq_list);
1378
1379 if (!plug->rq_count) {
1380 trace_block_plug(rq->q);
1381 } else if (plug->rq_count >= blk_plug_max_rq_count(plug) ||
1382 (!blk_queue_nomerges(rq->q) &&
1383 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE)) {
1384 blk_mq_flush_plug_list(plug, false);
1385 last = NULL;
1386 trace_block_plug(rq->q);
1387 }
1388
1389 if (!plug->multiple_queues && last && last->q != rq->q)
1390 plug->multiple_queues = true;
1391 /*
1392 * Any request allocated from sched tags can't be issued to
1393 * ->queue_rqs() directly
1394 */
1395 if (!plug->has_elevator && (rq->rq_flags & RQF_SCHED_TAGS))
1396 plug->has_elevator = true;
1397 rq_list_add_tail(&plug->mq_list, rq);
1398 plug->rq_count++;
1399 }
1400
1401 /**
1402 * blk_execute_rq_nowait - insert a request to I/O scheduler for execution
1403 * @rq: request to insert
1404 * @at_head: insert request at head or tail of queue
1405 *
1406 * Description:
1407 * Insert a fully prepared request at the back of the I/O scheduler queue
1408 * for execution. Don't wait for completion.
1409 *
1410 * Note:
1411 * This function will invoke @done directly if the queue is dead.
1412 */
blk_execute_rq_nowait(struct request * rq,bool at_head)1413 void blk_execute_rq_nowait(struct request *rq, bool at_head)
1414 {
1415 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1416
1417 WARN_ON(irqs_disabled());
1418 WARN_ON(!blk_rq_is_passthrough(rq));
1419
1420 blk_account_io_start(rq);
1421
1422 if (current->plug && !at_head) {
1423 blk_add_rq_to_plug(current->plug, rq);
1424 return;
1425 }
1426
1427 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1428 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
1429 }
1430 EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
1431
1432 struct blk_rq_wait {
1433 struct completion done;
1434 blk_status_t ret;
1435 };
1436
blk_end_sync_rq(struct request * rq,blk_status_t ret)1437 static enum rq_end_io_ret blk_end_sync_rq(struct request *rq, blk_status_t ret)
1438 {
1439 struct blk_rq_wait *wait = rq->end_io_data;
1440
1441 wait->ret = ret;
1442 complete(&wait->done);
1443 return RQ_END_IO_NONE;
1444 }
1445
blk_rq_is_poll(struct request * rq)1446 bool blk_rq_is_poll(struct request *rq)
1447 {
1448 if (!rq->mq_hctx)
1449 return false;
1450 if (rq->mq_hctx->type != HCTX_TYPE_POLL)
1451 return false;
1452 return true;
1453 }
1454 EXPORT_SYMBOL_GPL(blk_rq_is_poll);
1455
blk_rq_poll_completion(struct request * rq,struct completion * wait)1456 static void blk_rq_poll_completion(struct request *rq, struct completion *wait)
1457 {
1458 do {
1459 blk_hctx_poll(rq->q, rq->mq_hctx, NULL, 0);
1460 cond_resched();
1461 } while (!completion_done(wait));
1462 }
1463
1464 /**
1465 * blk_execute_rq - insert a request into queue for execution
1466 * @rq: request to insert
1467 * @at_head: insert request at head or tail of queue
1468 *
1469 * Description:
1470 * Insert a fully prepared request at the back of the I/O scheduler queue
1471 * for execution and wait for completion.
1472 * Return: The blk_status_t result provided to blk_mq_end_request().
1473 */
blk_execute_rq(struct request * rq,bool at_head)1474 blk_status_t blk_execute_rq(struct request *rq, bool at_head)
1475 {
1476 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1477 struct blk_rq_wait wait = {
1478 .done = COMPLETION_INITIALIZER_ONSTACK(wait.done),
1479 };
1480
1481 WARN_ON(irqs_disabled());
1482 WARN_ON(!blk_rq_is_passthrough(rq));
1483
1484 rq->end_io_data = &wait;
1485 rq->end_io = blk_end_sync_rq;
1486
1487 blk_account_io_start(rq);
1488 blk_mq_insert_request(rq, at_head ? BLK_MQ_INSERT_AT_HEAD : 0);
1489 blk_mq_run_hw_queue(hctx, false);
1490
1491 if (blk_rq_is_poll(rq))
1492 blk_rq_poll_completion(rq, &wait.done);
1493 else
1494 blk_wait_io(&wait.done);
1495
1496 return wait.ret;
1497 }
1498 EXPORT_SYMBOL(blk_execute_rq);
1499
__blk_mq_requeue_request(struct request * rq)1500 static void __blk_mq_requeue_request(struct request *rq)
1501 {
1502 struct request_queue *q = rq->q;
1503
1504 blk_mq_put_driver_tag(rq);
1505
1506 trace_block_rq_requeue(rq);
1507 rq_qos_requeue(q, rq);
1508
1509 if (blk_mq_request_started(rq)) {
1510 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
1511 rq->rq_flags &= ~RQF_TIMED_OUT;
1512 }
1513 }
1514
blk_mq_requeue_request(struct request * rq,bool kick_requeue_list)1515 void blk_mq_requeue_request(struct request *rq, bool kick_requeue_list)
1516 {
1517 struct request_queue *q = rq->q;
1518 unsigned long flags;
1519
1520 __blk_mq_requeue_request(rq);
1521
1522 /* this request will be re-inserted to io scheduler queue */
1523 blk_mq_sched_requeue_request(rq);
1524
1525 spin_lock_irqsave(&q->requeue_lock, flags);
1526 list_add_tail(&rq->queuelist, &q->requeue_list);
1527 spin_unlock_irqrestore(&q->requeue_lock, flags);
1528
1529 if (kick_requeue_list)
1530 blk_mq_kick_requeue_list(q);
1531 }
1532 EXPORT_SYMBOL(blk_mq_requeue_request);
1533
blk_mq_requeue_work(struct work_struct * work)1534 static void blk_mq_requeue_work(struct work_struct *work)
1535 {
1536 struct request_queue *q =
1537 container_of(work, struct request_queue, requeue_work.work);
1538 LIST_HEAD(rq_list);
1539 LIST_HEAD(flush_list);
1540 struct request *rq;
1541
1542 spin_lock_irq(&q->requeue_lock);
1543 list_splice_init(&q->requeue_list, &rq_list);
1544 list_splice_init(&q->flush_list, &flush_list);
1545 spin_unlock_irq(&q->requeue_lock);
1546
1547 while (!list_empty(&rq_list)) {
1548 rq = list_entry(rq_list.next, struct request, queuelist);
1549 list_del_init(&rq->queuelist);
1550 /*
1551 * If RQF_DONTPREP is set, the request has been started by the
1552 * driver already and might have driver-specific data allocated
1553 * already. Insert it into the hctx dispatch list to avoid
1554 * block layer merges for the request.
1555 */
1556 if (rq->rq_flags & RQF_DONTPREP)
1557 blk_mq_request_bypass_insert(rq, 0);
1558 else
1559 blk_mq_insert_request(rq, BLK_MQ_INSERT_AT_HEAD);
1560 }
1561
1562 while (!list_empty(&flush_list)) {
1563 rq = list_entry(flush_list.next, struct request, queuelist);
1564 list_del_init(&rq->queuelist);
1565 blk_mq_insert_request(rq, 0);
1566 }
1567
1568 blk_mq_run_hw_queues(q, false);
1569 }
1570
blk_mq_kick_requeue_list(struct request_queue * q)1571 void blk_mq_kick_requeue_list(struct request_queue *q)
1572 {
1573 bool skip = false;
1574
1575 trace_android_vh_blk_mq_kick_requeue_list(q, 0, &skip);
1576 if (skip)
1577 return;
1578
1579 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work, 0);
1580 }
1581 EXPORT_SYMBOL(blk_mq_kick_requeue_list);
1582
blk_mq_delay_kick_requeue_list(struct request_queue * q,unsigned long msecs)1583 void blk_mq_delay_kick_requeue_list(struct request_queue *q,
1584 unsigned long msecs)
1585 {
1586 bool skip = false;
1587
1588 trace_android_vh_blk_mq_kick_requeue_list(q,
1589 msecs_to_jiffies(msecs), &skip);
1590 if (skip)
1591 return;
1592
1593 kblockd_mod_delayed_work_on(WORK_CPU_UNBOUND, &q->requeue_work,
1594 msecs_to_jiffies(msecs));
1595 }
1596 EXPORT_SYMBOL(blk_mq_delay_kick_requeue_list);
1597
blk_is_flush_data_rq(struct request * rq)1598 static bool blk_is_flush_data_rq(struct request *rq)
1599 {
1600 return (rq->rq_flags & RQF_FLUSH_SEQ) && !is_flush_rq(rq);
1601 }
1602
blk_mq_rq_inflight(struct request * rq,void * priv)1603 static bool blk_mq_rq_inflight(struct request *rq, void *priv)
1604 {
1605 /*
1606 * If we find a request that isn't idle we know the queue is busy
1607 * as it's checked in the iter.
1608 * Return false to stop the iteration.
1609 *
1610 * In case of queue quiesce, if one flush data request is completed,
1611 * don't count it as inflight given the flush sequence is suspended,
1612 * and the original flush data request is invisible to driver, just
1613 * like other pending requests because of quiesce
1614 */
1615 if (blk_mq_request_started(rq) && !(blk_queue_quiesced(rq->q) &&
1616 blk_is_flush_data_rq(rq) &&
1617 blk_mq_request_completed(rq))) {
1618 bool *busy = priv;
1619
1620 *busy = true;
1621 return false;
1622 }
1623
1624 return true;
1625 }
1626
blk_mq_queue_inflight(struct request_queue * q)1627 bool blk_mq_queue_inflight(struct request_queue *q)
1628 {
1629 bool busy = false;
1630
1631 blk_mq_queue_tag_busy_iter(q, blk_mq_rq_inflight, &busy);
1632 return busy;
1633 }
1634 EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
1635
blk_mq_rq_timed_out(struct request * req)1636 static void blk_mq_rq_timed_out(struct request *req)
1637 {
1638 req->rq_flags |= RQF_TIMED_OUT;
1639 if (req->q->mq_ops->timeout) {
1640 enum blk_eh_timer_return ret;
1641
1642 ret = req->q->mq_ops->timeout(req);
1643 if (ret == BLK_EH_DONE)
1644 return;
1645 WARN_ON_ONCE(ret != BLK_EH_RESET_TIMER);
1646 }
1647
1648 blk_add_timer(req);
1649 }
1650
1651 struct blk_expired_data {
1652 bool has_timedout_rq;
1653 unsigned long next;
1654 unsigned long timeout_start;
1655 };
1656
blk_mq_req_expired(struct request * rq,struct blk_expired_data * expired)1657 static bool blk_mq_req_expired(struct request *rq, struct blk_expired_data *expired)
1658 {
1659 unsigned long deadline;
1660
1661 if (blk_mq_rq_state(rq) != MQ_RQ_IN_FLIGHT)
1662 return false;
1663 if (rq->rq_flags & RQF_TIMED_OUT)
1664 return false;
1665
1666 deadline = READ_ONCE(rq->deadline);
1667 if (time_after_eq(expired->timeout_start, deadline))
1668 return true;
1669
1670 if (expired->next == 0)
1671 expired->next = deadline;
1672 else if (time_after(expired->next, deadline))
1673 expired->next = deadline;
1674 return false;
1675 }
1676
blk_mq_put_rq_ref(struct request * rq)1677 void blk_mq_put_rq_ref(struct request *rq)
1678 {
1679 if (is_flush_rq(rq)) {
1680 if (rq->end_io(rq, 0) == RQ_END_IO_FREE)
1681 blk_mq_free_request(rq);
1682 } else if (req_ref_put_and_test(rq)) {
1683 __blk_mq_free_request(rq);
1684 }
1685 }
1686
blk_mq_check_expired(struct request * rq,void * priv)1687 static bool blk_mq_check_expired(struct request *rq, void *priv)
1688 {
1689 struct blk_expired_data *expired = priv;
1690
1691 /*
1692 * blk_mq_queue_tag_busy_iter() has locked the request, so it cannot
1693 * be reallocated underneath the timeout handler's processing, then
1694 * the expire check is reliable. If the request is not expired, then
1695 * it was completed and reallocated as a new request after returning
1696 * from blk_mq_check_expired().
1697 */
1698 if (blk_mq_req_expired(rq, expired)) {
1699 expired->has_timedout_rq = true;
1700 return false;
1701 }
1702 return true;
1703 }
1704
blk_mq_handle_expired(struct request * rq,void * priv)1705 static bool blk_mq_handle_expired(struct request *rq, void *priv)
1706 {
1707 struct blk_expired_data *expired = priv;
1708
1709 if (blk_mq_req_expired(rq, expired))
1710 blk_mq_rq_timed_out(rq);
1711 return true;
1712 }
1713
blk_mq_timeout_work(struct work_struct * work)1714 static void blk_mq_timeout_work(struct work_struct *work)
1715 {
1716 struct request_queue *q =
1717 container_of(work, struct request_queue, timeout_work);
1718 struct blk_expired_data expired = {
1719 .timeout_start = jiffies,
1720 };
1721 struct blk_mq_hw_ctx *hctx;
1722 unsigned long i;
1723
1724 /* A deadlock might occur if a request is stuck requiring a
1725 * timeout at the same time a queue freeze is waiting
1726 * completion, since the timeout code would not be able to
1727 * acquire the queue reference here.
1728 *
1729 * That's why we don't use blk_queue_enter here; instead, we use
1730 * percpu_ref_tryget directly, because we need to be able to
1731 * obtain a reference even in the short window between the queue
1732 * starting to freeze, by dropping the first reference in
1733 * blk_freeze_queue_start, and the moment the last request is
1734 * consumed, marked by the instant q_usage_counter reaches
1735 * zero.
1736 */
1737 if (!percpu_ref_tryget(&q->q_usage_counter))
1738 return;
1739
1740 /* check if there is any timed-out request */
1741 blk_mq_queue_tag_busy_iter(q, blk_mq_check_expired, &expired);
1742 if (expired.has_timedout_rq) {
1743 /*
1744 * Before walking tags, we must ensure any submit started
1745 * before the current time has finished. Since the submit
1746 * uses srcu or rcu, wait for a synchronization point to
1747 * ensure all running submits have finished
1748 */
1749 blk_mq_wait_quiesce_done(q->tag_set);
1750
1751 expired.next = 0;
1752 blk_mq_queue_tag_busy_iter(q, blk_mq_handle_expired, &expired);
1753 }
1754
1755 if (expired.next != 0) {
1756 mod_timer(&q->timeout, expired.next);
1757 } else {
1758 /*
1759 * Request timeouts are handled as a forward rolling timer. If
1760 * we end up here it means that no requests are pending and
1761 * also that no request has been pending for a while. Mark
1762 * each hctx as idle.
1763 */
1764 queue_for_each_hw_ctx(q, hctx, i) {
1765 /* the hctx may be unmapped, so check it here */
1766 if (blk_mq_hw_queue_mapped(hctx))
1767 blk_mq_tag_idle(hctx);
1768 }
1769 }
1770 blk_queue_exit(q);
1771 }
1772
1773 struct flush_busy_ctx_data {
1774 struct blk_mq_hw_ctx *hctx;
1775 struct list_head *list;
1776 };
1777
flush_busy_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1778 static bool flush_busy_ctx(struct sbitmap *sb, unsigned int bitnr, void *data)
1779 {
1780 struct flush_busy_ctx_data *flush_data = data;
1781 struct blk_mq_hw_ctx *hctx = flush_data->hctx;
1782 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1783 enum hctx_type type = hctx->type;
1784
1785 spin_lock(&ctx->lock);
1786 list_splice_tail_init(&ctx->rq_lists[type], flush_data->list);
1787 sbitmap_clear_bit(sb, bitnr);
1788 spin_unlock(&ctx->lock);
1789 return true;
1790 }
1791
1792 /*
1793 * Process software queues that have been marked busy, splicing them
1794 * to the for-dispatch
1795 */
blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx * hctx,struct list_head * list)1796 void blk_mq_flush_busy_ctxs(struct blk_mq_hw_ctx *hctx, struct list_head *list)
1797 {
1798 struct flush_busy_ctx_data data = {
1799 .hctx = hctx,
1800 .list = list,
1801 };
1802
1803 sbitmap_for_each_set(&hctx->ctx_map, flush_busy_ctx, &data);
1804 }
1805 EXPORT_SYMBOL_GPL(blk_mq_flush_busy_ctxs);
1806
1807 struct dispatch_rq_data {
1808 struct blk_mq_hw_ctx *hctx;
1809 struct request *rq;
1810 };
1811
dispatch_rq_from_ctx(struct sbitmap * sb,unsigned int bitnr,void * data)1812 static bool dispatch_rq_from_ctx(struct sbitmap *sb, unsigned int bitnr,
1813 void *data)
1814 {
1815 struct dispatch_rq_data *dispatch_data = data;
1816 struct blk_mq_hw_ctx *hctx = dispatch_data->hctx;
1817 struct blk_mq_ctx *ctx = hctx->ctxs[bitnr];
1818 enum hctx_type type = hctx->type;
1819
1820 spin_lock(&ctx->lock);
1821 if (!list_empty(&ctx->rq_lists[type])) {
1822 dispatch_data->rq = list_entry_rq(ctx->rq_lists[type].next);
1823 list_del_init(&dispatch_data->rq->queuelist);
1824 if (list_empty(&ctx->rq_lists[type]))
1825 sbitmap_clear_bit(sb, bitnr);
1826 }
1827 spin_unlock(&ctx->lock);
1828
1829 return !dispatch_data->rq;
1830 }
1831
blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * start)1832 struct request *blk_mq_dequeue_from_ctx(struct blk_mq_hw_ctx *hctx,
1833 struct blk_mq_ctx *start)
1834 {
1835 unsigned off = start ? start->index_hw[hctx->type] : 0;
1836 struct dispatch_rq_data data = {
1837 .hctx = hctx,
1838 .rq = NULL,
1839 };
1840
1841 __sbitmap_for_each_set(&hctx->ctx_map, off,
1842 dispatch_rq_from_ctx, &data);
1843
1844 return data.rq;
1845 }
1846
__blk_mq_alloc_driver_tag(struct request * rq)1847 bool __blk_mq_alloc_driver_tag(struct request *rq)
1848 {
1849 struct sbitmap_queue *bt = &rq->mq_hctx->tags->bitmap_tags;
1850 unsigned int tag_offset = rq->mq_hctx->tags->nr_reserved_tags;
1851 int tag;
1852
1853 blk_mq_tag_busy(rq->mq_hctx);
1854
1855 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag)) {
1856 bt = &rq->mq_hctx->tags->breserved_tags;
1857 tag_offset = 0;
1858 }
1859
1860 tag = __sbitmap_queue_get(bt);
1861 if (tag == BLK_MQ_NO_TAG)
1862 return false;
1863
1864 rq->tag = tag + tag_offset;
1865 blk_mq_inc_active_requests(rq->mq_hctx);
1866 return true;
1867 }
1868
blk_mq_dispatch_wake(wait_queue_entry_t * wait,unsigned mode,int flags,void * key)1869 static int blk_mq_dispatch_wake(wait_queue_entry_t *wait, unsigned mode,
1870 int flags, void *key)
1871 {
1872 struct blk_mq_hw_ctx *hctx;
1873
1874 hctx = container_of(wait, struct blk_mq_hw_ctx, dispatch_wait);
1875
1876 spin_lock(&hctx->dispatch_wait_lock);
1877 if (!list_empty(&wait->entry)) {
1878 struct sbitmap_queue *sbq;
1879
1880 list_del_init(&wait->entry);
1881 sbq = &hctx->tags->bitmap_tags;
1882 atomic_dec(&sbq->ws_active);
1883 }
1884 spin_unlock(&hctx->dispatch_wait_lock);
1885
1886 blk_mq_run_hw_queue(hctx, true);
1887 return 1;
1888 }
1889
1890 /*
1891 * Mark us waiting for a tag. For shared tags, this involves hooking us into
1892 * the tag wakeups. For non-shared tags, we can simply mark us needing a
1893 * restart. For both cases, take care to check the condition again after
1894 * marking us as waiting.
1895 */
blk_mq_mark_tag_wait(struct blk_mq_hw_ctx * hctx,struct request * rq)1896 static bool blk_mq_mark_tag_wait(struct blk_mq_hw_ctx *hctx,
1897 struct request *rq)
1898 {
1899 struct sbitmap_queue *sbq;
1900 struct wait_queue_head *wq;
1901 wait_queue_entry_t *wait;
1902 bool ret;
1903
1904 if (!(hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) &&
1905 !(blk_mq_is_shared_tags(hctx->flags))) {
1906 blk_mq_sched_mark_restart_hctx(hctx);
1907
1908 /*
1909 * It's possible that a tag was freed in the window between the
1910 * allocation failure and adding the hardware queue to the wait
1911 * queue.
1912 *
1913 * Don't clear RESTART here, someone else could have set it.
1914 * At most this will cost an extra queue run.
1915 */
1916 return blk_mq_get_driver_tag(rq);
1917 }
1918
1919 wait = &hctx->dispatch_wait;
1920 if (!list_empty_careful(&wait->entry))
1921 return false;
1922
1923 if (blk_mq_tag_is_reserved(rq->mq_hctx->sched_tags, rq->internal_tag))
1924 sbq = &hctx->tags->breserved_tags;
1925 else
1926 sbq = &hctx->tags->bitmap_tags;
1927 wq = &bt_wait_ptr(sbq, hctx)->wait;
1928
1929 spin_lock_irq(&wq->lock);
1930 spin_lock(&hctx->dispatch_wait_lock);
1931 if (!list_empty(&wait->entry)) {
1932 spin_unlock(&hctx->dispatch_wait_lock);
1933 spin_unlock_irq(&wq->lock);
1934 return false;
1935 }
1936
1937 atomic_inc(&sbq->ws_active);
1938 wait->flags &= ~WQ_FLAG_EXCLUSIVE;
1939 __add_wait_queue(wq, wait);
1940
1941 /*
1942 * Add one explicit barrier since blk_mq_get_driver_tag() may
1943 * not imply barrier in case of failure.
1944 *
1945 * Order adding us to wait queue and allocating driver tag.
1946 *
1947 * The pair is the one implied in sbitmap_queue_wake_up() which
1948 * orders clearing sbitmap tag bits and waitqueue_active() in
1949 * __sbitmap_queue_wake_up(), since waitqueue_active() is lockless
1950 *
1951 * Otherwise, re-order of adding wait queue and getting driver tag
1952 * may cause __sbitmap_queue_wake_up() to wake up nothing because
1953 * the waitqueue_active() may not observe us in wait queue.
1954 */
1955 smp_mb();
1956
1957 /*
1958 * It's possible that a tag was freed in the window between the
1959 * allocation failure and adding the hardware queue to the wait
1960 * queue.
1961 */
1962 ret = blk_mq_get_driver_tag(rq);
1963 if (!ret) {
1964 spin_unlock(&hctx->dispatch_wait_lock);
1965 spin_unlock_irq(&wq->lock);
1966 return false;
1967 }
1968
1969 /*
1970 * We got a tag, remove ourselves from the wait queue to ensure
1971 * someone else gets the wakeup.
1972 */
1973 list_del_init(&wait->entry);
1974 atomic_dec(&sbq->ws_active);
1975 spin_unlock(&hctx->dispatch_wait_lock);
1976 spin_unlock_irq(&wq->lock);
1977
1978 return true;
1979 }
1980
1981 #define BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT 8
1982 #define BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR 4
1983 /*
1984 * Update dispatch busy with the Exponential Weighted Moving Average(EWMA):
1985 * - EWMA is one simple way to compute running average value
1986 * - weight(7/8 and 1/8) is applied so that it can decrease exponentially
1987 * - take 4 as factor for avoiding to get too small(0) result, and this
1988 * factor doesn't matter because EWMA decreases exponentially
1989 */
blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx * hctx,bool busy)1990 static void blk_mq_update_dispatch_busy(struct blk_mq_hw_ctx *hctx, bool busy)
1991 {
1992 unsigned int ewma;
1993
1994 ewma = hctx->dispatch_busy;
1995
1996 if (!ewma && !busy)
1997 return;
1998
1999 ewma *= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT - 1;
2000 if (busy)
2001 ewma += 1 << BLK_MQ_DISPATCH_BUSY_EWMA_FACTOR;
2002 ewma /= BLK_MQ_DISPATCH_BUSY_EWMA_WEIGHT;
2003
2004 hctx->dispatch_busy = ewma;
2005 }
2006
2007 #define BLK_MQ_RESOURCE_DELAY 3 /* ms units */
2008
blk_mq_handle_dev_resource(struct request * rq,struct list_head * list)2009 static void blk_mq_handle_dev_resource(struct request *rq,
2010 struct list_head *list)
2011 {
2012 list_add(&rq->queuelist, list);
2013 __blk_mq_requeue_request(rq);
2014 }
2015
2016 enum prep_dispatch {
2017 PREP_DISPATCH_OK,
2018 PREP_DISPATCH_NO_TAG,
2019 PREP_DISPATCH_NO_BUDGET,
2020 };
2021
blk_mq_prep_dispatch_rq(struct request * rq,bool need_budget)2022 static enum prep_dispatch blk_mq_prep_dispatch_rq(struct request *rq,
2023 bool need_budget)
2024 {
2025 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2026 int budget_token = -1;
2027
2028 if (need_budget) {
2029 budget_token = blk_mq_get_dispatch_budget(rq->q);
2030 if (budget_token < 0) {
2031 blk_mq_put_driver_tag(rq);
2032 return PREP_DISPATCH_NO_BUDGET;
2033 }
2034 blk_mq_set_rq_budget_token(rq, budget_token);
2035 }
2036
2037 if (!blk_mq_get_driver_tag(rq)) {
2038 /*
2039 * The initial allocation attempt failed, so we need to
2040 * rerun the hardware queue when a tag is freed. The
2041 * waitqueue takes care of that. If the queue is run
2042 * before we add this entry back on the dispatch list,
2043 * we'll re-run it below.
2044 */
2045 if (!blk_mq_mark_tag_wait(hctx, rq)) {
2046 /*
2047 * All budgets not got from this function will be put
2048 * together during handling partial dispatch
2049 */
2050 if (need_budget)
2051 blk_mq_put_dispatch_budget(rq->q, budget_token);
2052 return PREP_DISPATCH_NO_TAG;
2053 }
2054 }
2055
2056 return PREP_DISPATCH_OK;
2057 }
2058
2059 /* release all allocated budgets before calling to blk_mq_dispatch_rq_list */
blk_mq_release_budgets(struct request_queue * q,struct list_head * list)2060 static void blk_mq_release_budgets(struct request_queue *q,
2061 struct list_head *list)
2062 {
2063 struct request *rq;
2064
2065 list_for_each_entry(rq, list, queuelist) {
2066 int budget_token = blk_mq_get_rq_budget_token(rq);
2067
2068 if (budget_token >= 0)
2069 blk_mq_put_dispatch_budget(q, budget_token);
2070 }
2071 }
2072
2073 /*
2074 * blk_mq_commit_rqs will notify driver using bd->last that there is no
2075 * more requests. (See comment in struct blk_mq_ops for commit_rqs for
2076 * details)
2077 * Attention, we should explicitly call this in unusual cases:
2078 * 1) did not queue everything initially scheduled to queue
2079 * 2) the last attempt to queue a request failed
2080 */
blk_mq_commit_rqs(struct blk_mq_hw_ctx * hctx,int queued,bool from_schedule)2081 static void blk_mq_commit_rqs(struct blk_mq_hw_ctx *hctx, int queued,
2082 bool from_schedule)
2083 {
2084 if (hctx->queue->mq_ops->commit_rqs && queued) {
2085 trace_block_unplug(hctx->queue, queued, !from_schedule);
2086 hctx->queue->mq_ops->commit_rqs(hctx);
2087 }
2088 }
2089
2090 /*
2091 * Returns true if we did some work AND can potentially do more.
2092 */
blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx * hctx,struct list_head * list,unsigned int nr_budgets)2093 bool blk_mq_dispatch_rq_list(struct blk_mq_hw_ctx *hctx, struct list_head *list,
2094 unsigned int nr_budgets)
2095 {
2096 enum prep_dispatch prep;
2097 struct request_queue *q = hctx->queue;
2098 struct request *rq;
2099 int queued;
2100 blk_status_t ret = BLK_STS_OK;
2101 bool needs_resource = false;
2102
2103 if (list_empty(list))
2104 return false;
2105
2106 /*
2107 * Now process all the entries, sending them to the driver.
2108 */
2109 queued = 0;
2110 do {
2111 struct blk_mq_queue_data bd;
2112
2113 rq = list_first_entry(list, struct request, queuelist);
2114
2115 WARN_ON_ONCE(hctx != rq->mq_hctx);
2116 prep = blk_mq_prep_dispatch_rq(rq, !nr_budgets);
2117 if (prep != PREP_DISPATCH_OK)
2118 break;
2119
2120 list_del_init(&rq->queuelist);
2121
2122 bd.rq = rq;
2123 bd.last = list_empty(list);
2124
2125 /*
2126 * once the request is queued to lld, no need to cover the
2127 * budget any more
2128 */
2129 if (nr_budgets)
2130 nr_budgets--;
2131 ret = q->mq_ops->queue_rq(hctx, &bd);
2132 switch (ret) {
2133 case BLK_STS_OK:
2134 queued++;
2135 break;
2136 case BLK_STS_RESOURCE:
2137 needs_resource = true;
2138 fallthrough;
2139 case BLK_STS_DEV_RESOURCE:
2140 blk_mq_handle_dev_resource(rq, list);
2141 goto out;
2142 default:
2143 blk_mq_end_request(rq, ret);
2144 }
2145 } while (!list_empty(list));
2146 out:
2147 /* If we didn't flush the entire list, we could have told the driver
2148 * there was more coming, but that turned out to be a lie.
2149 */
2150 if (!list_empty(list) || ret != BLK_STS_OK)
2151 blk_mq_commit_rqs(hctx, queued, false);
2152
2153 /*
2154 * Any items that need requeuing? Stuff them into hctx->dispatch,
2155 * that is where we will continue on next queue run.
2156 */
2157 if (!list_empty(list)) {
2158 bool needs_restart;
2159 /* For non-shared tags, the RESTART check will suffice */
2160 bool no_tag = prep == PREP_DISPATCH_NO_TAG &&
2161 ((hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED) ||
2162 blk_mq_is_shared_tags(hctx->flags));
2163
2164 if (nr_budgets)
2165 blk_mq_release_budgets(q, list);
2166
2167 spin_lock(&hctx->lock);
2168 list_splice_tail_init(list, &hctx->dispatch);
2169 spin_unlock(&hctx->lock);
2170
2171 /*
2172 * Order adding requests to hctx->dispatch and checking
2173 * SCHED_RESTART flag. The pair of this smp_mb() is the one
2174 * in blk_mq_sched_restart(). Avoid restart code path to
2175 * miss the new added requests to hctx->dispatch, meantime
2176 * SCHED_RESTART is observed here.
2177 */
2178 smp_mb();
2179
2180 /*
2181 * If SCHED_RESTART was set by the caller of this function and
2182 * it is no longer set that means that it was cleared by another
2183 * thread and hence that a queue rerun is needed.
2184 *
2185 * If 'no_tag' is set, that means that we failed getting
2186 * a driver tag with an I/O scheduler attached. If our dispatch
2187 * waitqueue is no longer active, ensure that we run the queue
2188 * AFTER adding our entries back to the list.
2189 *
2190 * If no I/O scheduler has been configured it is possible that
2191 * the hardware queue got stopped and restarted before requests
2192 * were pushed back onto the dispatch list. Rerun the queue to
2193 * avoid starvation. Notes:
2194 * - blk_mq_run_hw_queue() checks whether or not a queue has
2195 * been stopped before rerunning a queue.
2196 * - Some but not all block drivers stop a queue before
2197 * returning BLK_STS_RESOURCE. Two exceptions are scsi-mq
2198 * and dm-rq.
2199 *
2200 * If driver returns BLK_STS_RESOURCE and SCHED_RESTART
2201 * bit is set, run queue after a delay to avoid IO stalls
2202 * that could otherwise occur if the queue is idle. We'll do
2203 * similar if we couldn't get budget or couldn't lock a zone
2204 * and SCHED_RESTART is set.
2205 */
2206 needs_restart = blk_mq_sched_needs_restart(hctx);
2207 if (prep == PREP_DISPATCH_NO_BUDGET)
2208 needs_resource = true;
2209 if (!needs_restart ||
2210 (no_tag && list_empty_careful(&hctx->dispatch_wait.entry)))
2211 blk_mq_run_hw_queue(hctx, true);
2212 else if (needs_resource)
2213 blk_mq_delay_run_hw_queue(hctx, BLK_MQ_RESOURCE_DELAY);
2214
2215 blk_mq_update_dispatch_busy(hctx, true);
2216 return false;
2217 }
2218
2219 blk_mq_update_dispatch_busy(hctx, false);
2220 return true;
2221 }
2222
blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx * hctx)2223 static inline int blk_mq_first_mapped_cpu(struct blk_mq_hw_ctx *hctx)
2224 {
2225 int cpu = cpumask_first_and(hctx->cpumask, cpu_online_mask);
2226
2227 if (cpu >= nr_cpu_ids)
2228 cpu = cpumask_first(hctx->cpumask);
2229 return cpu;
2230 }
2231
2232 /*
2233 * ->next_cpu is always calculated from hctx->cpumask, so simply use
2234 * it for speeding up the check
2235 */
blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx * hctx)2236 static bool blk_mq_hctx_empty_cpumask(struct blk_mq_hw_ctx *hctx)
2237 {
2238 return hctx->next_cpu >= nr_cpu_ids;
2239 }
2240
2241 /*
2242 * It'd be great if the workqueue API had a way to pass
2243 * in a mask and had some smarts for more clever placement.
2244 * For now we just round-robin here, switching for every
2245 * BLK_MQ_CPU_WORK_BATCH queued items.
2246 */
blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx * hctx)2247 static int blk_mq_hctx_next_cpu(struct blk_mq_hw_ctx *hctx)
2248 {
2249 bool tried = false;
2250 int next_cpu = hctx->next_cpu;
2251
2252 /* Switch to unbound if no allowable CPUs in this hctx */
2253 if (hctx->queue->nr_hw_queues == 1 || blk_mq_hctx_empty_cpumask(hctx))
2254 return WORK_CPU_UNBOUND;
2255
2256 if (--hctx->next_cpu_batch <= 0) {
2257 select_cpu:
2258 next_cpu = cpumask_next_and(next_cpu, hctx->cpumask,
2259 cpu_online_mask);
2260 if (next_cpu >= nr_cpu_ids)
2261 next_cpu = blk_mq_first_mapped_cpu(hctx);
2262 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
2263 }
2264
2265 /*
2266 * Do unbound schedule if we can't find a online CPU for this hctx,
2267 * and it should only happen in the path of handling CPU DEAD.
2268 */
2269 if (!cpu_online(next_cpu)) {
2270 if (!tried) {
2271 tried = true;
2272 goto select_cpu;
2273 }
2274
2275 /*
2276 * Make sure to re-select CPU next time once after CPUs
2277 * in hctx->cpumask become online again.
2278 */
2279 hctx->next_cpu = next_cpu;
2280 hctx->next_cpu_batch = 1;
2281 return WORK_CPU_UNBOUND;
2282 }
2283
2284 hctx->next_cpu = next_cpu;
2285 return next_cpu;
2286 }
2287
2288 /**
2289 * blk_mq_delay_run_hw_queue - Run a hardware queue asynchronously.
2290 * @hctx: Pointer to the hardware queue to run.
2291 * @msecs: Milliseconds of delay to wait before running the queue.
2292 *
2293 * Run a hardware queue asynchronously with a delay of @msecs.
2294 */
blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx * hctx,unsigned long msecs)2295 void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
2296 {
2297 bool skip = false;
2298
2299 if (unlikely(blk_mq_hctx_stopped(hctx)))
2300 return;
2301
2302 trace_android_vh_blk_mq_delay_run_hw_queue(blk_mq_hctx_next_cpu(hctx),
2303 hctx, msecs_to_jiffies(msecs), &skip);
2304 if (skip)
2305 return;
2306
2307 kblockd_mod_delayed_work_on(blk_mq_hctx_next_cpu(hctx), &hctx->run_work,
2308 msecs_to_jiffies(msecs));
2309 }
2310 EXPORT_SYMBOL(blk_mq_delay_run_hw_queue);
2311
blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx * hctx)2312 static inline bool blk_mq_hw_queue_need_run(struct blk_mq_hw_ctx *hctx)
2313 {
2314 bool need_run;
2315
2316 /*
2317 * When queue is quiesced, we may be switching io scheduler, or
2318 * updating nr_hw_queues, or other things, and we can't run queue
2319 * any more, even blk_mq_hctx_has_pending() can't be called safely.
2320 *
2321 * And queue will be rerun in blk_mq_unquiesce_queue() if it is
2322 * quiesced.
2323 */
2324 __blk_mq_run_dispatch_ops(hctx->queue, false,
2325 need_run = !blk_queue_quiesced(hctx->queue) &&
2326 blk_mq_hctx_has_pending(hctx));
2327 return need_run;
2328 }
2329
2330 /**
2331 * blk_mq_run_hw_queue - Start to run a hardware queue.
2332 * @hctx: Pointer to the hardware queue to run.
2333 * @async: If we want to run the queue asynchronously.
2334 *
2335 * Check if the request queue is not in a quiesced state and if there are
2336 * pending requests to be sent. If this is true, run the queue to send requests
2337 * to hardware.
2338 */
blk_mq_run_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)2339 void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2340 {
2341 bool need_run;
2342
2343 /*
2344 * We can't run the queue inline with interrupts disabled.
2345 */
2346 WARN_ON_ONCE(!async && in_interrupt());
2347
2348 might_sleep_if(!async && hctx->flags & BLK_MQ_F_BLOCKING);
2349
2350 need_run = blk_mq_hw_queue_need_run(hctx);
2351 if (!need_run) {
2352 unsigned long flags;
2353
2354 /*
2355 * Synchronize with blk_mq_unquiesce_queue(), because we check
2356 * if hw queue is quiesced locklessly above, we need the use
2357 * ->queue_lock to make sure we see the up-to-date status to
2358 * not miss rerunning the hw queue.
2359 */
2360 spin_lock_irqsave(&hctx->queue->queue_lock, flags);
2361 need_run = blk_mq_hw_queue_need_run(hctx);
2362 spin_unlock_irqrestore(&hctx->queue->queue_lock, flags);
2363
2364 if (!need_run)
2365 return;
2366 }
2367
2368 if (async || !cpumask_test_cpu(raw_smp_processor_id(), hctx->cpumask)) {
2369 blk_mq_delay_run_hw_queue(hctx, 0);
2370 return;
2371 }
2372
2373 blk_mq_run_dispatch_ops(hctx->queue,
2374 blk_mq_sched_dispatch_requests(hctx));
2375 }
2376 EXPORT_SYMBOL(blk_mq_run_hw_queue);
2377
2378 /*
2379 * Return prefered queue to dispatch from (if any) for non-mq aware IO
2380 * scheduler.
2381 */
blk_mq_get_sq_hctx(struct request_queue * q)2382 static struct blk_mq_hw_ctx *blk_mq_get_sq_hctx(struct request_queue *q)
2383 {
2384 struct blk_mq_ctx *ctx = blk_mq_get_ctx(q);
2385 /*
2386 * If the IO scheduler does not respect hardware queues when
2387 * dispatching, we just don't bother with multiple HW queues and
2388 * dispatch from hctx for the current CPU since running multiple queues
2389 * just causes lock contention inside the scheduler and pointless cache
2390 * bouncing.
2391 */
2392 struct blk_mq_hw_ctx *hctx = ctx->hctxs[HCTX_TYPE_DEFAULT];
2393
2394 if (!blk_mq_hctx_stopped(hctx))
2395 return hctx;
2396 return NULL;
2397 }
2398
2399 /**
2400 * blk_mq_run_hw_queues - Run all hardware queues in a request queue.
2401 * @q: Pointer to the request queue to run.
2402 * @async: If we want to run the queue asynchronously.
2403 */
blk_mq_run_hw_queues(struct request_queue * q,bool async)2404 void blk_mq_run_hw_queues(struct request_queue *q, bool async)
2405 {
2406 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2407 unsigned long i;
2408
2409 sq_hctx = NULL;
2410 if (blk_queue_sq_sched(q))
2411 sq_hctx = blk_mq_get_sq_hctx(q);
2412 queue_for_each_hw_ctx(q, hctx, i) {
2413 if (blk_mq_hctx_stopped(hctx))
2414 continue;
2415 /*
2416 * Dispatch from this hctx either if there's no hctx preferred
2417 * by IO scheduler or if it has requests that bypass the
2418 * scheduler.
2419 */
2420 if (!sq_hctx || sq_hctx == hctx ||
2421 !list_empty_careful(&hctx->dispatch))
2422 blk_mq_run_hw_queue(hctx, async);
2423 }
2424 }
2425 EXPORT_SYMBOL(blk_mq_run_hw_queues);
2426
2427 /**
2428 * blk_mq_delay_run_hw_queues - Run all hardware queues asynchronously.
2429 * @q: Pointer to the request queue to run.
2430 * @msecs: Milliseconds of delay to wait before running the queues.
2431 */
blk_mq_delay_run_hw_queues(struct request_queue * q,unsigned long msecs)2432 void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
2433 {
2434 struct blk_mq_hw_ctx *hctx, *sq_hctx;
2435 unsigned long i;
2436
2437 sq_hctx = NULL;
2438 if (blk_queue_sq_sched(q))
2439 sq_hctx = blk_mq_get_sq_hctx(q);
2440 queue_for_each_hw_ctx(q, hctx, i) {
2441 if (blk_mq_hctx_stopped(hctx))
2442 continue;
2443 /*
2444 * If there is already a run_work pending, leave the
2445 * pending delay untouched. Otherwise, a hctx can stall
2446 * if another hctx is re-delaying the other's work
2447 * before the work executes.
2448 */
2449 if (delayed_work_pending(&hctx->run_work))
2450 continue;
2451 /*
2452 * Dispatch from this hctx either if there's no hctx preferred
2453 * by IO scheduler or if it has requests that bypass the
2454 * scheduler.
2455 */
2456 if (!sq_hctx || sq_hctx == hctx ||
2457 !list_empty_careful(&hctx->dispatch))
2458 blk_mq_delay_run_hw_queue(hctx, msecs);
2459 }
2460 }
2461 EXPORT_SYMBOL(blk_mq_delay_run_hw_queues);
2462
2463 /*
2464 * This function is often used for pausing .queue_rq() by driver when
2465 * there isn't enough resource or some conditions aren't satisfied, and
2466 * BLK_STS_RESOURCE is usually returned.
2467 *
2468 * We do not guarantee that dispatch can be drained or blocked
2469 * after blk_mq_stop_hw_queue() returns. Please use
2470 * blk_mq_quiesce_queue() for that requirement.
2471 */
blk_mq_stop_hw_queue(struct blk_mq_hw_ctx * hctx)2472 void blk_mq_stop_hw_queue(struct blk_mq_hw_ctx *hctx)
2473 {
2474 cancel_delayed_work(&hctx->run_work);
2475
2476 set_bit(BLK_MQ_S_STOPPED, &hctx->state);
2477 }
2478 EXPORT_SYMBOL(blk_mq_stop_hw_queue);
2479
2480 /*
2481 * This function is often used for pausing .queue_rq() by driver when
2482 * there isn't enough resource or some conditions aren't satisfied, and
2483 * BLK_STS_RESOURCE is usually returned.
2484 *
2485 * We do not guarantee that dispatch can be drained or blocked
2486 * after blk_mq_stop_hw_queues() returns. Please use
2487 * blk_mq_quiesce_queue() for that requirement.
2488 */
blk_mq_stop_hw_queues(struct request_queue * q)2489 void blk_mq_stop_hw_queues(struct request_queue *q)
2490 {
2491 struct blk_mq_hw_ctx *hctx;
2492 unsigned long i;
2493
2494 queue_for_each_hw_ctx(q, hctx, i)
2495 blk_mq_stop_hw_queue(hctx);
2496 }
2497 EXPORT_SYMBOL(blk_mq_stop_hw_queues);
2498
blk_mq_start_hw_queue(struct blk_mq_hw_ctx * hctx)2499 void blk_mq_start_hw_queue(struct blk_mq_hw_ctx *hctx)
2500 {
2501 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2502
2503 blk_mq_run_hw_queue(hctx, hctx->flags & BLK_MQ_F_BLOCKING);
2504 }
2505 EXPORT_SYMBOL(blk_mq_start_hw_queue);
2506
blk_mq_start_hw_queues(struct request_queue * q)2507 void blk_mq_start_hw_queues(struct request_queue *q)
2508 {
2509 struct blk_mq_hw_ctx *hctx;
2510 unsigned long i;
2511
2512 queue_for_each_hw_ctx(q, hctx, i)
2513 blk_mq_start_hw_queue(hctx);
2514 }
2515 EXPORT_SYMBOL(blk_mq_start_hw_queues);
2516
blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx * hctx,bool async)2517 void blk_mq_start_stopped_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
2518 {
2519 if (!blk_mq_hctx_stopped(hctx))
2520 return;
2521
2522 clear_bit(BLK_MQ_S_STOPPED, &hctx->state);
2523 /*
2524 * Pairs with the smp_mb() in blk_mq_hctx_stopped() to order the
2525 * clearing of BLK_MQ_S_STOPPED above and the checking of dispatch
2526 * list in the subsequent routine.
2527 */
2528 smp_mb__after_atomic();
2529 blk_mq_run_hw_queue(hctx, async);
2530 }
2531 EXPORT_SYMBOL_GPL(blk_mq_start_stopped_hw_queue);
2532
blk_mq_start_stopped_hw_queues(struct request_queue * q,bool async)2533 void blk_mq_start_stopped_hw_queues(struct request_queue *q, bool async)
2534 {
2535 struct blk_mq_hw_ctx *hctx;
2536 unsigned long i;
2537
2538 queue_for_each_hw_ctx(q, hctx, i)
2539 blk_mq_start_stopped_hw_queue(hctx, async ||
2540 (hctx->flags & BLK_MQ_F_BLOCKING));
2541 }
2542 EXPORT_SYMBOL(blk_mq_start_stopped_hw_queues);
2543
blk_mq_run_work_fn(struct work_struct * work)2544 static void blk_mq_run_work_fn(struct work_struct *work)
2545 {
2546 struct blk_mq_hw_ctx *hctx =
2547 container_of(work, struct blk_mq_hw_ctx, run_work.work);
2548
2549 blk_mq_run_dispatch_ops(hctx->queue,
2550 blk_mq_sched_dispatch_requests(hctx));
2551 }
2552
2553 /**
2554 * blk_mq_request_bypass_insert - Insert a request at dispatch list.
2555 * @rq: Pointer to request to be inserted.
2556 * @flags: BLK_MQ_INSERT_*
2557 *
2558 * Should only be used carefully, when the caller knows we want to
2559 * bypass a potential IO scheduler on the target device.
2560 */
blk_mq_request_bypass_insert(struct request * rq,blk_insert_t flags)2561 static void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
2562 {
2563 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2564
2565 spin_lock(&hctx->lock);
2566 if (flags & BLK_MQ_INSERT_AT_HEAD)
2567 list_add(&rq->queuelist, &hctx->dispatch);
2568 else
2569 list_add_tail(&rq->queuelist, &hctx->dispatch);
2570 spin_unlock(&hctx->lock);
2571 }
2572
blk_mq_insert_requests(struct blk_mq_hw_ctx * hctx,struct blk_mq_ctx * ctx,struct list_head * list,bool run_queue_async)2573 static void blk_mq_insert_requests(struct blk_mq_hw_ctx *hctx,
2574 struct blk_mq_ctx *ctx, struct list_head *list,
2575 bool run_queue_async)
2576 {
2577 struct request *rq;
2578 enum hctx_type type = hctx->type;
2579
2580 /*
2581 * Try to issue requests directly if the hw queue isn't busy to save an
2582 * extra enqueue & dequeue to the sw queue.
2583 */
2584 if (!hctx->dispatch_busy && !run_queue_async) {
2585 blk_mq_run_dispatch_ops(hctx->queue,
2586 blk_mq_try_issue_list_directly(hctx, list));
2587 if (list_empty(list))
2588 goto out;
2589 }
2590
2591 /*
2592 * preemption doesn't flush plug list, so it's possible ctx->cpu is
2593 * offline now
2594 */
2595 list_for_each_entry(rq, list, queuelist) {
2596 BUG_ON(rq->mq_ctx != ctx);
2597 trace_block_rq_insert(rq);
2598 if (rq->cmd_flags & REQ_NOWAIT)
2599 run_queue_async = true;
2600 }
2601
2602 spin_lock(&ctx->lock);
2603 list_splice_tail_init(list, &ctx->rq_lists[type]);
2604 blk_mq_hctx_mark_pending(hctx, ctx);
2605 spin_unlock(&ctx->lock);
2606 out:
2607 blk_mq_run_hw_queue(hctx, run_queue_async);
2608 }
2609
blk_mq_insert_request(struct request * rq,blk_insert_t flags)2610 static void blk_mq_insert_request(struct request *rq, blk_insert_t flags)
2611 {
2612 struct request_queue *q = rq->q;
2613 struct blk_mq_ctx *ctx = rq->mq_ctx;
2614 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2615
2616 if (blk_rq_is_passthrough(rq)) {
2617 /*
2618 * Passthrough request have to be added to hctx->dispatch
2619 * directly. The device may be in a situation where it can't
2620 * handle FS request, and always returns BLK_STS_RESOURCE for
2621 * them, which gets them added to hctx->dispatch.
2622 *
2623 * If a passthrough request is required to unblock the queues,
2624 * and it is added to the scheduler queue, there is no chance to
2625 * dispatch it given we prioritize requests in hctx->dispatch.
2626 */
2627 blk_mq_request_bypass_insert(rq, flags);
2628 } else if (req_op(rq) == REQ_OP_FLUSH) {
2629 /*
2630 * Firstly normal IO request is inserted to scheduler queue or
2631 * sw queue, meantime we add flush request to dispatch queue(
2632 * hctx->dispatch) directly and there is at most one in-flight
2633 * flush request for each hw queue, so it doesn't matter to add
2634 * flush request to tail or front of the dispatch queue.
2635 *
2636 * Secondly in case of NCQ, flush request belongs to non-NCQ
2637 * command, and queueing it will fail when there is any
2638 * in-flight normal IO request(NCQ command). When adding flush
2639 * rq to the front of hctx->dispatch, it is easier to introduce
2640 * extra time to flush rq's latency because of S_SCHED_RESTART
2641 * compared with adding to the tail of dispatch queue, then
2642 * chance of flush merge is increased, and less flush requests
2643 * will be issued to controller. It is observed that ~10% time
2644 * is saved in blktests block/004 on disk attached to AHCI/NCQ
2645 * drive when adding flush rq to the front of hctx->dispatch.
2646 *
2647 * Simply queue flush rq to the front of hctx->dispatch so that
2648 * intensive flush workloads can benefit in case of NCQ HW.
2649 */
2650 blk_mq_request_bypass_insert(rq, BLK_MQ_INSERT_AT_HEAD);
2651 } else if (q->elevator) {
2652 LIST_HEAD(list);
2653
2654 WARN_ON_ONCE(rq->tag != BLK_MQ_NO_TAG);
2655
2656 list_add(&rq->queuelist, &list);
2657 q->elevator->type->ops.insert_requests(hctx, &list, flags);
2658 } else {
2659 trace_block_rq_insert(rq);
2660
2661 spin_lock(&ctx->lock);
2662 if (flags & BLK_MQ_INSERT_AT_HEAD)
2663 list_add(&rq->queuelist, &ctx->rq_lists[hctx->type]);
2664 else
2665 list_add_tail(&rq->queuelist,
2666 &ctx->rq_lists[hctx->type]);
2667 blk_mq_hctx_mark_pending(hctx, ctx);
2668 spin_unlock(&ctx->lock);
2669 }
2670 }
2671
blk_mq_bio_to_request(struct request * rq,struct bio * bio,unsigned int nr_segs)2672 static void blk_mq_bio_to_request(struct request *rq, struct bio *bio,
2673 unsigned int nr_segs)
2674 {
2675 int err;
2676
2677 if (bio->bi_opf & REQ_RAHEAD)
2678 rq->cmd_flags |= REQ_FAILFAST_MASK;
2679
2680 rq->__sector = bio->bi_iter.bi_sector;
2681 rq->write_hint = bio->bi_write_hint;
2682 blk_rq_bio_prep(rq, bio, nr_segs);
2683 if (bio_integrity(bio))
2684 rq->nr_integrity_segments = blk_rq_count_integrity_sg(rq->q,
2685 bio);
2686
2687 /* This can't fail, since GFP_NOIO includes __GFP_DIRECT_RECLAIM. */
2688 err = blk_crypto_rq_bio_prep(rq, bio, GFP_NOIO);
2689 WARN_ON_ONCE(err);
2690
2691 blk_account_io_start(rq);
2692 }
2693
__blk_mq_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq,bool last)2694 static blk_status_t __blk_mq_issue_directly(struct blk_mq_hw_ctx *hctx,
2695 struct request *rq, bool last)
2696 {
2697 struct request_queue *q = rq->q;
2698 struct blk_mq_queue_data bd = {
2699 .rq = rq,
2700 .last = last,
2701 };
2702 blk_status_t ret;
2703
2704 /*
2705 * For OK queue, we are done. For error, caller may kill it.
2706 * Any other error (busy), just add it to our list as we
2707 * previously would have done.
2708 */
2709 ret = q->mq_ops->queue_rq(hctx, &bd);
2710 switch (ret) {
2711 case BLK_STS_OK:
2712 blk_mq_update_dispatch_busy(hctx, false);
2713 break;
2714 case BLK_STS_RESOURCE:
2715 case BLK_STS_DEV_RESOURCE:
2716 blk_mq_update_dispatch_busy(hctx, true);
2717 __blk_mq_requeue_request(rq);
2718 break;
2719 default:
2720 blk_mq_update_dispatch_busy(hctx, false);
2721 break;
2722 }
2723
2724 return ret;
2725 }
2726
blk_mq_get_budget_and_tag(struct request * rq)2727 static bool blk_mq_get_budget_and_tag(struct request *rq)
2728 {
2729 int budget_token;
2730
2731 budget_token = blk_mq_get_dispatch_budget(rq->q);
2732 if (budget_token < 0)
2733 return false;
2734 blk_mq_set_rq_budget_token(rq, budget_token);
2735 if (!blk_mq_get_driver_tag(rq)) {
2736 blk_mq_put_dispatch_budget(rq->q, budget_token);
2737 return false;
2738 }
2739 return true;
2740 }
2741
2742 /**
2743 * blk_mq_try_issue_directly - Try to send a request directly to device driver.
2744 * @hctx: Pointer of the associated hardware queue.
2745 * @rq: Pointer to request to be sent.
2746 *
2747 * If the device has enough resources to accept a new request now, send the
2748 * request directly to device driver. Else, insert at hctx->dispatch queue, so
2749 * we can try send it another time in the future. Requests inserted at this
2750 * queue have higher priority.
2751 */
blk_mq_try_issue_directly(struct blk_mq_hw_ctx * hctx,struct request * rq)2752 static void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx,
2753 struct request *rq)
2754 {
2755 blk_status_t ret;
2756
2757 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2758 blk_mq_insert_request(rq, 0);
2759 blk_mq_run_hw_queue(hctx, false);
2760 return;
2761 }
2762
2763 if ((rq->rq_flags & RQF_USE_SCHED) || !blk_mq_get_budget_and_tag(rq)) {
2764 blk_mq_insert_request(rq, 0);
2765 blk_mq_run_hw_queue(hctx, rq->cmd_flags & REQ_NOWAIT);
2766 return;
2767 }
2768
2769 ret = __blk_mq_issue_directly(hctx, rq, true);
2770 switch (ret) {
2771 case BLK_STS_OK:
2772 break;
2773 case BLK_STS_RESOURCE:
2774 case BLK_STS_DEV_RESOURCE:
2775 blk_mq_request_bypass_insert(rq, 0);
2776 blk_mq_run_hw_queue(hctx, false);
2777 break;
2778 default:
2779 blk_mq_end_request(rq, ret);
2780 break;
2781 }
2782 }
2783
blk_mq_request_issue_directly(struct request * rq,bool last)2784 static blk_status_t blk_mq_request_issue_directly(struct request *rq, bool last)
2785 {
2786 struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
2787
2788 if (blk_mq_hctx_stopped(hctx) || blk_queue_quiesced(rq->q)) {
2789 blk_mq_insert_request(rq, 0);
2790 blk_mq_run_hw_queue(hctx, false);
2791 return BLK_STS_OK;
2792 }
2793
2794 if (!blk_mq_get_budget_and_tag(rq))
2795 return BLK_STS_RESOURCE;
2796 return __blk_mq_issue_directly(hctx, rq, last);
2797 }
2798
blk_mq_plug_issue_direct(struct blk_plug * plug)2799 static void blk_mq_plug_issue_direct(struct blk_plug *plug)
2800 {
2801 struct blk_mq_hw_ctx *hctx = NULL;
2802 struct request *rq;
2803 int queued = 0;
2804 blk_status_t ret = BLK_STS_OK;
2805
2806 while ((rq = rq_list_pop(&plug->mq_list))) {
2807 bool last = rq_list_empty(&plug->mq_list);
2808
2809 if (hctx != rq->mq_hctx) {
2810 if (hctx) {
2811 blk_mq_commit_rqs(hctx, queued, false);
2812 queued = 0;
2813 }
2814 hctx = rq->mq_hctx;
2815 }
2816
2817 ret = blk_mq_request_issue_directly(rq, last);
2818 switch (ret) {
2819 case BLK_STS_OK:
2820 queued++;
2821 break;
2822 case BLK_STS_RESOURCE:
2823 case BLK_STS_DEV_RESOURCE:
2824 blk_mq_request_bypass_insert(rq, 0);
2825 blk_mq_run_hw_queue(hctx, false);
2826 goto out;
2827 default:
2828 blk_mq_end_request(rq, ret);
2829 break;
2830 }
2831 }
2832
2833 out:
2834 if (ret != BLK_STS_OK)
2835 blk_mq_commit_rqs(hctx, queued, false);
2836 }
2837
__blk_mq_flush_plug_list(struct request_queue * q,struct blk_plug * plug)2838 static void __blk_mq_flush_plug_list(struct request_queue *q,
2839 struct blk_plug *plug)
2840 {
2841 if (blk_queue_quiesced(q))
2842 return;
2843 q->mq_ops->queue_rqs(&plug->mq_list);
2844 }
2845
blk_mq_dispatch_plug_list(struct blk_plug * plug,bool from_sched)2846 static void blk_mq_dispatch_plug_list(struct blk_plug *plug, bool from_sched)
2847 {
2848 struct blk_mq_hw_ctx *this_hctx = NULL;
2849 struct blk_mq_ctx *this_ctx = NULL;
2850 struct rq_list requeue_list = {};
2851 unsigned int depth = 0;
2852 bool is_passthrough = false;
2853 LIST_HEAD(list);
2854
2855 do {
2856 struct request *rq = rq_list_pop(&plug->mq_list);
2857
2858 if (!this_hctx) {
2859 this_hctx = rq->mq_hctx;
2860 this_ctx = rq->mq_ctx;
2861 is_passthrough = blk_rq_is_passthrough(rq);
2862 } else if (this_hctx != rq->mq_hctx || this_ctx != rq->mq_ctx ||
2863 is_passthrough != blk_rq_is_passthrough(rq)) {
2864 rq_list_add_tail(&requeue_list, rq);
2865 continue;
2866 }
2867 list_add_tail(&rq->queuelist, &list);
2868 depth++;
2869 } while (!rq_list_empty(&plug->mq_list));
2870
2871 plug->mq_list = requeue_list;
2872 trace_block_unplug(this_hctx->queue, depth, !from_sched);
2873
2874 percpu_ref_get(&this_hctx->queue->q_usage_counter);
2875 /* passthrough requests should never be issued to the I/O scheduler */
2876 if (is_passthrough) {
2877 spin_lock(&this_hctx->lock);
2878 list_splice_tail_init(&list, &this_hctx->dispatch);
2879 spin_unlock(&this_hctx->lock);
2880 blk_mq_run_hw_queue(this_hctx, from_sched);
2881 } else if (this_hctx->queue->elevator) {
2882 this_hctx->queue->elevator->type->ops.insert_requests(this_hctx,
2883 &list, 0);
2884 blk_mq_run_hw_queue(this_hctx, from_sched);
2885 } else {
2886 blk_mq_insert_requests(this_hctx, this_ctx, &list, from_sched);
2887 }
2888 percpu_ref_put(&this_hctx->queue->q_usage_counter);
2889 }
2890
blk_mq_flush_plug_list(struct blk_plug * plug,bool from_schedule)2891 void blk_mq_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2892 {
2893 struct request *rq;
2894 unsigned int depth;
2895
2896 /*
2897 * We may have been called recursively midway through handling
2898 * plug->mq_list via a schedule() in the driver's queue_rq() callback.
2899 * To avoid mq_list changing under our feet, clear rq_count early and
2900 * bail out specifically if rq_count is 0 rather than checking
2901 * whether the mq_list is empty.
2902 */
2903 if (plug->rq_count == 0)
2904 return;
2905 depth = plug->rq_count;
2906 plug->rq_count = 0;
2907
2908 if (!plug->multiple_queues && !plug->has_elevator && !from_schedule) {
2909 struct request_queue *q;
2910
2911 rq = rq_list_peek(&plug->mq_list);
2912 q = rq->q;
2913 trace_block_unplug(q, depth, true);
2914
2915 /*
2916 * Peek first request and see if we have a ->queue_rqs() hook.
2917 * If we do, we can dispatch the whole plug list in one go. We
2918 * already know at this point that all requests belong to the
2919 * same queue, caller must ensure that's the case.
2920 */
2921 if (q->mq_ops->queue_rqs) {
2922 blk_mq_run_dispatch_ops(q,
2923 __blk_mq_flush_plug_list(q, plug));
2924 if (rq_list_empty(&plug->mq_list))
2925 return;
2926 }
2927
2928 blk_mq_run_dispatch_ops(q,
2929 blk_mq_plug_issue_direct(plug));
2930 if (rq_list_empty(&plug->mq_list))
2931 return;
2932 }
2933
2934 do {
2935 blk_mq_dispatch_plug_list(plug, from_schedule);
2936 } while (!rq_list_empty(&plug->mq_list));
2937 }
2938
blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx * hctx,struct list_head * list)2939 static void blk_mq_try_issue_list_directly(struct blk_mq_hw_ctx *hctx,
2940 struct list_head *list)
2941 {
2942 int queued = 0;
2943 blk_status_t ret = BLK_STS_OK;
2944
2945 while (!list_empty(list)) {
2946 struct request *rq = list_first_entry(list, struct request,
2947 queuelist);
2948
2949 list_del_init(&rq->queuelist);
2950 ret = blk_mq_request_issue_directly(rq, list_empty(list));
2951 switch (ret) {
2952 case BLK_STS_OK:
2953 queued++;
2954 break;
2955 case BLK_STS_RESOURCE:
2956 case BLK_STS_DEV_RESOURCE:
2957 blk_mq_request_bypass_insert(rq, 0);
2958 if (list_empty(list))
2959 blk_mq_run_hw_queue(hctx, false);
2960 goto out;
2961 default:
2962 blk_mq_end_request(rq, ret);
2963 break;
2964 }
2965 }
2966
2967 out:
2968 if (ret != BLK_STS_OK)
2969 blk_mq_commit_rqs(hctx, queued, false);
2970 }
2971
blk_mq_attempt_bio_merge(struct request_queue * q,struct bio * bio,unsigned int nr_segs)2972 static bool blk_mq_attempt_bio_merge(struct request_queue *q,
2973 struct bio *bio, unsigned int nr_segs)
2974 {
2975 if (!blk_queue_nomerges(q) && bio_mergeable(bio)) {
2976 if (blk_attempt_plug_merge(q, bio, nr_segs))
2977 return true;
2978 if (blk_mq_sched_bio_merge(q, bio, nr_segs))
2979 return true;
2980 }
2981 return false;
2982 }
2983
blk_mq_get_new_requests(struct request_queue * q,struct blk_plug * plug,struct bio * bio,unsigned int nsegs)2984 static struct request *blk_mq_get_new_requests(struct request_queue *q,
2985 struct blk_plug *plug,
2986 struct bio *bio,
2987 unsigned int nsegs)
2988 {
2989 struct blk_mq_alloc_data data = {
2990 .q = q,
2991 .nr_tags = 1,
2992 .cmd_flags = bio->bi_opf,
2993 };
2994 struct request *rq;
2995
2996 rq_qos_throttle(q, bio);
2997
2998 if (plug) {
2999 data.nr_tags = plug->nr_ios;
3000 plug->nr_ios = 1;
3001 data.cached_rqs = &plug->cached_rqs;
3002 }
3003
3004 rq = __blk_mq_alloc_requests(&data);
3005 if (rq)
3006 return rq;
3007 rq_qos_cleanup(q, bio);
3008 if (bio->bi_opf & REQ_NOWAIT)
3009 bio_wouldblock_error(bio);
3010 return NULL;
3011 }
3012
3013 /*
3014 * Check if there is a suitable cached request and return it.
3015 */
blk_mq_peek_cached_request(struct blk_plug * plug,struct request_queue * q,blk_opf_t opf)3016 static struct request *blk_mq_peek_cached_request(struct blk_plug *plug,
3017 struct request_queue *q, blk_opf_t opf)
3018 {
3019 enum hctx_type type = blk_mq_get_hctx_type(opf);
3020 struct request *rq;
3021
3022 if (!plug)
3023 return NULL;
3024 rq = rq_list_peek(&plug->cached_rqs);
3025 if (!rq || rq->q != q)
3026 return NULL;
3027 if (type != rq->mq_hctx->type &&
3028 (type != HCTX_TYPE_READ || rq->mq_hctx->type != HCTX_TYPE_DEFAULT))
3029 return NULL;
3030 if (op_is_flush(rq->cmd_flags) != op_is_flush(opf))
3031 return NULL;
3032 return rq;
3033 }
3034
blk_mq_use_cached_rq(struct request * rq,struct blk_plug * plug,struct bio * bio)3035 static void blk_mq_use_cached_rq(struct request *rq, struct blk_plug *plug,
3036 struct bio *bio)
3037 {
3038 if (rq_list_pop(&plug->cached_rqs) != rq)
3039 WARN_ON_ONCE(1);
3040
3041 /*
3042 * If any qos ->throttle() end up blocking, we will have flushed the
3043 * plug and hence killed the cached_rq list as well. Pop this entry
3044 * before we throttle.
3045 */
3046 rq_qos_throttle(rq->q, bio);
3047
3048 blk_mq_rq_time_init(rq, 0);
3049 rq->cmd_flags = bio->bi_opf;
3050 INIT_LIST_HEAD(&rq->queuelist);
3051 }
3052
bio_unaligned(const struct bio * bio,struct request_queue * q)3053 static bool bio_unaligned(const struct bio *bio, struct request_queue *q)
3054 {
3055 unsigned int bs_mask = queue_logical_block_size(q) - 1;
3056
3057 /* .bi_sector of any zero sized bio need to be initialized */
3058 if ((bio->bi_iter.bi_size & bs_mask) ||
3059 ((bio->bi_iter.bi_sector << SECTOR_SHIFT) & bs_mask))
3060 return true;
3061 return false;
3062 }
3063
3064 /**
3065 * blk_mq_submit_bio - Create and send a request to block device.
3066 * @bio: Bio pointer.
3067 *
3068 * Builds up a request structure from @q and @bio and send to the device. The
3069 * request may not be queued directly to hardware if:
3070 * * This request can be merged with another one
3071 * * We want to place request at plug queue for possible future merging
3072 * * There is an IO scheduler active at this queue
3073 *
3074 * It will not queue the request if there is an error with the bio, or at the
3075 * request creation.
3076 */
blk_mq_submit_bio(struct bio * bio)3077 void blk_mq_submit_bio(struct bio *bio)
3078 {
3079 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
3080 struct blk_plug *plug = current->plug;
3081 const int is_sync = op_is_sync(bio->bi_opf);
3082 struct blk_mq_hw_ctx *hctx;
3083 unsigned int nr_segs;
3084 struct request *rq;
3085 blk_status_t ret;
3086
3087 /*
3088 * If the plug has a cached request for this queue, try to use it.
3089 */
3090 rq = blk_mq_peek_cached_request(plug, q, bio->bi_opf);
3091
3092 /*
3093 * A BIO that was released from a zone write plug has already been
3094 * through the preparation in this function, already holds a reference
3095 * on the queue usage counter, and is the only write BIO in-flight for
3096 * the target zone. Go straight to preparing a request for it.
3097 */
3098 if (bio_zone_write_plugging(bio)) {
3099 nr_segs = bio->__bi_nr_segments;
3100 if (rq)
3101 blk_queue_exit(q);
3102 goto new_request;
3103 }
3104
3105 bio = blk_queue_bounce(bio, q);
3106
3107 /*
3108 * The cached request already holds a q_usage_counter reference and we
3109 * don't have to acquire a new one if we use it.
3110 */
3111 if (!rq) {
3112 if (unlikely(bio_queue_enter(bio)))
3113 return;
3114 }
3115
3116 /*
3117 * Device reconfiguration may change logical block size or reduce the
3118 * number of poll queues, so the checks for alignment and poll support
3119 * have to be done with queue usage counter held.
3120 */
3121 if (unlikely(bio_unaligned(bio, q))) {
3122 bio_io_error(bio);
3123 goto queue_exit;
3124 }
3125
3126 if ((bio->bi_opf & REQ_POLLED) && !blk_mq_can_poll(q)) {
3127 bio->bi_status = BLK_STS_NOTSUPP;
3128 bio_endio(bio);
3129 goto queue_exit;
3130 }
3131
3132 bio = __bio_split_to_limits(bio, &q->limits, &nr_segs);
3133 if (!bio)
3134 goto queue_exit;
3135
3136 if (!bio_integrity_prep(bio))
3137 goto queue_exit;
3138
3139 if (blk_mq_attempt_bio_merge(q, bio, nr_segs))
3140 goto queue_exit;
3141
3142 if (bio_needs_zone_write_plugging(bio)) {
3143 if (blk_zone_plug_bio(bio, nr_segs))
3144 goto queue_exit;
3145 }
3146
3147 new_request:
3148 if (!rq) {
3149 rq = blk_mq_get_new_requests(q, plug, bio, nr_segs);
3150 if (unlikely(!rq))
3151 goto queue_exit;
3152 } else {
3153 blk_mq_use_cached_rq(rq, plug, bio);
3154 }
3155
3156 trace_block_getrq(bio);
3157
3158 rq_qos_track(q, rq, bio);
3159
3160 blk_mq_bio_to_request(rq, bio, nr_segs);
3161
3162 ret = blk_crypto_rq_get_keyslot(rq);
3163 if (ret != BLK_STS_OK) {
3164 bio->bi_status = ret;
3165 bio_endio(bio);
3166 blk_mq_free_request(rq);
3167 return;
3168 }
3169
3170 if (bio_zone_write_plugging(bio))
3171 blk_zone_write_plug_init_request(rq);
3172
3173 if (op_is_flush(bio->bi_opf) && blk_insert_flush(rq))
3174 return;
3175
3176 if (plug) {
3177 blk_add_rq_to_plug(plug, rq);
3178 return;
3179 }
3180
3181 hctx = rq->mq_hctx;
3182 if ((rq->rq_flags & RQF_USE_SCHED) ||
3183 (hctx->dispatch_busy && (q->nr_hw_queues == 1 || !is_sync))) {
3184 blk_mq_insert_request(rq, 0);
3185 blk_mq_run_hw_queue(hctx, true);
3186 } else {
3187 blk_mq_run_dispatch_ops(q, blk_mq_try_issue_directly(hctx, rq));
3188 }
3189 return;
3190
3191 queue_exit:
3192 /*
3193 * Don't drop the queue reference if we were trying to use a cached
3194 * request and thus didn't acquire one.
3195 */
3196 if (!rq)
3197 blk_queue_exit(q);
3198 }
3199
3200 #ifdef CONFIG_BLK_MQ_STACKING
3201 /**
3202 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
3203 * @rq: the request being queued
3204 */
blk_insert_cloned_request(struct request * rq)3205 blk_status_t blk_insert_cloned_request(struct request *rq)
3206 {
3207 struct request_queue *q = rq->q;
3208 unsigned int max_sectors = blk_queue_get_max_sectors(rq);
3209 unsigned int max_segments = blk_rq_get_max_segments(rq);
3210 blk_status_t ret;
3211
3212 if (blk_rq_sectors(rq) > max_sectors) {
3213 /*
3214 * SCSI device does not have a good way to return if
3215 * Write Same/Zero is actually supported. If a device rejects
3216 * a non-read/write command (discard, write same,etc.) the
3217 * low-level device driver will set the relevant queue limit to
3218 * 0 to prevent blk-lib from issuing more of the offending
3219 * operations. Commands queued prior to the queue limit being
3220 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
3221 * errors being propagated to upper layers.
3222 */
3223 if (max_sectors == 0)
3224 return BLK_STS_NOTSUPP;
3225
3226 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
3227 __func__, blk_rq_sectors(rq), max_sectors);
3228 return BLK_STS_IOERR;
3229 }
3230
3231 /*
3232 * The queue settings related to segment counting may differ from the
3233 * original queue.
3234 */
3235 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
3236 if (rq->nr_phys_segments > max_segments) {
3237 printk(KERN_ERR "%s: over max segments limit. (%u > %u)\n",
3238 __func__, rq->nr_phys_segments, max_segments);
3239 return BLK_STS_IOERR;
3240 }
3241
3242 if (q->disk && should_fail_request(q->disk->part0, blk_rq_bytes(rq)))
3243 return BLK_STS_IOERR;
3244
3245 ret = blk_crypto_rq_get_keyslot(rq);
3246 if (ret != BLK_STS_OK)
3247 return ret;
3248
3249 blk_account_io_start(rq);
3250
3251 /*
3252 * Since we have a scheduler attached on the top device,
3253 * bypass a potential scheduler on the bottom device for
3254 * insert.
3255 */
3256 blk_mq_run_dispatch_ops(q,
3257 ret = blk_mq_request_issue_directly(rq, true));
3258 if (ret)
3259 blk_account_io_done(rq, blk_time_get_ns());
3260 return ret;
3261 }
3262 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
3263
3264 /**
3265 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3266 * @rq: the clone request to be cleaned up
3267 *
3268 * Description:
3269 * Free all bios in @rq for a cloned request.
3270 */
blk_rq_unprep_clone(struct request * rq)3271 void blk_rq_unprep_clone(struct request *rq)
3272 {
3273 struct bio *bio;
3274
3275 while ((bio = rq->bio) != NULL) {
3276 rq->bio = bio->bi_next;
3277
3278 bio_put(bio);
3279 }
3280 }
3281 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3282
3283 /**
3284 * blk_rq_prep_clone - Helper function to setup clone request
3285 * @rq: the request to be setup
3286 * @rq_src: original request to be cloned
3287 * @bs: bio_set that bios for clone are allocated from
3288 * @gfp_mask: memory allocation mask for bio
3289 * @bio_ctr: setup function to be called for each clone bio.
3290 * Returns %0 for success, non %0 for failure.
3291 * @data: private data to be passed to @bio_ctr
3292 *
3293 * Description:
3294 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3295 * Also, pages which the original bios are pointing to are not copied
3296 * and the cloned bios just point same pages.
3297 * So cloned bios must be completed before original bios, which means
3298 * the caller must complete @rq before @rq_src.
3299 */
blk_rq_prep_clone(struct request * rq,struct request * rq_src,struct bio_set * bs,gfp_t gfp_mask,int (* bio_ctr)(struct bio *,struct bio *,void *),void * data)3300 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3301 struct bio_set *bs, gfp_t gfp_mask,
3302 int (*bio_ctr)(struct bio *, struct bio *, void *),
3303 void *data)
3304 {
3305 struct bio *bio, *bio_src;
3306
3307 if (!bs)
3308 bs = &fs_bio_set;
3309
3310 __rq_for_each_bio(bio_src, rq_src) {
3311 bio = bio_alloc_clone(rq->q->disk->part0, bio_src, gfp_mask,
3312 bs);
3313 if (!bio)
3314 goto free_and_out;
3315
3316 if (bio_ctr && bio_ctr(bio, bio_src, data))
3317 goto free_and_out;
3318
3319 if (rq->bio) {
3320 rq->biotail->bi_next = bio;
3321 rq->biotail = bio;
3322 } else {
3323 rq->bio = rq->biotail = bio;
3324 }
3325 bio = NULL;
3326 }
3327
3328 /* Copy attributes of the original request to the clone request. */
3329 rq->__sector = blk_rq_pos(rq_src);
3330 rq->__data_len = blk_rq_bytes(rq_src);
3331 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
3332 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
3333 rq->special_vec = rq_src->special_vec;
3334 }
3335 rq->nr_phys_segments = rq_src->nr_phys_segments;
3336 rq->ioprio = rq_src->ioprio;
3337 rq->write_hint = rq_src->write_hint;
3338
3339 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
3340 goto free_and_out;
3341
3342 return 0;
3343
3344 free_and_out:
3345 if (bio)
3346 bio_put(bio);
3347 blk_rq_unprep_clone(rq);
3348
3349 return -ENOMEM;
3350 }
3351 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3352 #endif /* CONFIG_BLK_MQ_STACKING */
3353
3354 /*
3355 * Steal bios from a request and add them to a bio list.
3356 * The request must not have been partially completed before.
3357 */
blk_steal_bios(struct bio_list * list,struct request * rq)3358 void blk_steal_bios(struct bio_list *list, struct request *rq)
3359 {
3360 if (rq->bio) {
3361 if (list->tail)
3362 list->tail->bi_next = rq->bio;
3363 else
3364 list->head = rq->bio;
3365 list->tail = rq->biotail;
3366
3367 rq->bio = NULL;
3368 rq->biotail = NULL;
3369 }
3370
3371 rq->__data_len = 0;
3372 }
3373 EXPORT_SYMBOL_GPL(blk_steal_bios);
3374
order_to_size(unsigned int order)3375 static size_t order_to_size(unsigned int order)
3376 {
3377 return (size_t)PAGE_SIZE << order;
3378 }
3379
3380 /* called before freeing request pool in @tags */
blk_mq_clear_rq_mapping(struct blk_mq_tags * drv_tags,struct blk_mq_tags * tags)3381 static void blk_mq_clear_rq_mapping(struct blk_mq_tags *drv_tags,
3382 struct blk_mq_tags *tags)
3383 {
3384 struct page *page;
3385 unsigned long flags;
3386
3387 /*
3388 * There is no need to clear mapping if driver tags is not initialized
3389 * or the mapping belongs to the driver tags.
3390 */
3391 if (!drv_tags || drv_tags == tags)
3392 return;
3393
3394 list_for_each_entry(page, &tags->page_list, lru) {
3395 unsigned long start = (unsigned long)page_address(page);
3396 unsigned long end = start + order_to_size(page->private);
3397 int i;
3398
3399 for (i = 0; i < drv_tags->nr_tags; i++) {
3400 struct request *rq = drv_tags->rqs[i];
3401 unsigned long rq_addr = (unsigned long)rq;
3402
3403 if (rq_addr >= start && rq_addr < end) {
3404 WARN_ON_ONCE(req_ref_read(rq) != 0);
3405 cmpxchg(&drv_tags->rqs[i], rq, NULL);
3406 }
3407 }
3408 }
3409
3410 /*
3411 * Wait until all pending iteration is done.
3412 *
3413 * Request reference is cleared and it is guaranteed to be observed
3414 * after the ->lock is released.
3415 */
3416 spin_lock_irqsave(&drv_tags->lock, flags);
3417 spin_unlock_irqrestore(&drv_tags->lock, flags);
3418 }
3419
blk_mq_free_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)3420 void blk_mq_free_rqs(struct blk_mq_tag_set *set, struct blk_mq_tags *tags,
3421 unsigned int hctx_idx)
3422 {
3423 struct blk_mq_tags *drv_tags;
3424 struct page *page;
3425
3426 if (list_empty(&tags->page_list))
3427 return;
3428
3429 if (blk_mq_is_shared_tags(set->flags))
3430 drv_tags = set->shared_tags;
3431 else
3432 drv_tags = set->tags[hctx_idx];
3433
3434 if (tags->static_rqs && set->ops->exit_request) {
3435 int i;
3436
3437 for (i = 0; i < tags->nr_tags; i++) {
3438 struct request *rq = tags->static_rqs[i];
3439
3440 if (!rq)
3441 continue;
3442 set->ops->exit_request(set, rq, hctx_idx);
3443 tags->static_rqs[i] = NULL;
3444 }
3445 }
3446
3447 blk_mq_clear_rq_mapping(drv_tags, tags);
3448
3449 while (!list_empty(&tags->page_list)) {
3450 page = list_first_entry(&tags->page_list, struct page, lru);
3451 list_del_init(&page->lru);
3452 /*
3453 * Remove kmemleak object previously allocated in
3454 * blk_mq_alloc_rqs().
3455 */
3456 kmemleak_free(page_address(page));
3457 __free_pages(page, page->private);
3458 }
3459 }
3460
blk_mq_free_rq_map(struct blk_mq_tags * tags)3461 void blk_mq_free_rq_map(struct blk_mq_tags *tags)
3462 {
3463 kfree(tags->rqs);
3464 tags->rqs = NULL;
3465 kfree(tags->static_rqs);
3466 tags->static_rqs = NULL;
3467
3468 blk_mq_free_tags(tags);
3469 }
3470
hctx_idx_to_type(struct blk_mq_tag_set * set,unsigned int hctx_idx)3471 static enum hctx_type hctx_idx_to_type(struct blk_mq_tag_set *set,
3472 unsigned int hctx_idx)
3473 {
3474 int i;
3475
3476 for (i = 0; i < set->nr_maps; i++) {
3477 unsigned int start = set->map[i].queue_offset;
3478 unsigned int end = start + set->map[i].nr_queues;
3479
3480 if (hctx_idx >= start && hctx_idx < end)
3481 break;
3482 }
3483
3484 if (i >= set->nr_maps)
3485 i = HCTX_TYPE_DEFAULT;
3486
3487 return i;
3488 }
3489
blk_mq_get_hctx_node(struct blk_mq_tag_set * set,unsigned int hctx_idx)3490 static int blk_mq_get_hctx_node(struct blk_mq_tag_set *set,
3491 unsigned int hctx_idx)
3492 {
3493 enum hctx_type type = hctx_idx_to_type(set, hctx_idx);
3494
3495 return blk_mq_hw_queue_to_node(&set->map[type], hctx_idx);
3496 }
3497
blk_mq_alloc_rq_map(struct blk_mq_tag_set * set,unsigned int hctx_idx,unsigned int nr_tags,unsigned int reserved_tags)3498 static struct blk_mq_tags *blk_mq_alloc_rq_map(struct blk_mq_tag_set *set,
3499 unsigned int hctx_idx,
3500 unsigned int nr_tags,
3501 unsigned int reserved_tags)
3502 {
3503 int node = blk_mq_get_hctx_node(set, hctx_idx);
3504 struct blk_mq_tags *tags;
3505
3506 if (node == NUMA_NO_NODE)
3507 node = set->numa_node;
3508
3509 tags = blk_mq_init_tags(nr_tags, reserved_tags, node,
3510 BLK_MQ_FLAG_TO_ALLOC_POLICY(set->flags));
3511 if (!tags)
3512 return NULL;
3513
3514 tags->rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3515 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3516 node);
3517 if (!tags->rqs)
3518 goto err_free_tags;
3519
3520 tags->static_rqs = kcalloc_node(nr_tags, sizeof(struct request *),
3521 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY,
3522 node);
3523 if (!tags->static_rqs)
3524 goto err_free_rqs;
3525
3526 return tags;
3527
3528 err_free_rqs:
3529 kfree(tags->rqs);
3530 err_free_tags:
3531 blk_mq_free_tags(tags);
3532 return NULL;
3533 }
3534
blk_mq_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,int node)3535 static int blk_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
3536 unsigned int hctx_idx, int node)
3537 {
3538 int ret;
3539
3540 if (set->ops->init_request) {
3541 ret = set->ops->init_request(set, rq, hctx_idx, node);
3542 if (ret)
3543 return ret;
3544 }
3545
3546 WRITE_ONCE(rq->state, MQ_RQ_IDLE);
3547 return 0;
3548 }
3549
blk_mq_alloc_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx,unsigned int depth)3550 static int blk_mq_alloc_rqs(struct blk_mq_tag_set *set,
3551 struct blk_mq_tags *tags,
3552 unsigned int hctx_idx, unsigned int depth)
3553 {
3554 unsigned int i, j, entries_per_page, max_order = 4;
3555 int node = blk_mq_get_hctx_node(set, hctx_idx);
3556 size_t rq_size, left;
3557
3558 if (node == NUMA_NO_NODE)
3559 node = set->numa_node;
3560
3561 INIT_LIST_HEAD(&tags->page_list);
3562
3563 /*
3564 * rq_size is the size of the request plus driver payload, rounded
3565 * to the cacheline size
3566 */
3567 rq_size = round_up(sizeof(struct request) + set->cmd_size,
3568 cache_line_size());
3569 left = rq_size * depth;
3570
3571 for (i = 0; i < depth; ) {
3572 int this_order = max_order;
3573 struct page *page;
3574 int to_do;
3575 void *p;
3576
3577 while (this_order && left < order_to_size(this_order - 1))
3578 this_order--;
3579
3580 do {
3581 page = alloc_pages_node(node,
3582 GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY | __GFP_ZERO,
3583 this_order);
3584 if (page)
3585 break;
3586 if (!this_order--)
3587 break;
3588 if (order_to_size(this_order) < rq_size)
3589 break;
3590 } while (1);
3591
3592 if (!page)
3593 goto fail;
3594
3595 page->private = this_order;
3596 list_add_tail(&page->lru, &tags->page_list);
3597
3598 p = page_address(page);
3599 /*
3600 * Allow kmemleak to scan these pages as they contain pointers
3601 * to additional allocations like via ops->init_request().
3602 */
3603 kmemleak_alloc(p, order_to_size(this_order), 1, GFP_NOIO);
3604 entries_per_page = order_to_size(this_order) / rq_size;
3605 to_do = min(entries_per_page, depth - i);
3606 left -= to_do * rq_size;
3607 for (j = 0; j < to_do; j++) {
3608 struct request *rq = p;
3609
3610 tags->static_rqs[i] = rq;
3611 if (blk_mq_init_request(set, rq, hctx_idx, node)) {
3612 tags->static_rqs[i] = NULL;
3613 goto fail;
3614 }
3615
3616 p += rq_size;
3617 i++;
3618 }
3619 }
3620 return 0;
3621
3622 fail:
3623 blk_mq_free_rqs(set, tags, hctx_idx);
3624 return -ENOMEM;
3625 }
3626
3627 struct rq_iter_data {
3628 struct blk_mq_hw_ctx *hctx;
3629 bool has_rq;
3630 };
3631
blk_mq_has_request(struct request * rq,void * data)3632 static bool blk_mq_has_request(struct request *rq, void *data)
3633 {
3634 struct rq_iter_data *iter_data = data;
3635
3636 if (rq->mq_hctx != iter_data->hctx)
3637 return true;
3638 iter_data->has_rq = true;
3639 return false;
3640 }
3641
blk_mq_hctx_has_requests(struct blk_mq_hw_ctx * hctx)3642 static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx)
3643 {
3644 struct blk_mq_tags *tags = hctx->sched_tags ?
3645 hctx->sched_tags : hctx->tags;
3646 struct rq_iter_data data = {
3647 .hctx = hctx,
3648 };
3649
3650 blk_mq_all_tag_iter(tags, blk_mq_has_request, &data);
3651 return data.has_rq;
3652 }
3653
blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx * hctx,unsigned int this_cpu)3654 static bool blk_mq_hctx_has_online_cpu(struct blk_mq_hw_ctx *hctx,
3655 unsigned int this_cpu)
3656 {
3657 enum hctx_type type = hctx->type;
3658 int cpu;
3659
3660 /*
3661 * hctx->cpumask has to rule out isolated CPUs, but userspace still
3662 * might submit IOs on these isolated CPUs, so use the queue map to
3663 * check if all CPUs mapped to this hctx are offline
3664 */
3665 for_each_online_cpu(cpu) {
3666 struct blk_mq_hw_ctx *h = blk_mq_map_queue_type(hctx->queue,
3667 type, cpu);
3668
3669 if (h != hctx)
3670 continue;
3671
3672 /* this hctx has at least one online CPU */
3673 if (this_cpu != cpu)
3674 return true;
3675 }
3676
3677 return false;
3678 }
3679
blk_mq_hctx_notify_offline(unsigned int cpu,struct hlist_node * node)3680 static int blk_mq_hctx_notify_offline(unsigned int cpu, struct hlist_node *node)
3681 {
3682 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3683 struct blk_mq_hw_ctx, cpuhp_online);
3684
3685 if (blk_mq_hctx_has_online_cpu(hctx, cpu))
3686 return 0;
3687
3688 /*
3689 * Prevent new request from being allocated on the current hctx.
3690 *
3691 * The smp_mb__after_atomic() Pairs with the implied barrier in
3692 * test_and_set_bit_lock in sbitmap_get(). Ensures the inactive flag is
3693 * seen once we return from the tag allocator.
3694 */
3695 set_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3696 smp_mb__after_atomic();
3697
3698 /*
3699 * Try to grab a reference to the queue and wait for any outstanding
3700 * requests. If we could not grab a reference the queue has been
3701 * frozen and there are no requests.
3702 */
3703 if (percpu_ref_tryget(&hctx->queue->q_usage_counter)) {
3704 while (blk_mq_hctx_has_requests(hctx))
3705 msleep(5);
3706 percpu_ref_put(&hctx->queue->q_usage_counter);
3707 }
3708
3709 return 0;
3710 }
3711
3712 /*
3713 * Check if one CPU is mapped to the specified hctx
3714 *
3715 * Isolated CPUs have been ruled out from hctx->cpumask, which is supposed
3716 * to be used for scheduling kworker only. For other usage, please call this
3717 * helper for checking if one CPU belongs to the specified hctx
3718 */
blk_mq_cpu_mapped_to_hctx(unsigned int cpu,const struct blk_mq_hw_ctx * hctx)3719 static bool blk_mq_cpu_mapped_to_hctx(unsigned int cpu,
3720 const struct blk_mq_hw_ctx *hctx)
3721 {
3722 struct blk_mq_hw_ctx *mapped_hctx = blk_mq_map_queue_type(hctx->queue,
3723 hctx->type, cpu);
3724
3725 return mapped_hctx == hctx;
3726 }
3727
blk_mq_hctx_notify_online(unsigned int cpu,struct hlist_node * node)3728 static int blk_mq_hctx_notify_online(unsigned int cpu, struct hlist_node *node)
3729 {
3730 struct blk_mq_hw_ctx *hctx = hlist_entry_safe(node,
3731 struct blk_mq_hw_ctx, cpuhp_online);
3732
3733 if (blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3734 clear_bit(BLK_MQ_S_INACTIVE, &hctx->state);
3735 return 0;
3736 }
3737
3738 /*
3739 * 'cpu' is going away. splice any existing rq_list entries from this
3740 * software queue to the hw queue dispatch list, and ensure that it
3741 * gets run.
3742 */
blk_mq_hctx_notify_dead(unsigned int cpu,struct hlist_node * node)3743 static int blk_mq_hctx_notify_dead(unsigned int cpu, struct hlist_node *node)
3744 {
3745 struct blk_mq_hw_ctx *hctx;
3746 struct blk_mq_ctx *ctx;
3747 LIST_HEAD(tmp);
3748 enum hctx_type type;
3749
3750 hctx = hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_dead);
3751 if (!blk_mq_cpu_mapped_to_hctx(cpu, hctx))
3752 return 0;
3753
3754 ctx = __blk_mq_get_ctx(hctx->queue, cpu);
3755 type = hctx->type;
3756
3757 spin_lock(&ctx->lock);
3758 if (!list_empty(&ctx->rq_lists[type])) {
3759 list_splice_init(&ctx->rq_lists[type], &tmp);
3760 blk_mq_hctx_clear_pending(hctx, ctx);
3761 }
3762 spin_unlock(&ctx->lock);
3763
3764 if (list_empty(&tmp))
3765 return 0;
3766
3767 spin_lock(&hctx->lock);
3768 list_splice_tail_init(&tmp, &hctx->dispatch);
3769 spin_unlock(&hctx->lock);
3770
3771 blk_mq_run_hw_queue(hctx, true);
3772 return 0;
3773 }
3774
__blk_mq_remove_cpuhp(struct blk_mq_hw_ctx * hctx)3775 static void __blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3776 {
3777 lockdep_assert_held(&blk_mq_cpuhp_lock);
3778
3779 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3780 !hlist_unhashed(&hctx->cpuhp_online)) {
3781 cpuhp_state_remove_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3782 &hctx->cpuhp_online);
3783 INIT_HLIST_NODE(&hctx->cpuhp_online);
3784 }
3785
3786 if (!hlist_unhashed(&hctx->cpuhp_dead)) {
3787 cpuhp_state_remove_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3788 &hctx->cpuhp_dead);
3789 INIT_HLIST_NODE(&hctx->cpuhp_dead);
3790 }
3791 }
3792
blk_mq_remove_cpuhp(struct blk_mq_hw_ctx * hctx)3793 static void blk_mq_remove_cpuhp(struct blk_mq_hw_ctx *hctx)
3794 {
3795 mutex_lock(&blk_mq_cpuhp_lock);
3796 __blk_mq_remove_cpuhp(hctx);
3797 mutex_unlock(&blk_mq_cpuhp_lock);
3798 }
3799
__blk_mq_add_cpuhp(struct blk_mq_hw_ctx * hctx)3800 static void __blk_mq_add_cpuhp(struct blk_mq_hw_ctx *hctx)
3801 {
3802 lockdep_assert_held(&blk_mq_cpuhp_lock);
3803
3804 if (!(hctx->flags & BLK_MQ_F_STACKING) &&
3805 hlist_unhashed(&hctx->cpuhp_online))
3806 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3807 &hctx->cpuhp_online);
3808
3809 if (hlist_unhashed(&hctx->cpuhp_dead))
3810 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD,
3811 &hctx->cpuhp_dead);
3812 }
3813
__blk_mq_remove_cpuhp_list(struct list_head * head)3814 static void __blk_mq_remove_cpuhp_list(struct list_head *head)
3815 {
3816 struct blk_mq_hw_ctx *hctx;
3817
3818 lockdep_assert_held(&blk_mq_cpuhp_lock);
3819
3820 list_for_each_entry(hctx, head, hctx_list)
3821 __blk_mq_remove_cpuhp(hctx);
3822 }
3823
3824 /*
3825 * Unregister cpuhp callbacks from exited hw queues
3826 *
3827 * Safe to call if this `request_queue` is live
3828 */
blk_mq_remove_hw_queues_cpuhp(struct request_queue * q)3829 static void blk_mq_remove_hw_queues_cpuhp(struct request_queue *q)
3830 {
3831 LIST_HEAD(hctx_list);
3832
3833 spin_lock(&q->unused_hctx_lock);
3834 list_splice_init(&q->unused_hctx_list, &hctx_list);
3835 spin_unlock(&q->unused_hctx_lock);
3836
3837 mutex_lock(&blk_mq_cpuhp_lock);
3838 __blk_mq_remove_cpuhp_list(&hctx_list);
3839 mutex_unlock(&blk_mq_cpuhp_lock);
3840
3841 spin_lock(&q->unused_hctx_lock);
3842 list_splice(&hctx_list, &q->unused_hctx_list);
3843 spin_unlock(&q->unused_hctx_lock);
3844 }
3845
3846 /*
3847 * Register cpuhp callbacks from all hw queues
3848 *
3849 * Safe to call if this `request_queue` is live
3850 */
blk_mq_add_hw_queues_cpuhp(struct request_queue * q)3851 static void blk_mq_add_hw_queues_cpuhp(struct request_queue *q)
3852 {
3853 struct blk_mq_hw_ctx *hctx;
3854 unsigned long i;
3855
3856 mutex_lock(&blk_mq_cpuhp_lock);
3857 queue_for_each_hw_ctx(q, hctx, i)
3858 __blk_mq_add_cpuhp(hctx);
3859 mutex_unlock(&blk_mq_cpuhp_lock);
3860 }
3861
3862 /*
3863 * Before freeing hw queue, clearing the flush request reference in
3864 * tags->rqs[] for avoiding potential UAF.
3865 */
blk_mq_clear_flush_rq_mapping(struct blk_mq_tags * tags,unsigned int queue_depth,struct request * flush_rq)3866 static void blk_mq_clear_flush_rq_mapping(struct blk_mq_tags *tags,
3867 unsigned int queue_depth, struct request *flush_rq)
3868 {
3869 int i;
3870 unsigned long flags;
3871
3872 /* The hw queue may not be mapped yet */
3873 if (!tags)
3874 return;
3875
3876 WARN_ON_ONCE(req_ref_read(flush_rq) != 0);
3877
3878 for (i = 0; i < queue_depth; i++)
3879 cmpxchg(&tags->rqs[i], flush_rq, NULL);
3880
3881 /*
3882 * Wait until all pending iteration is done.
3883 *
3884 * Request reference is cleared and it is guaranteed to be observed
3885 * after the ->lock is released.
3886 */
3887 spin_lock_irqsave(&tags->lock, flags);
3888 spin_unlock_irqrestore(&tags->lock, flags);
3889 }
3890
3891 /* 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)3892 static void blk_mq_exit_hctx(struct request_queue *q,
3893 struct blk_mq_tag_set *set,
3894 struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
3895 {
3896 struct request *flush_rq = hctx->fq->flush_rq;
3897
3898 if (blk_mq_hw_queue_mapped(hctx))
3899 blk_mq_tag_idle(hctx);
3900
3901 if (blk_queue_init_done(q))
3902 blk_mq_clear_flush_rq_mapping(set->tags[hctx_idx],
3903 set->queue_depth, flush_rq);
3904 if (set->ops->exit_request)
3905 set->ops->exit_request(set, flush_rq, hctx_idx);
3906
3907 if (set->ops->exit_hctx)
3908 set->ops->exit_hctx(hctx, hctx_idx);
3909
3910 xa_erase(&q->hctx_table, hctx_idx);
3911
3912 spin_lock(&q->unused_hctx_lock);
3913 list_add(&hctx->hctx_list, &q->unused_hctx_list);
3914 spin_unlock(&q->unused_hctx_lock);
3915 }
3916
blk_mq_exit_hw_queues(struct request_queue * q,struct blk_mq_tag_set * set,int nr_queue)3917 static void blk_mq_exit_hw_queues(struct request_queue *q,
3918 struct blk_mq_tag_set *set, int nr_queue)
3919 {
3920 struct blk_mq_hw_ctx *hctx;
3921 unsigned long i;
3922
3923 queue_for_each_hw_ctx(q, hctx, i) {
3924 if (i == nr_queue)
3925 break;
3926 blk_mq_remove_cpuhp(hctx);
3927 blk_mq_exit_hctx(q, set, hctx, i);
3928 }
3929 }
3930
blk_mq_init_hctx(struct request_queue * q,struct blk_mq_tag_set * set,struct blk_mq_hw_ctx * hctx,unsigned hctx_idx)3931 static int blk_mq_init_hctx(struct request_queue *q,
3932 struct blk_mq_tag_set *set,
3933 struct blk_mq_hw_ctx *hctx, unsigned hctx_idx)
3934 {
3935 hctx->queue_num = hctx_idx;
3936
3937 hctx->tags = set->tags[hctx_idx];
3938
3939 if (set->ops->init_hctx &&
3940 set->ops->init_hctx(hctx, set->driver_data, hctx_idx))
3941 goto fail;
3942
3943 if (blk_mq_init_request(set, hctx->fq->flush_rq, hctx_idx,
3944 hctx->numa_node))
3945 goto exit_hctx;
3946
3947 if (xa_insert(&q->hctx_table, hctx_idx, hctx, GFP_KERNEL))
3948 goto exit_flush_rq;
3949
3950 if (!(hctx->flags & BLK_MQ_F_STACKING))
3951 cpuhp_state_add_instance_nocalls(CPUHP_AP_BLK_MQ_ONLINE,
3952 &hctx->cpuhp_online);
3953 cpuhp_state_add_instance_nocalls(CPUHP_BLK_MQ_DEAD, &hctx->cpuhp_dead);
3954
3955 return 0;
3956
3957 exit_flush_rq:
3958 if (set->ops->exit_request)
3959 set->ops->exit_request(set, hctx->fq->flush_rq, hctx_idx);
3960 exit_hctx:
3961 if (set->ops->exit_hctx)
3962 set->ops->exit_hctx(hctx, hctx_idx);
3963 fail:
3964 return -1;
3965 }
3966
3967 static struct blk_mq_hw_ctx *
blk_mq_alloc_hctx(struct request_queue * q,struct blk_mq_tag_set * set,int node)3968 blk_mq_alloc_hctx(struct request_queue *q, struct blk_mq_tag_set *set,
3969 int node)
3970 {
3971 struct blk_mq_hw_ctx *hctx;
3972 gfp_t gfp = GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY;
3973
3974 hctx = kzalloc_node(sizeof(struct blk_mq_hw_ctx), gfp, node);
3975 if (!hctx)
3976 goto fail_alloc_hctx;
3977
3978 if (!zalloc_cpumask_var_node(&hctx->cpumask, gfp, node))
3979 goto free_hctx;
3980
3981 atomic_set(&hctx->nr_active, 0);
3982 if (node == NUMA_NO_NODE)
3983 node = set->numa_node;
3984 hctx->numa_node = node;
3985
3986 INIT_DELAYED_WORK(&hctx->run_work, blk_mq_run_work_fn);
3987 spin_lock_init(&hctx->lock);
3988 INIT_LIST_HEAD(&hctx->dispatch);
3989 INIT_HLIST_NODE(&hctx->cpuhp_dead);
3990 INIT_HLIST_NODE(&hctx->cpuhp_online);
3991 hctx->queue = q;
3992 hctx->flags = set->flags & ~BLK_MQ_F_TAG_QUEUE_SHARED;
3993
3994 INIT_LIST_HEAD(&hctx->hctx_list);
3995
3996 /*
3997 * Allocate space for all possible cpus to avoid allocation at
3998 * runtime
3999 */
4000 hctx->ctxs = kmalloc_array_node(nr_cpu_ids, sizeof(void *),
4001 gfp, node);
4002 if (!hctx->ctxs)
4003 goto free_cpumask;
4004
4005 if (sbitmap_init_node(&hctx->ctx_map, nr_cpu_ids, ilog2(8),
4006 gfp, node, false, false))
4007 goto free_ctxs;
4008 hctx->nr_ctx = 0;
4009
4010 spin_lock_init(&hctx->dispatch_wait_lock);
4011 init_waitqueue_func_entry(&hctx->dispatch_wait, blk_mq_dispatch_wake);
4012 INIT_LIST_HEAD(&hctx->dispatch_wait.entry);
4013
4014 hctx->fq = blk_alloc_flush_queue(hctx->numa_node, set->cmd_size, gfp);
4015 if (!hctx->fq)
4016 goto free_bitmap;
4017
4018 blk_mq_hctx_kobj_init(hctx);
4019
4020 return hctx;
4021
4022 free_bitmap:
4023 sbitmap_free(&hctx->ctx_map);
4024 free_ctxs:
4025 kfree(hctx->ctxs);
4026 free_cpumask:
4027 free_cpumask_var(hctx->cpumask);
4028 free_hctx:
4029 kfree(hctx);
4030 fail_alloc_hctx:
4031 return NULL;
4032 }
4033
blk_mq_init_cpu_queues(struct request_queue * q,unsigned int nr_hw_queues)4034 static void blk_mq_init_cpu_queues(struct request_queue *q,
4035 unsigned int nr_hw_queues)
4036 {
4037 struct blk_mq_tag_set *set = q->tag_set;
4038 unsigned int i, j;
4039
4040 for_each_possible_cpu(i) {
4041 struct blk_mq_ctx *__ctx = per_cpu_ptr(q->queue_ctx, i);
4042 struct blk_mq_hw_ctx *hctx;
4043 int k;
4044
4045 __ctx->cpu = i;
4046 spin_lock_init(&__ctx->lock);
4047 for (k = HCTX_TYPE_DEFAULT; k < HCTX_MAX_TYPES; k++)
4048 INIT_LIST_HEAD(&__ctx->rq_lists[k]);
4049
4050 __ctx->queue = q;
4051
4052 /*
4053 * Set local node, IFF we have more than one hw queue. If
4054 * not, we remain on the home node of the device
4055 */
4056 for (j = 0; j < set->nr_maps; j++) {
4057 hctx = blk_mq_map_queue_type(q, j, i);
4058 if (nr_hw_queues > 1 && hctx->numa_node == NUMA_NO_NODE)
4059 hctx->numa_node = cpu_to_node(i);
4060 }
4061 }
4062 }
4063
blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set * set,unsigned int hctx_idx,unsigned int depth)4064 struct blk_mq_tags *blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4065 unsigned int hctx_idx,
4066 unsigned int depth)
4067 {
4068 struct blk_mq_tags *tags;
4069 int ret;
4070
4071 tags = blk_mq_alloc_rq_map(set, hctx_idx, depth, set->reserved_tags);
4072 if (!tags)
4073 return NULL;
4074
4075 ret = blk_mq_alloc_rqs(set, tags, hctx_idx, depth);
4076 if (ret) {
4077 blk_mq_free_rq_map(tags);
4078 return NULL;
4079 }
4080
4081 return tags;
4082 }
4083
__blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set * set,int hctx_idx)4084 static bool __blk_mq_alloc_map_and_rqs(struct blk_mq_tag_set *set,
4085 int hctx_idx)
4086 {
4087 if (blk_mq_is_shared_tags(set->flags)) {
4088 set->tags[hctx_idx] = set->shared_tags;
4089
4090 return true;
4091 }
4092
4093 set->tags[hctx_idx] = blk_mq_alloc_map_and_rqs(set, hctx_idx,
4094 set->queue_depth);
4095
4096 return set->tags[hctx_idx];
4097 }
4098
blk_mq_free_map_and_rqs(struct blk_mq_tag_set * set,struct blk_mq_tags * tags,unsigned int hctx_idx)4099 void blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4100 struct blk_mq_tags *tags,
4101 unsigned int hctx_idx)
4102 {
4103 if (tags) {
4104 blk_mq_free_rqs(set, tags, hctx_idx);
4105 blk_mq_free_rq_map(tags);
4106 }
4107 }
4108
__blk_mq_free_map_and_rqs(struct blk_mq_tag_set * set,unsigned int hctx_idx)4109 static void __blk_mq_free_map_and_rqs(struct blk_mq_tag_set *set,
4110 unsigned int hctx_idx)
4111 {
4112 if (!blk_mq_is_shared_tags(set->flags))
4113 blk_mq_free_map_and_rqs(set, set->tags[hctx_idx], hctx_idx);
4114
4115 set->tags[hctx_idx] = NULL;
4116 }
4117
blk_mq_map_swqueue(struct request_queue * q)4118 static void blk_mq_map_swqueue(struct request_queue *q)
4119 {
4120 unsigned int j, hctx_idx;
4121 unsigned long i;
4122 struct blk_mq_hw_ctx *hctx;
4123 struct blk_mq_ctx *ctx;
4124 struct blk_mq_tag_set *set = q->tag_set;
4125
4126 queue_for_each_hw_ctx(q, hctx, i) {
4127 cpumask_clear(hctx->cpumask);
4128 hctx->nr_ctx = 0;
4129 hctx->dispatch_from = NULL;
4130 }
4131
4132 /*
4133 * Map software to hardware queues.
4134 *
4135 * If the cpu isn't present, the cpu is mapped to first hctx.
4136 */
4137 for_each_possible_cpu(i) {
4138
4139 ctx = per_cpu_ptr(q->queue_ctx, i);
4140 for (j = 0; j < set->nr_maps; j++) {
4141 if (!set->map[j].nr_queues) {
4142 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4143 HCTX_TYPE_DEFAULT, i);
4144 continue;
4145 }
4146 hctx_idx = set->map[j].mq_map[i];
4147 /* unmapped hw queue can be remapped after CPU topo changed */
4148 if (!set->tags[hctx_idx] &&
4149 !__blk_mq_alloc_map_and_rqs(set, hctx_idx)) {
4150 /*
4151 * If tags initialization fail for some hctx,
4152 * that hctx won't be brought online. In this
4153 * case, remap the current ctx to hctx[0] which
4154 * is guaranteed to always have tags allocated
4155 */
4156 set->map[j].mq_map[i] = 0;
4157 }
4158
4159 hctx = blk_mq_map_queue_type(q, j, i);
4160 ctx->hctxs[j] = hctx;
4161 /*
4162 * If the CPU is already set in the mask, then we've
4163 * mapped this one already. This can happen if
4164 * devices share queues across queue maps.
4165 */
4166 if (cpumask_test_cpu(i, hctx->cpumask))
4167 continue;
4168
4169 cpumask_set_cpu(i, hctx->cpumask);
4170 hctx->type = j;
4171 ctx->index_hw[hctx->type] = hctx->nr_ctx;
4172 hctx->ctxs[hctx->nr_ctx++] = ctx;
4173
4174 /*
4175 * If the nr_ctx type overflows, we have exceeded the
4176 * amount of sw queues we can support.
4177 */
4178 BUG_ON(!hctx->nr_ctx);
4179 }
4180
4181 for (; j < HCTX_MAX_TYPES; j++)
4182 ctx->hctxs[j] = blk_mq_map_queue_type(q,
4183 HCTX_TYPE_DEFAULT, i);
4184 }
4185
4186 queue_for_each_hw_ctx(q, hctx, i) {
4187 int cpu;
4188
4189 /*
4190 * If no software queues are mapped to this hardware queue,
4191 * disable it and free the request entries.
4192 */
4193 if (!hctx->nr_ctx) {
4194 /* Never unmap queue 0. We need it as a
4195 * fallback in case of a new remap fails
4196 * allocation
4197 */
4198 if (i)
4199 __blk_mq_free_map_and_rqs(set, i);
4200
4201 hctx->tags = NULL;
4202 continue;
4203 }
4204
4205 hctx->tags = set->tags[i];
4206 WARN_ON(!hctx->tags);
4207
4208 /*
4209 * Set the map size to the number of mapped software queues.
4210 * This is more accurate and more efficient than looping
4211 * over all possibly mapped software queues.
4212 */
4213 sbitmap_resize(&hctx->ctx_map, hctx->nr_ctx);
4214
4215 /*
4216 * Rule out isolated CPUs from hctx->cpumask to avoid
4217 * running block kworker on isolated CPUs
4218 */
4219 for_each_cpu(cpu, hctx->cpumask) {
4220 if (cpu_is_isolated(cpu))
4221 cpumask_clear_cpu(cpu, hctx->cpumask);
4222 }
4223
4224 /*
4225 * Initialize batch roundrobin counts
4226 */
4227 hctx->next_cpu = blk_mq_first_mapped_cpu(hctx);
4228 hctx->next_cpu_batch = BLK_MQ_CPU_WORK_BATCH;
4229 }
4230 }
4231
4232 /*
4233 * Caller needs to ensure that we're either frozen/quiesced, or that
4234 * the queue isn't live yet.
4235 */
queue_set_hctx_shared(struct request_queue * q,bool shared)4236 static void queue_set_hctx_shared(struct request_queue *q, bool shared)
4237 {
4238 struct blk_mq_hw_ctx *hctx;
4239 unsigned long i;
4240
4241 queue_for_each_hw_ctx(q, hctx, i) {
4242 if (shared) {
4243 hctx->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4244 } else {
4245 blk_mq_tag_idle(hctx);
4246 hctx->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4247 }
4248 }
4249 }
4250
blk_mq_update_tag_set_shared(struct blk_mq_tag_set * set,bool shared)4251 static void blk_mq_update_tag_set_shared(struct blk_mq_tag_set *set,
4252 bool shared)
4253 {
4254 struct request_queue *q;
4255
4256 lockdep_assert_held(&set->tag_list_lock);
4257
4258 list_for_each_entry(q, &set->tag_list, tag_set_list) {
4259 blk_mq_freeze_queue(q);
4260 queue_set_hctx_shared(q, shared);
4261 blk_mq_unfreeze_queue(q);
4262 }
4263 }
4264
blk_mq_del_queue_tag_set(struct request_queue * q)4265 static void blk_mq_del_queue_tag_set(struct request_queue *q)
4266 {
4267 struct blk_mq_tag_set *set = q->tag_set;
4268
4269 mutex_lock(&set->tag_list_lock);
4270 list_del(&q->tag_set_list);
4271 if (list_is_singular(&set->tag_list)) {
4272 /* just transitioned to unshared */
4273 set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED;
4274 /* update existing queue */
4275 blk_mq_update_tag_set_shared(set, false);
4276 }
4277 mutex_unlock(&set->tag_list_lock);
4278 INIT_LIST_HEAD(&q->tag_set_list);
4279 }
4280
blk_mq_add_queue_tag_set(struct blk_mq_tag_set * set,struct request_queue * q)4281 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
4282 struct request_queue *q)
4283 {
4284 mutex_lock(&set->tag_list_lock);
4285
4286 /*
4287 * Check to see if we're transitioning to shared (from 1 to 2 queues).
4288 */
4289 if (!list_empty(&set->tag_list) &&
4290 !(set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)) {
4291 set->flags |= BLK_MQ_F_TAG_QUEUE_SHARED;
4292 /* update existing queue */
4293 blk_mq_update_tag_set_shared(set, true);
4294 }
4295 if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
4296 queue_set_hctx_shared(q, true);
4297 list_add_tail(&q->tag_set_list, &set->tag_list);
4298
4299 mutex_unlock(&set->tag_list_lock);
4300 }
4301
4302 /* All allocations will be freed in release handler of q->mq_kobj */
blk_mq_alloc_ctxs(struct request_queue * q)4303 static int blk_mq_alloc_ctxs(struct request_queue *q)
4304 {
4305 struct blk_mq_ctxs *ctxs;
4306 int cpu;
4307
4308 ctxs = kzalloc(sizeof(*ctxs), GFP_KERNEL);
4309 if (!ctxs)
4310 return -ENOMEM;
4311
4312 ctxs->queue_ctx = alloc_percpu(struct blk_mq_ctx);
4313 if (!ctxs->queue_ctx)
4314 goto fail;
4315
4316 for_each_possible_cpu(cpu) {
4317 struct blk_mq_ctx *ctx = per_cpu_ptr(ctxs->queue_ctx, cpu);
4318 ctx->ctxs = ctxs;
4319 }
4320
4321 q->mq_kobj = &ctxs->kobj;
4322 q->queue_ctx = ctxs->queue_ctx;
4323
4324 return 0;
4325 fail:
4326 kfree(ctxs);
4327 return -ENOMEM;
4328 }
4329
4330 /*
4331 * It is the actual release handler for mq, but we do it from
4332 * request queue's release handler for avoiding use-after-free
4333 * and headache because q->mq_kobj shouldn't have been introduced,
4334 * but we can't group ctx/kctx kobj without it.
4335 */
blk_mq_release(struct request_queue * q)4336 void blk_mq_release(struct request_queue *q)
4337 {
4338 struct blk_mq_hw_ctx *hctx, *next;
4339 unsigned long i;
4340
4341 queue_for_each_hw_ctx(q, hctx, i)
4342 WARN_ON_ONCE(hctx && list_empty(&hctx->hctx_list));
4343
4344 /* all hctx are in .unused_hctx_list now */
4345 list_for_each_entry_safe(hctx, next, &q->unused_hctx_list, hctx_list) {
4346 list_del_init(&hctx->hctx_list);
4347 kobject_put(&hctx->kobj);
4348 }
4349
4350 xa_destroy(&q->hctx_table);
4351
4352 /*
4353 * release .mq_kobj and sw queue's kobject now because
4354 * both share lifetime with request queue.
4355 */
4356 blk_mq_sysfs_deinit(q);
4357 }
4358
blk_mq_alloc_queue(struct blk_mq_tag_set * set,struct queue_limits * lim,void * queuedata)4359 struct request_queue *blk_mq_alloc_queue(struct blk_mq_tag_set *set,
4360 struct queue_limits *lim, void *queuedata)
4361 {
4362 struct queue_limits default_lim = { };
4363 struct request_queue *q;
4364 int ret;
4365
4366 if (!lim)
4367 lim = &default_lim;
4368 lim->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT;
4369 if (set->nr_maps > HCTX_TYPE_POLL)
4370 lim->features |= BLK_FEAT_POLL;
4371
4372 q = blk_alloc_queue(lim, set->numa_node);
4373 if (IS_ERR(q))
4374 return q;
4375 q->queuedata = queuedata;
4376 ret = blk_mq_init_allocated_queue(set, q);
4377 if (ret) {
4378 blk_put_queue(q);
4379 return ERR_PTR(ret);
4380 }
4381 return q;
4382 }
4383 EXPORT_SYMBOL(blk_mq_alloc_queue);
4384
4385 /**
4386 * blk_mq_destroy_queue - shutdown a request queue
4387 * @q: request queue to shutdown
4388 *
4389 * This shuts down a request queue allocated by blk_mq_alloc_queue(). All future
4390 * requests will be failed with -ENODEV. The caller is responsible for dropping
4391 * the reference from blk_mq_alloc_queue() by calling blk_put_queue().
4392 *
4393 * Context: can sleep
4394 */
blk_mq_destroy_queue(struct request_queue * q)4395 void blk_mq_destroy_queue(struct request_queue *q)
4396 {
4397 WARN_ON_ONCE(!queue_is_mq(q));
4398 WARN_ON_ONCE(blk_queue_registered(q));
4399
4400 might_sleep();
4401
4402 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
4403 blk_queue_start_drain(q);
4404 blk_mq_freeze_queue_wait(q);
4405
4406 blk_sync_queue(q);
4407 blk_mq_cancel_work_sync(q);
4408 blk_mq_exit_queue(q);
4409 }
4410 EXPORT_SYMBOL(blk_mq_destroy_queue);
4411
__blk_mq_alloc_disk(struct blk_mq_tag_set * set,struct queue_limits * lim,void * queuedata,struct lock_class_key * lkclass)4412 struct gendisk *__blk_mq_alloc_disk(struct blk_mq_tag_set *set,
4413 struct queue_limits *lim, void *queuedata,
4414 struct lock_class_key *lkclass)
4415 {
4416 struct request_queue *q;
4417 struct gendisk *disk;
4418
4419 q = blk_mq_alloc_queue(set, lim, queuedata);
4420 if (IS_ERR(q))
4421 return ERR_CAST(q);
4422
4423 disk = __alloc_disk_node(q, set->numa_node, lkclass);
4424 if (!disk) {
4425 blk_mq_destroy_queue(q);
4426 blk_put_queue(q);
4427 return ERR_PTR(-ENOMEM);
4428 }
4429 set_bit(GD_OWNS_QUEUE, &disk->state);
4430 return disk;
4431 }
4432 EXPORT_SYMBOL(__blk_mq_alloc_disk);
4433
blk_mq_alloc_disk_for_queue(struct request_queue * q,struct lock_class_key * lkclass)4434 struct gendisk *blk_mq_alloc_disk_for_queue(struct request_queue *q,
4435 struct lock_class_key *lkclass)
4436 {
4437 struct gendisk *disk;
4438
4439 if (!blk_get_queue(q))
4440 return NULL;
4441 disk = __alloc_disk_node(q, NUMA_NO_NODE, lkclass);
4442 if (!disk)
4443 blk_put_queue(q);
4444 return disk;
4445 }
4446 EXPORT_SYMBOL(blk_mq_alloc_disk_for_queue);
4447
4448 /*
4449 * Only hctx removed from cpuhp list can be reused
4450 */
blk_mq_hctx_is_reusable(struct blk_mq_hw_ctx * hctx)4451 static bool blk_mq_hctx_is_reusable(struct blk_mq_hw_ctx *hctx)
4452 {
4453 return hlist_unhashed(&hctx->cpuhp_online) &&
4454 hlist_unhashed(&hctx->cpuhp_dead);
4455 }
4456
blk_mq_alloc_and_init_hctx(struct blk_mq_tag_set * set,struct request_queue * q,int hctx_idx,int node)4457 static struct blk_mq_hw_ctx *blk_mq_alloc_and_init_hctx(
4458 struct blk_mq_tag_set *set, struct request_queue *q,
4459 int hctx_idx, int node)
4460 {
4461 struct blk_mq_hw_ctx *hctx = NULL, *tmp;
4462
4463 /* reuse dead hctx first */
4464 spin_lock(&q->unused_hctx_lock);
4465 list_for_each_entry(tmp, &q->unused_hctx_list, hctx_list) {
4466 if (tmp->numa_node == node && blk_mq_hctx_is_reusable(tmp)) {
4467 hctx = tmp;
4468 break;
4469 }
4470 }
4471 if (hctx)
4472 list_del_init(&hctx->hctx_list);
4473 spin_unlock(&q->unused_hctx_lock);
4474
4475 if (!hctx)
4476 hctx = blk_mq_alloc_hctx(q, set, node);
4477 if (!hctx)
4478 goto fail;
4479
4480 if (blk_mq_init_hctx(q, set, hctx, hctx_idx))
4481 goto free_hctx;
4482
4483 return hctx;
4484
4485 free_hctx:
4486 kobject_put(&hctx->kobj);
4487 fail:
4488 return NULL;
4489 }
4490
blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set * set,struct request_queue * q)4491 static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set,
4492 struct request_queue *q)
4493 {
4494 struct blk_mq_hw_ctx *hctx;
4495 unsigned long i, j;
4496
4497 /* protect against switching io scheduler */
4498 mutex_lock(&q->sysfs_lock);
4499 for (i = 0; i < set->nr_hw_queues; i++) {
4500 int old_node;
4501 int node = blk_mq_get_hctx_node(set, i);
4502 struct blk_mq_hw_ctx *old_hctx = xa_load(&q->hctx_table, i);
4503
4504 if (old_hctx) {
4505 old_node = old_hctx->numa_node;
4506 blk_mq_exit_hctx(q, set, old_hctx, i);
4507 }
4508
4509 if (!blk_mq_alloc_and_init_hctx(set, q, i, node)) {
4510 if (!old_hctx)
4511 break;
4512 pr_warn("Allocate new hctx on node %d fails, fallback to previous one on node %d\n",
4513 node, old_node);
4514 hctx = blk_mq_alloc_and_init_hctx(set, q, i, old_node);
4515 WARN_ON_ONCE(!hctx);
4516 }
4517 }
4518 /*
4519 * Increasing nr_hw_queues fails. Free the newly allocated
4520 * hctxs and keep the previous q->nr_hw_queues.
4521 */
4522 if (i != set->nr_hw_queues) {
4523 j = q->nr_hw_queues;
4524 } else {
4525 j = i;
4526 q->nr_hw_queues = set->nr_hw_queues;
4527 }
4528
4529 xa_for_each_start(&q->hctx_table, j, hctx, j)
4530 blk_mq_exit_hctx(q, set, hctx, j);
4531 mutex_unlock(&q->sysfs_lock);
4532
4533 /* unregister cpuhp callbacks for exited hctxs */
4534 blk_mq_remove_hw_queues_cpuhp(q);
4535
4536 /* register cpuhp for new initialized hctxs */
4537 blk_mq_add_hw_queues_cpuhp(q);
4538 }
4539
blk_mq_init_allocated_queue(struct blk_mq_tag_set * set,struct request_queue * q)4540 int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
4541 struct request_queue *q)
4542 {
4543 /* mark the queue as mq asap */
4544 q->mq_ops = set->ops;
4545
4546 /*
4547 * ->tag_set has to be setup before initialize hctx, which cpuphp
4548 * handler needs it for checking queue mapping
4549 */
4550 q->tag_set = set;
4551
4552 if (blk_mq_alloc_ctxs(q))
4553 goto err_exit;
4554
4555 /* init q->mq_kobj and sw queues' kobjects */
4556 blk_mq_sysfs_init(q);
4557
4558 INIT_LIST_HEAD(&q->unused_hctx_list);
4559 spin_lock_init(&q->unused_hctx_lock);
4560
4561 xa_init(&q->hctx_table);
4562
4563 blk_mq_realloc_hw_ctxs(set, q);
4564 if (!q->nr_hw_queues)
4565 goto err_hctxs;
4566
4567 INIT_WORK(&q->timeout_work, blk_mq_timeout_work);
4568 blk_queue_rq_timeout(q, set->timeout ? set->timeout : 30 * HZ);
4569
4570 q->queue_flags |= QUEUE_FLAG_MQ_DEFAULT;
4571
4572 INIT_DELAYED_WORK(&q->requeue_work, blk_mq_requeue_work);
4573 INIT_LIST_HEAD(&q->flush_list);
4574 INIT_LIST_HEAD(&q->requeue_list);
4575 spin_lock_init(&q->requeue_lock);
4576
4577 q->nr_requests = set->queue_depth;
4578
4579 blk_mq_init_cpu_queues(q, set->nr_hw_queues);
4580 blk_mq_add_queue_tag_set(set, q);
4581 blk_mq_map_swqueue(q);
4582 return 0;
4583
4584 err_hctxs:
4585 blk_mq_release(q);
4586 err_exit:
4587 q->mq_ops = NULL;
4588 return -ENOMEM;
4589 }
4590 EXPORT_SYMBOL(blk_mq_init_allocated_queue);
4591
4592 /* tags can _not_ be used after returning from blk_mq_exit_queue */
blk_mq_exit_queue(struct request_queue * q)4593 void blk_mq_exit_queue(struct request_queue *q)
4594 {
4595 struct blk_mq_tag_set *set = q->tag_set;
4596
4597 /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
4598 blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
4599 /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
4600 blk_mq_del_queue_tag_set(q);
4601 }
4602
__blk_mq_alloc_rq_maps(struct blk_mq_tag_set * set)4603 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
4604 {
4605 int i;
4606
4607 if (blk_mq_is_shared_tags(set->flags)) {
4608 set->shared_tags = blk_mq_alloc_map_and_rqs(set,
4609 BLK_MQ_NO_HCTX_IDX,
4610 set->queue_depth);
4611 if (!set->shared_tags)
4612 return -ENOMEM;
4613 }
4614
4615 for (i = 0; i < set->nr_hw_queues; i++) {
4616 if (!__blk_mq_alloc_map_and_rqs(set, i))
4617 goto out_unwind;
4618 cond_resched();
4619 }
4620
4621 return 0;
4622
4623 out_unwind:
4624 while (--i >= 0)
4625 __blk_mq_free_map_and_rqs(set, i);
4626
4627 if (blk_mq_is_shared_tags(set->flags)) {
4628 blk_mq_free_map_and_rqs(set, set->shared_tags,
4629 BLK_MQ_NO_HCTX_IDX);
4630 }
4631
4632 return -ENOMEM;
4633 }
4634
4635 /*
4636 * Allocate the request maps associated with this tag_set. Note that this
4637 * may reduce the depth asked for, if memory is tight. set->queue_depth
4638 * will be updated to reflect the allocated depth.
4639 */
blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set * set)4640 static int blk_mq_alloc_set_map_and_rqs(struct blk_mq_tag_set *set)
4641 {
4642 unsigned int depth;
4643 int err;
4644
4645 depth = set->queue_depth;
4646 do {
4647 err = __blk_mq_alloc_rq_maps(set);
4648 if (!err)
4649 break;
4650
4651 set->queue_depth >>= 1;
4652 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN) {
4653 err = -ENOMEM;
4654 break;
4655 }
4656 } while (set->queue_depth);
4657
4658 if (!set->queue_depth || err) {
4659 pr_err("blk-mq: failed to allocate request map\n");
4660 return -ENOMEM;
4661 }
4662
4663 if (depth != set->queue_depth)
4664 pr_info("blk-mq: reduced tag depth (%u -> %u)\n",
4665 depth, set->queue_depth);
4666
4667 return 0;
4668 }
4669
blk_mq_update_queue_map(struct blk_mq_tag_set * set)4670 static void blk_mq_update_queue_map(struct blk_mq_tag_set *set)
4671 {
4672 /*
4673 * blk_mq_map_queues() and multiple .map_queues() implementations
4674 * expect that set->map[HCTX_TYPE_DEFAULT].nr_queues is set to the
4675 * number of hardware queues.
4676 */
4677 if (set->nr_maps == 1)
4678 set->map[HCTX_TYPE_DEFAULT].nr_queues = set->nr_hw_queues;
4679
4680 if (set->ops->map_queues) {
4681 int i;
4682
4683 /*
4684 * transport .map_queues is usually done in the following
4685 * way:
4686 *
4687 * for (queue = 0; queue < set->nr_hw_queues; queue++) {
4688 * mask = get_cpu_mask(queue)
4689 * for_each_cpu(cpu, mask)
4690 * set->map[x].mq_map[cpu] = queue;
4691 * }
4692 *
4693 * When we need to remap, the table has to be cleared for
4694 * killing stale mapping since one CPU may not be mapped
4695 * to any hw queue.
4696 */
4697 for (i = 0; i < set->nr_maps; i++)
4698 blk_mq_clear_mq_map(&set->map[i]);
4699
4700 set->ops->map_queues(set);
4701 } else {
4702 BUG_ON(set->nr_maps > 1);
4703 blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
4704 }
4705 }
4706
blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set * set,int new_nr_hw_queues)4707 static int blk_mq_realloc_tag_set_tags(struct blk_mq_tag_set *set,
4708 int new_nr_hw_queues)
4709 {
4710 struct blk_mq_tags **new_tags;
4711 int i;
4712
4713 if (set->nr_hw_queues >= new_nr_hw_queues)
4714 goto done;
4715
4716 new_tags = kcalloc_node(new_nr_hw_queues, sizeof(struct blk_mq_tags *),
4717 GFP_KERNEL, set->numa_node);
4718 if (!new_tags)
4719 return -ENOMEM;
4720
4721 if (set->tags)
4722 memcpy(new_tags, set->tags, set->nr_hw_queues *
4723 sizeof(*set->tags));
4724 kfree(set->tags);
4725 set->tags = new_tags;
4726
4727 for (i = set->nr_hw_queues; i < new_nr_hw_queues; i++) {
4728 if (!__blk_mq_alloc_map_and_rqs(set, i)) {
4729 while (--i >= set->nr_hw_queues)
4730 __blk_mq_free_map_and_rqs(set, i);
4731 return -ENOMEM;
4732 }
4733 cond_resched();
4734 }
4735
4736 done:
4737 set->nr_hw_queues = new_nr_hw_queues;
4738 return 0;
4739 }
4740
4741 /*
4742 * Alloc a tag set to be associated with one or more request queues.
4743 * May fail with EINVAL for various error conditions. May adjust the
4744 * requested depth down, if it's too large. In that case, the set
4745 * value will be stored in set->queue_depth.
4746 */
blk_mq_alloc_tag_set(struct blk_mq_tag_set * set)4747 int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
4748 {
4749 int i, ret;
4750
4751 BUILD_BUG_ON(BLK_MQ_MAX_DEPTH > 1 << BLK_MQ_UNIQUE_TAG_BITS);
4752
4753 if (!set->nr_hw_queues)
4754 return -EINVAL;
4755 if (!set->queue_depth)
4756 return -EINVAL;
4757 if (set->queue_depth < set->reserved_tags + BLK_MQ_TAG_MIN)
4758 return -EINVAL;
4759
4760 if (!set->ops->queue_rq)
4761 return -EINVAL;
4762
4763 if (!set->ops->get_budget ^ !set->ops->put_budget)
4764 return -EINVAL;
4765
4766 if (set->queue_depth > BLK_MQ_MAX_DEPTH) {
4767 pr_info("blk-mq: reduced tag depth to %u\n",
4768 BLK_MQ_MAX_DEPTH);
4769 set->queue_depth = BLK_MQ_MAX_DEPTH;
4770 }
4771
4772 if (!set->nr_maps)
4773 set->nr_maps = 1;
4774 else if (set->nr_maps > HCTX_MAX_TYPES)
4775 return -EINVAL;
4776
4777 /*
4778 * If a crashdump is active, then we are potentially in a very
4779 * memory constrained environment. Limit us to 64 tags to prevent
4780 * using too much memory.
4781 */
4782 if (is_kdump_kernel())
4783 set->queue_depth = min(64U, set->queue_depth);
4784
4785 /*
4786 * There is no use for more h/w queues than cpus if we just have
4787 * a single map
4788 */
4789 if (set->nr_maps == 1 && set->nr_hw_queues > nr_cpu_ids)
4790 set->nr_hw_queues = nr_cpu_ids;
4791
4792 if (set->flags & BLK_MQ_F_BLOCKING) {
4793 set->srcu = kmalloc(sizeof(*set->srcu), GFP_KERNEL);
4794 if (!set->srcu)
4795 return -ENOMEM;
4796 ret = init_srcu_struct(set->srcu);
4797 if (ret)
4798 goto out_free_srcu;
4799 }
4800
4801 ret = -ENOMEM;
4802 set->tags = kcalloc_node(set->nr_hw_queues,
4803 sizeof(struct blk_mq_tags *), GFP_KERNEL,
4804 set->numa_node);
4805 if (!set->tags)
4806 goto out_cleanup_srcu;
4807
4808 for (i = 0; i < set->nr_maps; i++) {
4809 set->map[i].mq_map = kcalloc_node(nr_cpu_ids,
4810 sizeof(set->map[i].mq_map[0]),
4811 GFP_KERNEL, set->numa_node);
4812 if (!set->map[i].mq_map)
4813 goto out_free_mq_map;
4814 set->map[i].nr_queues = set->nr_hw_queues;
4815 }
4816
4817 blk_mq_update_queue_map(set);
4818
4819 ret = blk_mq_alloc_set_map_and_rqs(set);
4820 if (ret)
4821 goto out_free_mq_map;
4822
4823 mutex_init(&set->tag_list_lock);
4824 INIT_LIST_HEAD(&set->tag_list);
4825
4826 return 0;
4827
4828 out_free_mq_map:
4829 for (i = 0; i < set->nr_maps; i++) {
4830 kfree(set->map[i].mq_map);
4831 set->map[i].mq_map = NULL;
4832 }
4833 kfree(set->tags);
4834 set->tags = NULL;
4835 out_cleanup_srcu:
4836 if (set->flags & BLK_MQ_F_BLOCKING)
4837 cleanup_srcu_struct(set->srcu);
4838 out_free_srcu:
4839 if (set->flags & BLK_MQ_F_BLOCKING)
4840 kfree(set->srcu);
4841 return ret;
4842 }
4843 EXPORT_SYMBOL(blk_mq_alloc_tag_set);
4844
4845 /* 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)4846 int blk_mq_alloc_sq_tag_set(struct blk_mq_tag_set *set,
4847 const struct blk_mq_ops *ops, unsigned int queue_depth,
4848 unsigned int set_flags)
4849 {
4850 memset(set, 0, sizeof(*set));
4851 set->ops = ops;
4852 set->nr_hw_queues = 1;
4853 set->nr_maps = 1;
4854 set->queue_depth = queue_depth;
4855 set->numa_node = NUMA_NO_NODE;
4856 set->flags = set_flags;
4857 return blk_mq_alloc_tag_set(set);
4858 }
4859 EXPORT_SYMBOL_GPL(blk_mq_alloc_sq_tag_set);
4860
blk_mq_free_tag_set(struct blk_mq_tag_set * set)4861 void blk_mq_free_tag_set(struct blk_mq_tag_set *set)
4862 {
4863 int i, j;
4864
4865 for (i = 0; i < set->nr_hw_queues; i++)
4866 __blk_mq_free_map_and_rqs(set, i);
4867
4868 if (blk_mq_is_shared_tags(set->flags)) {
4869 blk_mq_free_map_and_rqs(set, set->shared_tags,
4870 BLK_MQ_NO_HCTX_IDX);
4871 }
4872
4873 for (j = 0; j < set->nr_maps; j++) {
4874 kfree(set->map[j].mq_map);
4875 set->map[j].mq_map = NULL;
4876 }
4877
4878 kfree(set->tags);
4879 set->tags = NULL;
4880 if (set->flags & BLK_MQ_F_BLOCKING) {
4881 cleanup_srcu_struct(set->srcu);
4882 kfree(set->srcu);
4883 }
4884 }
4885 EXPORT_SYMBOL(blk_mq_free_tag_set);
4886
blk_mq_update_nr_requests(struct request_queue * q,unsigned int nr)4887 int blk_mq_update_nr_requests(struct request_queue *q, unsigned int nr)
4888 {
4889 struct blk_mq_tag_set *set = q->tag_set;
4890 struct blk_mq_hw_ctx *hctx;
4891 int ret;
4892 unsigned long i;
4893
4894 if (WARN_ON_ONCE(!q->mq_freeze_depth))
4895 return -EINVAL;
4896
4897 if (!set)
4898 return -EINVAL;
4899
4900 if (q->nr_requests == nr)
4901 return 0;
4902
4903 blk_mq_quiesce_queue(q);
4904
4905 ret = 0;
4906 queue_for_each_hw_ctx(q, hctx, i) {
4907 if (!hctx->tags)
4908 continue;
4909 /*
4910 * If we're using an MQ scheduler, just update the scheduler
4911 * queue depth. This is similar to what the old code would do.
4912 */
4913 if (hctx->sched_tags) {
4914 ret = blk_mq_tag_update_depth(hctx, &hctx->sched_tags,
4915 nr, true);
4916 } else {
4917 ret = blk_mq_tag_update_depth(hctx, &hctx->tags, nr,
4918 false);
4919 }
4920 if (ret)
4921 break;
4922 if (q->elevator && q->elevator->type->ops.depth_updated)
4923 q->elevator->type->ops.depth_updated(hctx);
4924 }
4925 if (!ret) {
4926 q->nr_requests = nr;
4927 if (blk_mq_is_shared_tags(set->flags)) {
4928 if (q->elevator)
4929 blk_mq_tag_update_sched_shared_tags(q);
4930 else
4931 blk_mq_tag_resize_shared_tags(set, nr);
4932 }
4933 }
4934
4935 blk_mq_unquiesce_queue(q);
4936
4937 return ret;
4938 }
4939
4940 /*
4941 * request_queue and elevator_type pair.
4942 * It is just used by __blk_mq_update_nr_hw_queues to cache
4943 * the elevator_type associated with a request_queue.
4944 */
4945 struct blk_mq_qe_pair {
4946 struct list_head node;
4947 struct request_queue *q;
4948 struct elevator_type *type;
4949 };
4950
4951 /*
4952 * Cache the elevator_type in qe pair list and switch the
4953 * io scheduler to 'none'
4954 */
blk_mq_elv_switch_none(struct list_head * head,struct request_queue * q)4955 static bool blk_mq_elv_switch_none(struct list_head *head,
4956 struct request_queue *q)
4957 {
4958 struct blk_mq_qe_pair *qe;
4959
4960 qe = kmalloc(sizeof(*qe), GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY);
4961 if (!qe)
4962 return false;
4963
4964 /* q->elevator needs protection from ->sysfs_lock */
4965 mutex_lock(&q->sysfs_lock);
4966
4967 /* the check has to be done with holding sysfs_lock */
4968 if (!q->elevator) {
4969 kfree(qe);
4970 goto unlock;
4971 }
4972
4973 INIT_LIST_HEAD(&qe->node);
4974 qe->q = q;
4975 qe->type = q->elevator->type;
4976 /* keep a reference to the elevator module as we'll switch back */
4977 __elevator_get(qe->type);
4978 list_add(&qe->node, head);
4979 elevator_disable(q);
4980 unlock:
4981 mutex_unlock(&q->sysfs_lock);
4982
4983 return true;
4984 }
4985
blk_lookup_qe_pair(struct list_head * head,struct request_queue * q)4986 static struct blk_mq_qe_pair *blk_lookup_qe_pair(struct list_head *head,
4987 struct request_queue *q)
4988 {
4989 struct blk_mq_qe_pair *qe;
4990
4991 list_for_each_entry(qe, head, node)
4992 if (qe->q == q)
4993 return qe;
4994
4995 return NULL;
4996 }
4997
blk_mq_elv_switch_back(struct list_head * head,struct request_queue * q)4998 static void blk_mq_elv_switch_back(struct list_head *head,
4999 struct request_queue *q)
5000 {
5001 struct blk_mq_qe_pair *qe;
5002 struct elevator_type *t;
5003
5004 qe = blk_lookup_qe_pair(head, q);
5005 if (!qe)
5006 return;
5007 t = qe->type;
5008 list_del(&qe->node);
5009 kfree(qe);
5010
5011 mutex_lock(&q->sysfs_lock);
5012 elevator_switch(q, t);
5013 /* drop the reference acquired in blk_mq_elv_switch_none */
5014 elevator_put(t);
5015 mutex_unlock(&q->sysfs_lock);
5016 }
5017
__blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)5018 static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
5019 int nr_hw_queues)
5020 {
5021 struct request_queue *q;
5022 LIST_HEAD(head);
5023 int prev_nr_hw_queues = set->nr_hw_queues;
5024 int i;
5025
5026 lockdep_assert_held(&set->tag_list_lock);
5027
5028 if (set->nr_maps == 1 && nr_hw_queues > nr_cpu_ids)
5029 nr_hw_queues = nr_cpu_ids;
5030 if (nr_hw_queues < 1)
5031 return;
5032 if (set->nr_maps == 1 && nr_hw_queues == set->nr_hw_queues)
5033 return;
5034
5035 list_for_each_entry(q, &set->tag_list, tag_set_list)
5036 blk_mq_freeze_queue(q);
5037 /*
5038 * Switch IO scheduler to 'none', cleaning up the data associated
5039 * with the previous scheduler. We will switch back once we are done
5040 * updating the new sw to hw queue mappings.
5041 */
5042 list_for_each_entry(q, &set->tag_list, tag_set_list)
5043 if (!blk_mq_elv_switch_none(&head, q))
5044 goto switch_back;
5045
5046 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5047 blk_mq_debugfs_unregister_hctxs(q);
5048 blk_mq_sysfs_unregister_hctxs(q);
5049 }
5050
5051 if (blk_mq_realloc_tag_set_tags(set, nr_hw_queues) < 0)
5052 goto reregister;
5053
5054 fallback:
5055 blk_mq_update_queue_map(set);
5056 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5057 blk_mq_realloc_hw_ctxs(set, q);
5058
5059 if (q->nr_hw_queues != set->nr_hw_queues) {
5060 int i = prev_nr_hw_queues;
5061
5062 pr_warn("Increasing nr_hw_queues to %d fails, fallback to %d\n",
5063 nr_hw_queues, prev_nr_hw_queues);
5064 for (; i < set->nr_hw_queues; i++)
5065 __blk_mq_free_map_and_rqs(set, i);
5066
5067 set->nr_hw_queues = prev_nr_hw_queues;
5068 goto fallback;
5069 }
5070 blk_mq_map_swqueue(q);
5071 }
5072
5073 reregister:
5074 list_for_each_entry(q, &set->tag_list, tag_set_list) {
5075 blk_mq_sysfs_register_hctxs(q);
5076 blk_mq_debugfs_register_hctxs(q);
5077 }
5078
5079 switch_back:
5080 list_for_each_entry(q, &set->tag_list, tag_set_list)
5081 blk_mq_elv_switch_back(&head, q);
5082
5083 list_for_each_entry(q, &set->tag_list, tag_set_list)
5084 blk_mq_unfreeze_queue(q);
5085
5086 /* Free the excess tags when nr_hw_queues shrink. */
5087 for (i = set->nr_hw_queues; i < prev_nr_hw_queues; i++)
5088 __blk_mq_free_map_and_rqs(set, i);
5089 }
5090
blk_mq_update_nr_hw_queues(struct blk_mq_tag_set * set,int nr_hw_queues)5091 void blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, int nr_hw_queues)
5092 {
5093 mutex_lock(&set->tag_list_lock);
5094 __blk_mq_update_nr_hw_queues(set, nr_hw_queues);
5095 mutex_unlock(&set->tag_list_lock);
5096 }
5097 EXPORT_SYMBOL_GPL(blk_mq_update_nr_hw_queues);
5098
blk_hctx_poll(struct request_queue * q,struct blk_mq_hw_ctx * hctx,struct io_comp_batch * iob,unsigned int flags)5099 static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
5100 struct io_comp_batch *iob, unsigned int flags)
5101 {
5102 long state = get_current_state();
5103 int ret;
5104
5105 do {
5106 ret = q->mq_ops->poll(hctx, iob);
5107 if (ret > 0) {
5108 __set_current_state(TASK_RUNNING);
5109 return ret;
5110 }
5111
5112 if (signal_pending_state(state, current))
5113 __set_current_state(TASK_RUNNING);
5114 if (task_is_running(current))
5115 return 1;
5116
5117 if (ret < 0 || (flags & BLK_POLL_ONESHOT))
5118 break;
5119 cpu_relax();
5120 } while (!need_resched());
5121
5122 __set_current_state(TASK_RUNNING);
5123 return 0;
5124 }
5125
blk_mq_poll(struct request_queue * q,blk_qc_t cookie,struct io_comp_batch * iob,unsigned int flags)5126 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
5127 struct io_comp_batch *iob, unsigned int flags)
5128 {
5129 if (!blk_mq_can_poll(q))
5130 return 0;
5131 return blk_hctx_poll(q, xa_load(&q->hctx_table, cookie), iob, flags);
5132 }
5133
blk_rq_poll(struct request * rq,struct io_comp_batch * iob,unsigned int poll_flags)5134 int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
5135 unsigned int poll_flags)
5136 {
5137 struct request_queue *q = rq->q;
5138 int ret;
5139
5140 if (!blk_rq_is_poll(rq))
5141 return 0;
5142 if (!percpu_ref_tryget(&q->q_usage_counter))
5143 return 0;
5144
5145 ret = blk_hctx_poll(q, rq->mq_hctx, iob, poll_flags);
5146 blk_queue_exit(q);
5147
5148 return ret;
5149 }
5150 EXPORT_SYMBOL_GPL(blk_rq_poll);
5151
blk_mq_rq_cpu(struct request * rq)5152 unsigned int blk_mq_rq_cpu(struct request *rq)
5153 {
5154 return rq->mq_ctx->cpu;
5155 }
5156 EXPORT_SYMBOL(blk_mq_rq_cpu);
5157
blk_mq_cancel_work_sync(struct request_queue * q)5158 void blk_mq_cancel_work_sync(struct request_queue *q)
5159 {
5160 struct blk_mq_hw_ctx *hctx;
5161 unsigned long i;
5162
5163 cancel_delayed_work_sync(&q->requeue_work);
5164
5165 queue_for_each_hw_ctx(q, hctx, i)
5166 cancel_delayed_work_sync(&hctx->run_work);
5167 }
5168
blk_mq_init(void)5169 static int __init blk_mq_init(void)
5170 {
5171 int i;
5172
5173 for_each_possible_cpu(i)
5174 init_llist_head(&per_cpu(blk_cpu_done, i));
5175 for_each_possible_cpu(i)
5176 INIT_CSD(&per_cpu(blk_cpu_csd, i),
5177 __blk_mq_complete_request_remote, NULL);
5178 open_softirq(BLOCK_SOFTIRQ, blk_done_softirq);
5179
5180 cpuhp_setup_state_nocalls(CPUHP_BLOCK_SOFTIRQ_DEAD,
5181 "block/softirq:dead", NULL,
5182 blk_softirq_cpu_dead);
5183 cpuhp_setup_state_multi(CPUHP_BLK_MQ_DEAD, "block/mq:dead", NULL,
5184 blk_mq_hctx_notify_dead);
5185 cpuhp_setup_state_multi(CPUHP_AP_BLK_MQ_ONLINE, "block/mq:online",
5186 blk_mq_hctx_notify_online,
5187 blk_mq_hctx_notify_offline);
5188 return 0;
5189 }
5190 subsys_initcall(blk_mq_init);
5191