2 * Budget Fair Queueing (BFQ) I/O scheduler.
4 * Based on ideas and code from CFQ:
5 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
7 * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
8 * Paolo Valente <paolo.valente@unimore.it>
10 * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it>
11 * Arianna Avanzini <avanzini@google.com>
13 * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org>
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License as
17 * published by the Free Software Foundation; either version 2 of the
18 * License, or (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * General Public License for more details.
25 * BFQ is a proportional-share I/O scheduler, with some extra
26 * low-latency capabilities. BFQ also supports full hierarchical
27 * scheduling through cgroups. Next paragraphs provide an introduction
28 * on BFQ inner workings. Details on BFQ benefits, usage and
29 * limitations can be found in Documentation/block/bfq-iosched.txt.
31 * BFQ is a proportional-share storage-I/O scheduling algorithm based
32 * on the slice-by-slice service scheme of CFQ. But BFQ assigns
33 * budgets, measured in number of sectors, to processes instead of
34 * time slices. The device is not granted to the in-service process
35 * for a given time slice, but until it has exhausted its assigned
36 * budget. This change from the time to the service domain enables BFQ
37 * to distribute the device throughput among processes as desired,
38 * without any distortion due to throughput fluctuations, or to device
39 * internal queueing. BFQ uses an ad hoc internal scheduler, called
40 * B-WF2Q+, to schedule processes according to their budgets. More
41 * precisely, BFQ schedules queues associated with processes. Each
42 * process/queue is assigned a user-configurable weight, and B-WF2Q+
43 * guarantees that each queue receives a fraction of the throughput
44 * proportional to its weight. Thanks to the accurate policy of
45 * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound
46 * processes issuing sequential requests (to boost the throughput),
47 * and yet guarantee a low latency to interactive and soft real-time
50 * In particular, to provide these low-latency guarantees, BFQ
51 * explicitly privileges the I/O of two classes of time-sensitive
52 * applications: interactive and soft real-time. In more detail, BFQ
53 * behaves this way if the low_latency parameter is set (default
54 * configuration). This feature enables BFQ to provide applications in
55 * these classes with a very low latency.
57 * To implement this feature, BFQ constantly tries to detect whether
58 * the I/O requests in a bfq_queue come from an interactive or a soft
59 * real-time application. For brevity, in these cases, the queue is
60 * said to be interactive or soft real-time. In both cases, BFQ
61 * privileges the service of the queue, over that of non-interactive
62 * and non-soft-real-time queues. This privileging is performed,
63 * mainly, by raising the weight of the queue. So, for brevity, we
64 * call just weight-raising periods the time periods during which a
65 * queue is privileged, because deemed interactive or soft real-time.
67 * The detection of soft real-time queues/applications is described in
68 * detail in the comments on the function
69 * bfq_bfqq_softrt_next_start. On the other hand, the detection of an
70 * interactive queue works as follows: a queue is deemed interactive
71 * if it is constantly non empty only for a limited time interval,
72 * after which it does become empty. The queue may be deemed
73 * interactive again (for a limited time), if it restarts being
74 * constantly non empty, provided that this happens only after the
75 * queue has remained empty for a given minimum idle time.
77 * By default, BFQ computes automatically the above maximum time
78 * interval, i.e., the time interval after which a constantly
79 * non-empty queue stops being deemed interactive. Since a queue is
80 * weight-raised while it is deemed interactive, this maximum time
81 * interval happens to coincide with the (maximum) duration of the
82 * weight-raising for interactive queues.
84 * Finally, BFQ also features additional heuristics for
85 * preserving both a low latency and a high throughput on NCQ-capable,
86 * rotational or flash-based devices, and to get the job done quickly
87 * for applications consisting in many I/O-bound processes.
89 * NOTE: if the main or only goal, with a given device, is to achieve
90 * the maximum-possible throughput at all times, then do switch off
91 * all low-latency heuristics for that device, by setting low_latency
94 * BFQ is described in [1], where also a reference to the initial,
95 * more theoretical paper on BFQ can be found. The interested reader
96 * can find in the latter paper full details on the main algorithm, as
97 * well as formulas of the guarantees and formal proofs of all the
98 * properties. With respect to the version of BFQ presented in these
99 * papers, this implementation adds a few more heuristics, such as the
100 * ones that guarantee a low latency to interactive and soft real-time
101 * applications, and a hierarchical extension based on H-WF2Q+.
103 * B-WF2Q+ is based on WF2Q+, which is described in [2], together with
104 * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+
105 * with O(log N) complexity derives from the one introduced with EEVDF
108 * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O
109 * Scheduler", Proceedings of the First Workshop on Mobile System
110 * Technologies (MST-2015), May 2015.
111 * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf
113 * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing
114 * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689,
117 * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz
119 * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline
120 * First: A Flexible and Accurate Mechanism for Proportional Share
121 * Resource Allocation", technical report.
123 * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf
125 #include <linux/module.h>
126 #include <linux/slab.h>
127 #include <linux/blkdev.h>
128 #include <linux/cgroup.h>
129 #include <linux/elevator.h>
130 #include <linux/ktime.h>
131 #include <linux/rbtree.h>
132 #include <linux/ioprio.h>
133 #include <linux/sbitmap.h>
134 #include <linux/delay.h>
135 #include <linux/backing-dev.h>
139 #include "blk-mq-tag.h"
140 #include "blk-mq-sched.h"
141 #include "bfq-iosched.h"
144 #define BFQ_BFQQ_FNS(name) \
145 void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
147 __set_bit(BFQQF_##name, &(bfqq)->flags); \
149 void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
151 __clear_bit(BFQQF_##name, &(bfqq)->flags); \
153 int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
155 return test_bit(BFQQF_##name, &(bfqq)->flags); \
158 BFQ_BFQQ_FNS(just_created);
160 BFQ_BFQQ_FNS(wait_request);
161 BFQ_BFQQ_FNS(non_blocking_wait_rq);
162 BFQ_BFQQ_FNS(fifo_expire);
163 BFQ_BFQQ_FNS(has_short_ttime);
165 BFQ_BFQQ_FNS(IO_bound);
166 BFQ_BFQQ_FNS(in_large_burst);
168 BFQ_BFQQ_FNS(split_coop);
169 BFQ_BFQQ_FNS(softrt_update);
170 #undef BFQ_BFQQ_FNS \
172 /* Expiration time of sync (0) and async (1) requests, in ns. */
173 static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
175 /* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
176 static const int bfq_back_max = 16 * 1024;
178 /* Penalty of a backwards seek, in number of sectors. */
179 static const int bfq_back_penalty = 2;
181 /* Idling period duration, in ns. */
182 static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
184 /* Minimum number of assigned budgets for which stats are safe to compute. */
185 static const int bfq_stats_min_budgets = 194;
187 /* Default maximum budget values, in sectors and number of requests. */
188 static const int bfq_default_max_budget = 16 * 1024;
191 * When a sync request is dispatched, the queue that contains that
192 * request, and all the ancestor entities of that queue, are charged
193 * with the number of sectors of the request. In constrast, if the
194 * request is async, then the queue and its ancestor entities are
195 * charged with the number of sectors of the request, multiplied by
196 * the factor below. This throttles the bandwidth for async I/O,
197 * w.r.t. to sync I/O, and it is done to counter the tendency of async
198 * writes to steal I/O throughput to reads.
200 * The current value of this parameter is the result of a tuning with
201 * several hardware and software configurations. We tried to find the
202 * lowest value for which writes do not cause noticeable problems to
203 * reads. In fact, the lower this parameter, the stabler I/O control,
204 * in the following respect. The lower this parameter is, the less
205 * the bandwidth enjoyed by a group decreases
206 * - when the group does writes, w.r.t. to when it does reads;
207 * - when other groups do reads, w.r.t. to when they do writes.
209 static const int bfq_async_charge_factor = 3;
211 /* Default timeout values, in jiffies, approximating CFQ defaults. */
212 const int bfq_timeout = HZ / 8;
215 * Time limit for merging (see comments in bfq_setup_cooperator). Set
216 * to the slowest value that, in our tests, proved to be effective in
217 * removing false positives, while not causing true positives to miss
220 * As can be deduced from the low time limit below, queue merging, if
221 * successful, happens at the very beggining of the I/O of the involved
222 * cooperating processes, as a consequence of the arrival of the very
223 * first requests from each cooperator. After that, there is very
224 * little chance to find cooperators.
226 static const unsigned long bfq_merge_time_limit = HZ/10;
228 static struct kmem_cache *bfq_pool;
230 /* Below this threshold (in ns), we consider thinktime immediate. */
231 #define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
233 /* hw_tag detection: parallel requests threshold and min samples needed. */
234 #define BFQ_HW_QUEUE_THRESHOLD 4
235 #define BFQ_HW_QUEUE_SAMPLES 32
237 #define BFQQ_SEEK_THR (sector_t)(8 * 100)
238 #define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
239 #define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
240 #define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19)
242 /* Min number of samples required to perform peak-rate update */
243 #define BFQ_RATE_MIN_SAMPLES 32
244 /* Min observation time interval required to perform a peak-rate update (ns) */
245 #define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
246 /* Target observation time interval for a peak-rate update (ns) */
247 #define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
250 * Shift used for peak-rate fixed precision calculations.
252 * - the current shift: 16 positions
253 * - the current type used to store rate: u32
254 * - the current unit of measure for rate: [sectors/usec], or, more precisely,
255 * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift,
256 * the range of rates that can be stored is
257 * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec =
258 * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec =
259 * [15, 65G] sectors/sec
260 * Which, assuming a sector size of 512B, corresponds to a range of
263 #define BFQ_RATE_SHIFT 16
266 * When configured for computing the duration of the weight-raising
267 * for interactive queues automatically (see the comments at the
268 * beginning of this file), BFQ does it using the following formula:
269 * duration = (ref_rate / r) * ref_wr_duration,
270 * where r is the peak rate of the device, and ref_rate and
271 * ref_wr_duration are two reference parameters. In particular,
272 * ref_rate is the peak rate of the reference storage device (see
273 * below), and ref_wr_duration is about the maximum time needed, with
274 * BFQ and while reading two files in parallel, to load typical large
275 * applications on the reference device (see the comments on
276 * max_service_from_wr below, for more details on how ref_wr_duration
277 * is obtained). In practice, the slower/faster the device at hand
278 * is, the more/less it takes to load applications with respect to the
279 * reference device. Accordingly, the longer/shorter BFQ grants
280 * weight raising to interactive applications.
282 * BFQ uses two different reference pairs (ref_rate, ref_wr_duration),
283 * depending on whether the device is rotational or non-rotational.
285 * In the following definitions, ref_rate[0] and ref_wr_duration[0]
286 * are the reference values for a rotational device, whereas
287 * ref_rate[1] and ref_wr_duration[1] are the reference values for a
288 * non-rotational device. The reference rates are not the actual peak
289 * rates of the devices used as a reference, but slightly lower
290 * values. The reason for using slightly lower values is that the
291 * peak-rate estimator tends to yield slightly lower values than the
292 * actual peak rate (it can yield the actual peak rate only if there
293 * is only one process doing I/O, and the process does sequential
296 * The reference peak rates are measured in sectors/usec, left-shifted
299 static int ref_rate[2] = {14000, 33000};
301 * To improve readability, a conversion function is used to initialize
302 * the following array, which entails that the array can be
303 * initialized only in a function.
305 static int ref_wr_duration[2];
308 * BFQ uses the above-detailed, time-based weight-raising mechanism to
309 * privilege interactive tasks. This mechanism is vulnerable to the
310 * following false positives: I/O-bound applications that will go on
311 * doing I/O for much longer than the duration of weight
312 * raising. These applications have basically no benefit from being
313 * weight-raised at the beginning of their I/O. On the opposite end,
314 * while being weight-raised, these applications
315 * a) unjustly steal throughput to applications that may actually need
317 * b) make BFQ uselessly perform device idling; device idling results
318 * in loss of device throughput with most flash-based storage, and may
319 * increase latencies when used purposelessly.
321 * BFQ tries to reduce these problems, by adopting the following
322 * countermeasure. To introduce this countermeasure, we need first to
323 * finish explaining how the duration of weight-raising for
324 * interactive tasks is computed.
326 * For a bfq_queue deemed as interactive, the duration of weight
327 * raising is dynamically adjusted, as a function of the estimated
328 * peak rate of the device, so as to be equal to the time needed to
329 * execute the 'largest' interactive task we benchmarked so far. By
330 * largest task, we mean the task for which each involved process has
331 * to do more I/O than for any of the other tasks we benchmarked. This
332 * reference interactive task is the start-up of LibreOffice Writer,
333 * and in this task each process/bfq_queue needs to have at most ~110K
334 * sectors transferred.
336 * This last piece of information enables BFQ to reduce the actual
337 * duration of weight-raising for at least one class of I/O-bound
338 * applications: those doing sequential or quasi-sequential I/O. An
339 * example is file copy. In fact, once started, the main I/O-bound
340 * processes of these applications usually consume the above 110K
341 * sectors in much less time than the processes of an application that
342 * is starting, because these I/O-bound processes will greedily devote
343 * almost all their CPU cycles only to their target,
344 * throughput-friendly I/O operations. This is even more true if BFQ
345 * happens to be underestimating the device peak rate, and thus
346 * overestimating the duration of weight raising. But, according to
347 * our measurements, once transferred 110K sectors, these processes
348 * have no right to be weight-raised any longer.
350 * Basing on the last consideration, BFQ ends weight-raising for a
351 * bfq_queue if the latter happens to have received an amount of
352 * service at least equal to the following constant. The constant is
353 * set to slightly more than 110K, to have a minimum safety margin.
355 * This early ending of weight-raising reduces the amount of time
356 * during which interactive false positives cause the two problems
357 * described at the beginning of these comments.
359 static const unsigned long max_service_from_wr = 120000;
361 #define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0])
362 #define RQ_BFQQ(rq) ((rq)->elv.priv[1])
364 struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync)
366 return bic->bfqq[is_sync];
369 void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync)
371 bic->bfqq[is_sync] = bfqq;
374 struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
376 return bic->icq.q->elevator->elevator_data;
380 * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
381 * @icq: the iocontext queue.
383 static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
385 /* bic->icq is the first member, %NULL will convert to %NULL */
386 return container_of(icq, struct bfq_io_cq, icq);
390 * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
391 * @bfqd: the lookup key.
392 * @ioc: the io_context of the process doing I/O.
393 * @q: the request queue.
395 static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
396 struct io_context *ioc,
397 struct request_queue *q)
401 struct bfq_io_cq *icq;
403 spin_lock_irqsave(q->queue_lock, flags);
404 icq = icq_to_bic(ioc_lookup_icq(ioc, q));
405 spin_unlock_irqrestore(q->queue_lock, flags);
414 * Scheduler run of queue, if there are requests pending and no one in the
415 * driver that will restart queueing.
417 void bfq_schedule_dispatch(struct bfq_data *bfqd)
419 if (bfqd->queued != 0) {
420 bfq_log(bfqd, "schedule dispatch");
421 blk_mq_run_hw_queues(bfqd->queue, true);
425 #define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
426 #define bfq_class_rt(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_RT)
428 #define bfq_sample_valid(samples) ((samples) > 80)
431 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
432 * We choose the request that is closesr to the head right now. Distance
433 * behind the head is penalized and only allowed to a certain extent.
435 static struct request *bfq_choose_req(struct bfq_data *bfqd,
440 sector_t s1, s2, d1 = 0, d2 = 0;
441 unsigned long back_max;
442 #define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */
443 #define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */
444 unsigned int wrap = 0; /* bit mask: requests behind the disk head? */
446 if (!rq1 || rq1 == rq2)
451 if (rq_is_sync(rq1) && !rq_is_sync(rq2))
453 else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
455 if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META))
457 else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META))
460 s1 = blk_rq_pos(rq1);
461 s2 = blk_rq_pos(rq2);
464 * By definition, 1KiB is 2 sectors.
466 back_max = bfqd->bfq_back_max * 2;
469 * Strict one way elevator _except_ in the case where we allow
470 * short backward seeks which are biased as twice the cost of a
471 * similar forward seek.
475 else if (s1 + back_max >= last)
476 d1 = (last - s1) * bfqd->bfq_back_penalty;
478 wrap |= BFQ_RQ1_WRAP;
482 else if (s2 + back_max >= last)
483 d2 = (last - s2) * bfqd->bfq_back_penalty;
485 wrap |= BFQ_RQ2_WRAP;
487 /* Found required data */
490 * By doing switch() on the bit mask "wrap" we avoid having to
491 * check two variables for all permutations: --> faster!
494 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
509 case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */
512 * Since both rqs are wrapped,
513 * start with the one that's further behind head
514 * (--> only *one* back seek required),
515 * since back seek takes more time than forward.
525 * Async I/O can easily starve sync I/O (both sync reads and sync
526 * writes), by consuming all tags. Similarly, storms of sync writes,
527 * such as those that sync(2) may trigger, can starve sync reads.
528 * Limit depths of async I/O and sync writes so as to counter both
531 static void bfq_limit_depth(unsigned int op, struct blk_mq_alloc_data *data)
533 struct bfq_data *bfqd = data->q->elevator->elevator_data;
535 if (op_is_sync(op) && !op_is_write(op))
538 data->shallow_depth =
539 bfqd->word_depths[!!bfqd->wr_busy_queues][op_is_sync(op)];
541 bfq_log(bfqd, "[%s] wr_busy %d sync %d depth %u",
542 __func__, bfqd->wr_busy_queues, op_is_sync(op),
543 data->shallow_depth);
546 static struct bfq_queue *
547 bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
548 sector_t sector, struct rb_node **ret_parent,
549 struct rb_node ***rb_link)
551 struct rb_node **p, *parent;
552 struct bfq_queue *bfqq = NULL;
560 bfqq = rb_entry(parent, struct bfq_queue, pos_node);
563 * Sort strictly based on sector. Smallest to the left,
564 * largest to the right.
566 if (sector > blk_rq_pos(bfqq->next_rq))
568 else if (sector < blk_rq_pos(bfqq->next_rq))
576 *ret_parent = parent;
580 bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
581 (unsigned long long)sector,
582 bfqq ? bfqq->pid : 0);
587 static bool bfq_too_late_for_merging(struct bfq_queue *bfqq)
589 return bfqq->service_from_backlogged > 0 &&
590 time_is_before_jiffies(bfqq->first_IO_time +
591 bfq_merge_time_limit);
594 void bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq)
596 struct rb_node **p, *parent;
597 struct bfq_queue *__bfqq;
599 if (bfqq->pos_root) {
600 rb_erase(&bfqq->pos_node, bfqq->pos_root);
601 bfqq->pos_root = NULL;
605 * bfqq cannot be merged any longer (see comments in
606 * bfq_setup_cooperator): no point in adding bfqq into the
609 if (bfq_too_late_for_merging(bfqq))
612 if (bfq_class_idle(bfqq))
617 bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
618 __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
619 blk_rq_pos(bfqq->next_rq), &parent, &p);
621 rb_link_node(&bfqq->pos_node, parent, p);
622 rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
624 bfqq->pos_root = NULL;
628 * Tell whether there are active queues or groups with differentiated weights.
630 static bool bfq_differentiated_weights(struct bfq_data *bfqd)
633 * For weights to differ, at least one of the trees must contain
634 * at least two nodes.
636 return (!RB_EMPTY_ROOT(&bfqd->queue_weights_tree) &&
637 (bfqd->queue_weights_tree.rb_node->rb_left ||
638 bfqd->queue_weights_tree.rb_node->rb_right)
639 #ifdef CONFIG_BFQ_GROUP_IOSCHED
641 (!RB_EMPTY_ROOT(&bfqd->group_weights_tree) &&
642 (bfqd->group_weights_tree.rb_node->rb_left ||
643 bfqd->group_weights_tree.rb_node->rb_right)
649 * The following function returns true if every queue must receive the
650 * same share of the throughput (this condition is used when deciding
651 * whether idling may be disabled, see the comments in the function
652 * bfq_better_to_idle()).
654 * Such a scenario occurs when:
655 * 1) all active queues have the same weight,
656 * 2) all active groups at the same level in the groups tree have the same
658 * 3) all active groups at the same level in the groups tree have the same
659 * number of children.
661 * Unfortunately, keeping the necessary state for evaluating exactly the
662 * above symmetry conditions would be quite complex and time-consuming.
663 * Therefore this function evaluates, instead, the following stronger
664 * sub-conditions, for which it is much easier to maintain the needed
666 * 1) all active queues have the same weight,
667 * 2) all active groups have the same weight,
668 * 3) all active groups have at most one active child each.
669 * In particular, the last two conditions are always true if hierarchical
670 * support and the cgroups interface are not enabled, thus no state needs
671 * to be maintained in this case.
673 static bool bfq_symmetric_scenario(struct bfq_data *bfqd)
675 return !bfq_differentiated_weights(bfqd);
679 * If the weight-counter tree passed as input contains no counter for
680 * the weight of the input entity, then add that counter; otherwise just
681 * increment the existing counter.
683 * Note that weight-counter trees contain few nodes in mostly symmetric
684 * scenarios. For example, if all queues have the same weight, then the
685 * weight-counter tree for the queues may contain at most one node.
686 * This holds even if low_latency is on, because weight-raised queues
687 * are not inserted in the tree.
688 * In most scenarios, the rate at which nodes are created/destroyed
691 void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_entity *entity,
692 struct rb_root *root)
694 struct rb_node **new = &(root->rb_node), *parent = NULL;
697 * Do not insert if the entity is already associated with a
698 * counter, which happens if:
699 * 1) the entity is associated with a queue,
700 * 2) a request arrival has caused the queue to become both
701 * non-weight-raised, and hence change its weight, and
702 * backlogged; in this respect, each of the two events
703 * causes an invocation of this function,
704 * 3) this is the invocation of this function caused by the
705 * second event. This second invocation is actually useless,
706 * and we handle this fact by exiting immediately. More
707 * efficient or clearer solutions might possibly be adopted.
709 if (entity->weight_counter)
713 struct bfq_weight_counter *__counter = container_of(*new,
714 struct bfq_weight_counter,
718 if (entity->weight == __counter->weight) {
719 entity->weight_counter = __counter;
722 if (entity->weight < __counter->weight)
723 new = &((*new)->rb_left);
725 new = &((*new)->rb_right);
728 entity->weight_counter = kzalloc(sizeof(struct bfq_weight_counter),
732 * In the unlucky event of an allocation failure, we just
733 * exit. This will cause the weight of entity to not be
734 * considered in bfq_differentiated_weights, which, in its
735 * turn, causes the scenario to be deemed wrongly symmetric in
736 * case entity's weight would have been the only weight making
737 * the scenario asymmetric. On the bright side, no unbalance
738 * will however occur when entity becomes inactive again (the
739 * invocation of this function is triggered by an activation
740 * of entity). In fact, bfq_weights_tree_remove does nothing
741 * if !entity->weight_counter.
743 if (unlikely(!entity->weight_counter))
746 entity->weight_counter->weight = entity->weight;
747 rb_link_node(&entity->weight_counter->weights_node, parent, new);
748 rb_insert_color(&entity->weight_counter->weights_node, root);
751 entity->weight_counter->num_active++;
755 * Decrement the weight counter associated with the entity, and, if the
756 * counter reaches 0, remove the counter from the tree.
757 * See the comments to the function bfq_weights_tree_add() for considerations
760 void __bfq_weights_tree_remove(struct bfq_data *bfqd,
761 struct bfq_entity *entity,
762 struct rb_root *root)
764 if (!entity->weight_counter)
767 entity->weight_counter->num_active--;
768 if (entity->weight_counter->num_active > 0)
769 goto reset_entity_pointer;
771 rb_erase(&entity->weight_counter->weights_node, root);
772 kfree(entity->weight_counter);
774 reset_entity_pointer:
775 entity->weight_counter = NULL;
779 * Invoke __bfq_weights_tree_remove on bfqq and all its inactive
782 void bfq_weights_tree_remove(struct bfq_data *bfqd,
783 struct bfq_queue *bfqq)
785 struct bfq_entity *entity = bfqq->entity.parent;
787 __bfq_weights_tree_remove(bfqd, &bfqq->entity,
788 &bfqd->queue_weights_tree);
790 for_each_entity(entity) {
791 struct bfq_sched_data *sd = entity->my_sched_data;
793 if (sd->next_in_service || sd->in_service_entity) {
795 * entity is still active, because either
796 * next_in_service or in_service_entity is not
797 * NULL (see the comments on the definition of
798 * next_in_service for details on why
799 * in_service_entity must be checked too).
801 * As a consequence, the weight of entity is
802 * not to be removed. In addition, if entity
803 * is active, then its parent entities are
804 * active as well, and thus their weights are
805 * not to be removed either. In the end, this
806 * loop must stop here.
810 __bfq_weights_tree_remove(bfqd, entity,
811 &bfqd->group_weights_tree);
816 * Return expired entry, or NULL to just start from scratch in rbtree.
818 static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
819 struct request *last)
823 if (bfq_bfqq_fifo_expire(bfqq))
826 bfq_mark_bfqq_fifo_expire(bfqq);
828 rq = rq_entry_fifo(bfqq->fifo.next);
830 if (rq == last || ktime_get_ns() < rq->fifo_time)
833 bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
837 static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
838 struct bfq_queue *bfqq,
839 struct request *last)
841 struct rb_node *rbnext = rb_next(&last->rb_node);
842 struct rb_node *rbprev = rb_prev(&last->rb_node);
843 struct request *next, *prev = NULL;
845 /* Follow expired path, else get first next available. */
846 next = bfq_check_fifo(bfqq, last);
851 prev = rb_entry_rq(rbprev);
854 next = rb_entry_rq(rbnext);
856 rbnext = rb_first(&bfqq->sort_list);
857 if (rbnext && rbnext != &last->rb_node)
858 next = rb_entry_rq(rbnext);
861 return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
864 /* see the definition of bfq_async_charge_factor for details */
865 static unsigned long bfq_serv_to_charge(struct request *rq,
866 struct bfq_queue *bfqq)
868 if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1)
869 return blk_rq_sectors(rq);
871 return blk_rq_sectors(rq) * bfq_async_charge_factor;
875 * bfq_updated_next_req - update the queue after a new next_rq selection.
876 * @bfqd: the device data the queue belongs to.
877 * @bfqq: the queue to update.
879 * If the first request of a queue changes we make sure that the queue
880 * has enough budget to serve at least its first request (if the
881 * request has grown). We do this because if the queue has not enough
882 * budget for its first request, it has to go through two dispatch
883 * rounds to actually get it dispatched.
885 static void bfq_updated_next_req(struct bfq_data *bfqd,
886 struct bfq_queue *bfqq)
888 struct bfq_entity *entity = &bfqq->entity;
889 struct request *next_rq = bfqq->next_rq;
890 unsigned long new_budget;
895 if (bfqq == bfqd->in_service_queue)
897 * In order not to break guarantees, budgets cannot be
898 * changed after an entity has been selected.
902 new_budget = max_t(unsigned long, bfqq->max_budget,
903 bfq_serv_to_charge(next_rq, bfqq));
904 if (entity->budget != new_budget) {
905 entity->budget = new_budget;
906 bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
908 bfq_requeue_bfqq(bfqd, bfqq, false);
912 static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
916 if (bfqd->bfq_wr_max_time > 0)
917 return bfqd->bfq_wr_max_time;
919 dur = bfqd->rate_dur_prod;
920 do_div(dur, bfqd->peak_rate);
923 * Limit duration between 3 and 25 seconds. The upper limit
924 * has been conservatively set after the following worst case:
925 * on a QEMU/KVM virtual machine
926 * - running in a slow PC
927 * - with a virtual disk stacked on a slow low-end 5400rpm HDD
928 * - serving a heavy I/O workload, such as the sequential reading
930 * mplayer took 23 seconds to start, if constantly weight-raised.
932 * As for higher values than that accomodating the above bad
933 * scenario, tests show that higher values would often yield
934 * the opposite of the desired result, i.e., would worsen
935 * responsiveness by allowing non-interactive applications to
936 * preserve weight raising for too long.
938 * On the other end, lower values than 3 seconds make it
939 * difficult for most interactive tasks to complete their jobs
940 * before weight-raising finishes.
942 return clamp_val(dur, msecs_to_jiffies(3000), msecs_to_jiffies(25000));
945 /* switch back from soft real-time to interactive weight raising */
946 static void switch_back_to_interactive_wr(struct bfq_queue *bfqq,
947 struct bfq_data *bfqd)
949 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
950 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
951 bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt;
955 bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
956 struct bfq_io_cq *bic, bool bfq_already_existing)
958 unsigned int old_wr_coeff = bfqq->wr_coeff;
959 bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
961 if (bic->saved_has_short_ttime)
962 bfq_mark_bfqq_has_short_ttime(bfqq);
964 bfq_clear_bfqq_has_short_ttime(bfqq);
966 if (bic->saved_IO_bound)
967 bfq_mark_bfqq_IO_bound(bfqq);
969 bfq_clear_bfqq_IO_bound(bfqq);
971 bfqq->ttime = bic->saved_ttime;
972 bfqq->wr_coeff = bic->saved_wr_coeff;
973 bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt;
974 bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish;
975 bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time;
977 if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
978 time_is_before_jiffies(bfqq->last_wr_start_finish +
979 bfqq->wr_cur_max_time))) {
980 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
981 !bfq_bfqq_in_large_burst(bfqq) &&
982 time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt +
983 bfq_wr_duration(bfqd))) {
984 switch_back_to_interactive_wr(bfqq, bfqd);
987 bfq_log_bfqq(bfqq->bfqd, bfqq,
988 "resume state: switching off wr");
992 /* make sure weight will be updated, however we got here */
993 bfqq->entity.prio_changed = 1;
998 if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
999 bfqd->wr_busy_queues++;
1000 else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
1001 bfqd->wr_busy_queues--;
1004 static int bfqq_process_refs(struct bfq_queue *bfqq)
1006 return bfqq->ref - bfqq->allocated - bfqq->entity.on_st;
1009 /* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
1010 static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1012 struct bfq_queue *item;
1013 struct hlist_node *n;
1015 hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
1016 hlist_del_init(&item->burst_list_node);
1017 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1018 bfqd->burst_size = 1;
1019 bfqd->burst_parent_entity = bfqq->entity.parent;
1022 /* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
1023 static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1025 /* Increment burst size to take into account also bfqq */
1028 if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
1029 struct bfq_queue *pos, *bfqq_item;
1030 struct hlist_node *n;
1033 * Enough queues have been activated shortly after each
1034 * other to consider this burst as large.
1036 bfqd->large_burst = true;
1039 * We can now mark all queues in the burst list as
1040 * belonging to a large burst.
1042 hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
1044 bfq_mark_bfqq_in_large_burst(bfqq_item);
1045 bfq_mark_bfqq_in_large_burst(bfqq);
1048 * From now on, and until the current burst finishes, any
1049 * new queue being activated shortly after the last queue
1050 * was inserted in the burst can be immediately marked as
1051 * belonging to a large burst. So the burst list is not
1052 * needed any more. Remove it.
1054 hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
1056 hlist_del_init(&pos->burst_list_node);
1058 * Burst not yet large: add bfqq to the burst list. Do
1059 * not increment the ref counter for bfqq, because bfqq
1060 * is removed from the burst list before freeing bfqq
1063 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1067 * If many queues belonging to the same group happen to be created
1068 * shortly after each other, then the processes associated with these
1069 * queues have typically a common goal. In particular, bursts of queue
1070 * creations are usually caused by services or applications that spawn
1071 * many parallel threads/processes. Examples are systemd during boot,
1072 * or git grep. To help these processes get their job done as soon as
1073 * possible, it is usually better to not grant either weight-raising
1074 * or device idling to their queues.
1076 * In this comment we describe, firstly, the reasons why this fact
1077 * holds, and, secondly, the next function, which implements the main
1078 * steps needed to properly mark these queues so that they can then be
1079 * treated in a different way.
1081 * The above services or applications benefit mostly from a high
1082 * throughput: the quicker the requests of the activated queues are
1083 * cumulatively served, the sooner the target job of these queues gets
1084 * completed. As a consequence, weight-raising any of these queues,
1085 * which also implies idling the device for it, is almost always
1086 * counterproductive. In most cases it just lowers throughput.
1088 * On the other hand, a burst of queue creations may be caused also by
1089 * the start of an application that does not consist of a lot of
1090 * parallel I/O-bound threads. In fact, with a complex application,
1091 * several short processes may need to be executed to start-up the
1092 * application. In this respect, to start an application as quickly as
1093 * possible, the best thing to do is in any case to privilege the I/O
1094 * related to the application with respect to all other
1095 * I/O. Therefore, the best strategy to start as quickly as possible
1096 * an application that causes a burst of queue creations is to
1097 * weight-raise all the queues created during the burst. This is the
1098 * exact opposite of the best strategy for the other type of bursts.
1100 * In the end, to take the best action for each of the two cases, the
1101 * two types of bursts need to be distinguished. Fortunately, this
1102 * seems relatively easy, by looking at the sizes of the bursts. In
1103 * particular, we found a threshold such that only bursts with a
1104 * larger size than that threshold are apparently caused by
1105 * services or commands such as systemd or git grep. For brevity,
1106 * hereafter we call just 'large' these bursts. BFQ *does not*
1107 * weight-raise queues whose creation occurs in a large burst. In
1108 * addition, for each of these queues BFQ performs or does not perform
1109 * idling depending on which choice boosts the throughput more. The
1110 * exact choice depends on the device and request pattern at
1113 * Unfortunately, false positives may occur while an interactive task
1114 * is starting (e.g., an application is being started). The
1115 * consequence is that the queues associated with the task do not
1116 * enjoy weight raising as expected. Fortunately these false positives
1117 * are very rare. They typically occur if some service happens to
1118 * start doing I/O exactly when the interactive task starts.
1120 * Turning back to the next function, it implements all the steps
1121 * needed to detect the occurrence of a large burst and to properly
1122 * mark all the queues belonging to it (so that they can then be
1123 * treated in a different way). This goal is achieved by maintaining a
1124 * "burst list" that holds, temporarily, the queues that belong to the
1125 * burst in progress. The list is then used to mark these queues as
1126 * belonging to a large burst if the burst does become large. The main
1127 * steps are the following.
1129 * . when the very first queue is created, the queue is inserted into the
1130 * list (as it could be the first queue in a possible burst)
1132 * . if the current burst has not yet become large, and a queue Q that does
1133 * not yet belong to the burst is activated shortly after the last time
1134 * at which a new queue entered the burst list, then the function appends
1135 * Q to the burst list
1137 * . if, as a consequence of the previous step, the burst size reaches
1138 * the large-burst threshold, then
1140 * . all the queues in the burst list are marked as belonging to a
1143 * . the burst list is deleted; in fact, the burst list already served
1144 * its purpose (keeping temporarily track of the queues in a burst,
1145 * so as to be able to mark them as belonging to a large burst in the
1146 * previous sub-step), and now is not needed any more
1148 * . the device enters a large-burst mode
1150 * . if a queue Q that does not belong to the burst is created while
1151 * the device is in large-burst mode and shortly after the last time
1152 * at which a queue either entered the burst list or was marked as
1153 * belonging to the current large burst, then Q is immediately marked
1154 * as belonging to a large burst.
1156 * . if a queue Q that does not belong to the burst is created a while
1157 * later, i.e., not shortly after, than the last time at which a queue
1158 * either entered the burst list or was marked as belonging to the
1159 * current large burst, then the current burst is deemed as finished and:
1161 * . the large-burst mode is reset if set
1163 * . the burst list is emptied
1165 * . Q is inserted in the burst list, as Q may be the first queue
1166 * in a possible new burst (then the burst list contains just Q
1169 static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1172 * If bfqq is already in the burst list or is part of a large
1173 * burst, or finally has just been split, then there is
1174 * nothing else to do.
1176 if (!hlist_unhashed(&bfqq->burst_list_node) ||
1177 bfq_bfqq_in_large_burst(bfqq) ||
1178 time_is_after_eq_jiffies(bfqq->split_time +
1179 msecs_to_jiffies(10)))
1183 * If bfqq's creation happens late enough, or bfqq belongs to
1184 * a different group than the burst group, then the current
1185 * burst is finished, and related data structures must be
1188 * In this respect, consider the special case where bfqq is
1189 * the very first queue created after BFQ is selected for this
1190 * device. In this case, last_ins_in_burst and
1191 * burst_parent_entity are not yet significant when we get
1192 * here. But it is easy to verify that, whether or not the
1193 * following condition is true, bfqq will end up being
1194 * inserted into the burst list. In particular the list will
1195 * happen to contain only bfqq. And this is exactly what has
1196 * to happen, as bfqq may be the first queue of the first
1199 if (time_is_before_jiffies(bfqd->last_ins_in_burst +
1200 bfqd->bfq_burst_interval) ||
1201 bfqq->entity.parent != bfqd->burst_parent_entity) {
1202 bfqd->large_burst = false;
1203 bfq_reset_burst_list(bfqd, bfqq);
1208 * If we get here, then bfqq is being activated shortly after the
1209 * last queue. So, if the current burst is also large, we can mark
1210 * bfqq as belonging to this large burst immediately.
1212 if (bfqd->large_burst) {
1213 bfq_mark_bfqq_in_large_burst(bfqq);
1218 * If we get here, then a large-burst state has not yet been
1219 * reached, but bfqq is being activated shortly after the last
1220 * queue. Then we add bfqq to the burst.
1222 bfq_add_to_burst(bfqd, bfqq);
1225 * At this point, bfqq either has been added to the current
1226 * burst or has caused the current burst to terminate and a
1227 * possible new burst to start. In particular, in the second
1228 * case, bfqq has become the first queue in the possible new
1229 * burst. In both cases last_ins_in_burst needs to be moved
1232 bfqd->last_ins_in_burst = jiffies;
1235 static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
1237 struct bfq_entity *entity = &bfqq->entity;
1239 return entity->budget - entity->service;
1243 * If enough samples have been computed, return the current max budget
1244 * stored in bfqd, which is dynamically updated according to the
1245 * estimated disk peak rate; otherwise return the default max budget
1247 static int bfq_max_budget(struct bfq_data *bfqd)
1249 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1250 return bfq_default_max_budget;
1252 return bfqd->bfq_max_budget;
1256 * Return min budget, which is a fraction of the current or default
1257 * max budget (trying with 1/32)
1259 static int bfq_min_budget(struct bfq_data *bfqd)
1261 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1262 return bfq_default_max_budget / 32;
1264 return bfqd->bfq_max_budget / 32;
1268 * The next function, invoked after the input queue bfqq switches from
1269 * idle to busy, updates the budget of bfqq. The function also tells
1270 * whether the in-service queue should be expired, by returning
1271 * true. The purpose of expiring the in-service queue is to give bfqq
1272 * the chance to possibly preempt the in-service queue, and the reason
1273 * for preempting the in-service queue is to achieve one of the two
1276 * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
1277 * expired because it has remained idle. In particular, bfqq may have
1278 * expired for one of the following two reasons:
1280 * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
1281 * and did not make it to issue a new request before its last
1282 * request was served;
1284 * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
1285 * a new request before the expiration of the idling-time.
1287 * Even if bfqq has expired for one of the above reasons, the process
1288 * associated with the queue may be however issuing requests greedily,
1289 * and thus be sensitive to the bandwidth it receives (bfqq may have
1290 * remained idle for other reasons: CPU high load, bfqq not enjoying
1291 * idling, I/O throttling somewhere in the path from the process to
1292 * the I/O scheduler, ...). But if, after every expiration for one of
1293 * the above two reasons, bfqq has to wait for the service of at least
1294 * one full budget of another queue before being served again, then
1295 * bfqq is likely to get a much lower bandwidth or resource time than
1296 * its reserved ones. To address this issue, two countermeasures need
1299 * First, the budget and the timestamps of bfqq need to be updated in
1300 * a special way on bfqq reactivation: they need to be updated as if
1301 * bfqq did not remain idle and did not expire. In fact, if they are
1302 * computed as if bfqq expired and remained idle until reactivation,
1303 * then the process associated with bfqq is treated as if, instead of
1304 * being greedy, it stopped issuing requests when bfqq remained idle,
1305 * and restarts issuing requests only on this reactivation. In other
1306 * words, the scheduler does not help the process recover the "service
1307 * hole" between bfqq expiration and reactivation. As a consequence,
1308 * the process receives a lower bandwidth than its reserved one. In
1309 * contrast, to recover this hole, the budget must be updated as if
1310 * bfqq was not expired at all before this reactivation, i.e., it must
1311 * be set to the value of the remaining budget when bfqq was
1312 * expired. Along the same line, timestamps need to be assigned the
1313 * value they had the last time bfqq was selected for service, i.e.,
1314 * before last expiration. Thus timestamps need to be back-shifted
1315 * with respect to their normal computation (see [1] for more details
1316 * on this tricky aspect).
1318 * Secondly, to allow the process to recover the hole, the in-service
1319 * queue must be expired too, to give bfqq the chance to preempt it
1320 * immediately. In fact, if bfqq has to wait for a full budget of the
1321 * in-service queue to be completed, then it may become impossible to
1322 * let the process recover the hole, even if the back-shifted
1323 * timestamps of bfqq are lower than those of the in-service queue. If
1324 * this happens for most or all of the holes, then the process may not
1325 * receive its reserved bandwidth. In this respect, it is worth noting
1326 * that, being the service of outstanding requests unpreemptible, a
1327 * little fraction of the holes may however be unrecoverable, thereby
1328 * causing a little loss of bandwidth.
1330 * The last important point is detecting whether bfqq does need this
1331 * bandwidth recovery. In this respect, the next function deems the
1332 * process associated with bfqq greedy, and thus allows it to recover
1333 * the hole, if: 1) the process is waiting for the arrival of a new
1334 * request (which implies that bfqq expired for one of the above two
1335 * reasons), and 2) such a request has arrived soon. The first
1336 * condition is controlled through the flag non_blocking_wait_rq,
1337 * while the second through the flag arrived_in_time. If both
1338 * conditions hold, then the function computes the budget in the
1339 * above-described special way, and signals that the in-service queue
1340 * should be expired. Timestamp back-shifting is done later in
1341 * __bfq_activate_entity.
1343 * 2. Reduce latency. Even if timestamps are not backshifted to let
1344 * the process associated with bfqq recover a service hole, bfqq may
1345 * however happen to have, after being (re)activated, a lower finish
1346 * timestamp than the in-service queue. That is, the next budget of
1347 * bfqq may have to be completed before the one of the in-service
1348 * queue. If this is the case, then preempting the in-service queue
1349 * allows this goal to be achieved, apart from the unpreemptible,
1350 * outstanding requests mentioned above.
1352 * Unfortunately, regardless of which of the above two goals one wants
1353 * to achieve, service trees need first to be updated to know whether
1354 * the in-service queue must be preempted. To have service trees
1355 * correctly updated, the in-service queue must be expired and
1356 * rescheduled, and bfqq must be scheduled too. This is one of the
1357 * most costly operations (in future versions, the scheduling
1358 * mechanism may be re-designed in such a way to make it possible to
1359 * know whether preemption is needed without needing to update service
1360 * trees). In addition, queue preemptions almost always cause random
1361 * I/O, and thus loss of throughput. Because of these facts, the next
1362 * function adopts the following simple scheme to avoid both costly
1363 * operations and too frequent preemptions: it requests the expiration
1364 * of the in-service queue (unconditionally) only for queues that need
1365 * to recover a hole, or that either are weight-raised or deserve to
1368 static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
1369 struct bfq_queue *bfqq,
1370 bool arrived_in_time,
1371 bool wr_or_deserves_wr)
1373 struct bfq_entity *entity = &bfqq->entity;
1375 if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time) {
1377 * We do not clear the flag non_blocking_wait_rq here, as
1378 * the latter is used in bfq_activate_bfqq to signal
1379 * that timestamps need to be back-shifted (and is
1380 * cleared right after).
1384 * In next assignment we rely on that either
1385 * entity->service or entity->budget are not updated
1386 * on expiration if bfqq is empty (see
1387 * __bfq_bfqq_recalc_budget). Thus both quantities
1388 * remain unchanged after such an expiration, and the
1389 * following statement therefore assigns to
1390 * entity->budget the remaining budget on such an
1393 entity->budget = min_t(unsigned long,
1394 bfq_bfqq_budget_left(bfqq),
1398 * At this point, we have used entity->service to get
1399 * the budget left (needed for updating
1400 * entity->budget). Thus we finally can, and have to,
1401 * reset entity->service. The latter must be reset
1402 * because bfqq would otherwise be charged again for
1403 * the service it has received during its previous
1406 entity->service = 0;
1412 * We can finally complete expiration, by setting service to 0.
1414 entity->service = 0;
1415 entity->budget = max_t(unsigned long, bfqq->max_budget,
1416 bfq_serv_to_charge(bfqq->next_rq, bfqq));
1417 bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
1418 return wr_or_deserves_wr;
1422 * Return the farthest past time instant according to jiffies
1425 static unsigned long bfq_smallest_from_now(void)
1427 return jiffies - MAX_JIFFY_OFFSET;
1430 static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
1431 struct bfq_queue *bfqq,
1432 unsigned int old_wr_coeff,
1433 bool wr_or_deserves_wr,
1438 if (old_wr_coeff == 1 && wr_or_deserves_wr) {
1439 /* start a weight-raising period */
1441 bfqq->service_from_wr = 0;
1442 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1443 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1446 * No interactive weight raising in progress
1447 * here: assign minus infinity to
1448 * wr_start_at_switch_to_srt, to make sure
1449 * that, at the end of the soft-real-time
1450 * weight raising periods that is starting
1451 * now, no interactive weight-raising period
1452 * may be wrongly considered as still in
1453 * progress (and thus actually started by
1456 bfqq->wr_start_at_switch_to_srt =
1457 bfq_smallest_from_now();
1458 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1459 BFQ_SOFTRT_WEIGHT_FACTOR;
1460 bfqq->wr_cur_max_time =
1461 bfqd->bfq_wr_rt_max_time;
1465 * If needed, further reduce budget to make sure it is
1466 * close to bfqq's backlog, so as to reduce the
1467 * scheduling-error component due to a too large
1468 * budget. Do not care about throughput consequences,
1469 * but only about latency. Finally, do not assign a
1470 * too small budget either, to avoid increasing
1471 * latency by causing too frequent expirations.
1473 bfqq->entity.budget = min_t(unsigned long,
1474 bfqq->entity.budget,
1475 2 * bfq_min_budget(bfqd));
1476 } else if (old_wr_coeff > 1) {
1477 if (interactive) { /* update wr coeff and duration */
1478 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1479 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1480 } else if (in_burst)
1484 * The application is now or still meeting the
1485 * requirements for being deemed soft rt. We
1486 * can then correctly and safely (re)charge
1487 * the weight-raising duration for the
1488 * application with the weight-raising
1489 * duration for soft rt applications.
1491 * In particular, doing this recharge now, i.e.,
1492 * before the weight-raising period for the
1493 * application finishes, reduces the probability
1494 * of the following negative scenario:
1495 * 1) the weight of a soft rt application is
1496 * raised at startup (as for any newly
1497 * created application),
1498 * 2) since the application is not interactive,
1499 * at a certain time weight-raising is
1500 * stopped for the application,
1501 * 3) at that time the application happens to
1502 * still have pending requests, and hence
1503 * is destined to not have a chance to be
1504 * deemed soft rt before these requests are
1505 * completed (see the comments to the
1506 * function bfq_bfqq_softrt_next_start()
1507 * for details on soft rt detection),
1508 * 4) these pending requests experience a high
1509 * latency because the application is not
1510 * weight-raised while they are pending.
1512 if (bfqq->wr_cur_max_time !=
1513 bfqd->bfq_wr_rt_max_time) {
1514 bfqq->wr_start_at_switch_to_srt =
1515 bfqq->last_wr_start_finish;
1517 bfqq->wr_cur_max_time =
1518 bfqd->bfq_wr_rt_max_time;
1519 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1520 BFQ_SOFTRT_WEIGHT_FACTOR;
1522 bfqq->last_wr_start_finish = jiffies;
1527 static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
1528 struct bfq_queue *bfqq)
1530 return bfqq->dispatched == 0 &&
1531 time_is_before_jiffies(
1532 bfqq->budget_timeout +
1533 bfqd->bfq_wr_min_idle_time);
1536 static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
1537 struct bfq_queue *bfqq,
1542 bool soft_rt, in_burst, wr_or_deserves_wr,
1543 bfqq_wants_to_preempt,
1544 idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
1546 * See the comments on
1547 * bfq_bfqq_update_budg_for_activation for
1548 * details on the usage of the next variable.
1550 arrived_in_time = ktime_get_ns() <=
1551 bfqq->ttime.last_end_request +
1552 bfqd->bfq_slice_idle * 3;
1556 * bfqq deserves to be weight-raised if:
1558 * - it does not belong to a large burst,
1559 * - it has been idle for enough time or is soft real-time,
1560 * - is linked to a bfq_io_cq (it is not shared in any sense).
1562 in_burst = bfq_bfqq_in_large_burst(bfqq);
1563 soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
1565 time_is_before_jiffies(bfqq->soft_rt_next_start) &&
1566 bfqq->dispatched == 0;
1567 *interactive = !in_burst && idle_for_long_time;
1568 wr_or_deserves_wr = bfqd->low_latency &&
1569 (bfqq->wr_coeff > 1 ||
1570 (bfq_bfqq_sync(bfqq) &&
1571 bfqq->bic && (*interactive || soft_rt)));
1574 * Using the last flag, update budget and check whether bfqq
1575 * may want to preempt the in-service queue.
1577 bfqq_wants_to_preempt =
1578 bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
1583 * If bfqq happened to be activated in a burst, but has been
1584 * idle for much more than an interactive queue, then we
1585 * assume that, in the overall I/O initiated in the burst, the
1586 * I/O associated with bfqq is finished. So bfqq does not need
1587 * to be treated as a queue belonging to a burst
1588 * anymore. Accordingly, we reset bfqq's in_large_burst flag
1589 * if set, and remove bfqq from the burst list if it's
1590 * there. We do not decrement burst_size, because the fact
1591 * that bfqq does not need to belong to the burst list any
1592 * more does not invalidate the fact that bfqq was created in
1595 if (likely(!bfq_bfqq_just_created(bfqq)) &&
1596 idle_for_long_time &&
1597 time_is_before_jiffies(
1598 bfqq->budget_timeout +
1599 msecs_to_jiffies(10000))) {
1600 hlist_del_init(&bfqq->burst_list_node);
1601 bfq_clear_bfqq_in_large_burst(bfqq);
1604 bfq_clear_bfqq_just_created(bfqq);
1607 if (!bfq_bfqq_IO_bound(bfqq)) {
1608 if (arrived_in_time) {
1609 bfqq->requests_within_timer++;
1610 if (bfqq->requests_within_timer >=
1611 bfqd->bfq_requests_within_timer)
1612 bfq_mark_bfqq_IO_bound(bfqq);
1614 bfqq->requests_within_timer = 0;
1617 if (bfqd->low_latency) {
1618 if (unlikely(time_is_after_jiffies(bfqq->split_time)))
1621 jiffies - bfqd->bfq_wr_min_idle_time - 1;
1623 if (time_is_before_jiffies(bfqq->split_time +
1624 bfqd->bfq_wr_min_idle_time)) {
1625 bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
1632 if (old_wr_coeff != bfqq->wr_coeff)
1633 bfqq->entity.prio_changed = 1;
1637 bfqq->last_idle_bklogged = jiffies;
1638 bfqq->service_from_backlogged = 0;
1639 bfq_clear_bfqq_softrt_update(bfqq);
1641 bfq_add_bfqq_busy(bfqd, bfqq);
1644 * Expire in-service queue only if preemption may be needed
1645 * for guarantees. In this respect, the function
1646 * next_queue_may_preempt just checks a simple, necessary
1647 * condition, and not a sufficient condition based on
1648 * timestamps. In fact, for the latter condition to be
1649 * evaluated, timestamps would need first to be updated, and
1650 * this operation is quite costly (see the comments on the
1651 * function bfq_bfqq_update_budg_for_activation).
1653 if (bfqd->in_service_queue && bfqq_wants_to_preempt &&
1654 bfqd->in_service_queue->wr_coeff < bfqq->wr_coeff &&
1655 next_queue_may_preempt(bfqd))
1656 bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
1657 false, BFQQE_PREEMPTED);
1660 static void bfq_add_request(struct request *rq)
1662 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1663 struct bfq_data *bfqd = bfqq->bfqd;
1664 struct request *next_rq, *prev;
1665 unsigned int old_wr_coeff = bfqq->wr_coeff;
1666 bool interactive = false;
1668 bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
1669 bfqq->queued[rq_is_sync(rq)]++;
1672 elv_rb_add(&bfqq->sort_list, rq);
1675 * Check if this request is a better next-serve candidate.
1677 prev = bfqq->next_rq;
1678 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
1679 bfqq->next_rq = next_rq;
1682 * Adjust priority tree position, if next_rq changes.
1684 if (prev != bfqq->next_rq)
1685 bfq_pos_tree_add_move(bfqd, bfqq);
1687 if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
1688 bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
1691 if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
1692 time_is_before_jiffies(
1693 bfqq->last_wr_start_finish +
1694 bfqd->bfq_wr_min_inter_arr_async)) {
1695 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1696 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1698 bfqd->wr_busy_queues++;
1699 bfqq->entity.prio_changed = 1;
1701 if (prev != bfqq->next_rq)
1702 bfq_updated_next_req(bfqd, bfqq);
1706 * Assign jiffies to last_wr_start_finish in the following
1709 * . if bfqq is not going to be weight-raised, because, for
1710 * non weight-raised queues, last_wr_start_finish stores the
1711 * arrival time of the last request; as of now, this piece
1712 * of information is used only for deciding whether to
1713 * weight-raise async queues
1715 * . if bfqq is not weight-raised, because, if bfqq is now
1716 * switching to weight-raised, then last_wr_start_finish
1717 * stores the time when weight-raising starts
1719 * . if bfqq is interactive, because, regardless of whether
1720 * bfqq is currently weight-raised, the weight-raising
1721 * period must start or restart (this case is considered
1722 * separately because it is not detected by the above
1723 * conditions, if bfqq is already weight-raised)
1725 * last_wr_start_finish has to be updated also if bfqq is soft
1726 * real-time, because the weight-raising period is constantly
1727 * restarted on idle-to-busy transitions for these queues, but
1728 * this is already done in bfq_bfqq_handle_idle_busy_switch if
1731 if (bfqd->low_latency &&
1732 (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
1733 bfqq->last_wr_start_finish = jiffies;
1736 static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
1738 struct request_queue *q)
1740 struct bfq_queue *bfqq = bfqd->bio_bfqq;
1744 return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
1749 static sector_t get_sdist(sector_t last_pos, struct request *rq)
1752 return abs(blk_rq_pos(rq) - last_pos);
1757 #if 0 /* Still not clear if we can do without next two functions */
1758 static void bfq_activate_request(struct request_queue *q, struct request *rq)
1760 struct bfq_data *bfqd = q->elevator->elevator_data;
1762 bfqd->rq_in_driver++;
1765 static void bfq_deactivate_request(struct request_queue *q, struct request *rq)
1767 struct bfq_data *bfqd = q->elevator->elevator_data;
1769 bfqd->rq_in_driver--;
1773 static void bfq_remove_request(struct request_queue *q,
1776 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1777 struct bfq_data *bfqd = bfqq->bfqd;
1778 const int sync = rq_is_sync(rq);
1780 if (bfqq->next_rq == rq) {
1781 bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
1782 bfq_updated_next_req(bfqd, bfqq);
1785 if (rq->queuelist.prev != &rq->queuelist)
1786 list_del_init(&rq->queuelist);
1787 bfqq->queued[sync]--;
1789 elv_rb_del(&bfqq->sort_list, rq);
1791 elv_rqhash_del(q, rq);
1792 if (q->last_merge == rq)
1793 q->last_merge = NULL;
1795 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
1796 bfqq->next_rq = NULL;
1798 if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
1799 bfq_del_bfqq_busy(bfqd, bfqq, false);
1801 * bfqq emptied. In normal operation, when
1802 * bfqq is empty, bfqq->entity.service and
1803 * bfqq->entity.budget must contain,
1804 * respectively, the service received and the
1805 * budget used last time bfqq emptied. These
1806 * facts do not hold in this case, as at least
1807 * this last removal occurred while bfqq is
1808 * not in service. To avoid inconsistencies,
1809 * reset both bfqq->entity.service and
1810 * bfqq->entity.budget, if bfqq has still a
1811 * process that may issue I/O requests to it.
1813 bfqq->entity.budget = bfqq->entity.service = 0;
1817 * Remove queue from request-position tree as it is empty.
1819 if (bfqq->pos_root) {
1820 rb_erase(&bfqq->pos_node, bfqq->pos_root);
1821 bfqq->pos_root = NULL;
1824 bfq_pos_tree_add_move(bfqd, bfqq);
1827 if (rq->cmd_flags & REQ_META)
1828 bfqq->meta_pending--;
1832 static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio)
1834 struct request_queue *q = hctx->queue;
1835 struct bfq_data *bfqd = q->elevator->elevator_data;
1836 struct request *free = NULL;
1838 * bfq_bic_lookup grabs the queue_lock: invoke it now and
1839 * store its return value for later use, to avoid nesting
1840 * queue_lock inside the bfqd->lock. We assume that the bic
1841 * returned by bfq_bic_lookup does not go away before
1842 * bfqd->lock is taken.
1844 struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q);
1847 spin_lock_irq(&bfqd->lock);
1850 bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf));
1852 bfqd->bio_bfqq = NULL;
1853 bfqd->bio_bic = bic;
1855 ret = blk_mq_sched_try_merge(q, bio, &free);
1858 blk_mq_free_request(free);
1859 spin_unlock_irq(&bfqd->lock);
1864 static int bfq_request_merge(struct request_queue *q, struct request **req,
1867 struct bfq_data *bfqd = q->elevator->elevator_data;
1868 struct request *__rq;
1870 __rq = bfq_find_rq_fmerge(bfqd, bio, q);
1871 if (__rq && elv_bio_merge_ok(__rq, bio)) {
1873 return ELEVATOR_FRONT_MERGE;
1876 return ELEVATOR_NO_MERGE;
1879 static struct bfq_queue *bfq_init_rq(struct request *rq);
1881 static void bfq_request_merged(struct request_queue *q, struct request *req,
1882 enum elv_merge type)
1884 if (type == ELEVATOR_FRONT_MERGE &&
1885 rb_prev(&req->rb_node) &&
1887 blk_rq_pos(container_of(rb_prev(&req->rb_node),
1888 struct request, rb_node))) {
1889 struct bfq_queue *bfqq = bfq_init_rq(req);
1890 struct bfq_data *bfqd;
1891 struct request *prev, *next_rq;
1898 /* Reposition request in its sort_list */
1899 elv_rb_del(&bfqq->sort_list, req);
1900 elv_rb_add(&bfqq->sort_list, req);
1902 /* Choose next request to be served for bfqq */
1903 prev = bfqq->next_rq;
1904 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
1905 bfqd->last_position);
1906 bfqq->next_rq = next_rq;
1908 * If next_rq changes, update both the queue's budget to
1909 * fit the new request and the queue's position in its
1912 if (prev != bfqq->next_rq) {
1913 bfq_updated_next_req(bfqd, bfqq);
1914 bfq_pos_tree_add_move(bfqd, bfqq);
1920 * This function is called to notify the scheduler that the requests
1921 * rq and 'next' have been merged, with 'next' going away. BFQ
1922 * exploits this hook to address the following issue: if 'next' has a
1923 * fifo_time lower that rq, then the fifo_time of rq must be set to
1924 * the value of 'next', to not forget the greater age of 'next'.
1926 * NOTE: in this function we assume that rq is in a bfq_queue, basing
1927 * on that rq is picked from the hash table q->elevator->hash, which,
1928 * in its turn, is filled only with I/O requests present in
1929 * bfq_queues, while BFQ is in use for the request queue q. In fact,
1930 * the function that fills this hash table (elv_rqhash_add) is called
1931 * only by bfq_insert_request.
1933 static void bfq_requests_merged(struct request_queue *q, struct request *rq,
1934 struct request *next)
1936 struct bfq_queue *bfqq = bfq_init_rq(rq),
1937 *next_bfqq = bfq_init_rq(next);
1943 * If next and rq belong to the same bfq_queue and next is older
1944 * than rq, then reposition rq in the fifo (by substituting next
1945 * with rq). Otherwise, if next and rq belong to different
1946 * bfq_queues, never reposition rq: in fact, we would have to
1947 * reposition it with respect to next's position in its own fifo,
1948 * which would most certainly be too expensive with respect to
1951 if (bfqq == next_bfqq &&
1952 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
1953 next->fifo_time < rq->fifo_time) {
1954 list_del_init(&rq->queuelist);
1955 list_replace_init(&next->queuelist, &rq->queuelist);
1956 rq->fifo_time = next->fifo_time;
1959 if (bfqq->next_rq == next)
1962 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
1965 /* Must be called with bfqq != NULL */
1966 static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
1968 if (bfq_bfqq_busy(bfqq))
1969 bfqq->bfqd->wr_busy_queues--;
1971 bfqq->wr_cur_max_time = 0;
1972 bfqq->last_wr_start_finish = jiffies;
1974 * Trigger a weight change on the next invocation of
1975 * __bfq_entity_update_weight_prio.
1977 bfqq->entity.prio_changed = 1;
1980 void bfq_end_wr_async_queues(struct bfq_data *bfqd,
1981 struct bfq_group *bfqg)
1985 for (i = 0; i < 2; i++)
1986 for (j = 0; j < IOPRIO_BE_NR; j++)
1987 if (bfqg->async_bfqq[i][j])
1988 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
1989 if (bfqg->async_idle_bfqq)
1990 bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
1993 static void bfq_end_wr(struct bfq_data *bfqd)
1995 struct bfq_queue *bfqq;
1997 spin_lock_irq(&bfqd->lock);
1999 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
2000 bfq_bfqq_end_wr(bfqq);
2001 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
2002 bfq_bfqq_end_wr(bfqq);
2003 bfq_end_wr_async(bfqd);
2005 spin_unlock_irq(&bfqd->lock);
2008 static sector_t bfq_io_struct_pos(void *io_struct, bool request)
2011 return blk_rq_pos(io_struct);
2013 return ((struct bio *)io_struct)->bi_iter.bi_sector;
2016 static int bfq_rq_close_to_sector(void *io_struct, bool request,
2019 return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
2023 static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
2024 struct bfq_queue *bfqq,
2027 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
2028 struct rb_node *parent, *node;
2029 struct bfq_queue *__bfqq;
2031 if (RB_EMPTY_ROOT(root))
2035 * First, if we find a request starting at the end of the last
2036 * request, choose it.
2038 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
2043 * If the exact sector wasn't found, the parent of the NULL leaf
2044 * will contain the closest sector (rq_pos_tree sorted by
2045 * next_request position).
2047 __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
2048 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2051 if (blk_rq_pos(__bfqq->next_rq) < sector)
2052 node = rb_next(&__bfqq->pos_node);
2054 node = rb_prev(&__bfqq->pos_node);
2058 __bfqq = rb_entry(node, struct bfq_queue, pos_node);
2059 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2065 static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
2066 struct bfq_queue *cur_bfqq,
2069 struct bfq_queue *bfqq;
2072 * We shall notice if some of the queues are cooperating,
2073 * e.g., working closely on the same area of the device. In
2074 * that case, we can group them together and: 1) don't waste
2075 * time idling, and 2) serve the union of their requests in
2076 * the best possible order for throughput.
2078 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
2079 if (!bfqq || bfqq == cur_bfqq)
2085 static struct bfq_queue *
2086 bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2088 int process_refs, new_process_refs;
2089 struct bfq_queue *__bfqq;
2092 * If there are no process references on the new_bfqq, then it is
2093 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
2094 * may have dropped their last reference (not just their last process
2097 if (!bfqq_process_refs(new_bfqq))
2100 /* Avoid a circular list and skip interim queue merges. */
2101 while ((__bfqq = new_bfqq->new_bfqq)) {
2107 process_refs = bfqq_process_refs(bfqq);
2108 new_process_refs = bfqq_process_refs(new_bfqq);
2110 * If the process for the bfqq has gone away, there is no
2111 * sense in merging the queues.
2113 if (process_refs == 0 || new_process_refs == 0)
2116 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
2120 * Merging is just a redirection: the requests of the process
2121 * owning one of the two queues are redirected to the other queue.
2122 * The latter queue, in its turn, is set as shared if this is the
2123 * first time that the requests of some process are redirected to
2126 * We redirect bfqq to new_bfqq and not the opposite, because
2127 * we are in the context of the process owning bfqq, thus we
2128 * have the io_cq of this process. So we can immediately
2129 * configure this io_cq to redirect the requests of the
2130 * process to new_bfqq. In contrast, the io_cq of new_bfqq is
2131 * not available any more (new_bfqq->bic == NULL).
2133 * Anyway, even in case new_bfqq coincides with the in-service
2134 * queue, redirecting requests the in-service queue is the
2135 * best option, as we feed the in-service queue with new
2136 * requests close to the last request served and, by doing so,
2137 * are likely to increase the throughput.
2139 bfqq->new_bfqq = new_bfqq;
2140 new_bfqq->ref += process_refs;
2144 static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
2145 struct bfq_queue *new_bfqq)
2147 if (bfq_too_late_for_merging(new_bfqq))
2150 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
2151 (bfqq->ioprio_class != new_bfqq->ioprio_class))
2155 * If either of the queues has already been detected as seeky,
2156 * then merging it with the other queue is unlikely to lead to
2159 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
2163 * Interleaved I/O is known to be done by (some) applications
2164 * only for reads, so it does not make sense to merge async
2167 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
2174 * Attempt to schedule a merge of bfqq with the currently in-service
2175 * queue or with a close queue among the scheduled queues. Return
2176 * NULL if no merge was scheduled, a pointer to the shared bfq_queue
2177 * structure otherwise.
2179 * The OOM queue is not allowed to participate to cooperation: in fact, since
2180 * the requests temporarily redirected to the OOM queue could be redirected
2181 * again to dedicated queues at any time, the state needed to correctly
2182 * handle merging with the OOM queue would be quite complex and expensive
2183 * to maintain. Besides, in such a critical condition as an out of memory,
2184 * the benefits of queue merging may be little relevant, or even negligible.
2186 * WARNING: queue merging may impair fairness among non-weight raised
2187 * queues, for at least two reasons: 1) the original weight of a
2188 * merged queue may change during the merged state, 2) even being the
2189 * weight the same, a merged queue may be bloated with many more
2190 * requests than the ones produced by its originally-associated
2193 static struct bfq_queue *
2194 bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2195 void *io_struct, bool request)
2197 struct bfq_queue *in_service_bfqq, *new_bfqq;
2200 * Prevent bfqq from being merged if it has been created too
2201 * long ago. The idea is that true cooperating processes, and
2202 * thus their associated bfq_queues, are supposed to be
2203 * created shortly after each other. This is the case, e.g.,
2204 * for KVM/QEMU and dump I/O threads. Basing on this
2205 * assumption, the following filtering greatly reduces the
2206 * probability that two non-cooperating processes, which just
2207 * happen to do close I/O for some short time interval, have
2208 * their queues merged by mistake.
2210 if (bfq_too_late_for_merging(bfqq))
2214 return bfqq->new_bfqq;
2216 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
2219 /* If there is only one backlogged queue, don't search. */
2220 if (bfqd->busy_queues == 1)
2223 in_service_bfqq = bfqd->in_service_queue;
2225 if (in_service_bfqq && in_service_bfqq != bfqq &&
2226 likely(in_service_bfqq != &bfqd->oom_bfqq) &&
2227 bfq_rq_close_to_sector(io_struct, request,
2228 bfqd->in_serv_last_pos) &&
2229 bfqq->entity.parent == in_service_bfqq->entity.parent &&
2230 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
2231 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
2236 * Check whether there is a cooperator among currently scheduled
2237 * queues. The only thing we need is that the bio/request is not
2238 * NULL, as we need it to establish whether a cooperator exists.
2240 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
2241 bfq_io_struct_pos(io_struct, request));
2243 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
2244 bfq_may_be_close_cooperator(bfqq, new_bfqq))
2245 return bfq_setup_merge(bfqq, new_bfqq);
2250 static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
2252 struct bfq_io_cq *bic = bfqq->bic;
2255 * If !bfqq->bic, the queue is already shared or its requests
2256 * have already been redirected to a shared queue; both idle window
2257 * and weight raising state have already been saved. Do nothing.
2262 bic->saved_ttime = bfqq->ttime;
2263 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
2264 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
2265 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
2266 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
2267 if (unlikely(bfq_bfqq_just_created(bfqq) &&
2268 !bfq_bfqq_in_large_burst(bfqq) &&
2269 bfqq->bfqd->low_latency)) {
2271 * bfqq being merged right after being created: bfqq
2272 * would have deserved interactive weight raising, but
2273 * did not make it to be set in a weight-raised state,
2274 * because of this early merge. Store directly the
2275 * weight-raising state that would have been assigned
2276 * to bfqq, so that to avoid that bfqq unjustly fails
2277 * to enjoy weight raising if split soon.
2279 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
2280 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd);
2281 bic->saved_last_wr_start_finish = jiffies;
2283 bic->saved_wr_coeff = bfqq->wr_coeff;
2284 bic->saved_wr_start_at_switch_to_srt =
2285 bfqq->wr_start_at_switch_to_srt;
2286 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
2287 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
2292 bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
2293 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2295 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
2296 (unsigned long)new_bfqq->pid);
2297 /* Save weight raising and idle window of the merged queues */
2298 bfq_bfqq_save_state(bfqq);
2299 bfq_bfqq_save_state(new_bfqq);
2300 if (bfq_bfqq_IO_bound(bfqq))
2301 bfq_mark_bfqq_IO_bound(new_bfqq);
2302 bfq_clear_bfqq_IO_bound(bfqq);
2305 * If bfqq is weight-raised, then let new_bfqq inherit
2306 * weight-raising. To reduce false positives, neglect the case
2307 * where bfqq has just been created, but has not yet made it
2308 * to be weight-raised (which may happen because EQM may merge
2309 * bfqq even before bfq_add_request is executed for the first
2310 * time for bfqq). Handling this case would however be very
2311 * easy, thanks to the flag just_created.
2313 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
2314 new_bfqq->wr_coeff = bfqq->wr_coeff;
2315 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
2316 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
2317 new_bfqq->wr_start_at_switch_to_srt =
2318 bfqq->wr_start_at_switch_to_srt;
2319 if (bfq_bfqq_busy(new_bfqq))
2320 bfqd->wr_busy_queues++;
2321 new_bfqq->entity.prio_changed = 1;
2324 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
2326 bfqq->entity.prio_changed = 1;
2327 if (bfq_bfqq_busy(bfqq))
2328 bfqd->wr_busy_queues--;
2331 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
2332 bfqd->wr_busy_queues);
2335 * Merge queues (that is, let bic redirect its requests to new_bfqq)
2337 bic_set_bfqq(bic, new_bfqq, 1);
2338 bfq_mark_bfqq_coop(new_bfqq);
2340 * new_bfqq now belongs to at least two bics (it is a shared queue):
2341 * set new_bfqq->bic to NULL. bfqq either:
2342 * - does not belong to any bic any more, and hence bfqq->bic must
2343 * be set to NULL, or
2344 * - is a queue whose owning bics have already been redirected to a
2345 * different queue, hence the queue is destined to not belong to
2346 * any bic soon and bfqq->bic is already NULL (therefore the next
2347 * assignment causes no harm).
2349 new_bfqq->bic = NULL;
2351 /* release process reference to bfqq */
2352 bfq_put_queue(bfqq);
2355 static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2358 struct bfq_data *bfqd = q->elevator->elevator_data;
2359 bool is_sync = op_is_sync(bio->bi_opf);
2360 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
2363 * Disallow merge of a sync bio into an async request.
2365 if (is_sync && !rq_is_sync(rq))
2369 * Lookup the bfqq that this bio will be queued with. Allow
2370 * merge only if rq is queued there.
2376 * We take advantage of this function to perform an early merge
2377 * of the queues of possible cooperating processes.
2379 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
2382 * bic still points to bfqq, then it has not yet been
2383 * redirected to some other bfq_queue, and a queue
2384 * merge beween bfqq and new_bfqq can be safely
2385 * fulfillled, i.e., bic can be redirected to new_bfqq
2386 * and bfqq can be put.
2388 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
2391 * If we get here, bio will be queued into new_queue,
2392 * so use new_bfqq to decide whether bio and rq can be
2398 * Change also bqfd->bio_bfqq, as
2399 * bfqd->bio_bic now points to new_bfqq, and
2400 * this function may be invoked again (and then may
2401 * use again bqfd->bio_bfqq).
2403 bfqd->bio_bfqq = bfqq;
2406 return bfqq == RQ_BFQQ(rq);
2410 * Set the maximum time for the in-service queue to consume its
2411 * budget. This prevents seeky processes from lowering the throughput.
2412 * In practice, a time-slice service scheme is used with seeky
2415 static void bfq_set_budget_timeout(struct bfq_data *bfqd,
2416 struct bfq_queue *bfqq)
2418 unsigned int timeout_coeff;
2420 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
2423 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
2425 bfqd->last_budget_start = ktime_get();
2427 bfqq->budget_timeout = jiffies +
2428 bfqd->bfq_timeout * timeout_coeff;
2431 static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
2432 struct bfq_queue *bfqq)
2435 bfq_clear_bfqq_fifo_expire(bfqq);
2437 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
2439 if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
2440 bfqq->wr_coeff > 1 &&
2441 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
2442 time_is_before_jiffies(bfqq->budget_timeout)) {
2444 * For soft real-time queues, move the start
2445 * of the weight-raising period forward by the
2446 * time the queue has not received any
2447 * service. Otherwise, a relatively long
2448 * service delay is likely to cause the
2449 * weight-raising period of the queue to end,
2450 * because of the short duration of the
2451 * weight-raising period of a soft real-time
2452 * queue. It is worth noting that this move
2453 * is not so dangerous for the other queues,
2454 * because soft real-time queues are not
2457 * To not add a further variable, we use the
2458 * overloaded field budget_timeout to
2459 * determine for how long the queue has not
2460 * received service, i.e., how much time has
2461 * elapsed since the queue expired. However,
2462 * this is a little imprecise, because
2463 * budget_timeout is set to jiffies if bfqq
2464 * not only expires, but also remains with no
2467 if (time_after(bfqq->budget_timeout,
2468 bfqq->last_wr_start_finish))
2469 bfqq->last_wr_start_finish +=
2470 jiffies - bfqq->budget_timeout;
2472 bfqq->last_wr_start_finish = jiffies;
2475 bfq_set_budget_timeout(bfqd, bfqq);
2476 bfq_log_bfqq(bfqd, bfqq,
2477 "set_in_service_queue, cur-budget = %d",
2478 bfqq->entity.budget);
2481 bfqd->in_service_queue = bfqq;
2482 bfqd->in_serv_last_pos = 0;
2486 * Get and set a new queue for service.
2488 static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
2490 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
2492 __bfq_set_in_service_queue(bfqd, bfqq);
2496 static void bfq_arm_slice_timer(struct bfq_data *bfqd)
2498 struct bfq_queue *bfqq = bfqd->in_service_queue;
2501 bfq_mark_bfqq_wait_request(bfqq);
2504 * We don't want to idle for seeks, but we do want to allow
2505 * fair distribution of slice time for a process doing back-to-back
2506 * seeks. So allow a little bit of time for him to submit a new rq.
2508 sl = bfqd->bfq_slice_idle;
2510 * Unless the queue is being weight-raised or the scenario is
2511 * asymmetric, grant only minimum idle time if the queue
2512 * is seeky. A long idling is preserved for a weight-raised
2513 * queue, or, more in general, in an asymmetric scenario,
2514 * because a long idling is needed for guaranteeing to a queue
2515 * its reserved share of the throughput (in particular, it is
2516 * needed if the queue has a higher weight than some other
2519 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
2520 bfq_symmetric_scenario(bfqd))
2521 sl = min_t(u64, sl, BFQ_MIN_TT);
2522 else if (bfqq->wr_coeff > 1)
2523 sl = max_t(u32, sl, 20ULL * NSEC_PER_MSEC);
2525 bfqd->last_idling_start = ktime_get();
2526 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
2528 bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
2532 * In autotuning mode, max_budget is dynamically recomputed as the
2533 * amount of sectors transferred in timeout at the estimated peak
2534 * rate. This enables BFQ to utilize a full timeslice with a full
2535 * budget, even if the in-service queue is served at peak rate. And
2536 * this maximises throughput with sequential workloads.
2538 static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
2540 return (u64)bfqd->peak_rate * USEC_PER_MSEC *
2541 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
2545 * Update parameters related to throughput and responsiveness, as a
2546 * function of the estimated peak rate. See comments on
2547 * bfq_calc_max_budget(), and on the ref_wr_duration array.
2549 static void update_thr_responsiveness_params(struct bfq_data *bfqd)
2551 if (bfqd->bfq_user_max_budget == 0) {
2552 bfqd->bfq_max_budget =
2553 bfq_calc_max_budget(bfqd);
2554 bfq_log(bfqd, "new max_budget = %d", bfqd->bfq_max_budget);
2558 static void bfq_reset_rate_computation(struct bfq_data *bfqd,
2561 if (rq != NULL) { /* new rq dispatch now, reset accordingly */
2562 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
2563 bfqd->peak_rate_samples = 1;
2564 bfqd->sequential_samples = 0;
2565 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
2567 } else /* no new rq dispatched, just reset the number of samples */
2568 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
2571 "reset_rate_computation at end, sample %u/%u tot_sects %llu",
2572 bfqd->peak_rate_samples, bfqd->sequential_samples,
2573 bfqd->tot_sectors_dispatched);
2576 static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
2578 u32 rate, weight, divisor;
2581 * For the convergence property to hold (see comments on
2582 * bfq_update_peak_rate()) and for the assessment to be
2583 * reliable, a minimum number of samples must be present, and
2584 * a minimum amount of time must have elapsed. If not so, do
2585 * not compute new rate. Just reset parameters, to get ready
2586 * for a new evaluation attempt.
2588 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
2589 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
2590 goto reset_computation;
2593 * If a new request completion has occurred after last
2594 * dispatch, then, to approximate the rate at which requests
2595 * have been served by the device, it is more precise to
2596 * extend the observation interval to the last completion.
2598 bfqd->delta_from_first =
2599 max_t(u64, bfqd->delta_from_first,
2600 bfqd->last_completion - bfqd->first_dispatch);
2603 * Rate computed in sects/usec, and not sects/nsec, for
2606 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
2607 div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
2610 * Peak rate not updated if:
2611 * - the percentage of sequential dispatches is below 3/4 of the
2612 * total, and rate is below the current estimated peak rate
2613 * - rate is unreasonably high (> 20M sectors/sec)
2615 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
2616 rate <= bfqd->peak_rate) ||
2617 rate > 20<<BFQ_RATE_SHIFT)
2618 goto reset_computation;
2621 * We have to update the peak rate, at last! To this purpose,
2622 * we use a low-pass filter. We compute the smoothing constant
2623 * of the filter as a function of the 'weight' of the new
2626 * As can be seen in next formulas, we define this weight as a
2627 * quantity proportional to how sequential the workload is,
2628 * and to how long the observation time interval is.
2630 * The weight runs from 0 to 8. The maximum value of the
2631 * weight, 8, yields the minimum value for the smoothing
2632 * constant. At this minimum value for the smoothing constant,
2633 * the measured rate contributes for half of the next value of
2634 * the estimated peak rate.
2636 * So, the first step is to compute the weight as a function
2637 * of how sequential the workload is. Note that the weight
2638 * cannot reach 9, because bfqd->sequential_samples cannot
2639 * become equal to bfqd->peak_rate_samples, which, in its
2640 * turn, holds true because bfqd->sequential_samples is not
2641 * incremented for the first sample.
2643 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
2646 * Second step: further refine the weight as a function of the
2647 * duration of the observation interval.
2649 weight = min_t(u32, 8,
2650 div_u64(weight * bfqd->delta_from_first,
2651 BFQ_RATE_REF_INTERVAL));
2654 * Divisor ranging from 10, for minimum weight, to 2, for
2657 divisor = 10 - weight;
2660 * Finally, update peak rate:
2662 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
2664 bfqd->peak_rate *= divisor-1;
2665 bfqd->peak_rate /= divisor;
2666 rate /= divisor; /* smoothing constant alpha = 1/divisor */
2668 bfqd->peak_rate += rate;
2671 * For a very slow device, bfqd->peak_rate can reach 0 (see
2672 * the minimum representable values reported in the comments
2673 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
2674 * divisions by zero where bfqd->peak_rate is used as a
2677 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
2679 update_thr_responsiveness_params(bfqd);
2682 bfq_reset_rate_computation(bfqd, rq);
2686 * Update the read/write peak rate (the main quantity used for
2687 * auto-tuning, see update_thr_responsiveness_params()).
2689 * It is not trivial to estimate the peak rate (correctly): because of
2690 * the presence of sw and hw queues between the scheduler and the
2691 * device components that finally serve I/O requests, it is hard to
2692 * say exactly when a given dispatched request is served inside the
2693 * device, and for how long. As a consequence, it is hard to know
2694 * precisely at what rate a given set of requests is actually served
2697 * On the opposite end, the dispatch time of any request is trivially
2698 * available, and, from this piece of information, the "dispatch rate"
2699 * of requests can be immediately computed. So, the idea in the next
2700 * function is to use what is known, namely request dispatch times
2701 * (plus, when useful, request completion times), to estimate what is
2702 * unknown, namely in-device request service rate.
2704 * The main issue is that, because of the above facts, the rate at
2705 * which a certain set of requests is dispatched over a certain time
2706 * interval can vary greatly with respect to the rate at which the
2707 * same requests are then served. But, since the size of any
2708 * intermediate queue is limited, and the service scheme is lossless
2709 * (no request is silently dropped), the following obvious convergence
2710 * property holds: the number of requests dispatched MUST become
2711 * closer and closer to the number of requests completed as the
2712 * observation interval grows. This is the key property used in
2713 * the next function to estimate the peak service rate as a function
2714 * of the observed dispatch rate. The function assumes to be invoked
2715 * on every request dispatch.
2717 static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
2719 u64 now_ns = ktime_get_ns();
2721 if (bfqd->peak_rate_samples == 0) { /* first dispatch */
2722 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
2723 bfqd->peak_rate_samples);
2724 bfq_reset_rate_computation(bfqd, rq);
2725 goto update_last_values; /* will add one sample */
2729 * Device idle for very long: the observation interval lasting
2730 * up to this dispatch cannot be a valid observation interval
2731 * for computing a new peak rate (similarly to the late-
2732 * completion event in bfq_completed_request()). Go to
2733 * update_rate_and_reset to have the following three steps
2735 * - close the observation interval at the last (previous)
2736 * request dispatch or completion
2737 * - compute rate, if possible, for that observation interval
2738 * - start a new observation interval with this dispatch
2740 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
2741 bfqd->rq_in_driver == 0)
2742 goto update_rate_and_reset;
2744 /* Update sampling information */
2745 bfqd->peak_rate_samples++;
2747 if ((bfqd->rq_in_driver > 0 ||
2748 now_ns - bfqd->last_completion < BFQ_MIN_TT)
2749 && get_sdist(bfqd->last_position, rq) < BFQQ_SEEK_THR)
2750 bfqd->sequential_samples++;
2752 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
2754 /* Reset max observed rq size every 32 dispatches */
2755 if (likely(bfqd->peak_rate_samples % 32))
2756 bfqd->last_rq_max_size =
2757 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
2759 bfqd->last_rq_max_size = blk_rq_sectors(rq);
2761 bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
2763 /* Target observation interval not yet reached, go on sampling */
2764 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
2765 goto update_last_values;
2767 update_rate_and_reset:
2768 bfq_update_rate_reset(bfqd, rq);
2770 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2771 if (RQ_BFQQ(rq) == bfqd->in_service_queue)
2772 bfqd->in_serv_last_pos = bfqd->last_position;
2773 bfqd->last_dispatch = now_ns;
2777 * Remove request from internal lists.
2779 static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
2781 struct bfq_queue *bfqq = RQ_BFQQ(rq);
2784 * For consistency, the next instruction should have been
2785 * executed after removing the request from the queue and
2786 * dispatching it. We execute instead this instruction before
2787 * bfq_remove_request() (and hence introduce a temporary
2788 * inconsistency), for efficiency. In fact, should this
2789 * dispatch occur for a non in-service bfqq, this anticipated
2790 * increment prevents two counters related to bfqq->dispatched
2791 * from risking to be, first, uselessly decremented, and then
2792 * incremented again when the (new) value of bfqq->dispatched
2793 * happens to be taken into account.
2796 bfq_update_peak_rate(q->elevator->elevator_data, rq);
2798 bfq_remove_request(q, rq);
2801 static void __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq)
2804 * If this bfqq is shared between multiple processes, check
2805 * to make sure that those processes are still issuing I/Os
2806 * within the mean seek distance. If not, it may be time to
2807 * break the queues apart again.
2809 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
2810 bfq_mark_bfqq_split_coop(bfqq);
2812 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
2813 if (bfqq->dispatched == 0)
2815 * Overloading budget_timeout field to store
2816 * the time at which the queue remains with no
2817 * backlog and no outstanding request; used by
2818 * the weight-raising mechanism.
2820 bfqq->budget_timeout = jiffies;
2822 bfq_del_bfqq_busy(bfqd, bfqq, true);
2824 bfq_requeue_bfqq(bfqd, bfqq, true);
2826 * Resort priority tree of potential close cooperators.
2828 bfq_pos_tree_add_move(bfqd, bfqq);
2832 * All in-service entities must have been properly deactivated
2833 * or requeued before executing the next function, which
2834 * resets all in-service entites as no more in service.
2836 __bfq_bfqd_reset_in_service(bfqd);
2840 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
2841 * @bfqd: device data.
2842 * @bfqq: queue to update.
2843 * @reason: reason for expiration.
2845 * Handle the feedback on @bfqq budget at queue expiration.
2846 * See the body for detailed comments.
2848 static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
2849 struct bfq_queue *bfqq,
2850 enum bfqq_expiration reason)
2852 struct request *next_rq;
2853 int budget, min_budget;
2855 min_budget = bfq_min_budget(bfqd);
2857 if (bfqq->wr_coeff == 1)
2858 budget = bfqq->max_budget;
2860 * Use a constant, low budget for weight-raised queues,
2861 * to help achieve a low latency. Keep it slightly higher
2862 * than the minimum possible budget, to cause a little
2863 * bit fewer expirations.
2865 budget = 2 * min_budget;
2867 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
2868 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
2869 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
2870 budget, bfq_min_budget(bfqd));
2871 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
2872 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
2874 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
2877 * Caveat: in all the following cases we trade latency
2880 case BFQQE_TOO_IDLE:
2882 * This is the only case where we may reduce
2883 * the budget: if there is no request of the
2884 * process still waiting for completion, then
2885 * we assume (tentatively) that the timer has
2886 * expired because the batch of requests of
2887 * the process could have been served with a
2888 * smaller budget. Hence, betting that
2889 * process will behave in the same way when it
2890 * becomes backlogged again, we reduce its
2891 * next budget. As long as we guess right,
2892 * this budget cut reduces the latency
2893 * experienced by the process.
2895 * However, if there are still outstanding
2896 * requests, then the process may have not yet
2897 * issued its next request just because it is
2898 * still waiting for the completion of some of
2899 * the still outstanding ones. So in this
2900 * subcase we do not reduce its budget, on the
2901 * contrary we increase it to possibly boost
2902 * the throughput, as discussed in the
2903 * comments to the BUDGET_TIMEOUT case.
2905 if (bfqq->dispatched > 0) /* still outstanding reqs */
2906 budget = min(budget * 2, bfqd->bfq_max_budget);
2908 if (budget > 5 * min_budget)
2909 budget -= 4 * min_budget;
2911 budget = min_budget;
2914 case BFQQE_BUDGET_TIMEOUT:
2916 * We double the budget here because it gives
2917 * the chance to boost the throughput if this
2918 * is not a seeky process (and has bumped into
2919 * this timeout because of, e.g., ZBR).
2921 budget = min(budget * 2, bfqd->bfq_max_budget);
2923 case BFQQE_BUDGET_EXHAUSTED:
2925 * The process still has backlog, and did not
2926 * let either the budget timeout or the disk
2927 * idling timeout expire. Hence it is not
2928 * seeky, has a short thinktime and may be
2929 * happy with a higher budget too. So
2930 * definitely increase the budget of this good
2931 * candidate to boost the disk throughput.
2933 budget = min(budget * 4, bfqd->bfq_max_budget);
2935 case BFQQE_NO_MORE_REQUESTS:
2937 * For queues that expire for this reason, it
2938 * is particularly important to keep the
2939 * budget close to the actual service they
2940 * need. Doing so reduces the timestamp
2941 * misalignment problem described in the
2942 * comments in the body of
2943 * __bfq_activate_entity. In fact, suppose
2944 * that a queue systematically expires for
2945 * BFQQE_NO_MORE_REQUESTS and presents a
2946 * new request in time to enjoy timestamp
2947 * back-shifting. The larger the budget of the
2948 * queue is with respect to the service the
2949 * queue actually requests in each service
2950 * slot, the more times the queue can be
2951 * reactivated with the same virtual finish
2952 * time. It follows that, even if this finish
2953 * time is pushed to the system virtual time
2954 * to reduce the consequent timestamp
2955 * misalignment, the queue unjustly enjoys for
2956 * many re-activations a lower finish time
2957 * than all newly activated queues.
2959 * The service needed by bfqq is measured
2960 * quite precisely by bfqq->entity.service.
2961 * Since bfqq does not enjoy device idling,
2962 * bfqq->entity.service is equal to the number
2963 * of sectors that the process associated with
2964 * bfqq requested to read/write before waiting
2965 * for request completions, or blocking for
2968 budget = max_t(int, bfqq->entity.service, min_budget);
2973 } else if (!bfq_bfqq_sync(bfqq)) {
2975 * Async queues get always the maximum possible
2976 * budget, as for them we do not care about latency
2977 * (in addition, their ability to dispatch is limited
2978 * by the charging factor).
2980 budget = bfqd->bfq_max_budget;
2983 bfqq->max_budget = budget;
2985 if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
2986 !bfqd->bfq_user_max_budget)
2987 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
2990 * If there is still backlog, then assign a new budget, making
2991 * sure that it is large enough for the next request. Since
2992 * the finish time of bfqq must be kept in sync with the
2993 * budget, be sure to call __bfq_bfqq_expire() *after* this
2996 * If there is no backlog, then no need to update the budget;
2997 * it will be updated on the arrival of a new request.
2999 next_rq = bfqq->next_rq;
3001 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
3002 bfq_serv_to_charge(next_rq, bfqq));
3004 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
3005 next_rq ? blk_rq_sectors(next_rq) : 0,
3006 bfqq->entity.budget);
3010 * Return true if the process associated with bfqq is "slow". The slow
3011 * flag is used, in addition to the budget timeout, to reduce the
3012 * amount of service provided to seeky processes, and thus reduce
3013 * their chances to lower the throughput. More details in the comments
3014 * on the function bfq_bfqq_expire().
3016 * An important observation is in order: as discussed in the comments
3017 * on the function bfq_update_peak_rate(), with devices with internal
3018 * queues, it is hard if ever possible to know when and for how long
3019 * an I/O request is processed by the device (apart from the trivial
3020 * I/O pattern where a new request is dispatched only after the
3021 * previous one has been completed). This makes it hard to evaluate
3022 * the real rate at which the I/O requests of each bfq_queue are
3023 * served. In fact, for an I/O scheduler like BFQ, serving a
3024 * bfq_queue means just dispatching its requests during its service
3025 * slot (i.e., until the budget of the queue is exhausted, or the
3026 * queue remains idle, or, finally, a timeout fires). But, during the
3027 * service slot of a bfq_queue, around 100 ms at most, the device may
3028 * be even still processing requests of bfq_queues served in previous
3029 * service slots. On the opposite end, the requests of the in-service
3030 * bfq_queue may be completed after the service slot of the queue
3033 * Anyway, unless more sophisticated solutions are used
3034 * (where possible), the sum of the sizes of the requests dispatched
3035 * during the service slot of a bfq_queue is probably the only
3036 * approximation available for the service received by the bfq_queue
3037 * during its service slot. And this sum is the quantity used in this
3038 * function to evaluate the I/O speed of a process.
3040 static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
3041 bool compensate, enum bfqq_expiration reason,
3042 unsigned long *delta_ms)
3044 ktime_t delta_ktime;
3046 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
3048 if (!bfq_bfqq_sync(bfqq))
3052 delta_ktime = bfqd->last_idling_start;
3054 delta_ktime = ktime_get();
3055 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
3056 delta_usecs = ktime_to_us(delta_ktime);
3058 /* don't use too short time intervals */
3059 if (delta_usecs < 1000) {
3060 if (blk_queue_nonrot(bfqd->queue))
3062 * give same worst-case guarantees as idling
3065 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
3066 else /* charge at least one seek */
3067 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
3072 *delta_ms = delta_usecs / USEC_PER_MSEC;
3075 * Use only long (> 20ms) intervals to filter out excessive
3076 * spikes in service rate estimation.
3078 if (delta_usecs > 20000) {
3080 * Caveat for rotational devices: processes doing I/O
3081 * in the slower disk zones tend to be slow(er) even
3082 * if not seeky. In this respect, the estimated peak
3083 * rate is likely to be an average over the disk
3084 * surface. Accordingly, to not be too harsh with
3085 * unlucky processes, a process is deemed slow only if
3086 * its rate has been lower than half of the estimated
3089 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
3092 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
3098 * To be deemed as soft real-time, an application must meet two
3099 * requirements. First, the application must not require an average
3100 * bandwidth higher than the approximate bandwidth required to playback or
3101 * record a compressed high-definition video.
3102 * The next function is invoked on the completion of the last request of a
3103 * batch, to compute the next-start time instant, soft_rt_next_start, such
3104 * that, if the next request of the application does not arrive before
3105 * soft_rt_next_start, then the above requirement on the bandwidth is met.
3107 * The second requirement is that the request pattern of the application is
3108 * isochronous, i.e., that, after issuing a request or a batch of requests,
3109 * the application stops issuing new requests until all its pending requests
3110 * have been completed. After that, the application may issue a new batch,
3112 * For this reason the next function is invoked to compute
3113 * soft_rt_next_start only for applications that meet this requirement,
3114 * whereas soft_rt_next_start is set to infinity for applications that do
3117 * Unfortunately, even a greedy (i.e., I/O-bound) application may
3118 * happen to meet, occasionally or systematically, both the above
3119 * bandwidth and isochrony requirements. This may happen at least in
3120 * the following circumstances. First, if the CPU load is high. The
3121 * application may stop issuing requests while the CPUs are busy
3122 * serving other processes, then restart, then stop again for a while,
3123 * and so on. The other circumstances are related to the storage
3124 * device: the storage device is highly loaded or reaches a low-enough
3125 * throughput with the I/O of the application (e.g., because the I/O
3126 * is random and/or the device is slow). In all these cases, the
3127 * I/O of the application may be simply slowed down enough to meet
3128 * the bandwidth and isochrony requirements. To reduce the probability
3129 * that greedy applications are deemed as soft real-time in these
3130 * corner cases, a further rule is used in the computation of
3131 * soft_rt_next_start: the return value of this function is forced to
3132 * be higher than the maximum between the following two quantities.
3134 * (a) Current time plus: (1) the maximum time for which the arrival
3135 * of a request is waited for when a sync queue becomes idle,
3136 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
3137 * postpone for a moment the reason for adding a few extra
3138 * jiffies; we get back to it after next item (b). Lower-bounding
3139 * the return value of this function with the current time plus
3140 * bfqd->bfq_slice_idle tends to filter out greedy applications,
3141 * because the latter issue their next request as soon as possible
3142 * after the last one has been completed. In contrast, a soft
3143 * real-time application spends some time processing data, after a
3144 * batch of its requests has been completed.
3146 * (b) Current value of bfqq->soft_rt_next_start. As pointed out
3147 * above, greedy applications may happen to meet both the
3148 * bandwidth and isochrony requirements under heavy CPU or
3149 * storage-device load. In more detail, in these scenarios, these
3150 * applications happen, only for limited time periods, to do I/O
3151 * slowly enough to meet all the requirements described so far,
3152 * including the filtering in above item (a). These slow-speed
3153 * time intervals are usually interspersed between other time
3154 * intervals during which these applications do I/O at a very high
3155 * speed. Fortunately, exactly because of the high speed of the
3156 * I/O in the high-speed intervals, the values returned by this
3157 * function happen to be so high, near the end of any such
3158 * high-speed interval, to be likely to fall *after* the end of
3159 * the low-speed time interval that follows. These high values are
3160 * stored in bfqq->soft_rt_next_start after each invocation of
3161 * this function. As a consequence, if the last value of
3162 * bfqq->soft_rt_next_start is constantly used to lower-bound the
3163 * next value that this function may return, then, from the very
3164 * beginning of a low-speed interval, bfqq->soft_rt_next_start is
3165 * likely to be constantly kept so high that any I/O request
3166 * issued during the low-speed interval is considered as arriving
3167 * to soon for the application to be deemed as soft
3168 * real-time. Then, in the high-speed interval that follows, the
3169 * application will not be deemed as soft real-time, just because
3170 * it will do I/O at a high speed. And so on.
3172 * Getting back to the filtering in item (a), in the following two
3173 * cases this filtering might be easily passed by a greedy
3174 * application, if the reference quantity was just
3175 * bfqd->bfq_slice_idle:
3176 * 1) HZ is so low that the duration of a jiffy is comparable to or
3177 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
3178 * devices with HZ=100. The time granularity may be so coarse
3179 * that the approximation, in jiffies, of bfqd->bfq_slice_idle
3180 * is rather lower than the exact value.
3181 * 2) jiffies, instead of increasing at a constant rate, may stop increasing
3182 * for a while, then suddenly 'jump' by several units to recover the lost
3183 * increments. This seems to happen, e.g., inside virtual machines.
3184 * To address this issue, in the filtering in (a) we do not use as a
3185 * reference time interval just bfqd->bfq_slice_idle, but
3186 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
3187 * minimum number of jiffies for which the filter seems to be quite
3188 * precise also in embedded systems and KVM/QEMU virtual machines.
3190 static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
3191 struct bfq_queue *bfqq)
3193 return max3(bfqq->soft_rt_next_start,
3194 bfqq->last_idle_bklogged +
3195 HZ * bfqq->service_from_backlogged /
3196 bfqd->bfq_wr_max_softrt_rate,
3197 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
3200 static bool bfq_bfqq_injectable(struct bfq_queue *bfqq)
3202 return BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
3203 blk_queue_nonrot(bfqq->bfqd->queue) &&
3208 * bfq_bfqq_expire - expire a queue.
3209 * @bfqd: device owning the queue.
3210 * @bfqq: the queue to expire.
3211 * @compensate: if true, compensate for the time spent idling.
3212 * @reason: the reason causing the expiration.
3214 * If the process associated with bfqq does slow I/O (e.g., because it
3215 * issues random requests), we charge bfqq with the time it has been
3216 * in service instead of the service it has received (see
3217 * bfq_bfqq_charge_time for details on how this goal is achieved). As
3218 * a consequence, bfqq will typically get higher timestamps upon
3219 * reactivation, and hence it will be rescheduled as if it had
3220 * received more service than what it has actually received. In the
3221 * end, bfqq receives less service in proportion to how slowly its
3222 * associated process consumes its budgets (and hence how seriously it
3223 * tends to lower the throughput). In addition, this time-charging
3224 * strategy guarantees time fairness among slow processes. In
3225 * contrast, if the process associated with bfqq is not slow, we
3226 * charge bfqq exactly with the service it has received.
3228 * Charging time to the first type of queues and the exact service to
3229 * the other has the effect of using the WF2Q+ policy to schedule the
3230 * former on a timeslice basis, without violating service domain
3231 * guarantees among the latter.
3233 void bfq_bfqq_expire(struct bfq_data *bfqd,
3234 struct bfq_queue *bfqq,
3236 enum bfqq_expiration reason)
3239 unsigned long delta = 0;
3240 struct bfq_entity *entity = &bfqq->entity;
3244 * Check whether the process is slow (see bfq_bfqq_is_slow).
3246 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
3249 * As above explained, charge slow (typically seeky) and
3250 * timed-out queues with the time and not the service
3251 * received, to favor sequential workloads.
3253 * Processes doing I/O in the slower disk zones will tend to
3254 * be slow(er) even if not seeky. Therefore, since the
3255 * estimated peak rate is actually an average over the disk
3256 * surface, these processes may timeout just for bad luck. To
3257 * avoid punishing them, do not charge time to processes that
3258 * succeeded in consuming at least 2/3 of their budget. This
3259 * allows BFQ to preserve enough elasticity to still perform
3260 * bandwidth, and not time, distribution with little unlucky
3261 * or quasi-sequential processes.
3263 if (bfqq->wr_coeff == 1 &&
3265 (reason == BFQQE_BUDGET_TIMEOUT &&
3266 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
3267 bfq_bfqq_charge_time(bfqd, bfqq, delta);
3269 if (reason == BFQQE_TOO_IDLE &&
3270 entity->service <= 2 * entity->budget / 10)
3271 bfq_clear_bfqq_IO_bound(bfqq);
3273 if (bfqd->low_latency && bfqq->wr_coeff == 1)
3274 bfqq->last_wr_start_finish = jiffies;
3276 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
3277 RB_EMPTY_ROOT(&bfqq->sort_list)) {
3279 * If we get here, and there are no outstanding
3280 * requests, then the request pattern is isochronous
3281 * (see the comments on the function
3282 * bfq_bfqq_softrt_next_start()). Thus we can compute
3283 * soft_rt_next_start. If, instead, the queue still
3284 * has outstanding requests, then we have to wait for
3285 * the completion of all the outstanding requests to
3286 * discover whether the request pattern is actually
3289 if (bfqq->dispatched == 0)
3290 bfqq->soft_rt_next_start =
3291 bfq_bfqq_softrt_next_start(bfqd, bfqq);
3294 * Schedule an update of soft_rt_next_start to when
3295 * the task may be discovered to be isochronous.
3297 bfq_mark_bfqq_softrt_update(bfqq);
3301 bfq_log_bfqq(bfqd, bfqq,
3302 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
3303 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
3306 * Increase, decrease or leave budget unchanged according to
3309 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
3311 __bfq_bfqq_expire(bfqd, bfqq);
3313 if (ref == 1) /* bfqq is gone, no more actions on it */
3316 bfqq->injected_service = 0;
3318 /* mark bfqq as waiting a request only if a bic still points to it */
3319 if (!bfq_bfqq_busy(bfqq) &&
3320 reason != BFQQE_BUDGET_TIMEOUT &&
3321 reason != BFQQE_BUDGET_EXHAUSTED) {
3322 bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
3324 * Not setting service to 0, because, if the next rq
3325 * arrives in time, the queue will go on receiving
3326 * service with this same budget (as if it never expired)
3329 entity->service = 0;
3332 * Reset the received-service counter for every parent entity.
3333 * Differently from what happens with bfqq->entity.service,
3334 * the resetting of this counter never needs to be postponed
3335 * for parent entities. In fact, in case bfqq may have a
3336 * chance to go on being served using the last, partially
3337 * consumed budget, bfqq->entity.service needs to be kept,
3338 * because if bfqq then actually goes on being served using
3339 * the same budget, the last value of bfqq->entity.service is
3340 * needed to properly decrement bfqq->entity.budget by the
3341 * portion already consumed. In contrast, it is not necessary
3342 * to keep entity->service for parent entities too, because
3343 * the bubble up of the new value of bfqq->entity.budget will
3344 * make sure that the budgets of parent entities are correct,
3345 * even in case bfqq and thus parent entities go on receiving
3346 * service with the same budget.
3348 entity = entity->parent;
3349 for_each_entity(entity)
3350 entity->service = 0;
3354 * Budget timeout is not implemented through a dedicated timer, but
3355 * just checked on request arrivals and completions, as well as on
3356 * idle timer expirations.
3358 static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
3360 return time_is_before_eq_jiffies(bfqq->budget_timeout);
3364 * If we expire a queue that is actively waiting (i.e., with the
3365 * device idled) for the arrival of a new request, then we may incur
3366 * the timestamp misalignment problem described in the body of the
3367 * function __bfq_activate_entity. Hence we return true only if this
3368 * condition does not hold, or if the queue is slow enough to deserve
3369 * only to be kicked off for preserving a high throughput.
3371 static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
3373 bfq_log_bfqq(bfqq->bfqd, bfqq,
3374 "may_budget_timeout: wait_request %d left %d timeout %d",
3375 bfq_bfqq_wait_request(bfqq),
3376 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
3377 bfq_bfqq_budget_timeout(bfqq));
3379 return (!bfq_bfqq_wait_request(bfqq) ||
3380 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
3382 bfq_bfqq_budget_timeout(bfqq);
3386 * For a queue that becomes empty, device idling is allowed only if
3387 * this function returns true for the queue. As a consequence, since
3388 * device idling plays a critical role in both throughput boosting and
3389 * service guarantees, the return value of this function plays a
3390 * critical role in both these aspects as well.
3392 * In a nutshell, this function returns true only if idling is
3393 * beneficial for throughput or, even if detrimental for throughput,
3394 * idling is however necessary to preserve service guarantees (low
3395 * latency, desired throughput distribution, ...). In particular, on
3396 * NCQ-capable devices, this function tries to return false, so as to
3397 * help keep the drives' internal queues full, whenever this helps the
3398 * device boost the throughput without causing any service-guarantee
3401 * In more detail, the return value of this function is obtained by,
3402 * first, computing a number of boolean variables that take into
3403 * account throughput and service-guarantee issues, and, then,
3404 * combining these variables in a logical expression. Most of the
3405 * issues taken into account are not trivial. We discuss these issues
3406 * individually while introducing the variables.
3408 static bool bfq_better_to_idle(struct bfq_queue *bfqq)
3410 struct bfq_data *bfqd = bfqq->bfqd;
3411 bool rot_without_queueing =
3412 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
3413 bfqq_sequential_and_IO_bound,
3414 idling_boosts_thr, idling_boosts_thr_without_issues,
3415 idling_needed_for_service_guarantees,
3416 asymmetric_scenario;
3418 if (bfqd->strict_guarantees)
3422 * Idling is performed only if slice_idle > 0. In addition, we
3425 * (b) bfqq is in the idle io prio class: in this case we do
3426 * not idle because we want to minimize the bandwidth that
3427 * queues in this class can steal to higher-priority queues
3429 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
3430 bfq_class_idle(bfqq))
3433 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
3434 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
3437 * The next variable takes into account the cases where idling
3438 * boosts the throughput.
3440 * The value of the variable is computed considering, first, that
3441 * idling is virtually always beneficial for the throughput if:
3442 * (a) the device is not NCQ-capable and rotational, or
3443 * (b) regardless of the presence of NCQ, the device is rotational and
3444 * the request pattern for bfqq is I/O-bound and sequential, or
3445 * (c) regardless of whether it is rotational, the device is
3446 * not NCQ-capable and the request pattern for bfqq is
3447 * I/O-bound and sequential.
3449 * Secondly, and in contrast to the above item (b), idling an
3450 * NCQ-capable flash-based device would not boost the
3451 * throughput even with sequential I/O; rather it would lower
3452 * the throughput in proportion to how fast the device
3453 * is. Accordingly, the next variable is true if any of the
3454 * above conditions (a), (b) or (c) is true, and, in
3455 * particular, happens to be false if bfqd is an NCQ-capable
3456 * flash-based device.
3458 idling_boosts_thr = rot_without_queueing ||
3459 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
3460 bfqq_sequential_and_IO_bound);
3463 * The value of the next variable,
3464 * idling_boosts_thr_without_issues, is equal to that of
3465 * idling_boosts_thr, unless a special case holds. In this
3466 * special case, described below, idling may cause problems to
3467 * weight-raised queues.
3469 * When the request pool is saturated (e.g., in the presence
3470 * of write hogs), if the processes associated with
3471 * non-weight-raised queues ask for requests at a lower rate,
3472 * then processes associated with weight-raised queues have a
3473 * higher probability to get a request from the pool
3474 * immediately (or at least soon) when they need one. Thus
3475 * they have a higher probability to actually get a fraction
3476 * of the device throughput proportional to their high
3477 * weight. This is especially true with NCQ-capable drives,
3478 * which enqueue several requests in advance, and further
3479 * reorder internally-queued requests.
3481 * For this reason, we force to false the value of
3482 * idling_boosts_thr_without_issues if there are weight-raised
3483 * busy queues. In this case, and if bfqq is not weight-raised,
3484 * this guarantees that the device is not idled for bfqq (if,
3485 * instead, bfqq is weight-raised, then idling will be
3486 * guaranteed by another variable, see below). Combined with
3487 * the timestamping rules of BFQ (see [1] for details), this
3488 * behavior causes bfqq, and hence any sync non-weight-raised
3489 * queue, to get a lower number of requests served, and thus
3490 * to ask for a lower number of requests from the request
3491 * pool, before the busy weight-raised queues get served
3492 * again. This often mitigates starvation problems in the
3493 * presence of heavy write workloads and NCQ, thereby
3494 * guaranteeing a higher application and system responsiveness
3495 * in these hostile scenarios.
3497 idling_boosts_thr_without_issues = idling_boosts_thr &&
3498 bfqd->wr_busy_queues == 0;
3501 * There is then a case where idling must be performed not
3502 * for throughput concerns, but to preserve service
3505 * To introduce this case, we can note that allowing the drive
3506 * to enqueue more than one request at a time, and hence
3507 * delegating de facto final scheduling decisions to the
3508 * drive's internal scheduler, entails loss of control on the
3509 * actual request service order. In particular, the critical
3510 * situation is when requests from different processes happen
3511 * to be present, at the same time, in the internal queue(s)
3512 * of the drive. In such a situation, the drive, by deciding
3513 * the service order of the internally-queued requests, does
3514 * determine also the actual throughput distribution among
3515 * these processes. But the drive typically has no notion or
3516 * concern about per-process throughput distribution, and
3517 * makes its decisions only on a per-request basis. Therefore,
3518 * the service distribution enforced by the drive's internal
3519 * scheduler is likely to coincide with the desired
3520 * device-throughput distribution only in a completely
3521 * symmetric scenario where:
3522 * (i) each of these processes must get the same throughput as
3524 * (ii) all these processes have the same I/O pattern
3525 (either sequential or random).
3526 * In fact, in such a scenario, the drive will tend to treat
3527 * the requests of each of these processes in about the same
3528 * way as the requests of the others, and thus to provide
3529 * each of these processes with about the same throughput
3530 * (which is exactly the desired throughput distribution). In
3531 * contrast, in any asymmetric scenario, device idling is
3532 * certainly needed to guarantee that bfqq receives its
3533 * assigned fraction of the device throughput (see [1] for
3536 * We address this issue by controlling, actually, only the
3537 * symmetry sub-condition (i), i.e., provided that
3538 * sub-condition (i) holds, idling is not performed,
3539 * regardless of whether sub-condition (ii) holds. In other
3540 * words, only if sub-condition (i) holds, then idling is
3541 * allowed, and the device tends to be prevented from queueing
3542 * many requests, possibly of several processes. The reason
3543 * for not controlling also sub-condition (ii) is that we
3544 * exploit preemption to preserve guarantees in case of
3545 * symmetric scenarios, even if (ii) does not hold, as
3546 * explained in the next two paragraphs.
3548 * Even if a queue, say Q, is expired when it remains idle, Q
3549 * can still preempt the new in-service queue if the next
3550 * request of Q arrives soon (see the comments on
3551 * bfq_bfqq_update_budg_for_activation). If all queues and
3552 * groups have the same weight, this form of preemption,
3553 * combined with the hole-recovery heuristic described in the
3554 * comments on function bfq_bfqq_update_budg_for_activation,
3555 * are enough to preserve a correct bandwidth distribution in
3556 * the mid term, even without idling. In fact, even if not
3557 * idling allows the internal queues of the device to contain
3558 * many requests, and thus to reorder requests, we can rather
3559 * safely assume that the internal scheduler still preserves a
3560 * minimum of mid-term fairness. The motivation for using
3561 * preemption instead of idling is that, by not idling,
3562 * service guarantees are preserved without minimally
3563 * sacrificing throughput. In other words, both a high
3564 * throughput and its desired distribution are obtained.
3566 * More precisely, this preemption-based, idleless approach
3567 * provides fairness in terms of IOPS, and not sectors per
3568 * second. This can be seen with a simple example. Suppose
3569 * that there are two queues with the same weight, but that
3570 * the first queue receives requests of 8 sectors, while the
3571 * second queue receives requests of 1024 sectors. In
3572 * addition, suppose that each of the two queues contains at
3573 * most one request at a time, which implies that each queue
3574 * always remains idle after it is served. Finally, after
3575 * remaining idle, each queue receives very quickly a new
3576 * request. It follows that the two queues are served
3577 * alternatively, preempting each other if needed. This
3578 * implies that, although both queues have the same weight,
3579 * the queue with large requests receives a service that is
3580 * 1024/8 times as high as the service received by the other
3583 * On the other hand, device idling is performed, and thus
3584 * pure sector-domain guarantees are provided, for the
3585 * following queues, which are likely to need stronger
3586 * throughput guarantees: weight-raised queues, and queues
3587 * with a higher weight than other queues. When such queues
3588 * are active, sub-condition (i) is false, which triggers
3591 * According to the above considerations, the next variable is
3592 * true (only) if sub-condition (i) holds. To compute the
3593 * value of this variable, we not only use the return value of
3594 * the function bfq_symmetric_scenario(), but also check
3595 * whether bfqq is being weight-raised, because
3596 * bfq_symmetric_scenario() does not take into account also
3597 * weight-raised queues (see comments on
3598 * bfq_weights_tree_add()). In particular, if bfqq is being
3599 * weight-raised, it is important to idle only if there are
3600 * other, non-weight-raised queues that may steal throughput
3601 * to bfqq. Actually, we should be even more precise, and
3602 * differentiate between interactive weight raising and
3603 * soft real-time weight raising.
3605 * As a side note, it is worth considering that the above
3606 * device-idling countermeasures may however fail in the
3607 * following unlucky scenario: if idling is (correctly)
3608 * disabled in a time period during which all symmetry
3609 * sub-conditions hold, and hence the device is allowed to
3610 * enqueue many requests, but at some later point in time some
3611 * sub-condition stops to hold, then it may become impossible
3612 * to let requests be served in the desired order until all
3613 * the requests already queued in the device have been served.
3615 asymmetric_scenario = (bfqq->wr_coeff > 1 &&
3616 bfqd->wr_busy_queues < bfqd->busy_queues) ||
3617 !bfq_symmetric_scenario(bfqd);
3620 * Finally, there is a case where maximizing throughput is the
3621 * best choice even if it may cause unfairness toward
3622 * bfqq. Such a case is when bfqq became active in a burst of
3623 * queue activations. Queues that became active during a large
3624 * burst benefit only from throughput, as discussed in the
3625 * comments on bfq_handle_burst. Thus, if bfqq became active
3626 * in a burst and not idling the device maximizes throughput,
3627 * then the device must no be idled, because not idling the
3628 * device provides bfqq and all other queues in the burst with
3629 * maximum benefit. Combining this and the above case, we can
3630 * now establish when idling is actually needed to preserve
3631 * service guarantees.
3633 idling_needed_for_service_guarantees =
3634 asymmetric_scenario && !bfq_bfqq_in_large_burst(bfqq);
3637 * We have now all the components we need to compute the
3638 * return value of the function, which is true only if idling
3639 * either boosts the throughput (without issues), or is
3640 * necessary to preserve service guarantees.
3642 return idling_boosts_thr_without_issues ||
3643 idling_needed_for_service_guarantees;
3647 * If the in-service queue is empty but the function bfq_better_to_idle
3648 * returns true, then:
3649 * 1) the queue must remain in service and cannot be expired, and
3650 * 2) the device must be idled to wait for the possible arrival of a new
3651 * request for the queue.
3652 * See the comments on the function bfq_better_to_idle for the reasons
3653 * why performing device idling is the best choice to boost the throughput
3654 * and preserve service guarantees when bfq_better_to_idle itself
3657 static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
3659 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_better_to_idle(bfqq);
3662 static struct bfq_queue *bfq_choose_bfqq_for_injection(struct bfq_data *bfqd)
3664 struct bfq_queue *bfqq;
3667 * A linear search; but, with a high probability, very few
3668 * steps are needed to find a candidate queue, i.e., a queue
3669 * with enough budget left for its next request. In fact:
3670 * - BFQ dynamically updates the budget of every queue so as
3671 * to accommodate the expected backlog of the queue;
3672 * - if a queue gets all its requests dispatched as injected
3673 * service, then the queue is removed from the active list
3674 * (and re-added only if it gets new requests, but with
3675 * enough budget for its new backlog).
3677 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
3678 if (!RB_EMPTY_ROOT(&bfqq->sort_list) &&
3679 bfq_serv_to_charge(bfqq->next_rq, bfqq) <=
3680 bfq_bfqq_budget_left(bfqq))
3687 * Select a queue for service. If we have a current queue in service,
3688 * check whether to continue servicing it, or retrieve and set a new one.
3690 static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
3692 struct bfq_queue *bfqq;
3693 struct request *next_rq;
3694 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
3696 bfqq = bfqd->in_service_queue;
3700 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
3703 * Do not expire bfqq for budget timeout if bfqq may be about
3704 * to enjoy device idling. The reason why, in this case, we
3705 * prevent bfqq from expiring is the same as in the comments
3706 * on the case where bfq_bfqq_must_idle() returns true, in
3707 * bfq_completed_request().
3709 if (bfq_may_expire_for_budg_timeout(bfqq) &&
3710 !bfq_bfqq_must_idle(bfqq))
3715 * This loop is rarely executed more than once. Even when it
3716 * happens, it is much more convenient to re-execute this loop
3717 * than to return NULL and trigger a new dispatch to get a
3720 next_rq = bfqq->next_rq;
3722 * If bfqq has requests queued and it has enough budget left to
3723 * serve them, keep the queue, otherwise expire it.
3726 if (bfq_serv_to_charge(next_rq, bfqq) >
3727 bfq_bfqq_budget_left(bfqq)) {
3729 * Expire the queue for budget exhaustion,
3730 * which makes sure that the next budget is
3731 * enough to serve the next request, even if
3732 * it comes from the fifo expired path.
3734 reason = BFQQE_BUDGET_EXHAUSTED;
3738 * The idle timer may be pending because we may
3739 * not disable disk idling even when a new request
3742 if (bfq_bfqq_wait_request(bfqq)) {
3744 * If we get here: 1) at least a new request
3745 * has arrived but we have not disabled the
3746 * timer because the request was too small,
3747 * 2) then the block layer has unplugged
3748 * the device, causing the dispatch to be
3751 * Since the device is unplugged, now the
3752 * requests are probably large enough to
3753 * provide a reasonable throughput.
3754 * So we disable idling.
3756 bfq_clear_bfqq_wait_request(bfqq);
3757 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
3764 * No requests pending. However, if the in-service queue is idling
3765 * for a new request, or has requests waiting for a completion and
3766 * may idle after their completion, then keep it anyway.
3768 * Yet, to boost throughput, inject service from other queues if
3771 if (bfq_bfqq_wait_request(bfqq) ||
3772 (bfqq->dispatched != 0 && bfq_better_to_idle(bfqq))) {
3773 if (bfq_bfqq_injectable(bfqq) &&
3774 bfqq->injected_service * bfqq->inject_coeff <
3775 bfqq->entity.service * 10)
3776 bfqq = bfq_choose_bfqq_for_injection(bfqd);
3783 reason = BFQQE_NO_MORE_REQUESTS;
3785 bfq_bfqq_expire(bfqd, bfqq, false, reason);
3787 bfqq = bfq_set_in_service_queue(bfqd);
3789 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
3794 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
3796 bfq_log(bfqd, "select_queue: no queue returned");
3801 static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
3803 struct bfq_entity *entity = &bfqq->entity;
3805 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
3806 bfq_log_bfqq(bfqd, bfqq,
3807 "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
3808 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
3809 jiffies_to_msecs(bfqq->wr_cur_max_time),
3811 bfqq->entity.weight, bfqq->entity.orig_weight);
3813 if (entity->prio_changed)
3814 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
3817 * If the queue was activated in a burst, or too much
3818 * time has elapsed from the beginning of this
3819 * weight-raising period, then end weight raising.
3821 if (bfq_bfqq_in_large_burst(bfqq))
3822 bfq_bfqq_end_wr(bfqq);
3823 else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
3824 bfqq->wr_cur_max_time)) {
3825 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
3826 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
3827 bfq_wr_duration(bfqd)))
3828 bfq_bfqq_end_wr(bfqq);
3830 switch_back_to_interactive_wr(bfqq, bfqd);
3831 bfqq->entity.prio_changed = 1;
3834 if (bfqq->wr_coeff > 1 &&
3835 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
3836 bfqq->service_from_wr > max_service_from_wr) {
3837 /* see comments on max_service_from_wr */
3838 bfq_bfqq_end_wr(bfqq);
3842 * To improve latency (for this or other queues), immediately
3843 * update weight both if it must be raised and if it must be
3844 * lowered. Since, entity may be on some active tree here, and
3845 * might have a pending change of its ioprio class, invoke
3846 * next function with the last parameter unset (see the
3847 * comments on the function).
3849 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
3850 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
3855 * Dispatch next request from bfqq.
3857 static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
3858 struct bfq_queue *bfqq)
3860 struct request *rq = bfqq->next_rq;
3861 unsigned long service_to_charge;
3863 service_to_charge = bfq_serv_to_charge(rq, bfqq);
3865 bfq_bfqq_served(bfqq, service_to_charge);
3867 bfq_dispatch_remove(bfqd->queue, rq);
3869 if (bfqq != bfqd->in_service_queue) {
3870 if (likely(bfqd->in_service_queue))
3871 bfqd->in_service_queue->injected_service +=
3872 bfq_serv_to_charge(rq, bfqq);
3878 * If weight raising has to terminate for bfqq, then next
3879 * function causes an immediate update of bfqq's weight,
3880 * without waiting for next activation. As a consequence, on
3881 * expiration, bfqq will be timestamped as if has never been
3882 * weight-raised during this service slot, even if it has
3883 * received part or even most of the service as a
3884 * weight-raised queue. This inflates bfqq's timestamps, which
3885 * is beneficial, as bfqq is then more willing to leave the
3886 * device immediately to possible other weight-raised queues.
3888 bfq_update_wr_data(bfqd, bfqq);
3891 * Expire bfqq, pretending that its budget expired, if bfqq
3892 * belongs to CLASS_IDLE and other queues are waiting for
3895 if (!(bfqd->busy_queues > 1 && bfq_class_idle(bfqq)))
3898 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
3904 static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
3906 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3909 * Avoiding lock: a race on bfqd->busy_queues should cause at
3910 * most a call to dispatch for nothing
3912 return !list_empty_careful(&bfqd->dispatch) ||
3913 bfqd->busy_queues > 0;
3916 static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
3918 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
3919 struct request *rq = NULL;
3920 struct bfq_queue *bfqq = NULL;
3922 if (!list_empty(&bfqd->dispatch)) {
3923 rq = list_first_entry(&bfqd->dispatch, struct request,
3925 list_del_init(&rq->queuelist);
3931 * Increment counters here, because this
3932 * dispatch does not follow the standard
3933 * dispatch flow (where counters are
3938 goto inc_in_driver_start_rq;
3942 * We exploit the bfq_finish_requeue_request hook to
3943 * decrement rq_in_driver, but
3944 * bfq_finish_requeue_request will not be invoked on
3945 * this request. So, to avoid unbalance, just start
3946 * this request, without incrementing rq_in_driver. As
3947 * a negative consequence, rq_in_driver is deceptively
3948 * lower than it should be while this request is in
3949 * service. This may cause bfq_schedule_dispatch to be
3950 * invoked uselessly.
3952 * As for implementing an exact solution, the
3953 * bfq_finish_requeue_request hook, if defined, is
3954 * probably invoked also on this request. So, by
3955 * exploiting this hook, we could 1) increment
3956 * rq_in_driver here, and 2) decrement it in
3957 * bfq_finish_requeue_request. Such a solution would
3958 * let the value of the counter be always accurate,
3959 * but it would entail using an extra interface
3960 * function. This cost seems higher than the benefit,
3961 * being the frequency of non-elevator-private
3962 * requests very low.
3967 bfq_log(bfqd, "dispatch requests: %d busy queues", bfqd->busy_queues);
3969 if (bfqd->busy_queues == 0)
3973 * Force device to serve one request at a time if
3974 * strict_guarantees is true. Forcing this service scheme is
3975 * currently the ONLY way to guarantee that the request
3976 * service order enforced by the scheduler is respected by a
3977 * queueing device. Otherwise the device is free even to make
3978 * some unlucky request wait for as long as the device
3981 * Of course, serving one request at at time may cause loss of
3984 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
3987 bfqq = bfq_select_queue(bfqd);
3991 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
3994 inc_in_driver_start_rq:
3995 bfqd->rq_in_driver++;
3997 rq->rq_flags |= RQF_STARTED;
4003 #if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
4004 static void bfq_update_dispatch_stats(struct request_queue *q,
4006 struct bfq_queue *in_serv_queue,
4007 bool idle_timer_disabled)
4009 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
4011 if (!idle_timer_disabled && !bfqq)
4015 * rq and bfqq are guaranteed to exist until this function
4016 * ends, for the following reasons. First, rq can be
4017 * dispatched to the device, and then can be completed and
4018 * freed, only after this function ends. Second, rq cannot be
4019 * merged (and thus freed because of a merge) any longer,
4020 * because it has already started. Thus rq cannot be freed
4021 * before this function ends, and, since rq has a reference to
4022 * bfqq, the same guarantee holds for bfqq too.
4024 * In addition, the following queue lock guarantees that
4025 * bfqq_group(bfqq) exists as well.
4027 spin_lock_irq(q->queue_lock);
4028 if (idle_timer_disabled)
4030 * Since the idle timer has been disabled,
4031 * in_serv_queue contained some request when
4032 * __bfq_dispatch_request was invoked above, which
4033 * implies that rq was picked exactly from
4034 * in_serv_queue. Thus in_serv_queue == bfqq, and is
4035 * therefore guaranteed to exist because of the above
4038 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
4040 struct bfq_group *bfqg = bfqq_group(bfqq);
4042 bfqg_stats_update_avg_queue_size(bfqg);
4043 bfqg_stats_set_start_empty_time(bfqg);
4044 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
4046 spin_unlock_irq(q->queue_lock);
4049 static inline void bfq_update_dispatch_stats(struct request_queue *q,
4051 struct bfq_queue *in_serv_queue,
4052 bool idle_timer_disabled) {}
4055 static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
4057 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4059 struct bfq_queue *in_serv_queue;
4060 bool waiting_rq, idle_timer_disabled;
4062 spin_lock_irq(&bfqd->lock);
4064 in_serv_queue = bfqd->in_service_queue;
4065 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
4067 rq = __bfq_dispatch_request(hctx);
4069 idle_timer_disabled =
4070 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
4072 spin_unlock_irq(&bfqd->lock);
4074 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue,
4075 idle_timer_disabled);
4081 * Task holds one reference to the queue, dropped when task exits. Each rq
4082 * in-flight on this queue also holds a reference, dropped when rq is freed.
4084 * Scheduler lock must be held here. Recall not to use bfqq after calling
4085 * this function on it.
4087 void bfq_put_queue(struct bfq_queue *bfqq)
4089 #ifdef CONFIG_BFQ_GROUP_IOSCHED
4090 struct bfq_group *bfqg = bfqq_group(bfqq);
4094 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
4101 if (!hlist_unhashed(&bfqq->burst_list_node)) {
4102 hlist_del_init(&bfqq->burst_list_node);
4104 * Decrement also burst size after the removal, if the
4105 * process associated with bfqq is exiting, and thus
4106 * does not contribute to the burst any longer. This
4107 * decrement helps filter out false positives of large
4108 * bursts, when some short-lived process (often due to
4109 * the execution of commands by some service) happens
4110 * to start and exit while a complex application is
4111 * starting, and thus spawning several processes that
4112 * do I/O (and that *must not* be treated as a large
4113 * burst, see comments on bfq_handle_burst).
4115 * In particular, the decrement is performed only if:
4116 * 1) bfqq is not a merged queue, because, if it is,
4117 * then this free of bfqq is not triggered by the exit
4118 * of the process bfqq is associated with, but exactly
4119 * by the fact that bfqq has just been merged.
4120 * 2) burst_size is greater than 0, to handle
4121 * unbalanced decrements. Unbalanced decrements may
4122 * happen in te following case: bfqq is inserted into
4123 * the current burst list--without incrementing
4124 * bust_size--because of a split, but the current
4125 * burst list is not the burst list bfqq belonged to
4126 * (see comments on the case of a split in
4129 if (bfqq->bic && bfqq->bfqd->burst_size > 0)
4130 bfqq->bfqd->burst_size--;
4133 kmem_cache_free(bfq_pool, bfqq);
4134 #ifdef CONFIG_BFQ_GROUP_IOSCHED
4135 bfqg_and_blkg_put(bfqg);
4139 static void bfq_put_cooperator(struct bfq_queue *bfqq)
4141 struct bfq_queue *__bfqq, *next;
4144 * If this queue was scheduled to merge with another queue, be
4145 * sure to drop the reference taken on that queue (and others in
4146 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
4148 __bfqq = bfqq->new_bfqq;
4152 next = __bfqq->new_bfqq;
4153 bfq_put_queue(__bfqq);
4158 static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4160 if (bfqq == bfqd->in_service_queue) {
4161 __bfq_bfqq_expire(bfqd, bfqq);
4162 bfq_schedule_dispatch(bfqd);
4165 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
4167 bfq_put_cooperator(bfqq);
4169 bfq_put_queue(bfqq); /* release process reference */
4172 static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
4174 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4175 struct bfq_data *bfqd;
4178 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
4181 unsigned long flags;
4183 spin_lock_irqsave(&bfqd->lock, flags);
4185 bfq_exit_bfqq(bfqd, bfqq);
4186 bic_set_bfqq(bic, NULL, is_sync);
4187 spin_unlock_irqrestore(&bfqd->lock, flags);
4191 static void bfq_exit_icq(struct io_cq *icq)
4193 struct bfq_io_cq *bic = icq_to_bic(icq);
4195 bfq_exit_icq_bfqq(bic, true);
4196 bfq_exit_icq_bfqq(bic, false);
4200 * Update the entity prio values; note that the new values will not
4201 * be used until the next (re)activation.
4204 bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
4206 struct task_struct *tsk = current;
4208 struct bfq_data *bfqd = bfqq->bfqd;
4213 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4214 switch (ioprio_class) {
4216 pr_err("bdi %s: bfq: bad prio class %d\n",
4217 bdi_dev_name(bfqq->bfqd->queue->backing_dev_info),
4220 case IOPRIO_CLASS_NONE:
4222 * No prio set, inherit CPU scheduling settings.
4224 bfqq->new_ioprio = task_nice_ioprio(tsk);
4225 bfqq->new_ioprio_class = task_nice_ioclass(tsk);
4227 case IOPRIO_CLASS_RT:
4228 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4229 bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
4231 case IOPRIO_CLASS_BE:
4232 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4233 bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
4235 case IOPRIO_CLASS_IDLE:
4236 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
4237 bfqq->new_ioprio = 7;
4241 if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
4242 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
4244 bfqq->new_ioprio = IOPRIO_BE_NR - 1;
4247 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
4248 bfqq->entity.prio_changed = 1;
4251 static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4252 struct bio *bio, bool is_sync,
4253 struct bfq_io_cq *bic);
4255 static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
4257 struct bfq_data *bfqd = bic_to_bfqd(bic);
4258 struct bfq_queue *bfqq;
4259 int ioprio = bic->icq.ioc->ioprio;
4262 * This condition may trigger on a newly created bic, be sure to
4263 * drop the lock before returning.
4265 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
4268 bic->ioprio = ioprio;
4270 bfqq = bic_to_bfqq(bic, false);
4272 /* release process reference on this queue */
4273 bfq_put_queue(bfqq);
4274 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
4275 bic_set_bfqq(bic, bfqq, false);
4278 bfqq = bic_to_bfqq(bic, true);
4280 bfq_set_next_ioprio_data(bfqq, bic);
4283 static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4284 struct bfq_io_cq *bic, pid_t pid, int is_sync)
4286 RB_CLEAR_NODE(&bfqq->entity.rb_node);
4287 INIT_LIST_HEAD(&bfqq->fifo);
4288 INIT_HLIST_NODE(&bfqq->burst_list_node);
4294 bfq_set_next_ioprio_data(bfqq, bic);
4298 * No need to mark as has_short_ttime if in
4299 * idle_class, because no device idling is performed
4300 * for queues in idle class
4302 if (!bfq_class_idle(bfqq))
4303 /* tentatively mark as has_short_ttime */
4304 bfq_mark_bfqq_has_short_ttime(bfqq);
4305 bfq_mark_bfqq_sync(bfqq);
4306 bfq_mark_bfqq_just_created(bfqq);
4308 * Aggressively inject a lot of service: up to 90%.
4309 * This coefficient remains constant during bfqq life,
4310 * but this behavior might be changed, after enough
4311 * testing and tuning.
4313 bfqq->inject_coeff = 1;
4315 bfq_clear_bfqq_sync(bfqq);
4317 /* set end request to minus infinity from now */
4318 bfqq->ttime.last_end_request = ktime_get_ns() + 1;
4320 bfq_mark_bfqq_IO_bound(bfqq);
4324 /* Tentative initial value to trade off between thr and lat */
4325 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
4326 bfqq->budget_timeout = bfq_smallest_from_now();
4329 bfqq->last_wr_start_finish = jiffies;
4330 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
4331 bfqq->split_time = bfq_smallest_from_now();
4334 * To not forget the possibly high bandwidth consumed by a
4335 * process/queue in the recent past,
4336 * bfq_bfqq_softrt_next_start() returns a value at least equal
4337 * to the current value of bfqq->soft_rt_next_start (see
4338 * comments on bfq_bfqq_softrt_next_start). Set
4339 * soft_rt_next_start to now, to mean that bfqq has consumed
4340 * no bandwidth so far.
4342 bfqq->soft_rt_next_start = jiffies;
4344 /* first request is almost certainly seeky */
4345 bfqq->seek_history = 1;
4348 static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
4349 struct bfq_group *bfqg,
4350 int ioprio_class, int ioprio)
4352 switch (ioprio_class) {
4353 case IOPRIO_CLASS_RT:
4354 return &bfqg->async_bfqq[0][ioprio];
4355 case IOPRIO_CLASS_NONE:
4356 ioprio = IOPRIO_NORM;
4358 case IOPRIO_CLASS_BE:
4359 return &bfqg->async_bfqq[1][ioprio];
4360 case IOPRIO_CLASS_IDLE:
4361 return &bfqg->async_idle_bfqq;
4367 static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4368 struct bio *bio, bool is_sync,
4369 struct bfq_io_cq *bic)
4371 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4372 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4373 struct bfq_queue **async_bfqq = NULL;
4374 struct bfq_queue *bfqq;
4375 struct bfq_group *bfqg;
4379 bfqg = bfq_find_set_group(bfqd, bio_blkcg(bio));
4381 bfqq = &bfqd->oom_bfqq;
4386 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
4393 bfqq = kmem_cache_alloc_node(bfq_pool,
4394 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
4398 bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
4400 bfq_init_entity(&bfqq->entity, bfqg);
4401 bfq_log_bfqq(bfqd, bfqq, "allocated");
4403 bfqq = &bfqd->oom_bfqq;
4404 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
4409 * Pin the queue now that it's allocated, scheduler exit will
4414 * Extra group reference, w.r.t. sync
4415 * queue. This extra reference is removed
4416 * only if bfqq->bfqg disappears, to
4417 * guarantee that this queue is not freed
4418 * until its group goes away.
4420 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
4426 bfqq->ref++; /* get a process reference to this queue */
4427 bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
4432 static void bfq_update_io_thinktime(struct bfq_data *bfqd,
4433 struct bfq_queue *bfqq)
4435 struct bfq_ttime *ttime = &bfqq->ttime;
4436 u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
4438 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
4440 ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
4441 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
4442 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
4443 ttime->ttime_samples);
4447 bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4450 bfqq->seek_history <<= 1;
4451 bfqq->seek_history |=
4452 get_sdist(bfqq->last_request_pos, rq) > BFQQ_SEEK_THR &&
4453 (!blk_queue_nonrot(bfqd->queue) ||
4454 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT);
4457 static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
4458 struct bfq_queue *bfqq,
4459 struct bfq_io_cq *bic)
4461 bool has_short_ttime = true;
4464 * No need to update has_short_ttime if bfqq is async or in
4465 * idle io prio class, or if bfq_slice_idle is zero, because
4466 * no device idling is performed for bfqq in this case.
4468 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
4469 bfqd->bfq_slice_idle == 0)
4472 /* Idle window just restored, statistics are meaningless. */
4473 if (time_is_after_eq_jiffies(bfqq->split_time +
4474 bfqd->bfq_wr_min_idle_time))
4477 /* Think time is infinite if no process is linked to
4478 * bfqq. Otherwise check average think time to
4479 * decide whether to mark as has_short_ttime
4481 if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
4482 (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
4483 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
4484 has_short_ttime = false;
4486 bfq_log_bfqq(bfqd, bfqq, "update_has_short_ttime: has_short_ttime %d",
4489 if (has_short_ttime)
4490 bfq_mark_bfqq_has_short_ttime(bfqq);
4492 bfq_clear_bfqq_has_short_ttime(bfqq);
4496 * Called when a new fs request (rq) is added to bfqq. Check if there's
4497 * something we should do about it.
4499 static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4502 struct bfq_io_cq *bic = RQ_BIC(rq);
4504 if (rq->cmd_flags & REQ_META)
4505 bfqq->meta_pending++;
4507 bfq_update_io_thinktime(bfqd, bfqq);
4508 bfq_update_has_short_ttime(bfqd, bfqq, bic);
4509 bfq_update_io_seektime(bfqd, bfqq, rq);
4511 bfq_log_bfqq(bfqd, bfqq,
4512 "rq_enqueued: has_short_ttime=%d (seeky %d)",
4513 bfq_bfqq_has_short_ttime(bfqq), BFQQ_SEEKY(bfqq));
4515 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4517 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
4518 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
4519 blk_rq_sectors(rq) < 32;
4520 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
4523 * There is just this request queued: if the request
4524 * is small and the queue is not to be expired, then
4527 * In this way, if the device is being idled to wait
4528 * for a new request from the in-service queue, we
4529 * avoid unplugging the device and committing the
4530 * device to serve just a small request. On the
4531 * contrary, we wait for the block layer to decide
4532 * when to unplug the device: hopefully, new requests
4533 * will be merged to this one quickly, then the device
4534 * will be unplugged and larger requests will be
4537 if (small_req && !budget_timeout)
4541 * A large enough request arrived, or the queue is to
4542 * be expired: in both cases disk idling is to be
4543 * stopped, so clear wait_request flag and reset
4546 bfq_clear_bfqq_wait_request(bfqq);
4547 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
4550 * The queue is not empty, because a new request just
4551 * arrived. Hence we can safely expire the queue, in
4552 * case of budget timeout, without risking that the
4553 * timestamps of the queue are not updated correctly.
4554 * See [1] for more details.
4557 bfq_bfqq_expire(bfqd, bfqq, false,
4558 BFQQE_BUDGET_TIMEOUT);
4562 /* returns true if it causes the idle timer to be disabled */
4563 static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
4565 struct bfq_queue *bfqq = RQ_BFQQ(rq),
4566 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
4567 bool waiting, idle_timer_disabled = false;
4570 if (bic_to_bfqq(RQ_BIC(rq), 1) != bfqq)
4571 new_bfqq = bic_to_bfqq(RQ_BIC(rq), 1);
4573 * Release the request's reference to the old bfqq
4574 * and make sure one is taken to the shared queue.
4576 new_bfqq->allocated++;
4580 * If the bic associated with the process
4581 * issuing this request still points to bfqq
4582 * (and thus has not been already redirected
4583 * to new_bfqq or even some other bfq_queue),
4584 * then complete the merge and redirect it to
4587 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
4588 bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
4591 bfq_clear_bfqq_just_created(bfqq);
4593 * rq is about to be enqueued into new_bfqq,
4594 * release rq reference on bfqq
4596 bfq_put_queue(bfqq);
4597 rq->elv.priv[1] = new_bfqq;
4601 waiting = bfqq && bfq_bfqq_wait_request(bfqq);
4602 bfq_add_request(rq);
4603 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
4605 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
4606 list_add_tail(&rq->queuelist, &bfqq->fifo);
4608 bfq_rq_enqueued(bfqd, bfqq, rq);
4610 return idle_timer_disabled;
4613 #if defined(CONFIG_BFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
4614 static void bfq_update_insert_stats(struct request_queue *q,
4615 struct bfq_queue *bfqq,
4616 bool idle_timer_disabled,
4617 unsigned int cmd_flags)
4623 * bfqq still exists, because it can disappear only after
4624 * either it is merged with another queue, or the process it
4625 * is associated with exits. But both actions must be taken by
4626 * the same process currently executing this flow of
4629 * In addition, the following queue lock guarantees that
4630 * bfqq_group(bfqq) exists as well.
4632 spin_lock_irq(q->queue_lock);
4633 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
4634 if (idle_timer_disabled)
4635 bfqg_stats_update_idle_time(bfqq_group(bfqq));
4636 spin_unlock_irq(q->queue_lock);
4639 static inline void bfq_update_insert_stats(struct request_queue *q,
4640 struct bfq_queue *bfqq,
4641 bool idle_timer_disabled,
4642 unsigned int cmd_flags) {}
4645 static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
4648 struct request_queue *q = hctx->queue;
4649 struct bfq_data *bfqd = q->elevator->elevator_data;
4650 struct bfq_queue *bfqq;
4651 bool idle_timer_disabled = false;
4652 unsigned int cmd_flags;
4654 spin_lock_irq(&bfqd->lock);
4655 if (blk_mq_sched_try_insert_merge(q, rq)) {
4656 spin_unlock_irq(&bfqd->lock);
4660 spin_unlock_irq(&bfqd->lock);
4662 blk_mq_sched_request_inserted(rq);
4664 spin_lock_irq(&bfqd->lock);
4665 bfqq = bfq_init_rq(rq);
4666 if (!bfqq || at_head || blk_rq_is_passthrough(rq)) {
4668 list_add(&rq->queuelist, &bfqd->dispatch);
4670 list_add_tail(&rq->queuelist, &bfqd->dispatch);
4672 idle_timer_disabled = __bfq_insert_request(bfqd, rq);
4674 * Update bfqq, because, if a queue merge has occurred
4675 * in __bfq_insert_request, then rq has been
4676 * redirected into a new queue.
4680 if (rq_mergeable(rq)) {
4681 elv_rqhash_add(q, rq);
4688 * Cache cmd_flags before releasing scheduler lock, because rq
4689 * may disappear afterwards (for example, because of a request
4692 cmd_flags = rq->cmd_flags;
4694 spin_unlock_irq(&bfqd->lock);
4696 bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
4700 static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
4701 struct list_head *list, bool at_head)
4703 while (!list_empty(list)) {
4706 rq = list_first_entry(list, struct request, queuelist);
4707 list_del_init(&rq->queuelist);
4708 bfq_insert_request(hctx, rq, at_head);
4712 static void bfq_update_hw_tag(struct bfq_data *bfqd)
4714 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
4715 bfqd->rq_in_driver);
4717 if (bfqd->hw_tag == 1)
4721 * This sample is valid if the number of outstanding requests
4722 * is large enough to allow a queueing behavior. Note that the
4723 * sum is not exact, as it's not taking into account deactivated
4726 if (bfqd->rq_in_driver + bfqd->queued < BFQ_HW_QUEUE_THRESHOLD)
4729 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
4732 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
4733 bfqd->max_rq_in_driver = 0;
4734 bfqd->hw_tag_samples = 0;
4737 static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
4742 bfq_update_hw_tag(bfqd);
4744 bfqd->rq_in_driver--;
4747 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
4749 * Set budget_timeout (which we overload to store the
4750 * time at which the queue remains with no backlog and
4751 * no outstanding request; used by the weight-raising
4754 bfqq->budget_timeout = jiffies;
4756 bfq_weights_tree_remove(bfqd, bfqq);
4759 now_ns = ktime_get_ns();
4761 bfqq->ttime.last_end_request = now_ns;
4764 * Using us instead of ns, to get a reasonable precision in
4765 * computing rate in next check.
4767 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
4770 * If the request took rather long to complete, and, according
4771 * to the maximum request size recorded, this completion latency
4772 * implies that the request was certainly served at a very low
4773 * rate (less than 1M sectors/sec), then the whole observation
4774 * interval that lasts up to this time instant cannot be a
4775 * valid time interval for computing a new peak rate. Invoke
4776 * bfq_update_rate_reset to have the following three steps
4778 * - close the observation interval at the last (previous)
4779 * request dispatch or completion
4780 * - compute rate, if possible, for that observation interval
4781 * - reset to zero samples, which will trigger a proper
4782 * re-initialization of the observation interval on next
4785 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
4786 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
4787 1UL<<(BFQ_RATE_SHIFT - 10))
4788 bfq_update_rate_reset(bfqd, NULL);
4789 bfqd->last_completion = now_ns;
4792 * If we are waiting to discover whether the request pattern
4793 * of the task associated with the queue is actually
4794 * isochronous, and both requisites for this condition to hold
4795 * are now satisfied, then compute soft_rt_next_start (see the
4796 * comments on the function bfq_bfqq_softrt_next_start()). We
4797 * schedule this delayed check when bfqq expires, if it still
4798 * has in-flight requests.
4800 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
4801 RB_EMPTY_ROOT(&bfqq->sort_list))
4802 bfqq->soft_rt_next_start =
4803 bfq_bfqq_softrt_next_start(bfqd, bfqq);
4806 * If this is the in-service queue, check if it needs to be expired,
4807 * or if we want to idle in case it has no pending requests.
4809 if (bfqd->in_service_queue == bfqq) {
4810 if (bfq_bfqq_must_idle(bfqq)) {
4811 if (bfqq->dispatched == 0)
4812 bfq_arm_slice_timer(bfqd);
4814 * If we get here, we do not expire bfqq, even
4815 * if bfqq was in budget timeout or had no
4816 * more requests (as controlled in the next
4817 * conditional instructions). The reason for
4818 * not expiring bfqq is as follows.
4820 * Here bfqq->dispatched > 0 holds, but
4821 * bfq_bfqq_must_idle() returned true. This
4822 * implies that, even if no request arrives
4823 * for bfqq before bfqq->dispatched reaches 0,
4824 * bfqq will, however, not be expired on the
4825 * completion event that causes bfqq->dispatch
4826 * to reach zero. In contrast, on this event,
4827 * bfqq will start enjoying device idling
4828 * (I/O-dispatch plugging).
4830 * But, if we expired bfqq here, bfqq would
4831 * not have the chance to enjoy device idling
4832 * when bfqq->dispatched finally reaches
4833 * zero. This would expose bfqq to violation
4834 * of its reserved service guarantees.
4837 } else if (bfq_may_expire_for_budg_timeout(bfqq))
4838 bfq_bfqq_expire(bfqd, bfqq, false,
4839 BFQQE_BUDGET_TIMEOUT);
4840 else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
4841 (bfqq->dispatched == 0 ||
4842 !bfq_better_to_idle(bfqq)))
4843 bfq_bfqq_expire(bfqd, bfqq, false,
4844 BFQQE_NO_MORE_REQUESTS);
4847 if (!bfqd->rq_in_driver)
4848 bfq_schedule_dispatch(bfqd);
4851 static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq)
4855 bfq_put_queue(bfqq);
4859 * Handle either a requeue or a finish for rq. The things to do are
4860 * the same in both cases: all references to rq are to be dropped. In
4861 * particular, rq is considered completed from the point of view of
4864 static void bfq_finish_requeue_request(struct request *rq)
4866 struct bfq_queue *bfqq = RQ_BFQQ(rq);
4867 struct bfq_data *bfqd;
4870 * Requeue and finish hooks are invoked in blk-mq without
4871 * checking whether the involved request is actually still
4872 * referenced in the scheduler. To handle this fact, the
4873 * following two checks make this function exit in case of
4874 * spurious invocations, for which there is nothing to do.
4876 * First, check whether rq has nothing to do with an elevator.
4878 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV)))
4882 * rq either is not associated with any icq, or is an already
4883 * requeued request that has not (yet) been re-inserted into
4886 if (!rq->elv.icq || !bfqq)
4891 if (rq->rq_flags & RQF_STARTED)
4892 bfqg_stats_update_completion(bfqq_group(bfqq),
4894 rq->io_start_time_ns,
4897 if (likely(rq->rq_flags & RQF_STARTED)) {
4898 unsigned long flags;
4900 spin_lock_irqsave(&bfqd->lock, flags);
4902 bfq_completed_request(bfqq, bfqd);
4903 bfq_finish_requeue_request_body(bfqq);
4905 spin_unlock_irqrestore(&bfqd->lock, flags);
4908 * Request rq may be still/already in the scheduler,
4909 * in which case we need to remove it (this should
4910 * never happen in case of requeue). And we cannot
4911 * defer such a check and removal, to avoid
4912 * inconsistencies in the time interval from the end
4913 * of this function to the start of the deferred work.
4914 * This situation seems to occur only in process
4915 * context, as a consequence of a merge. In the
4916 * current version of the code, this implies that the
4920 if (!RB_EMPTY_NODE(&rq->rb_node)) {
4921 bfq_remove_request(rq->q, rq);
4922 bfqg_stats_update_io_remove(bfqq_group(bfqq),
4925 bfq_finish_requeue_request_body(bfqq);
4929 * Reset private fields. In case of a requeue, this allows
4930 * this function to correctly do nothing if it is spuriously
4931 * invoked again on this same request (see the check at the
4932 * beginning of the function). Probably, a better general
4933 * design would be to prevent blk-mq from invoking the requeue
4934 * or finish hooks of an elevator, for a request that is not
4935 * referred by that elevator.
4937 * Resetting the following fields would break the
4938 * request-insertion logic if rq is re-inserted into a bfq
4939 * internal queue, without a re-preparation. Here we assume
4940 * that re-insertions of requeued requests, without
4941 * re-preparation, can happen only for pass_through or at_head
4942 * requests (which are not re-inserted into bfq internal
4945 rq->elv.priv[0] = NULL;
4946 rq->elv.priv[1] = NULL;
4950 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
4951 * was the last process referring to that bfqq.
4953 static struct bfq_queue *
4954 bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
4956 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
4958 if (bfqq_process_refs(bfqq) == 1) {
4959 bfqq->pid = current->pid;
4960 bfq_clear_bfqq_coop(bfqq);
4961 bfq_clear_bfqq_split_coop(bfqq);
4965 bic_set_bfqq(bic, NULL, 1);
4967 bfq_put_cooperator(bfqq);
4969 bfq_put_queue(bfqq);
4973 static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
4974 struct bfq_io_cq *bic,
4976 bool split, bool is_sync,
4979 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4981 if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
4988 bfq_put_queue(bfqq);
4989 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
4991 bic_set_bfqq(bic, bfqq, is_sync);
4992 if (split && is_sync) {
4993 if ((bic->was_in_burst_list && bfqd->large_burst) ||
4994 bic->saved_in_large_burst)
4995 bfq_mark_bfqq_in_large_burst(bfqq);
4997 bfq_clear_bfqq_in_large_burst(bfqq);
4998 if (bic->was_in_burst_list)
5000 * If bfqq was in the current
5001 * burst list before being
5002 * merged, then we have to add
5003 * it back. And we do not need
5004 * to increase burst_size, as
5005 * we did not decrement
5006 * burst_size when we removed
5007 * bfqq from the burst list as
5008 * a consequence of a merge
5010 * bfq_put_queue). In this
5011 * respect, it would be rather
5012 * costly to know whether the
5013 * current burst list is still
5014 * the same burst list from
5015 * which bfqq was removed on
5016 * the merge. To avoid this
5017 * cost, if bfqq was in a
5018 * burst list, then we add
5019 * bfqq to the current burst
5020 * list without any further
5021 * check. This can cause
5022 * inappropriate insertions,
5023 * but rarely enough to not
5024 * harm the detection of large
5025 * bursts significantly.
5027 hlist_add_head(&bfqq->burst_list_node,
5030 bfqq->split_time = jiffies;
5037 * Only reset private fields. The actual request preparation will be
5038 * performed by bfq_init_rq, when rq is either inserted or merged. See
5039 * comments on bfq_init_rq for the reason behind this delayed
5042 static void bfq_prepare_request(struct request *rq, struct bio *bio)
5045 * Regardless of whether we have an icq attached, we have to
5046 * clear the scheduler pointers, as they might point to
5047 * previously allocated bic/bfqq structs.
5049 rq->elv.priv[0] = rq->elv.priv[1] = NULL;
5053 * If needed, init rq, allocate bfq data structures associated with
5054 * rq, and increment reference counters in the destination bfq_queue
5055 * for rq. Return the destination bfq_queue for rq, or NULL is rq is
5056 * not associated with any bfq_queue.
5058 * This function is invoked by the functions that perform rq insertion
5059 * or merging. One may have expected the above preparation operations
5060 * to be performed in bfq_prepare_request, and not delayed to when rq
5061 * is inserted or merged. The rationale behind this delayed
5062 * preparation is that, after the prepare_request hook is invoked for
5063 * rq, rq may still be transformed into a request with no icq, i.e., a
5064 * request not associated with any queue. No bfq hook is invoked to
5065 * signal this tranformation. As a consequence, should these
5066 * preparation operations be performed when the prepare_request hook
5067 * is invoked, and should rq be transformed one moment later, bfq
5068 * would end up in an inconsistent state, because it would have
5069 * incremented some queue counters for an rq destined to
5070 * transformation, without any chance to correctly lower these
5071 * counters back. In contrast, no transformation can still happen for
5072 * rq after rq has been inserted or merged. So, it is safe to execute
5073 * these preparation operations when rq is finally inserted or merged.
5075 static struct bfq_queue *bfq_init_rq(struct request *rq)
5077 struct request_queue *q = rq->q;
5078 struct bio *bio = rq->bio;
5079 struct bfq_data *bfqd = q->elevator->elevator_data;
5080 struct bfq_io_cq *bic;
5081 const int is_sync = rq_is_sync(rq);
5082 struct bfq_queue *bfqq;
5083 bool new_queue = false;
5084 bool bfqq_already_existing = false, split = false;
5086 if (unlikely(!rq->elv.icq))
5090 * Assuming that elv.priv[1] is set only if everything is set
5091 * for this rq. This holds true, because this function is
5092 * invoked only for insertion or merging, and, after such
5093 * events, a request cannot be manipulated any longer before
5094 * being removed from bfq.
5096 if (rq->elv.priv[1])
5097 return rq->elv.priv[1];
5099 bic = icq_to_bic(rq->elv.icq);
5101 bfq_check_ioprio_change(bic, bio);
5103 bfq_bic_update_cgroup(bic, bio);
5105 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
5108 if (likely(!new_queue)) {
5109 /* If the queue was seeky for too long, break it apart. */
5110 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
5111 bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
5113 /* Update bic before losing reference to bfqq */
5114 if (bfq_bfqq_in_large_burst(bfqq))
5115 bic->saved_in_large_burst = true;
5117 bfqq = bfq_split_bfqq(bic, bfqq);
5121 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
5125 bfqq_already_existing = true;
5131 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
5132 rq, bfqq, bfqq->ref);
5134 rq->elv.priv[0] = bic;
5135 rq->elv.priv[1] = bfqq;
5138 * If a bfq_queue has only one process reference, it is owned
5139 * by only this bic: we can then set bfqq->bic = bic. in
5140 * addition, if the queue has also just been split, we have to
5143 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
5147 * The queue has just been split from a shared
5148 * queue: restore the idle window and the
5149 * possible weight raising period.
5151 bfq_bfqq_resume_state(bfqq, bfqd, bic,
5152 bfqq_already_existing);
5156 if (unlikely(bfq_bfqq_just_created(bfqq)))
5157 bfq_handle_burst(bfqd, bfqq);
5163 bfq_idle_slice_timer_body(struct bfq_data *bfqd, struct bfq_queue *bfqq)
5165 enum bfqq_expiration reason;
5166 unsigned long flags;
5168 spin_lock_irqsave(&bfqd->lock, flags);
5171 * Considering that bfqq may be in race, we should firstly check
5172 * whether bfqq is in service before doing something on it. If
5173 * the bfqq in race is not in service, it has already been expired
5174 * through __bfq_bfqq_expire func and its wait_request flags has
5175 * been cleared in __bfq_bfqd_reset_in_service func.
5177 if (bfqq != bfqd->in_service_queue) {
5178 spin_unlock_irqrestore(&bfqd->lock, flags);
5182 bfq_clear_bfqq_wait_request(bfqq);
5184 if (bfq_bfqq_budget_timeout(bfqq))
5186 * Also here the queue can be safely expired
5187 * for budget timeout without wasting
5190 reason = BFQQE_BUDGET_TIMEOUT;
5191 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
5193 * The queue may not be empty upon timer expiration,
5194 * because we may not disable the timer when the
5195 * first request of the in-service queue arrives
5196 * during disk idling.
5198 reason = BFQQE_TOO_IDLE;
5200 goto schedule_dispatch;
5202 bfq_bfqq_expire(bfqd, bfqq, true, reason);
5205 spin_unlock_irqrestore(&bfqd->lock, flags);
5206 bfq_schedule_dispatch(bfqd);
5210 * Handler of the expiration of the timer running if the in-service queue
5211 * is idling inside its time slice.
5213 static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
5215 struct bfq_data *bfqd = container_of(timer, struct bfq_data,
5217 struct bfq_queue *bfqq = bfqd->in_service_queue;
5220 * Theoretical race here: the in-service queue can be NULL or
5221 * different from the queue that was idling if a new request
5222 * arrives for the current queue and there is a full dispatch
5223 * cycle that changes the in-service queue. This can hardly
5224 * happen, but in the worst case we just expire a queue too
5228 bfq_idle_slice_timer_body(bfqd, bfqq);
5230 return HRTIMER_NORESTART;
5233 static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
5234 struct bfq_queue **bfqq_ptr)
5236 struct bfq_queue *bfqq = *bfqq_ptr;
5238 bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
5240 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
5242 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
5244 bfq_put_queue(bfqq);
5250 * Release all the bfqg references to its async queues. If we are
5251 * deallocating the group these queues may still contain requests, so
5252 * we reparent them to the root cgroup (i.e., the only one that will
5253 * exist for sure until all the requests on a device are gone).
5255 void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
5259 for (i = 0; i < 2; i++)
5260 for (j = 0; j < IOPRIO_BE_NR; j++)
5261 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
5263 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
5267 * See the comments on bfq_limit_depth for the purpose of
5268 * the depths set in the function. Return minimum shallow depth we'll use.
5270 static unsigned int bfq_update_depths(struct bfq_data *bfqd,
5271 struct sbitmap_queue *bt)
5273 unsigned int i, j, min_shallow = UINT_MAX;
5276 * In-word depths if no bfq_queue is being weight-raised:
5277 * leaving 25% of tags only for sync reads.
5279 * In next formulas, right-shift the value
5280 * (1U<<bt->sb.shift), instead of computing directly
5281 * (1U<<(bt->sb.shift - something)), to be robust against
5282 * any possible value of bt->sb.shift, without having to
5283 * limit 'something'.
5285 /* no more than 50% of tags for async I/O */
5286 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U);
5288 * no more than 75% of tags for sync writes (25% extra tags
5289 * w.r.t. async I/O, to prevent async I/O from starving sync
5292 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U);
5295 * In-word depths in case some bfq_queue is being weight-
5296 * raised: leaving ~63% of tags for sync reads. This is the
5297 * highest percentage for which, in our tests, application
5298 * start-up times didn't suffer from any regression due to tag
5301 /* no more than ~18% of tags for async I/O */
5302 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U);
5303 /* no more than ~37% of tags for sync writes (~20% extra tags) */
5304 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U);
5306 for (i = 0; i < 2; i++)
5307 for (j = 0; j < 2; j++)
5308 min_shallow = min(min_shallow, bfqd->word_depths[i][j]);
5313 static void bfq_depth_updated(struct blk_mq_hw_ctx *hctx)
5315 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
5316 struct blk_mq_tags *tags = hctx->sched_tags;
5317 unsigned int min_shallow;
5319 min_shallow = bfq_update_depths(bfqd, &tags->bitmap_tags);
5320 sbitmap_queue_min_shallow_depth(&tags->bitmap_tags, min_shallow);
5323 static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index)
5325 bfq_depth_updated(hctx);
5329 static void bfq_exit_queue(struct elevator_queue *e)
5331 struct bfq_data *bfqd = e->elevator_data;
5332 struct bfq_queue *bfqq, *n;
5334 hrtimer_cancel(&bfqd->idle_slice_timer);
5336 spin_lock_irq(&bfqd->lock);
5337 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
5338 bfq_deactivate_bfqq(bfqd, bfqq, false, false);
5339 spin_unlock_irq(&bfqd->lock);
5341 hrtimer_cancel(&bfqd->idle_slice_timer);
5343 #ifdef CONFIG_BFQ_GROUP_IOSCHED
5344 /* release oom-queue reference to root group */
5345 bfqg_and_blkg_put(bfqd->root_group);
5347 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
5349 spin_lock_irq(&bfqd->lock);
5350 bfq_put_async_queues(bfqd, bfqd->root_group);
5351 kfree(bfqd->root_group);
5352 spin_unlock_irq(&bfqd->lock);
5358 static void bfq_init_root_group(struct bfq_group *root_group,
5359 struct bfq_data *bfqd)
5363 #ifdef CONFIG_BFQ_GROUP_IOSCHED
5364 root_group->entity.parent = NULL;
5365 root_group->my_entity = NULL;
5366 root_group->bfqd = bfqd;
5368 root_group->rq_pos_tree = RB_ROOT;
5369 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
5370 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
5371 root_group->sched_data.bfq_class_idle_last_service = jiffies;
5374 static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
5376 struct bfq_data *bfqd;
5377 struct elevator_queue *eq;
5379 eq = elevator_alloc(q, e);
5383 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
5385 kobject_put(&eq->kobj);
5388 eq->elevator_data = bfqd;
5390 spin_lock_irq(q->queue_lock);
5392 spin_unlock_irq(q->queue_lock);
5395 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
5396 * Grab a permanent reference to it, so that the normal code flow
5397 * will not attempt to free it.
5399 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
5400 bfqd->oom_bfqq.ref++;
5401 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
5402 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
5403 bfqd->oom_bfqq.entity.new_weight =
5404 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
5406 /* oom_bfqq does not participate to bursts */
5407 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
5410 * Trigger weight initialization, according to ioprio, at the
5411 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
5412 * class won't be changed any more.
5414 bfqd->oom_bfqq.entity.prio_changed = 1;
5418 INIT_LIST_HEAD(&bfqd->dispatch);
5420 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
5422 bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
5424 bfqd->queue_weights_tree = RB_ROOT;
5425 bfqd->group_weights_tree = RB_ROOT;
5427 INIT_LIST_HEAD(&bfqd->active_list);
5428 INIT_LIST_HEAD(&bfqd->idle_list);
5429 INIT_HLIST_HEAD(&bfqd->burst_list);
5433 bfqd->bfq_max_budget = bfq_default_max_budget;
5435 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
5436 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
5437 bfqd->bfq_back_max = bfq_back_max;
5438 bfqd->bfq_back_penalty = bfq_back_penalty;
5439 bfqd->bfq_slice_idle = bfq_slice_idle;
5440 bfqd->bfq_timeout = bfq_timeout;
5442 bfqd->bfq_requests_within_timer = 120;
5444 bfqd->bfq_large_burst_thresh = 8;
5445 bfqd->bfq_burst_interval = msecs_to_jiffies(180);
5447 bfqd->low_latency = true;
5450 * Trade-off between responsiveness and fairness.
5452 bfqd->bfq_wr_coeff = 30;
5453 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
5454 bfqd->bfq_wr_max_time = 0;
5455 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
5456 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
5457 bfqd->bfq_wr_max_softrt_rate = 7000; /*
5458 * Approximate rate required
5459 * to playback or record a
5460 * high-definition compressed
5463 bfqd->wr_busy_queues = 0;
5466 * Begin by assuming, optimistically, that the device peak
5467 * rate is equal to 2/3 of the highest reference rate.
5469 bfqd->rate_dur_prod = ref_rate[blk_queue_nonrot(bfqd->queue)] *
5470 ref_wr_duration[blk_queue_nonrot(bfqd->queue)];
5471 bfqd->peak_rate = ref_rate[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
5473 spin_lock_init(&bfqd->lock);
5476 * The invocation of the next bfq_create_group_hierarchy
5477 * function is the head of a chain of function calls
5478 * (bfq_create_group_hierarchy->blkcg_activate_policy->
5479 * blk_mq_freeze_queue) that may lead to the invocation of the
5480 * has_work hook function. For this reason,
5481 * bfq_create_group_hierarchy is invoked only after all
5482 * scheduler data has been initialized, apart from the fields
5483 * that can be initialized only after invoking
5484 * bfq_create_group_hierarchy. This, in particular, enables
5485 * has_work to correctly return false. Of course, to avoid
5486 * other inconsistencies, the blk-mq stack must then refrain
5487 * from invoking further scheduler hooks before this init
5488 * function is finished.
5490 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
5491 if (!bfqd->root_group)
5493 bfq_init_root_group(bfqd->root_group, bfqd);
5494 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
5496 wbt_disable_default(q);
5501 kobject_put(&eq->kobj);
5505 static void bfq_slab_kill(void)
5507 kmem_cache_destroy(bfq_pool);
5510 static int __init bfq_slab_setup(void)
5512 bfq_pool = KMEM_CACHE(bfq_queue, 0);
5518 static ssize_t bfq_var_show(unsigned int var, char *page)
5520 return sprintf(page, "%u\n", var);
5523 static int bfq_var_store(unsigned long *var, const char *page)
5525 unsigned long new_val;
5526 int ret = kstrtoul(page, 10, &new_val);
5534 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
5535 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5537 struct bfq_data *bfqd = e->elevator_data; \
5538 u64 __data = __VAR; \
5540 __data = jiffies_to_msecs(__data); \
5541 else if (__CONV == 2) \
5542 __data = div_u64(__data, NSEC_PER_MSEC); \
5543 return bfq_var_show(__data, (page)); \
5545 SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
5546 SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
5547 SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
5548 SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
5549 SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
5550 SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
5551 SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
5552 SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
5553 SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
5554 #undef SHOW_FUNCTION
5556 #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
5557 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
5559 struct bfq_data *bfqd = e->elevator_data; \
5560 u64 __data = __VAR; \
5561 __data = div_u64(__data, NSEC_PER_USEC); \
5562 return bfq_var_show(__data, (page)); \
5564 USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
5565 #undef USEC_SHOW_FUNCTION
5567 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
5569 __FUNC(struct elevator_queue *e, const char *page, size_t count) \
5571 struct bfq_data *bfqd = e->elevator_data; \
5572 unsigned long __data, __min = (MIN), __max = (MAX); \
5575 ret = bfq_var_store(&__data, (page)); \
5578 if (__data < __min) \
5580 else if (__data > __max) \
5583 *(__PTR) = msecs_to_jiffies(__data); \
5584 else if (__CONV == 2) \
5585 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
5587 *(__PTR) = __data; \
5590 STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
5592 STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
5594 STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
5595 STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
5597 STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
5598 #undef STORE_FUNCTION
5600 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
5601 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
5603 struct bfq_data *bfqd = e->elevator_data; \
5604 unsigned long __data, __min = (MIN), __max = (MAX); \
5607 ret = bfq_var_store(&__data, (page)); \
5610 if (__data < __min) \
5612 else if (__data > __max) \
5614 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
5617 USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
5619 #undef USEC_STORE_FUNCTION
5621 static ssize_t bfq_max_budget_store(struct elevator_queue *e,
5622 const char *page, size_t count)
5624 struct bfq_data *bfqd = e->elevator_data;
5625 unsigned long __data;
5628 ret = bfq_var_store(&__data, (page));
5633 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
5635 if (__data > INT_MAX)
5637 bfqd->bfq_max_budget = __data;
5640 bfqd->bfq_user_max_budget = __data;
5646 * Leaving this name to preserve name compatibility with cfq
5647 * parameters, but this timeout is used for both sync and async.
5649 static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
5650 const char *page, size_t count)
5652 struct bfq_data *bfqd = e->elevator_data;
5653 unsigned long __data;
5656 ret = bfq_var_store(&__data, (page));
5662 else if (__data > INT_MAX)
5665 bfqd->bfq_timeout = msecs_to_jiffies(__data);
5666 if (bfqd->bfq_user_max_budget == 0)
5667 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
5672 static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
5673 const char *page, size_t count)
5675 struct bfq_data *bfqd = e->elevator_data;
5676 unsigned long __data;
5679 ret = bfq_var_store(&__data, (page));
5685 if (!bfqd->strict_guarantees && __data == 1
5686 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
5687 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
5689 bfqd->strict_guarantees = __data;
5694 static ssize_t bfq_low_latency_store(struct elevator_queue *e,
5695 const char *page, size_t count)
5697 struct bfq_data *bfqd = e->elevator_data;
5698 unsigned long __data;
5701 ret = bfq_var_store(&__data, (page));
5707 if (__data == 0 && bfqd->low_latency != 0)
5709 bfqd->low_latency = __data;
5714 #define BFQ_ATTR(name) \
5715 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
5717 static struct elv_fs_entry bfq_attrs[] = {
5718 BFQ_ATTR(fifo_expire_sync),
5719 BFQ_ATTR(fifo_expire_async),
5720 BFQ_ATTR(back_seek_max),
5721 BFQ_ATTR(back_seek_penalty),
5722 BFQ_ATTR(slice_idle),
5723 BFQ_ATTR(slice_idle_us),
5724 BFQ_ATTR(max_budget),
5725 BFQ_ATTR(timeout_sync),
5726 BFQ_ATTR(strict_guarantees),
5727 BFQ_ATTR(low_latency),
5731 static struct elevator_type iosched_bfq_mq = {
5733 .limit_depth = bfq_limit_depth,
5734 .prepare_request = bfq_prepare_request,
5735 .requeue_request = bfq_finish_requeue_request,
5736 .finish_request = bfq_finish_requeue_request,
5737 .exit_icq = bfq_exit_icq,
5738 .insert_requests = bfq_insert_requests,
5739 .dispatch_request = bfq_dispatch_request,
5740 .next_request = elv_rb_latter_request,
5741 .former_request = elv_rb_former_request,
5742 .allow_merge = bfq_allow_bio_merge,
5743 .bio_merge = bfq_bio_merge,
5744 .request_merge = bfq_request_merge,
5745 .requests_merged = bfq_requests_merged,
5746 .request_merged = bfq_request_merged,
5747 .has_work = bfq_has_work,
5748 .depth_updated = bfq_depth_updated,
5749 .init_hctx = bfq_init_hctx,
5750 .init_sched = bfq_init_queue,
5751 .exit_sched = bfq_exit_queue,
5755 .icq_size = sizeof(struct bfq_io_cq),
5756 .icq_align = __alignof__(struct bfq_io_cq),
5757 .elevator_attrs = bfq_attrs,
5758 .elevator_name = "bfq",
5759 .elevator_owner = THIS_MODULE,
5761 MODULE_ALIAS("bfq-iosched");
5763 static int __init bfq_init(void)
5767 #ifdef CONFIG_BFQ_GROUP_IOSCHED
5768 ret = blkcg_policy_register(&blkcg_policy_bfq);
5774 if (bfq_slab_setup())
5778 * Times to load large popular applications for the typical
5779 * systems installed on the reference devices (see the
5780 * comments before the definition of the next
5781 * array). Actually, we use slightly lower values, as the
5782 * estimated peak rate tends to be smaller than the actual
5783 * peak rate. The reason for this last fact is that estimates
5784 * are computed over much shorter time intervals than the long
5785 * intervals typically used for benchmarking. Why? First, to
5786 * adapt more quickly to variations. Second, because an I/O
5787 * scheduler cannot rely on a peak-rate-evaluation workload to
5788 * be run for a long time.
5790 ref_wr_duration[0] = msecs_to_jiffies(7000); /* actually 8 sec */
5791 ref_wr_duration[1] = msecs_to_jiffies(2500); /* actually 3 sec */
5793 ret = elv_register(&iosched_bfq_mq);
5802 #ifdef CONFIG_BFQ_GROUP_IOSCHED
5803 blkcg_policy_unregister(&blkcg_policy_bfq);
5808 static void __exit bfq_exit(void)
5810 elv_unregister(&iosched_bfq_mq);
5811 #ifdef CONFIG_BFQ_GROUP_IOSCHED
5812 blkcg_policy_unregister(&blkcg_policy_bfq);
5817 module_init(bfq_init);
5818 module_exit(bfq_exit);
5820 MODULE_AUTHOR("Paolo Valente");
5821 MODULE_LICENSE("GPL");
5822 MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");