blob: 05041f84b8daf588211655579f464aeef5378a52 [file] [log] [blame]
Christoph Hellwiga497ee32019-04-30 14:42:40 -04001// SPDX-License-Identifier: GPL-2.0-or-later
Paolo Valenteaee69d72017-04-19 08:29:02 -06002/*
3 * Budget Fair Queueing (BFQ) I/O scheduler.
4 *
5 * Based on ideas and code from CFQ:
6 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
7 *
8 * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
9 * Paolo Valente <paolo.valente@unimore.it>
10 *
11 * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it>
12 * Arianna Avanzini <avanzini@google.com>
13 *
14 * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org>
15 *
Paolo Valenteaee69d72017-04-19 08:29:02 -060016 * BFQ is a proportional-share I/O scheduler, with some extra
17 * low-latency capabilities. BFQ also supports full hierarchical
18 * scheduling through cgroups. Next paragraphs provide an introduction
19 * on BFQ inner workings. Details on BFQ benefits, usage and
20 * limitations can be found in Documentation/block/bfq-iosched.txt.
21 *
22 * BFQ is a proportional-share storage-I/O scheduling algorithm based
23 * on the slice-by-slice service scheme of CFQ. But BFQ assigns
24 * budgets, measured in number of sectors, to processes instead of
25 * time slices. The device is not granted to the in-service process
26 * for a given time slice, but until it has exhausted its assigned
27 * budget. This change from the time to the service domain enables BFQ
28 * to distribute the device throughput among processes as desired,
29 * without any distortion due to throughput fluctuations, or to device
30 * internal queueing. BFQ uses an ad hoc internal scheduler, called
31 * B-WF2Q+, to schedule processes according to their budgets. More
32 * precisely, BFQ schedules queues associated with processes. Each
33 * process/queue is assigned a user-configurable weight, and B-WF2Q+
34 * guarantees that each queue receives a fraction of the throughput
35 * proportional to its weight. Thanks to the accurate policy of
36 * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound
37 * processes issuing sequential requests (to boost the throughput),
38 * and yet guarantee a low latency to interactive and soft real-time
39 * applications.
40 *
41 * In particular, to provide these low-latency guarantees, BFQ
42 * explicitly privileges the I/O of two classes of time-sensitive
Paolo Valente4029eef2018-05-31 16:45:05 +020043 * applications: interactive and soft real-time. In more detail, BFQ
44 * behaves this way if the low_latency parameter is set (default
45 * configuration). This feature enables BFQ to provide applications in
46 * these classes with a very low latency.
47 *
48 * To implement this feature, BFQ constantly tries to detect whether
49 * the I/O requests in a bfq_queue come from an interactive or a soft
50 * real-time application. For brevity, in these cases, the queue is
51 * said to be interactive or soft real-time. In both cases, BFQ
52 * privileges the service of the queue, over that of non-interactive
53 * and non-soft-real-time queues. This privileging is performed,
54 * mainly, by raising the weight of the queue. So, for brevity, we
55 * call just weight-raising periods the time periods during which a
56 * queue is privileged, because deemed interactive or soft real-time.
57 *
58 * The detection of soft real-time queues/applications is described in
59 * detail in the comments on the function
60 * bfq_bfqq_softrt_next_start. On the other hand, the detection of an
61 * interactive queue works as follows: a queue is deemed interactive
62 * if it is constantly non empty only for a limited time interval,
63 * after which it does become empty. The queue may be deemed
64 * interactive again (for a limited time), if it restarts being
65 * constantly non empty, provided that this happens only after the
66 * queue has remained empty for a given minimum idle time.
67 *
68 * By default, BFQ computes automatically the above maximum time
69 * interval, i.e., the time interval after which a constantly
70 * non-empty queue stops being deemed interactive. Since a queue is
71 * weight-raised while it is deemed interactive, this maximum time
72 * interval happens to coincide with the (maximum) duration of the
73 * weight-raising for interactive queues.
74 *
75 * Finally, BFQ also features additional heuristics for
Paolo Valenteaee69d72017-04-19 08:29:02 -060076 * preserving both a low latency and a high throughput on NCQ-capable,
77 * rotational or flash-based devices, and to get the job done quickly
78 * for applications consisting in many I/O-bound processes.
79 *
Paolo Valente43c1b3d2017-05-09 12:54:23 +020080 * NOTE: if the main or only goal, with a given device, is to achieve
81 * the maximum-possible throughput at all times, then do switch off
82 * all low-latency heuristics for that device, by setting low_latency
83 * to 0.
84 *
Paolo Valente4029eef2018-05-31 16:45:05 +020085 * BFQ is described in [1], where also a reference to the initial,
86 * more theoretical paper on BFQ can be found. The interested reader
87 * can find in the latter paper full details on the main algorithm, as
88 * well as formulas of the guarantees and formal proofs of all the
89 * properties. With respect to the version of BFQ presented in these
90 * papers, this implementation adds a few more heuristics, such as the
91 * ones that guarantee a low latency to interactive and soft real-time
92 * applications, and a hierarchical extension based on H-WF2Q+.
Paolo Valenteaee69d72017-04-19 08:29:02 -060093 *
94 * B-WF2Q+ is based on WF2Q+, which is described in [2], together with
95 * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+
96 * with O(log N) complexity derives from the one introduced with EEVDF
97 * in [3].
98 *
99 * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O
100 * Scheduler", Proceedings of the First Workshop on Mobile System
101 * Technologies (MST-2015), May 2015.
102 * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf
103 *
104 * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing
105 * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689,
106 * Oct 1997.
107 *
108 * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz
109 *
110 * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline
111 * First: A Flexible and Accurate Mechanism for Proportional Share
112 * Resource Allocation", technical report.
113 *
114 * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf
115 */
116#include <linux/module.h>
117#include <linux/slab.h>
118#include <linux/blkdev.h>
Arianna Avanzinie21b7a02017-04-12 18:23:08 +0200119#include <linux/cgroup.h>
Paolo Valenteaee69d72017-04-19 08:29:02 -0600120#include <linux/elevator.h>
121#include <linux/ktime.h>
122#include <linux/rbtree.h>
123#include <linux/ioprio.h>
124#include <linux/sbitmap.h>
125#include <linux/delay.h>
126
127#include "blk.h"
128#include "blk-mq.h"
129#include "blk-mq-tag.h"
130#include "blk-mq-sched.h"
Paolo Valenteea25da42017-04-19 08:48:24 -0600131#include "bfq-iosched.h"
Luca Micciob5dc5d42017-10-09 16:27:21 +0200132#include "blk-wbt.h"
Paolo Valenteaee69d72017-04-19 08:29:02 -0600133
134#define BFQ_BFQQ_FNS(name) \
Paolo Valenteea25da42017-04-19 08:48:24 -0600135void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600136{ \
137 __set_bit(BFQQF_##name, &(bfqq)->flags); \
138} \
Paolo Valenteea25da42017-04-19 08:48:24 -0600139void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600140{ \
141 __clear_bit(BFQQF_##name, &(bfqq)->flags); \
142} \
Paolo Valenteea25da42017-04-19 08:48:24 -0600143int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600144{ \
145 return test_bit(BFQQF_##name, &(bfqq)->flags); \
146}
147
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200148BFQ_BFQQ_FNS(just_created);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600149BFQ_BFQQ_FNS(busy);
150BFQ_BFQQ_FNS(wait_request);
151BFQ_BFQQ_FNS(non_blocking_wait_rq);
152BFQ_BFQQ_FNS(fifo_expire);
Paolo Valented5be3fe2017-08-04 07:35:10 +0200153BFQ_BFQQ_FNS(has_short_ttime);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600154BFQ_BFQQ_FNS(sync);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600155BFQ_BFQQ_FNS(IO_bound);
Arianna Avanzinie1b23242017-04-12 18:23:20 +0200156BFQ_BFQQ_FNS(in_large_burst);
Arianna Avanzini36eca892017-04-12 18:23:16 +0200157BFQ_BFQQ_FNS(coop);
158BFQ_BFQQ_FNS(split_coop);
Paolo Valente77b7dce2017-04-12 18:23:13 +0200159BFQ_BFQQ_FNS(softrt_update);
Paolo Valenteea25da42017-04-19 08:48:24 -0600160#undef BFQ_BFQQ_FNS \
Paolo Valenteaee69d72017-04-19 08:29:02 -0600161
Paolo Valenteaee69d72017-04-19 08:29:02 -0600162/* Expiration time of sync (0) and async (1) requests, in ns. */
163static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
164
165/* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
166static const int bfq_back_max = 16 * 1024;
167
168/* Penalty of a backwards seek, in number of sectors. */
169static const int bfq_back_penalty = 2;
170
171/* Idling period duration, in ns. */
172static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
173
174/* Minimum number of assigned budgets for which stats are safe to compute. */
175static const int bfq_stats_min_budgets = 194;
176
177/* Default maximum budget values, in sectors and number of requests. */
178static const int bfq_default_max_budget = 16 * 1024;
179
Paolo Valentec074170e2017-04-12 18:23:11 +0200180/*
Paolo Valented5801082018-08-16 18:51:17 +0200181 * When a sync request is dispatched, the queue that contains that
182 * request, and all the ancestor entities of that queue, are charged
Angelo Ruocco636b8fe2019-04-08 17:35:34 +0200183 * with the number of sectors of the request. In contrast, if the
Paolo Valented5801082018-08-16 18:51:17 +0200184 * request is async, then the queue and its ancestor entities are
185 * charged with the number of sectors of the request, multiplied by
186 * the factor below. This throttles the bandwidth for async I/O,
187 * w.r.t. to sync I/O, and it is done to counter the tendency of async
188 * writes to steal I/O throughput to reads.
189 *
190 * The current value of this parameter is the result of a tuning with
191 * several hardware and software configurations. We tried to find the
192 * lowest value for which writes do not cause noticeable problems to
193 * reads. In fact, the lower this parameter, the stabler I/O control,
194 * in the following respect. The lower this parameter is, the less
195 * the bandwidth enjoyed by a group decreases
196 * - when the group does writes, w.r.t. to when it does reads;
197 * - when other groups do reads, w.r.t. to when they do writes.
Paolo Valentec074170e2017-04-12 18:23:11 +0200198 */
Paolo Valented5801082018-08-16 18:51:17 +0200199static const int bfq_async_charge_factor = 3;
Paolo Valentec074170e2017-04-12 18:23:11 +0200200
Paolo Valenteaee69d72017-04-19 08:29:02 -0600201/* Default timeout values, in jiffies, approximating CFQ defaults. */
Paolo Valenteea25da42017-04-19 08:48:24 -0600202const int bfq_timeout = HZ / 8;
Paolo Valenteaee69d72017-04-19 08:29:02 -0600203
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100204/*
205 * Time limit for merging (see comments in bfq_setup_cooperator). Set
206 * to the slowest value that, in our tests, proved to be effective in
207 * removing false positives, while not causing true positives to miss
208 * queue merging.
209 *
210 * As can be deduced from the low time limit below, queue merging, if
Angelo Ruocco636b8fe2019-04-08 17:35:34 +0200211 * successful, happens at the very beginning of the I/O of the involved
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100212 * cooperating processes, as a consequence of the arrival of the very
213 * first requests from each cooperator. After that, there is very
214 * little chance to find cooperators.
215 */
216static const unsigned long bfq_merge_time_limit = HZ/10;
217
Paolo Valenteaee69d72017-04-19 08:29:02 -0600218static struct kmem_cache *bfq_pool;
219
Paolo Valenteab0e43e2017-04-12 18:23:10 +0200220/* Below this threshold (in ns), we consider thinktime immediate. */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600221#define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
222
223/* hw_tag detection: parallel requests threshold and min samples needed. */
Paolo Valentea3c92562019-01-29 12:06:35 +0100224#define BFQ_HW_QUEUE_THRESHOLD 3
Paolo Valenteaee69d72017-04-19 08:29:02 -0600225#define BFQ_HW_QUEUE_SAMPLES 32
226
227#define BFQQ_SEEK_THR (sector_t)(8 * 100)
228#define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
Paolo Valented87447d2019-01-29 12:06:33 +0100229#define BFQ_RQ_SEEKY(bfqd, last_pos, rq) \
230 (get_sdist(last_pos, rq) > \
231 BFQQ_SEEK_THR && \
232 (!blk_queue_nonrot(bfqd->queue) || \
233 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT))
Paolo Valenteaee69d72017-04-19 08:29:02 -0600234#define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
Paolo Valentef0ba5ea2017-12-20 17:27:36 +0100235#define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19)
Paolo Valente7074f072019-03-12 09:59:31 +0100236/*
237 * Sync random I/O is likely to be confused with soft real-time I/O,
238 * because it is characterized by limited throughput and apparently
239 * isochronous arrival pattern. To avoid false positives, queues
240 * containing only random (seeky) I/O are prevented from being tagged
241 * as soft real-time.
242 */
243#define BFQQ_TOTALLY_SEEKY(bfqq) (bfqq->seek_history & -1)
Paolo Valenteaee69d72017-04-19 08:29:02 -0600244
Paolo Valenteab0e43e2017-04-12 18:23:10 +0200245/* Min number of samples required to perform peak-rate update */
246#define BFQ_RATE_MIN_SAMPLES 32
247/* Min observation time interval required to perform a peak-rate update (ns) */
248#define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
249/* Target observation time interval for a peak-rate update (ns) */
250#define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
Paolo Valenteaee69d72017-04-19 08:29:02 -0600251
Paolo Valentebc56e2c2018-03-26 16:06:24 +0200252/*
253 * Shift used for peak-rate fixed precision calculations.
254 * With
255 * - the current shift: 16 positions
256 * - the current type used to store rate: u32
257 * - the current unit of measure for rate: [sectors/usec], or, more precisely,
258 * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift,
259 * the range of rates that can be stored is
260 * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec =
261 * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec =
262 * [15, 65G] sectors/sec
263 * Which, assuming a sector size of 512B, corresponds to a range of
264 * [7.5K, 33T] B/sec
265 */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600266#define BFQ_RATE_SHIFT 16
267
Paolo Valente44e44a12017-04-12 18:23:12 +0200268/*
Paolo Valente4029eef2018-05-31 16:45:05 +0200269 * When configured for computing the duration of the weight-raising
270 * for interactive queues automatically (see the comments at the
271 * beginning of this file), BFQ does it using the following formula:
Paolo Valentee24f1c22018-05-31 16:45:06 +0200272 * duration = (ref_rate / r) * ref_wr_duration,
273 * where r is the peak rate of the device, and ref_rate and
274 * ref_wr_duration are two reference parameters. In particular,
275 * ref_rate is the peak rate of the reference storage device (see
276 * below), and ref_wr_duration is about the maximum time needed, with
277 * BFQ and while reading two files in parallel, to load typical large
278 * applications on the reference device (see the comments on
279 * max_service_from_wr below, for more details on how ref_wr_duration
280 * is obtained). In practice, the slower/faster the device at hand
281 * is, the more/less it takes to load applications with respect to the
Paolo Valente4029eef2018-05-31 16:45:05 +0200282 * reference device. Accordingly, the longer/shorter BFQ grants
283 * weight raising to interactive applications.
Paolo Valente44e44a12017-04-12 18:23:12 +0200284 *
Paolo Valentee24f1c22018-05-31 16:45:06 +0200285 * BFQ uses two different reference pairs (ref_rate, ref_wr_duration),
286 * depending on whether the device is rotational or non-rotational.
Paolo Valente44e44a12017-04-12 18:23:12 +0200287 *
Paolo Valentee24f1c22018-05-31 16:45:06 +0200288 * In the following definitions, ref_rate[0] and ref_wr_duration[0]
289 * are the reference values for a rotational device, whereas
290 * ref_rate[1] and ref_wr_duration[1] are the reference values for a
291 * non-rotational device. The reference rates are not the actual peak
292 * rates of the devices used as a reference, but slightly lower
293 * values. The reason for using slightly lower values is that the
294 * peak-rate estimator tends to yield slightly lower values than the
295 * actual peak rate (it can yield the actual peak rate only if there
296 * is only one process doing I/O, and the process does sequential
297 * I/O).
Paolo Valente44e44a12017-04-12 18:23:12 +0200298 *
Paolo Valentee24f1c22018-05-31 16:45:06 +0200299 * The reference peak rates are measured in sectors/usec, left-shifted
300 * by BFQ_RATE_SHIFT.
Paolo Valente44e44a12017-04-12 18:23:12 +0200301 */
Paolo Valentee24f1c22018-05-31 16:45:06 +0200302static int ref_rate[2] = {14000, 33000};
Paolo Valente44e44a12017-04-12 18:23:12 +0200303/*
Paolo Valentee24f1c22018-05-31 16:45:06 +0200304 * To improve readability, a conversion function is used to initialize
305 * the following array, which entails that the array can be
306 * initialized only in a function.
Paolo Valente44e44a12017-04-12 18:23:12 +0200307 */
Paolo Valentee24f1c22018-05-31 16:45:06 +0200308static int ref_wr_duration[2];
Paolo Valente44e44a12017-04-12 18:23:12 +0200309
Paolo Valente8a8747d2018-01-13 12:05:18 +0100310/*
311 * BFQ uses the above-detailed, time-based weight-raising mechanism to
312 * privilege interactive tasks. This mechanism is vulnerable to the
313 * following false positives: I/O-bound applications that will go on
314 * doing I/O for much longer than the duration of weight
315 * raising. These applications have basically no benefit from being
316 * weight-raised at the beginning of their I/O. On the opposite end,
317 * while being weight-raised, these applications
318 * a) unjustly steal throughput to applications that may actually need
319 * low latency;
320 * b) make BFQ uselessly perform device idling; device idling results
321 * in loss of device throughput with most flash-based storage, and may
322 * increase latencies when used purposelessly.
323 *
324 * BFQ tries to reduce these problems, by adopting the following
325 * countermeasure. To introduce this countermeasure, we need first to
326 * finish explaining how the duration of weight-raising for
327 * interactive tasks is computed.
328 *
329 * For a bfq_queue deemed as interactive, the duration of weight
330 * raising is dynamically adjusted, as a function of the estimated
331 * peak rate of the device, so as to be equal to the time needed to
332 * execute the 'largest' interactive task we benchmarked so far. By
333 * largest task, we mean the task for which each involved process has
334 * to do more I/O than for any of the other tasks we benchmarked. This
335 * reference interactive task is the start-up of LibreOffice Writer,
336 * and in this task each process/bfq_queue needs to have at most ~110K
337 * sectors transferred.
338 *
339 * This last piece of information enables BFQ to reduce the actual
340 * duration of weight-raising for at least one class of I/O-bound
341 * applications: those doing sequential or quasi-sequential I/O. An
342 * example is file copy. In fact, once started, the main I/O-bound
343 * processes of these applications usually consume the above 110K
344 * sectors in much less time than the processes of an application that
345 * is starting, because these I/O-bound processes will greedily devote
346 * almost all their CPU cycles only to their target,
347 * throughput-friendly I/O operations. This is even more true if BFQ
348 * happens to be underestimating the device peak rate, and thus
349 * overestimating the duration of weight raising. But, according to
350 * our measurements, once transferred 110K sectors, these processes
351 * have no right to be weight-raised any longer.
352 *
353 * Basing on the last consideration, BFQ ends weight-raising for a
354 * bfq_queue if the latter happens to have received an amount of
355 * service at least equal to the following constant. The constant is
356 * set to slightly more than 110K, to have a minimum safety margin.
357 *
358 * This early ending of weight-raising reduces the amount of time
359 * during which interactive false positives cause the two problems
360 * described at the beginning of these comments.
361 */
362static const unsigned long max_service_from_wr = 120000;
363
Bart Van Assche12cd3a22017-08-30 11:42:11 -0700364#define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0])
Paolo Valenteaee69d72017-04-19 08:29:02 -0600365#define RQ_BFQQ(rq) ((rq)->elv.priv[1])
366
Paolo Valenteea25da42017-04-19 08:48:24 -0600367struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync)
368{
369 return bic->bfqq[is_sync];
370}
371
372void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync)
373{
374 bic->bfqq[is_sync] = bfqq;
375}
376
377struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
378{
379 return bic->icq.q->elevator->elevator_data;
380}
381
Paolo Valenteaee69d72017-04-19 08:29:02 -0600382/**
383 * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
384 * @icq: the iocontext queue.
385 */
386static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
387{
388 /* bic->icq is the first member, %NULL will convert to %NULL */
389 return container_of(icq, struct bfq_io_cq, icq);
390}
391
392/**
393 * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
394 * @bfqd: the lookup key.
395 * @ioc: the io_context of the process doing I/O.
396 * @q: the request queue.
397 */
398static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
399 struct io_context *ioc,
400 struct request_queue *q)
401{
402 if (ioc) {
403 unsigned long flags;
404 struct bfq_io_cq *icq;
405
Christoph Hellwig0d945c12018-11-15 12:17:28 -0700406 spin_lock_irqsave(&q->queue_lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600407 icq = icq_to_bic(ioc_lookup_icq(ioc, q));
Christoph Hellwig0d945c12018-11-15 12:17:28 -0700408 spin_unlock_irqrestore(&q->queue_lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600409
410 return icq;
411 }
412
413 return NULL;
414}
415
416/*
Arianna Avanzinie21b7a02017-04-12 18:23:08 +0200417 * Scheduler run of queue, if there are requests pending and no one in the
418 * driver that will restart queueing.
Paolo Valenteaee69d72017-04-19 08:29:02 -0600419 */
Paolo Valenteea25da42017-04-19 08:48:24 -0600420void bfq_schedule_dispatch(struct bfq_data *bfqd)
Paolo Valenteaee69d72017-04-19 08:29:02 -0600421{
Arianna Avanzinie21b7a02017-04-12 18:23:08 +0200422 if (bfqd->queued != 0) {
423 bfq_log(bfqd, "schedule dispatch");
424 blk_mq_run_hw_queues(bfqd->queue, true);
425 }
Paolo Valenteaee69d72017-04-19 08:29:02 -0600426}
427
Paolo Valenteaee69d72017-04-19 08:29:02 -0600428#define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
429#define bfq_class_rt(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_RT)
430
431#define bfq_sample_valid(samples) ((samples) > 80)
432
433/*
Paolo Valenteaee69d72017-04-19 08:29:02 -0600434 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
Angelo Ruocco636b8fe2019-04-08 17:35:34 +0200435 * We choose the request that is closer to the head right now. Distance
Paolo Valenteaee69d72017-04-19 08:29:02 -0600436 * behind the head is penalized and only allowed to a certain extent.
437 */
438static struct request *bfq_choose_req(struct bfq_data *bfqd,
439 struct request *rq1,
440 struct request *rq2,
441 sector_t last)
442{
443 sector_t s1, s2, d1 = 0, d2 = 0;
444 unsigned long back_max;
445#define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */
446#define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */
447 unsigned int wrap = 0; /* bit mask: requests behind the disk head? */
448
449 if (!rq1 || rq1 == rq2)
450 return rq2;
451 if (!rq2)
452 return rq1;
453
454 if (rq_is_sync(rq1) && !rq_is_sync(rq2))
455 return rq1;
456 else if (rq_is_sync(rq2) && !rq_is_sync(rq1))
457 return rq2;
458 if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META))
459 return rq1;
460 else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META))
461 return rq2;
462
463 s1 = blk_rq_pos(rq1);
464 s2 = blk_rq_pos(rq2);
465
466 /*
467 * By definition, 1KiB is 2 sectors.
468 */
469 back_max = bfqd->bfq_back_max * 2;
470
471 /*
472 * Strict one way elevator _except_ in the case where we allow
473 * short backward seeks which are biased as twice the cost of a
474 * similar forward seek.
475 */
476 if (s1 >= last)
477 d1 = s1 - last;
478 else if (s1 + back_max >= last)
479 d1 = (last - s1) * bfqd->bfq_back_penalty;
480 else
481 wrap |= BFQ_RQ1_WRAP;
482
483 if (s2 >= last)
484 d2 = s2 - last;
485 else if (s2 + back_max >= last)
486 d2 = (last - s2) * bfqd->bfq_back_penalty;
487 else
488 wrap |= BFQ_RQ2_WRAP;
489
490 /* Found required data */
491
492 /*
493 * By doing switch() on the bit mask "wrap" we avoid having to
494 * check two variables for all permutations: --> faster!
495 */
496 switch (wrap) {
497 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
498 if (d1 < d2)
499 return rq1;
500 else if (d2 < d1)
501 return rq2;
502
503 if (s1 >= s2)
504 return rq1;
505 else
506 return rq2;
507
508 case BFQ_RQ2_WRAP:
509 return rq1;
510 case BFQ_RQ1_WRAP:
511 return rq2;
512 case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */
513 default:
514 /*
515 * Since both rqs are wrapped,
516 * start with the one that's further behind head
517 * (--> only *one* back seek required),
518 * since back seek takes more time than forward.
519 */
520 if (s1 <= s2)
521 return rq1;
522 else
523 return rq2;
524 }
525}
526
Paolo Valentea52a69e2018-01-13 12:05:17 +0100527/*
Paolo Valentea52a69e2018-01-13 12:05:17 +0100528 * Async I/O can easily starve sync I/O (both sync reads and sync
529 * writes), by consuming all tags. Similarly, storms of sync writes,
530 * such as those that sync(2) may trigger, can starve sync reads.
531 * Limit depths of async I/O and sync writes so as to counter both
532 * problems.
533 */
534static void bfq_limit_depth(unsigned int op, struct blk_mq_alloc_data *data)
535{
Paolo Valentea52a69e2018-01-13 12:05:17 +0100536 struct bfq_data *bfqd = data->q->elevator->elevator_data;
Paolo Valentea52a69e2018-01-13 12:05:17 +0100537
538 if (op_is_sync(op) && !op_is_write(op))
539 return;
540
Paolo Valentea52a69e2018-01-13 12:05:17 +0100541 data->shallow_depth =
542 bfqd->word_depths[!!bfqd->wr_busy_queues][op_is_sync(op)];
543
544 bfq_log(bfqd, "[%s] wr_busy %d sync %d depth %u",
545 __func__, bfqd->wr_busy_queues, op_is_sync(op),
546 data->shallow_depth);
547}
548
Arianna Avanzini36eca892017-04-12 18:23:16 +0200549static struct bfq_queue *
550bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
551 sector_t sector, struct rb_node **ret_parent,
552 struct rb_node ***rb_link)
553{
554 struct rb_node **p, *parent;
555 struct bfq_queue *bfqq = NULL;
556
557 parent = NULL;
558 p = &root->rb_node;
559 while (*p) {
560 struct rb_node **n;
561
562 parent = *p;
563 bfqq = rb_entry(parent, struct bfq_queue, pos_node);
564
565 /*
566 * Sort strictly based on sector. Smallest to the left,
567 * largest to the right.
568 */
569 if (sector > blk_rq_pos(bfqq->next_rq))
570 n = &(*p)->rb_right;
571 else if (sector < blk_rq_pos(bfqq->next_rq))
572 n = &(*p)->rb_left;
573 else
574 break;
575 p = n;
576 bfqq = NULL;
577 }
578
579 *ret_parent = parent;
580 if (rb_link)
581 *rb_link = p;
582
583 bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
584 (unsigned long long)sector,
585 bfqq ? bfqq->pid : 0);
586
587 return bfqq;
588}
589
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100590static bool bfq_too_late_for_merging(struct bfq_queue *bfqq)
591{
592 return bfqq->service_from_backlogged > 0 &&
593 time_is_before_jiffies(bfqq->first_IO_time +
594 bfq_merge_time_limit);
595}
596
Paolo Valente8cacc5a2019-03-12 09:59:30 +0100597/*
598 * The following function is not marked as __cold because it is
599 * actually cold, but for the same performance goal described in the
600 * comments on the likely() at the beginning of
601 * bfq_setup_cooperator(). Unexpectedly, to reach an even lower
602 * execution time for the case where this function is not invoked, we
603 * had to add an unlikely() in each involved if().
604 */
605void __cold
606bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq)
Arianna Avanzini36eca892017-04-12 18:23:16 +0200607{
608 struct rb_node **p, *parent;
609 struct bfq_queue *__bfqq;
610
611 if (bfqq->pos_root) {
612 rb_erase(&bfqq->pos_node, bfqq->pos_root);
613 bfqq->pos_root = NULL;
614 }
615
Paolo Valente7b8fa3b2017-12-20 12:38:33 +0100616 /*
617 * bfqq cannot be merged any longer (see comments in
618 * bfq_setup_cooperator): no point in adding bfqq into the
619 * position tree.
620 */
621 if (bfq_too_late_for_merging(bfqq))
622 return;
623
Arianna Avanzini36eca892017-04-12 18:23:16 +0200624 if (bfq_class_idle(bfqq))
625 return;
626 if (!bfqq->next_rq)
627 return;
628
629 bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
630 __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
631 blk_rq_pos(bfqq->next_rq), &parent, &p);
632 if (!__bfqq) {
633 rb_link_node(&bfqq->pos_node, parent, p);
634 rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
635 } else
636 bfqq->pos_root = NULL;
637}
638
Paolo Valenteaee69d72017-04-19 08:29:02 -0600639/*
Paolo Valentefb53ac62019-03-12 09:59:28 +0100640 * The following function returns false either if every active queue
641 * must receive the same share of the throughput (symmetric scenario),
642 * or, as a special case, if bfqq must receive a share of the
643 * throughput lower than or equal to the share that every other active
644 * queue must receive. If bfqq does sync I/O, then these are the only
645 * two cases where bfqq happens to be guaranteed its share of the
646 * throughput even if I/O dispatching is not plugged when bfqq remains
647 * temporarily empty (for more details, see the comments in the
648 * function bfq_better_to_idle()). For this reason, the return value
649 * of this function is used to check whether I/O-dispatch plugging can
650 * be avoided.
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200651 *
Paolo Valentefb53ac62019-03-12 09:59:28 +0100652 * The above first case (symmetric scenario) occurs when:
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200653 * 1) all active queues have the same weight,
Paolo Valente73d58112019-01-29 12:06:29 +0100654 * 2) all active queues belong to the same I/O-priority class,
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200655 * 3) all active groups at the same level in the groups tree have the same
Paolo Valente73d58112019-01-29 12:06:29 +0100656 * weight,
657 * 4) all active groups at the same level in the groups tree have the same
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200658 * number of children.
659 *
Federico Motta2d29c9f2018-10-12 11:55:57 +0200660 * Unfortunately, keeping the necessary state for evaluating exactly
661 * the last two symmetry sub-conditions above would be quite complex
Paolo Valente73d58112019-01-29 12:06:29 +0100662 * and time consuming. Therefore this function evaluates, instead,
663 * only the following stronger three sub-conditions, for which it is
Federico Motta2d29c9f2018-10-12 11:55:57 +0200664 * much easier to maintain the needed state:
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200665 * 1) all active queues have the same weight,
Paolo Valente73d58112019-01-29 12:06:29 +0100666 * 2) all active queues belong to the same I/O-priority class,
667 * 3) there are no active groups.
Federico Motta2d29c9f2018-10-12 11:55:57 +0200668 * In particular, the last condition is always true if hierarchical
669 * support or the cgroups interface are not enabled, thus no state
670 * needs to be maintained in this case.
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200671 */
Paolo Valentefb53ac62019-03-12 09:59:28 +0100672static bool bfq_asymmetric_scenario(struct bfq_data *bfqd,
673 struct bfq_queue *bfqq)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200674{
Paolo Valentefb53ac62019-03-12 09:59:28 +0100675 bool smallest_weight = bfqq &&
676 bfqq->weight_counter &&
677 bfqq->weight_counter ==
678 container_of(
679 rb_first_cached(&bfqd->queue_weights_tree),
680 struct bfq_weight_counter,
681 weights_node);
682
Paolo Valente73d58112019-01-29 12:06:29 +0100683 /*
684 * For queue weights to differ, queue_weights_tree must contain
685 * at least two nodes.
686 */
Paolo Valentefb53ac62019-03-12 09:59:28 +0100687 bool varied_queue_weights = !smallest_weight &&
688 !RB_EMPTY_ROOT(&bfqd->queue_weights_tree.rb_root) &&
689 (bfqd->queue_weights_tree.rb_root.rb_node->rb_left ||
690 bfqd->queue_weights_tree.rb_root.rb_node->rb_right);
Paolo Valente73d58112019-01-29 12:06:29 +0100691
692 bool multiple_classes_busy =
693 (bfqd->busy_queues[0] && bfqd->busy_queues[1]) ||
694 (bfqd->busy_queues[0] && bfqd->busy_queues[2]) ||
695 (bfqd->busy_queues[1] && bfqd->busy_queues[2]);
696
Paolo Valentefb53ac62019-03-12 09:59:28 +0100697 return varied_queue_weights || multiple_classes_busy
Konstantin Khlebnikov42b1bd32019-03-29 17:01:18 +0300698#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente73d58112019-01-29 12:06:29 +0100699 || bfqd->num_groups_with_pending_reqs > 0
700#endif
Paolo Valentefb53ac62019-03-12 09:59:28 +0100701 ;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200702}
703
704/*
705 * If the weight-counter tree passed as input contains no counter for
Federico Motta2d29c9f2018-10-12 11:55:57 +0200706 * the weight of the input queue, then add that counter; otherwise just
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200707 * increment the existing counter.
708 *
709 * Note that weight-counter trees contain few nodes in mostly symmetric
710 * scenarios. For example, if all queues have the same weight, then the
711 * weight-counter tree for the queues may contain at most one node.
712 * This holds even if low_latency is on, because weight-raised queues
713 * are not inserted in the tree.
714 * In most scenarios, the rate at which nodes are created/destroyed
715 * should be low too.
716 */
Federico Motta2d29c9f2018-10-12 11:55:57 +0200717void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_queue *bfqq,
Paolo Valentefb53ac62019-03-12 09:59:28 +0100718 struct rb_root_cached *root)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200719{
Federico Motta2d29c9f2018-10-12 11:55:57 +0200720 struct bfq_entity *entity = &bfqq->entity;
Paolo Valentefb53ac62019-03-12 09:59:28 +0100721 struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
722 bool leftmost = true;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200723
724 /*
Federico Motta2d29c9f2018-10-12 11:55:57 +0200725 * Do not insert if the queue is already associated with a
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200726 * counter, which happens if:
Federico Motta2d29c9f2018-10-12 11:55:57 +0200727 * 1) a request arrival has caused the queue to become both
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200728 * non-weight-raised, and hence change its weight, and
729 * backlogged; in this respect, each of the two events
730 * causes an invocation of this function,
Federico Motta2d29c9f2018-10-12 11:55:57 +0200731 * 2) this is the invocation of this function caused by the
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200732 * second event. This second invocation is actually useless,
733 * and we handle this fact by exiting immediately. More
734 * efficient or clearer solutions might possibly be adopted.
735 */
Federico Motta2d29c9f2018-10-12 11:55:57 +0200736 if (bfqq->weight_counter)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200737 return;
738
739 while (*new) {
740 struct bfq_weight_counter *__counter = container_of(*new,
741 struct bfq_weight_counter,
742 weights_node);
743 parent = *new;
744
745 if (entity->weight == __counter->weight) {
Federico Motta2d29c9f2018-10-12 11:55:57 +0200746 bfqq->weight_counter = __counter;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200747 goto inc_counter;
748 }
749 if (entity->weight < __counter->weight)
750 new = &((*new)->rb_left);
Paolo Valentefb53ac62019-03-12 09:59:28 +0100751 else {
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200752 new = &((*new)->rb_right);
Paolo Valentefb53ac62019-03-12 09:59:28 +0100753 leftmost = false;
754 }
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200755 }
756
Federico Motta2d29c9f2018-10-12 11:55:57 +0200757 bfqq->weight_counter = kzalloc(sizeof(struct bfq_weight_counter),
758 GFP_ATOMIC);
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200759
760 /*
761 * In the unlucky event of an allocation failure, we just
Federico Motta2d29c9f2018-10-12 11:55:57 +0200762 * exit. This will cause the weight of queue to not be
Paolo Valentefb53ac62019-03-12 09:59:28 +0100763 * considered in bfq_asymmetric_scenario, which, in its turn,
Paolo Valente73d58112019-01-29 12:06:29 +0100764 * causes the scenario to be deemed wrongly symmetric in case
765 * bfqq's weight would have been the only weight making the
766 * scenario asymmetric. On the bright side, no unbalance will
767 * however occur when bfqq becomes inactive again (the
768 * invocation of this function is triggered by an activation
769 * of queue). In fact, bfq_weights_tree_remove does nothing
770 * if !bfqq->weight_counter.
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200771 */
Federico Motta2d29c9f2018-10-12 11:55:57 +0200772 if (unlikely(!bfqq->weight_counter))
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200773 return;
774
Federico Motta2d29c9f2018-10-12 11:55:57 +0200775 bfqq->weight_counter->weight = entity->weight;
776 rb_link_node(&bfqq->weight_counter->weights_node, parent, new);
Paolo Valentefb53ac62019-03-12 09:59:28 +0100777 rb_insert_color_cached(&bfqq->weight_counter->weights_node, root,
778 leftmost);
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200779
780inc_counter:
Federico Motta2d29c9f2018-10-12 11:55:57 +0200781 bfqq->weight_counter->num_active++;
Paolo Valente9dee8b32019-01-29 12:06:34 +0100782 bfqq->ref++;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200783}
784
785/*
Federico Motta2d29c9f2018-10-12 11:55:57 +0200786 * Decrement the weight counter associated with the queue, and, if the
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200787 * counter reaches 0, remove the counter from the tree.
788 * See the comments to the function bfq_weights_tree_add() for considerations
789 * about overhead.
790 */
Paolo Valente04715592018-06-25 21:55:34 +0200791void __bfq_weights_tree_remove(struct bfq_data *bfqd,
Federico Motta2d29c9f2018-10-12 11:55:57 +0200792 struct bfq_queue *bfqq,
Paolo Valentefb53ac62019-03-12 09:59:28 +0100793 struct rb_root_cached *root)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200794{
Federico Motta2d29c9f2018-10-12 11:55:57 +0200795 if (!bfqq->weight_counter)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200796 return;
797
Federico Motta2d29c9f2018-10-12 11:55:57 +0200798 bfqq->weight_counter->num_active--;
799 if (bfqq->weight_counter->num_active > 0)
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200800 goto reset_entity_pointer;
801
Paolo Valentefb53ac62019-03-12 09:59:28 +0100802 rb_erase_cached(&bfqq->weight_counter->weights_node, root);
Federico Motta2d29c9f2018-10-12 11:55:57 +0200803 kfree(bfqq->weight_counter);
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200804
805reset_entity_pointer:
Federico Motta2d29c9f2018-10-12 11:55:57 +0200806 bfqq->weight_counter = NULL;
Paolo Valente9dee8b32019-01-29 12:06:34 +0100807 bfq_put_queue(bfqq);
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +0200808}
809
810/*
Federico Motta2d29c9f2018-10-12 11:55:57 +0200811 * Invoke __bfq_weights_tree_remove on bfqq and decrement the number
812 * of active groups for each queue's inactive parent entity.
Paolo Valente04715592018-06-25 21:55:34 +0200813 */
814void bfq_weights_tree_remove(struct bfq_data *bfqd,
815 struct bfq_queue *bfqq)
816{
817 struct bfq_entity *entity = bfqq->entity.parent;
818
Paolo Valente04715592018-06-25 21:55:34 +0200819 for_each_entity(entity) {
820 struct bfq_sched_data *sd = entity->my_sched_data;
821
822 if (sd->next_in_service || sd->in_service_entity) {
823 /*
824 * entity is still active, because either
825 * next_in_service or in_service_entity is not
826 * NULL (see the comments on the definition of
827 * next_in_service for details on why
828 * in_service_entity must be checked too).
829 *
Federico Motta2d29c9f2018-10-12 11:55:57 +0200830 * As a consequence, its parent entities are
831 * active as well, and thus this loop must
832 * stop here.
Paolo Valente04715592018-06-25 21:55:34 +0200833 */
834 break;
835 }
Paolo Valenteba7aeae2018-12-06 19:18:18 +0100836
837 /*
838 * The decrement of num_groups_with_pending_reqs is
839 * not performed immediately upon the deactivation of
840 * entity, but it is delayed to when it also happens
841 * that the first leaf descendant bfqq of entity gets
842 * all its pending requests completed. The following
843 * instructions perform this delayed decrement, if
844 * needed. See the comments on
845 * num_groups_with_pending_reqs for details.
846 */
847 if (entity->in_groups_with_pending_reqs) {
848 entity->in_groups_with_pending_reqs = false;
849 bfqd->num_groups_with_pending_reqs--;
850 }
Paolo Valente04715592018-06-25 21:55:34 +0200851 }
Paolo Valente9dee8b32019-01-29 12:06:34 +0100852
853 /*
854 * Next function is invoked last, because it causes bfqq to be
855 * freed if the following holds: bfqq is not in service and
856 * has no dispatched request. DO NOT use bfqq after the next
857 * function invocation.
858 */
859 __bfq_weights_tree_remove(bfqd, bfqq,
860 &bfqd->queue_weights_tree);
Paolo Valente04715592018-06-25 21:55:34 +0200861}
862
863/*
Paolo Valenteaee69d72017-04-19 08:29:02 -0600864 * Return expired entry, or NULL to just start from scratch in rbtree.
865 */
866static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
867 struct request *last)
868{
869 struct request *rq;
870
871 if (bfq_bfqq_fifo_expire(bfqq))
872 return NULL;
873
874 bfq_mark_bfqq_fifo_expire(bfqq);
875
876 rq = rq_entry_fifo(bfqq->fifo.next);
877
878 if (rq == last || ktime_get_ns() < rq->fifo_time)
879 return NULL;
880
881 bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
882 return rq;
883}
884
885static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
886 struct bfq_queue *bfqq,
887 struct request *last)
888{
889 struct rb_node *rbnext = rb_next(&last->rb_node);
890 struct rb_node *rbprev = rb_prev(&last->rb_node);
891 struct request *next, *prev = NULL;
892
893 /* Follow expired path, else get first next available. */
894 next = bfq_check_fifo(bfqq, last);
895 if (next)
896 return next;
897
898 if (rbprev)
899 prev = rb_entry_rq(rbprev);
900
901 if (rbnext)
902 next = rb_entry_rq(rbnext);
903 else {
904 rbnext = rb_first(&bfqq->sort_list);
905 if (rbnext && rbnext != &last->rb_node)
906 next = rb_entry_rq(rbnext);
907 }
908
909 return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
910}
911
Paolo Valentec074170e2017-04-12 18:23:11 +0200912/* see the definition of bfq_async_charge_factor for details */
Paolo Valenteaee69d72017-04-19 08:29:02 -0600913static unsigned long bfq_serv_to_charge(struct request *rq,
914 struct bfq_queue *bfqq)
915{
Paolo Valente02a6d782019-01-29 12:06:37 +0100916 if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1 ||
Paolo Valentefb53ac62019-03-12 09:59:28 +0100917 bfq_asymmetric_scenario(bfqq->bfqd, bfqq))
Paolo Valentec074170e2017-04-12 18:23:11 +0200918 return blk_rq_sectors(rq);
919
Paolo Valented5801082018-08-16 18:51:17 +0200920 return blk_rq_sectors(rq) * bfq_async_charge_factor;
Paolo Valenteaee69d72017-04-19 08:29:02 -0600921}
922
923/**
924 * bfq_updated_next_req - update the queue after a new next_rq selection.
925 * @bfqd: the device data the queue belongs to.
926 * @bfqq: the queue to update.
927 *
928 * If the first request of a queue changes we make sure that the queue
929 * has enough budget to serve at least its first request (if the
930 * request has grown). We do this because if the queue has not enough
931 * budget for its first request, it has to go through two dispatch
932 * rounds to actually get it dispatched.
933 */
934static void bfq_updated_next_req(struct bfq_data *bfqd,
935 struct bfq_queue *bfqq)
936{
937 struct bfq_entity *entity = &bfqq->entity;
938 struct request *next_rq = bfqq->next_rq;
939 unsigned long new_budget;
940
941 if (!next_rq)
942 return;
943
944 if (bfqq == bfqd->in_service_queue)
945 /*
946 * In order not to break guarantees, budgets cannot be
947 * changed after an entity has been selected.
948 */
949 return;
950
Paolo Valentef3218ad2019-01-29 12:06:27 +0100951 new_budget = max_t(unsigned long,
952 max_t(unsigned long, bfqq->max_budget,
953 bfq_serv_to_charge(next_rq, bfqq)),
954 entity->service);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600955 if (entity->budget != new_budget) {
956 entity->budget = new_budget;
957 bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
958 new_budget);
Paolo Valente80294c32017-08-31 08:46:29 +0200959 bfq_requeue_bfqq(bfqd, bfqq, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -0600960 }
961}
962
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200963static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
964{
965 u64 dur;
966
967 if (bfqd->bfq_wr_max_time > 0)
968 return bfqd->bfq_wr_max_time;
969
Paolo Valentee24f1c22018-05-31 16:45:06 +0200970 dur = bfqd->rate_dur_prod;
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200971 do_div(dur, bfqd->peak_rate);
972
973 /*
Davide Sapienzad4505422018-05-31 16:45:07 +0200974 * Limit duration between 3 and 25 seconds. The upper limit
975 * has been conservatively set after the following worst case:
976 * on a QEMU/KVM virtual machine
977 * - running in a slow PC
978 * - with a virtual disk stacked on a slow low-end 5400rpm HDD
979 * - serving a heavy I/O workload, such as the sequential reading
980 * of several files
981 * mplayer took 23 seconds to start, if constantly weight-raised.
982 *
Angelo Ruocco636b8fe2019-04-08 17:35:34 +0200983 * As for higher values than that accommodating the above bad
Davide Sapienzad4505422018-05-31 16:45:07 +0200984 * scenario, tests show that higher values would often yield
985 * the opposite of the desired result, i.e., would worsen
986 * responsiveness by allowing non-interactive applications to
987 * preserve weight raising for too long.
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200988 *
989 * On the other end, lower values than 3 seconds make it
990 * difficult for most interactive tasks to complete their jobs
991 * before weight-raising finishes.
992 */
Davide Sapienzad4505422018-05-31 16:45:07 +0200993 return clamp_val(dur, msecs_to_jiffies(3000), msecs_to_jiffies(25000));
Paolo Valente3e2bdd62017-09-21 11:04:01 +0200994}
995
996/* switch back from soft real-time to interactive weight raising */
997static void switch_back_to_interactive_wr(struct bfq_queue *bfqq,
998 struct bfq_data *bfqd)
999{
1000 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1001 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1002 bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt;
1003}
1004
Arianna Avanzini36eca892017-04-12 18:23:16 +02001005static void
Paolo Valente13c931b2017-06-27 12:30:47 -06001006bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
1007 struct bfq_io_cq *bic, bool bfq_already_existing)
Arianna Avanzini36eca892017-04-12 18:23:16 +02001008{
Paolo Valente13c931b2017-06-27 12:30:47 -06001009 unsigned int old_wr_coeff = bfqq->wr_coeff;
1010 bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
1011
Paolo Valented5be3fe2017-08-04 07:35:10 +02001012 if (bic->saved_has_short_ttime)
1013 bfq_mark_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02001014 else
Paolo Valented5be3fe2017-08-04 07:35:10 +02001015 bfq_clear_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02001016
1017 if (bic->saved_IO_bound)
1018 bfq_mark_bfqq_IO_bound(bfqq);
1019 else
1020 bfq_clear_bfqq_IO_bound(bfqq);
1021
Francesco Pollicinofffca082019-03-12 09:59:34 +01001022 bfqq->entity.new_weight = bic->saved_weight;
Arianna Avanzini36eca892017-04-12 18:23:16 +02001023 bfqq->ttime = bic->saved_ttime;
1024 bfqq->wr_coeff = bic->saved_wr_coeff;
1025 bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt;
1026 bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish;
1027 bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time;
1028
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001029 if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
Arianna Avanzini36eca892017-04-12 18:23:16 +02001030 time_is_before_jiffies(bfqq->last_wr_start_finish +
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001031 bfqq->wr_cur_max_time))) {
Paolo Valente3e2bdd62017-09-21 11:04:01 +02001032 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
1033 !bfq_bfqq_in_large_burst(bfqq) &&
1034 time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt +
1035 bfq_wr_duration(bfqd))) {
1036 switch_back_to_interactive_wr(bfqq, bfqd);
1037 } else {
1038 bfqq->wr_coeff = 1;
1039 bfq_log_bfqq(bfqq->bfqd, bfqq,
1040 "resume state: switching off wr");
1041 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02001042 }
1043
1044 /* make sure weight will be updated, however we got here */
1045 bfqq->entity.prio_changed = 1;
Paolo Valente13c931b2017-06-27 12:30:47 -06001046
1047 if (likely(!busy))
1048 return;
1049
1050 if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
1051 bfqd->wr_busy_queues++;
1052 else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
1053 bfqd->wr_busy_queues--;
Arianna Avanzini36eca892017-04-12 18:23:16 +02001054}
1055
1056static int bfqq_process_refs(struct bfq_queue *bfqq)
1057{
Paolo Valente9dee8b32019-01-29 12:06:34 +01001058 return bfqq->ref - bfqq->allocated - bfqq->entity.on_st -
1059 (bfqq->weight_counter != NULL);
Arianna Avanzini36eca892017-04-12 18:23:16 +02001060}
1061
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001062/* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
1063static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1064{
1065 struct bfq_queue *item;
1066 struct hlist_node *n;
1067
1068 hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
1069 hlist_del_init(&item->burst_list_node);
Paolo Valente84a74682019-03-12 09:59:32 +01001070
1071 /*
1072 * Start the creation of a new burst list only if there is no
1073 * active queue. See comments on the conditional invocation of
1074 * bfq_handle_burst().
1075 */
1076 if (bfq_tot_busy_queues(bfqd) == 0) {
1077 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1078 bfqd->burst_size = 1;
1079 } else
1080 bfqd->burst_size = 0;
1081
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001082 bfqd->burst_parent_entity = bfqq->entity.parent;
1083}
1084
1085/* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
1086static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1087{
1088 /* Increment burst size to take into account also bfqq */
1089 bfqd->burst_size++;
1090
1091 if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
1092 struct bfq_queue *pos, *bfqq_item;
1093 struct hlist_node *n;
1094
1095 /*
1096 * Enough queues have been activated shortly after each
1097 * other to consider this burst as large.
1098 */
1099 bfqd->large_burst = true;
1100
1101 /*
1102 * We can now mark all queues in the burst list as
1103 * belonging to a large burst.
1104 */
1105 hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
1106 burst_list_node)
1107 bfq_mark_bfqq_in_large_burst(bfqq_item);
1108 bfq_mark_bfqq_in_large_burst(bfqq);
1109
1110 /*
1111 * From now on, and until the current burst finishes, any
1112 * new queue being activated shortly after the last queue
1113 * was inserted in the burst can be immediately marked as
1114 * belonging to a large burst. So the burst list is not
1115 * needed any more. Remove it.
1116 */
1117 hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
1118 burst_list_node)
1119 hlist_del_init(&pos->burst_list_node);
1120 } else /*
1121 * Burst not yet large: add bfqq to the burst list. Do
1122 * not increment the ref counter for bfqq, because bfqq
1123 * is removed from the burst list before freeing bfqq
1124 * in put_queue.
1125 */
1126 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1127}
1128
1129/*
1130 * If many queues belonging to the same group happen to be created
1131 * shortly after each other, then the processes associated with these
1132 * queues have typically a common goal. In particular, bursts of queue
1133 * creations are usually caused by services or applications that spawn
1134 * many parallel threads/processes. Examples are systemd during boot,
1135 * or git grep. To help these processes get their job done as soon as
1136 * possible, it is usually better to not grant either weight-raising
Paolo Valente84a74682019-03-12 09:59:32 +01001137 * or device idling to their queues, unless these queues must be
1138 * protected from the I/O flowing through other active queues.
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001139 *
1140 * In this comment we describe, firstly, the reasons why this fact
1141 * holds, and, secondly, the next function, which implements the main
1142 * steps needed to properly mark these queues so that they can then be
1143 * treated in a different way.
1144 *
1145 * The above services or applications benefit mostly from a high
1146 * throughput: the quicker the requests of the activated queues are
1147 * cumulatively served, the sooner the target job of these queues gets
1148 * completed. As a consequence, weight-raising any of these queues,
1149 * which also implies idling the device for it, is almost always
Paolo Valente84a74682019-03-12 09:59:32 +01001150 * counterproductive, unless there are other active queues to isolate
1151 * these new queues from. If there no other active queues, then
1152 * weight-raising these new queues just lowers throughput in most
1153 * cases.
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001154 *
1155 * On the other hand, a burst of queue creations may be caused also by
1156 * the start of an application that does not consist of a lot of
1157 * parallel I/O-bound threads. In fact, with a complex application,
1158 * several short processes may need to be executed to start-up the
1159 * application. In this respect, to start an application as quickly as
1160 * possible, the best thing to do is in any case to privilege the I/O
1161 * related to the application with respect to all other
1162 * I/O. Therefore, the best strategy to start as quickly as possible
1163 * an application that causes a burst of queue creations is to
1164 * weight-raise all the queues created during the burst. This is the
1165 * exact opposite of the best strategy for the other type of bursts.
1166 *
1167 * In the end, to take the best action for each of the two cases, the
1168 * two types of bursts need to be distinguished. Fortunately, this
1169 * seems relatively easy, by looking at the sizes of the bursts. In
1170 * particular, we found a threshold such that only bursts with a
1171 * larger size than that threshold are apparently caused by
1172 * services or commands such as systemd or git grep. For brevity,
1173 * hereafter we call just 'large' these bursts. BFQ *does not*
1174 * weight-raise queues whose creation occurs in a large burst. In
1175 * addition, for each of these queues BFQ performs or does not perform
1176 * idling depending on which choice boosts the throughput more. The
1177 * exact choice depends on the device and request pattern at
1178 * hand.
1179 *
1180 * Unfortunately, false positives may occur while an interactive task
1181 * is starting (e.g., an application is being started). The
1182 * consequence is that the queues associated with the task do not
1183 * enjoy weight raising as expected. Fortunately these false positives
1184 * are very rare. They typically occur if some service happens to
1185 * start doing I/O exactly when the interactive task starts.
1186 *
Paolo Valente84a74682019-03-12 09:59:32 +01001187 * Turning back to the next function, it is invoked only if there are
1188 * no active queues (apart from active queues that would belong to the
1189 * same, possible burst bfqq would belong to), and it implements all
1190 * the steps needed to detect the occurrence of a large burst and to
1191 * properly mark all the queues belonging to it (so that they can then
1192 * be treated in a different way). This goal is achieved by
1193 * maintaining a "burst list" that holds, temporarily, the queues that
1194 * belong to the burst in progress. The list is then used to mark
1195 * these queues as belonging to a large burst if the burst does become
1196 * large. The main steps are the following.
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001197 *
1198 * . when the very first queue is created, the queue is inserted into the
1199 * list (as it could be the first queue in a possible burst)
1200 *
1201 * . if the current burst has not yet become large, and a queue Q that does
1202 * not yet belong to the burst is activated shortly after the last time
1203 * at which a new queue entered the burst list, then the function appends
1204 * Q to the burst list
1205 *
1206 * . if, as a consequence of the previous step, the burst size reaches
1207 * the large-burst threshold, then
1208 *
1209 * . all the queues in the burst list are marked as belonging to a
1210 * large burst
1211 *
1212 * . the burst list is deleted; in fact, the burst list already served
1213 * its purpose (keeping temporarily track of the queues in a burst,
1214 * so as to be able to mark them as belonging to a large burst in the
1215 * previous sub-step), and now is not needed any more
1216 *
1217 * . the device enters a large-burst mode
1218 *
1219 * . if a queue Q that does not belong to the burst is created while
1220 * the device is in large-burst mode and shortly after the last time
1221 * at which a queue either entered the burst list or was marked as
1222 * belonging to the current large burst, then Q is immediately marked
1223 * as belonging to a large burst.
1224 *
1225 * . if a queue Q that does not belong to the burst is created a while
1226 * later, i.e., not shortly after, than the last time at which a queue
1227 * either entered the burst list or was marked as belonging to the
1228 * current large burst, then the current burst is deemed as finished and:
1229 *
1230 * . the large-burst mode is reset if set
1231 *
1232 * . the burst list is emptied
1233 *
1234 * . Q is inserted in the burst list, as Q may be the first queue
1235 * in a possible new burst (then the burst list contains just Q
1236 * after this step).
1237 */
1238static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1239{
1240 /*
1241 * If bfqq is already in the burst list or is part of a large
1242 * burst, or finally has just been split, then there is
1243 * nothing else to do.
1244 */
1245 if (!hlist_unhashed(&bfqq->burst_list_node) ||
1246 bfq_bfqq_in_large_burst(bfqq) ||
1247 time_is_after_eq_jiffies(bfqq->split_time +
1248 msecs_to_jiffies(10)))
1249 return;
1250
1251 /*
1252 * If bfqq's creation happens late enough, or bfqq belongs to
1253 * a different group than the burst group, then the current
1254 * burst is finished, and related data structures must be
1255 * reset.
1256 *
1257 * In this respect, consider the special case where bfqq is
1258 * the very first queue created after BFQ is selected for this
1259 * device. In this case, last_ins_in_burst and
1260 * burst_parent_entity are not yet significant when we get
1261 * here. But it is easy to verify that, whether or not the
1262 * following condition is true, bfqq will end up being
1263 * inserted into the burst list. In particular the list will
1264 * happen to contain only bfqq. And this is exactly what has
1265 * to happen, as bfqq may be the first queue of the first
1266 * burst.
1267 */
1268 if (time_is_before_jiffies(bfqd->last_ins_in_burst +
1269 bfqd->bfq_burst_interval) ||
1270 bfqq->entity.parent != bfqd->burst_parent_entity) {
1271 bfqd->large_burst = false;
1272 bfq_reset_burst_list(bfqd, bfqq);
1273 goto end;
1274 }
1275
1276 /*
1277 * If we get here, then bfqq is being activated shortly after the
1278 * last queue. So, if the current burst is also large, we can mark
1279 * bfqq as belonging to this large burst immediately.
1280 */
1281 if (bfqd->large_burst) {
1282 bfq_mark_bfqq_in_large_burst(bfqq);
1283 goto end;
1284 }
1285
1286 /*
1287 * If we get here, then a large-burst state has not yet been
1288 * reached, but bfqq is being activated shortly after the last
1289 * queue. Then we add bfqq to the burst.
1290 */
1291 bfq_add_to_burst(bfqd, bfqq);
1292end:
1293 /*
1294 * At this point, bfqq either has been added to the current
1295 * burst or has caused the current burst to terminate and a
1296 * possible new burst to start. In particular, in the second
1297 * case, bfqq has become the first queue in the possible new
1298 * burst. In both cases last_ins_in_burst needs to be moved
1299 * forward.
1300 */
1301 bfqd->last_ins_in_burst = jiffies;
1302}
1303
Paolo Valenteaee69d72017-04-19 08:29:02 -06001304static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
1305{
1306 struct bfq_entity *entity = &bfqq->entity;
1307
1308 return entity->budget - entity->service;
1309}
1310
1311/*
1312 * If enough samples have been computed, return the current max budget
1313 * stored in bfqd, which is dynamically updated according to the
1314 * estimated disk peak rate; otherwise return the default max budget
1315 */
1316static int bfq_max_budget(struct bfq_data *bfqd)
1317{
1318 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1319 return bfq_default_max_budget;
1320 else
1321 return bfqd->bfq_max_budget;
1322}
1323
1324/*
1325 * Return min budget, which is a fraction of the current or default
1326 * max budget (trying with 1/32)
1327 */
1328static int bfq_min_budget(struct bfq_data *bfqd)
1329{
1330 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1331 return bfq_default_max_budget / 32;
1332 else
1333 return bfqd->bfq_max_budget / 32;
1334}
1335
Paolo Valenteaee69d72017-04-19 08:29:02 -06001336/*
1337 * The next function, invoked after the input queue bfqq switches from
1338 * idle to busy, updates the budget of bfqq. The function also tells
1339 * whether the in-service queue should be expired, by returning
1340 * true. The purpose of expiring the in-service queue is to give bfqq
1341 * the chance to possibly preempt the in-service queue, and the reason
Paolo Valente44e44a12017-04-12 18:23:12 +02001342 * for preempting the in-service queue is to achieve one of the two
1343 * goals below.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001344 *
Paolo Valente44e44a12017-04-12 18:23:12 +02001345 * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
1346 * expired because it has remained idle. In particular, bfqq may have
1347 * expired for one of the following two reasons:
Paolo Valenteaee69d72017-04-19 08:29:02 -06001348 *
1349 * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
1350 * and did not make it to issue a new request before its last
1351 * request was served;
1352 *
1353 * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
1354 * a new request before the expiration of the idling-time.
1355 *
1356 * Even if bfqq has expired for one of the above reasons, the process
1357 * associated with the queue may be however issuing requests greedily,
1358 * and thus be sensitive to the bandwidth it receives (bfqq may have
1359 * remained idle for other reasons: CPU high load, bfqq not enjoying
1360 * idling, I/O throttling somewhere in the path from the process to
1361 * the I/O scheduler, ...). But if, after every expiration for one of
1362 * the above two reasons, bfqq has to wait for the service of at least
1363 * one full budget of another queue before being served again, then
1364 * bfqq is likely to get a much lower bandwidth or resource time than
1365 * its reserved ones. To address this issue, two countermeasures need
1366 * to be taken.
1367 *
1368 * First, the budget and the timestamps of bfqq need to be updated in
1369 * a special way on bfqq reactivation: they need to be updated as if
1370 * bfqq did not remain idle and did not expire. In fact, if they are
1371 * computed as if bfqq expired and remained idle until reactivation,
1372 * then the process associated with bfqq is treated as if, instead of
1373 * being greedy, it stopped issuing requests when bfqq remained idle,
1374 * and restarts issuing requests only on this reactivation. In other
1375 * words, the scheduler does not help the process recover the "service
1376 * hole" between bfqq expiration and reactivation. As a consequence,
1377 * the process receives a lower bandwidth than its reserved one. In
1378 * contrast, to recover this hole, the budget must be updated as if
1379 * bfqq was not expired at all before this reactivation, i.e., it must
1380 * be set to the value of the remaining budget when bfqq was
1381 * expired. Along the same line, timestamps need to be assigned the
1382 * value they had the last time bfqq was selected for service, i.e.,
1383 * before last expiration. Thus timestamps need to be back-shifted
1384 * with respect to their normal computation (see [1] for more details
1385 * on this tricky aspect).
1386 *
1387 * Secondly, to allow the process to recover the hole, the in-service
1388 * queue must be expired too, to give bfqq the chance to preempt it
1389 * immediately. In fact, if bfqq has to wait for a full budget of the
1390 * in-service queue to be completed, then it may become impossible to
1391 * let the process recover the hole, even if the back-shifted
1392 * timestamps of bfqq are lower than those of the in-service queue. If
1393 * this happens for most or all of the holes, then the process may not
1394 * receive its reserved bandwidth. In this respect, it is worth noting
1395 * that, being the service of outstanding requests unpreemptible, a
1396 * little fraction of the holes may however be unrecoverable, thereby
1397 * causing a little loss of bandwidth.
1398 *
1399 * The last important point is detecting whether bfqq does need this
1400 * bandwidth recovery. In this respect, the next function deems the
1401 * process associated with bfqq greedy, and thus allows it to recover
1402 * the hole, if: 1) the process is waiting for the arrival of a new
1403 * request (which implies that bfqq expired for one of the above two
1404 * reasons), and 2) such a request has arrived soon. The first
1405 * condition is controlled through the flag non_blocking_wait_rq,
1406 * while the second through the flag arrived_in_time. If both
1407 * conditions hold, then the function computes the budget in the
1408 * above-described special way, and signals that the in-service queue
1409 * should be expired. Timestamp back-shifting is done later in
1410 * __bfq_activate_entity.
Paolo Valente44e44a12017-04-12 18:23:12 +02001411 *
1412 * 2. Reduce latency. Even if timestamps are not backshifted to let
1413 * the process associated with bfqq recover a service hole, bfqq may
1414 * however happen to have, after being (re)activated, a lower finish
1415 * timestamp than the in-service queue. That is, the next budget of
1416 * bfqq may have to be completed before the one of the in-service
1417 * queue. If this is the case, then preempting the in-service queue
1418 * allows this goal to be achieved, apart from the unpreemptible,
1419 * outstanding requests mentioned above.
1420 *
1421 * Unfortunately, regardless of which of the above two goals one wants
1422 * to achieve, service trees need first to be updated to know whether
1423 * the in-service queue must be preempted. To have service trees
1424 * correctly updated, the in-service queue must be expired and
1425 * rescheduled, and bfqq must be scheduled too. This is one of the
1426 * most costly operations (in future versions, the scheduling
1427 * mechanism may be re-designed in such a way to make it possible to
1428 * know whether preemption is needed without needing to update service
1429 * trees). In addition, queue preemptions almost always cause random
1430 * I/O, and thus loss of throughput. Because of these facts, the next
1431 * function adopts the following simple scheme to avoid both costly
1432 * operations and too frequent preemptions: it requests the expiration
1433 * of the in-service queue (unconditionally) only for queues that need
1434 * to recover a hole, or that either are weight-raised or deserve to
1435 * be weight-raised.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001436 */
1437static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
1438 struct bfq_queue *bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001439 bool arrived_in_time,
1440 bool wr_or_deserves_wr)
Paolo Valenteaee69d72017-04-19 08:29:02 -06001441{
1442 struct bfq_entity *entity = &bfqq->entity;
1443
Paolo Valente218cb892019-01-29 12:06:26 +01001444 /*
1445 * In the next compound condition, we check also whether there
1446 * is some budget left, because otherwise there is no point in
1447 * trying to go on serving bfqq with this same budget: bfqq
1448 * would be expired immediately after being selected for
1449 * service. This would only cause useless overhead.
1450 */
1451 if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time &&
1452 bfq_bfqq_budget_left(bfqq) > 0) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06001453 /*
1454 * We do not clear the flag non_blocking_wait_rq here, as
1455 * the latter is used in bfq_activate_bfqq to signal
1456 * that timestamps need to be back-shifted (and is
1457 * cleared right after).
1458 */
1459
1460 /*
1461 * In next assignment we rely on that either
1462 * entity->service or entity->budget are not updated
1463 * on expiration if bfqq is empty (see
1464 * __bfq_bfqq_recalc_budget). Thus both quantities
1465 * remain unchanged after such an expiration, and the
1466 * following statement therefore assigns to
1467 * entity->budget the remaining budget on such an
Paolo Valente9fae8dd2018-06-25 21:55:36 +02001468 * expiration.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001469 */
1470 entity->budget = min_t(unsigned long,
1471 bfq_bfqq_budget_left(bfqq),
1472 bfqq->max_budget);
1473
Paolo Valente9fae8dd2018-06-25 21:55:36 +02001474 /*
1475 * At this point, we have used entity->service to get
1476 * the budget left (needed for updating
1477 * entity->budget). Thus we finally can, and have to,
1478 * reset entity->service. The latter must be reset
1479 * because bfqq would otherwise be charged again for
1480 * the service it has received during its previous
1481 * service slot(s).
1482 */
1483 entity->service = 0;
1484
Paolo Valenteaee69d72017-04-19 08:29:02 -06001485 return true;
1486 }
1487
Paolo Valente9fae8dd2018-06-25 21:55:36 +02001488 /*
1489 * We can finally complete expiration, by setting service to 0.
1490 */
1491 entity->service = 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001492 entity->budget = max_t(unsigned long, bfqq->max_budget,
1493 bfq_serv_to_charge(bfqq->next_rq, bfqq));
1494 bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
Paolo Valente44e44a12017-04-12 18:23:12 +02001495 return wr_or_deserves_wr;
1496}
1497
Paolo Valente4baa8bb2017-09-21 11:04:00 +02001498/*
Paolo Valente4baa8bb2017-09-21 11:04:00 +02001499 * Return the farthest past time instant according to jiffies
1500 * macros.
1501 */
1502static unsigned long bfq_smallest_from_now(void)
1503{
1504 return jiffies - MAX_JIFFY_OFFSET;
1505}
1506
Paolo Valente44e44a12017-04-12 18:23:12 +02001507static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
1508 struct bfq_queue *bfqq,
1509 unsigned int old_wr_coeff,
1510 bool wr_or_deserves_wr,
Paolo Valente77b7dce2017-04-12 18:23:13 +02001511 bool interactive,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001512 bool in_burst,
Paolo Valente77b7dce2017-04-12 18:23:13 +02001513 bool soft_rt)
Paolo Valente44e44a12017-04-12 18:23:12 +02001514{
1515 if (old_wr_coeff == 1 && wr_or_deserves_wr) {
1516 /* start a weight-raising period */
Paolo Valente77b7dce2017-04-12 18:23:13 +02001517 if (interactive) {
Paolo Valente8a8747d2018-01-13 12:05:18 +01001518 bfqq->service_from_wr = 0;
Paolo Valente77b7dce2017-04-12 18:23:13 +02001519 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1520 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1521 } else {
Paolo Valente4baa8bb2017-09-21 11:04:00 +02001522 /*
1523 * No interactive weight raising in progress
1524 * here: assign minus infinity to
1525 * wr_start_at_switch_to_srt, to make sure
1526 * that, at the end of the soft-real-time
1527 * weight raising periods that is starting
1528 * now, no interactive weight-raising period
1529 * may be wrongly considered as still in
1530 * progress (and thus actually started by
1531 * mistake).
1532 */
1533 bfqq->wr_start_at_switch_to_srt =
1534 bfq_smallest_from_now();
Paolo Valente77b7dce2017-04-12 18:23:13 +02001535 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1536 BFQ_SOFTRT_WEIGHT_FACTOR;
1537 bfqq->wr_cur_max_time =
1538 bfqd->bfq_wr_rt_max_time;
1539 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001540
1541 /*
1542 * If needed, further reduce budget to make sure it is
1543 * close to bfqq's backlog, so as to reduce the
1544 * scheduling-error component due to a too large
1545 * budget. Do not care about throughput consequences,
1546 * but only about latency. Finally, do not assign a
1547 * too small budget either, to avoid increasing
1548 * latency by causing too frequent expirations.
1549 */
1550 bfqq->entity.budget = min_t(unsigned long,
1551 bfqq->entity.budget,
1552 2 * bfq_min_budget(bfqd));
1553 } else if (old_wr_coeff > 1) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02001554 if (interactive) { /* update wr coeff and duration */
1555 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1556 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001557 } else if (in_burst)
1558 bfqq->wr_coeff = 1;
1559 else if (soft_rt) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02001560 /*
1561 * The application is now or still meeting the
1562 * requirements for being deemed soft rt. We
1563 * can then correctly and safely (re)charge
1564 * the weight-raising duration for the
1565 * application with the weight-raising
1566 * duration for soft rt applications.
1567 *
1568 * In particular, doing this recharge now, i.e.,
1569 * before the weight-raising period for the
1570 * application finishes, reduces the probability
1571 * of the following negative scenario:
1572 * 1) the weight of a soft rt application is
1573 * raised at startup (as for any newly
1574 * created application),
1575 * 2) since the application is not interactive,
1576 * at a certain time weight-raising is
1577 * stopped for the application,
1578 * 3) at that time the application happens to
1579 * still have pending requests, and hence
1580 * is destined to not have a chance to be
1581 * deemed soft rt before these requests are
1582 * completed (see the comments to the
1583 * function bfq_bfqq_softrt_next_start()
1584 * for details on soft rt detection),
1585 * 4) these pending requests experience a high
1586 * latency because the application is not
1587 * weight-raised while they are pending.
1588 */
1589 if (bfqq->wr_cur_max_time !=
1590 bfqd->bfq_wr_rt_max_time) {
1591 bfqq->wr_start_at_switch_to_srt =
1592 bfqq->last_wr_start_finish;
1593
1594 bfqq->wr_cur_max_time =
1595 bfqd->bfq_wr_rt_max_time;
1596 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1597 BFQ_SOFTRT_WEIGHT_FACTOR;
1598 }
1599 bfqq->last_wr_start_finish = jiffies;
1600 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001601 }
1602}
1603
1604static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
1605 struct bfq_queue *bfqq)
1606{
1607 return bfqq->dispatched == 0 &&
1608 time_is_before_jiffies(
1609 bfqq->budget_timeout +
1610 bfqd->bfq_wr_min_idle_time);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001611}
1612
1613static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
1614 struct bfq_queue *bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001615 int old_wr_coeff,
1616 struct request *rq,
1617 bool *interactive)
Paolo Valenteaee69d72017-04-19 08:29:02 -06001618{
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001619 bool soft_rt, in_burst, wr_or_deserves_wr,
1620 bfqq_wants_to_preempt,
Paolo Valente44e44a12017-04-12 18:23:12 +02001621 idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
Paolo Valenteaee69d72017-04-19 08:29:02 -06001622 /*
1623 * See the comments on
1624 * bfq_bfqq_update_budg_for_activation for
1625 * details on the usage of the next variable.
1626 */
1627 arrived_in_time = ktime_get_ns() <=
1628 bfqq->ttime.last_end_request +
1629 bfqd->bfq_slice_idle * 3;
1630
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001631
Paolo Valenteaee69d72017-04-19 08:29:02 -06001632 /*
Paolo Valente44e44a12017-04-12 18:23:12 +02001633 * bfqq deserves to be weight-raised if:
1634 * - it is sync,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001635 * - it does not belong to a large burst,
Arianna Avanzini36eca892017-04-12 18:23:16 +02001636 * - it has been idle for enough time or is soft real-time,
1637 * - is linked to a bfq_io_cq (it is not shared in any sense).
Paolo Valente44e44a12017-04-12 18:23:12 +02001638 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001639 in_burst = bfq_bfqq_in_large_burst(bfqq);
Paolo Valente77b7dce2017-04-12 18:23:13 +02001640 soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
Paolo Valente7074f072019-03-12 09:59:31 +01001641 !BFQQ_TOTALLY_SEEKY(bfqq) &&
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001642 !in_burst &&
Davide Sapienzaf6c3ca02018-05-31 16:45:08 +02001643 time_is_before_jiffies(bfqq->soft_rt_next_start) &&
1644 bfqq->dispatched == 0;
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001645 *interactive = !in_burst && idle_for_long_time;
Paolo Valente44e44a12017-04-12 18:23:12 +02001646 wr_or_deserves_wr = bfqd->low_latency &&
1647 (bfqq->wr_coeff > 1 ||
Arianna Avanzini36eca892017-04-12 18:23:16 +02001648 (bfq_bfqq_sync(bfqq) &&
1649 bfqq->bic && (*interactive || soft_rt)));
Paolo Valente44e44a12017-04-12 18:23:12 +02001650
1651 /*
1652 * Using the last flag, update budget and check whether bfqq
1653 * may want to preempt the in-service queue.
Paolo Valenteaee69d72017-04-19 08:29:02 -06001654 */
1655 bfqq_wants_to_preempt =
1656 bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
Paolo Valente44e44a12017-04-12 18:23:12 +02001657 arrived_in_time,
1658 wr_or_deserves_wr);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001659
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001660 /*
1661 * If bfqq happened to be activated in a burst, but has been
1662 * idle for much more than an interactive queue, then we
1663 * assume that, in the overall I/O initiated in the burst, the
1664 * I/O associated with bfqq is finished. So bfqq does not need
1665 * to be treated as a queue belonging to a burst
1666 * anymore. Accordingly, we reset bfqq's in_large_burst flag
1667 * if set, and remove bfqq from the burst list if it's
1668 * there. We do not decrement burst_size, because the fact
1669 * that bfqq does not need to belong to the burst list any
1670 * more does not invalidate the fact that bfqq was created in
1671 * a burst.
1672 */
1673 if (likely(!bfq_bfqq_just_created(bfqq)) &&
1674 idle_for_long_time &&
1675 time_is_before_jiffies(
1676 bfqq->budget_timeout +
1677 msecs_to_jiffies(10000))) {
1678 hlist_del_init(&bfqq->burst_list_node);
1679 bfq_clear_bfqq_in_large_burst(bfqq);
1680 }
1681
1682 bfq_clear_bfqq_just_created(bfqq);
1683
1684
Paolo Valenteaee69d72017-04-19 08:29:02 -06001685 if (!bfq_bfqq_IO_bound(bfqq)) {
1686 if (arrived_in_time) {
1687 bfqq->requests_within_timer++;
1688 if (bfqq->requests_within_timer >=
1689 bfqd->bfq_requests_within_timer)
1690 bfq_mark_bfqq_IO_bound(bfqq);
1691 } else
1692 bfqq->requests_within_timer = 0;
1693 }
1694
Paolo Valente44e44a12017-04-12 18:23:12 +02001695 if (bfqd->low_latency) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02001696 if (unlikely(time_is_after_jiffies(bfqq->split_time)))
1697 /* wraparound */
1698 bfqq->split_time =
1699 jiffies - bfqd->bfq_wr_min_idle_time - 1;
Paolo Valente44e44a12017-04-12 18:23:12 +02001700
Arianna Avanzini36eca892017-04-12 18:23:16 +02001701 if (time_is_before_jiffies(bfqq->split_time +
1702 bfqd->bfq_wr_min_idle_time)) {
1703 bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
1704 old_wr_coeff,
1705 wr_or_deserves_wr,
1706 *interactive,
Arianna Avanzinie1b23242017-04-12 18:23:20 +02001707 in_burst,
Arianna Avanzini36eca892017-04-12 18:23:16 +02001708 soft_rt);
1709
1710 if (old_wr_coeff != bfqq->wr_coeff)
1711 bfqq->entity.prio_changed = 1;
1712 }
Paolo Valente44e44a12017-04-12 18:23:12 +02001713 }
1714
Paolo Valente77b7dce2017-04-12 18:23:13 +02001715 bfqq->last_idle_bklogged = jiffies;
1716 bfqq->service_from_backlogged = 0;
1717 bfq_clear_bfqq_softrt_update(bfqq);
1718
Paolo Valenteaee69d72017-04-19 08:29:02 -06001719 bfq_add_bfqq_busy(bfqd, bfqq);
1720
1721 /*
1722 * Expire in-service queue only if preemption may be needed
1723 * for guarantees. In this respect, the function
1724 * next_queue_may_preempt just checks a simple, necessary
1725 * condition, and not a sufficient condition based on
1726 * timestamps. In fact, for the latter condition to be
1727 * evaluated, timestamps would need first to be updated, and
1728 * this operation is quite costly (see the comments on the
1729 * function bfq_bfqq_update_budg_for_activation).
1730 */
1731 if (bfqd->in_service_queue && bfqq_wants_to_preempt &&
Paolo Valente77b7dce2017-04-12 18:23:13 +02001732 bfqd->in_service_queue->wr_coeff < bfqq->wr_coeff &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06001733 next_queue_may_preempt(bfqd))
1734 bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
1735 false, BFQQE_PREEMPTED);
1736}
1737
Paolo Valente766d6142019-06-25 07:12:43 +02001738static void bfq_reset_inject_limit(struct bfq_data *bfqd,
1739 struct bfq_queue *bfqq)
1740{
1741 /* invalidate baseline total service time */
1742 bfqq->last_serv_time_ns = 0;
1743
1744 /*
1745 * Reset pointer in case we are waiting for
1746 * some request completion.
1747 */
1748 bfqd->waited_rq = NULL;
1749
1750 /*
1751 * If bfqq has a short think time, then start by setting the
1752 * inject limit to 0 prudentially, because the service time of
1753 * an injected I/O request may be higher than the think time
1754 * of bfqq, and therefore, if one request was injected when
1755 * bfqq remains empty, this injected request might delay the
1756 * service of the next I/O request for bfqq significantly. In
1757 * case bfqq can actually tolerate some injection, then the
1758 * adaptive update will however raise the limit soon. This
1759 * lucky circumstance holds exactly because bfqq has a short
1760 * think time, and thus, after remaining empty, is likely to
1761 * get new I/O enqueued---and then completed---before being
1762 * expired. This is the very pattern that gives the
1763 * limit-update algorithm the chance to measure the effect of
1764 * injection on request service times, and then to update the
1765 * limit accordingly.
1766 *
1767 * However, in the following special case, the inject limit is
1768 * left to 1 even if the think time is short: bfqq's I/O is
1769 * synchronized with that of some other queue, i.e., bfqq may
1770 * receive new I/O only after the I/O of the other queue is
1771 * completed. Keeping the inject limit to 1 allows the
1772 * blocking I/O to be served while bfqq is in service. And
1773 * this is very convenient both for bfqq and for overall
1774 * throughput, as explained in detail in the comments in
1775 * bfq_update_has_short_ttime().
1776 *
1777 * On the opposite end, if bfqq has a long think time, then
1778 * start directly by 1, because:
1779 * a) on the bright side, keeping at most one request in
1780 * service in the drive is unlikely to cause any harm to the
1781 * latency of bfqq's requests, as the service time of a single
1782 * request is likely to be lower than the think time of bfqq;
1783 * b) on the downside, after becoming empty, bfqq is likely to
1784 * expire before getting its next request. With this request
1785 * arrival pattern, it is very hard to sample total service
1786 * times and update the inject limit accordingly (see comments
1787 * on bfq_update_inject_limit()). So the limit is likely to be
1788 * never, or at least seldom, updated. As a consequence, by
1789 * setting the limit to 1, we avoid that no injection ever
1790 * occurs with bfqq. On the downside, this proactive step
1791 * further reduces chances to actually compute the baseline
1792 * total service time. Thus it reduces chances to execute the
1793 * limit-update algorithm and possibly raise the limit to more
1794 * than 1.
1795 */
1796 if (bfq_bfqq_has_short_ttime(bfqq))
1797 bfqq->inject_limit = 0;
1798 else
1799 bfqq->inject_limit = 1;
1800
1801 bfqq->decrease_time_jif = jiffies;
1802}
1803
Paolo Valenteaee69d72017-04-19 08:29:02 -06001804static void bfq_add_request(struct request *rq)
1805{
1806 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1807 struct bfq_data *bfqd = bfqq->bfqd;
1808 struct request *next_rq, *prev;
Paolo Valente44e44a12017-04-12 18:23:12 +02001809 unsigned int old_wr_coeff = bfqq->wr_coeff;
1810 bool interactive = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001811
1812 bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
1813 bfqq->queued[rq_is_sync(rq)]++;
1814 bfqd->queued++;
1815
Paolo Valente2341d6622019-03-12 09:59:29 +01001816 if (RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_sync(bfqq)) {
1817 /*
1818 * Periodically reset inject limit, to make sure that
1819 * the latter eventually drops in case workload
1820 * changes, see step (3) in the comments on
1821 * bfq_update_inject_limit().
1822 */
1823 if (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
Paolo Valente766d6142019-06-25 07:12:43 +02001824 msecs_to_jiffies(1000)))
1825 bfq_reset_inject_limit(bfqd, bfqq);
Paolo Valente2341d6622019-03-12 09:59:29 +01001826
1827 /*
1828 * The following conditions must hold to setup a new
1829 * sampling of total service time, and then a new
1830 * update of the inject limit:
1831 * - bfqq is in service, because the total service
1832 * time is evaluated only for the I/O requests of
1833 * the queues in service;
1834 * - this is the right occasion to compute or to
1835 * lower the baseline total service time, because
1836 * there are actually no requests in the drive,
1837 * or
1838 * the baseline total service time is available, and
1839 * this is the right occasion to compute the other
1840 * quantity needed to update the inject limit, i.e.,
1841 * the total service time caused by the amount of
1842 * injection allowed by the current value of the
1843 * limit. It is the right occasion because injection
1844 * has actually been performed during the service
1845 * hole, and there are still in-flight requests,
1846 * which are very likely to be exactly the injected
1847 * requests, or part of them;
1848 * - the minimum interval for sampling the total
1849 * service time and updating the inject limit has
1850 * elapsed.
1851 */
1852 if (bfqq == bfqd->in_service_queue &&
1853 (bfqd->rq_in_driver == 0 ||
1854 (bfqq->last_serv_time_ns > 0 &&
1855 bfqd->rqs_injected && bfqd->rq_in_driver > 0)) &&
1856 time_is_before_eq_jiffies(bfqq->decrease_time_jif +
1857 msecs_to_jiffies(100))) {
1858 bfqd->last_empty_occupied_ns = ktime_get_ns();
1859 /*
1860 * Start the state machine for measuring the
1861 * total service time of rq: setting
1862 * wait_dispatch will cause bfqd->waited_rq to
1863 * be set when rq will be dispatched.
1864 */
1865 bfqd->wait_dispatch = true;
1866 bfqd->rqs_injected = false;
1867 }
1868 }
1869
Paolo Valenteaee69d72017-04-19 08:29:02 -06001870 elv_rb_add(&bfqq->sort_list, rq);
1871
1872 /*
1873 * Check if this request is a better next-serve candidate.
1874 */
1875 prev = bfqq->next_rq;
1876 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
1877 bfqq->next_rq = next_rq;
1878
Arianna Avanzini36eca892017-04-12 18:23:16 +02001879 /*
1880 * Adjust priority tree position, if next_rq changes.
Paolo Valente8cacc5a2019-03-12 09:59:30 +01001881 * See comments on bfq_pos_tree_add_move() for the unlikely().
Arianna Avanzini36eca892017-04-12 18:23:16 +02001882 */
Paolo Valente8cacc5a2019-03-12 09:59:30 +01001883 if (unlikely(!bfqd->nonrot_with_queueing && prev != bfqq->next_rq))
Arianna Avanzini36eca892017-04-12 18:23:16 +02001884 bfq_pos_tree_add_move(bfqd, bfqq);
1885
Paolo Valenteaee69d72017-04-19 08:29:02 -06001886 if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
Paolo Valente44e44a12017-04-12 18:23:12 +02001887 bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
1888 rq, &interactive);
1889 else {
1890 if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
1891 time_is_before_jiffies(
1892 bfqq->last_wr_start_finish +
1893 bfqd->bfq_wr_min_inter_arr_async)) {
1894 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1895 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1896
Paolo Valentecfd69712017-04-12 18:23:15 +02001897 bfqd->wr_busy_queues++;
Paolo Valente44e44a12017-04-12 18:23:12 +02001898 bfqq->entity.prio_changed = 1;
1899 }
1900 if (prev != bfqq->next_rq)
1901 bfq_updated_next_req(bfqd, bfqq);
1902 }
1903
1904 /*
1905 * Assign jiffies to last_wr_start_finish in the following
1906 * cases:
1907 *
1908 * . if bfqq is not going to be weight-raised, because, for
1909 * non weight-raised queues, last_wr_start_finish stores the
1910 * arrival time of the last request; as of now, this piece
1911 * of information is used only for deciding whether to
1912 * weight-raise async queues
1913 *
1914 * . if bfqq is not weight-raised, because, if bfqq is now
1915 * switching to weight-raised, then last_wr_start_finish
1916 * stores the time when weight-raising starts
1917 *
1918 * . if bfqq is interactive, because, regardless of whether
1919 * bfqq is currently weight-raised, the weight-raising
1920 * period must start or restart (this case is considered
1921 * separately because it is not detected by the above
1922 * conditions, if bfqq is already weight-raised)
Paolo Valente77b7dce2017-04-12 18:23:13 +02001923 *
1924 * last_wr_start_finish has to be updated also if bfqq is soft
1925 * real-time, because the weight-raising period is constantly
1926 * restarted on idle-to-busy transitions for these queues, but
1927 * this is already done in bfq_bfqq_handle_idle_busy_switch if
1928 * needed.
Paolo Valente44e44a12017-04-12 18:23:12 +02001929 */
1930 if (bfqd->low_latency &&
1931 (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
1932 bfqq->last_wr_start_finish = jiffies;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001933}
1934
1935static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
1936 struct bio *bio,
1937 struct request_queue *q)
1938{
1939 struct bfq_queue *bfqq = bfqd->bio_bfqq;
1940
1941
1942 if (bfqq)
1943 return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
1944
1945 return NULL;
1946}
1947
Paolo Valenteab0e43e2017-04-12 18:23:10 +02001948static sector_t get_sdist(sector_t last_pos, struct request *rq)
1949{
1950 if (last_pos)
1951 return abs(blk_rq_pos(rq) - last_pos);
1952
1953 return 0;
1954}
1955
Paolo Valenteaee69d72017-04-19 08:29:02 -06001956#if 0 /* Still not clear if we can do without next two functions */
1957static void bfq_activate_request(struct request_queue *q, struct request *rq)
1958{
1959 struct bfq_data *bfqd = q->elevator->elevator_data;
1960
1961 bfqd->rq_in_driver++;
Paolo Valenteaee69d72017-04-19 08:29:02 -06001962}
1963
1964static void bfq_deactivate_request(struct request_queue *q, struct request *rq)
1965{
1966 struct bfq_data *bfqd = q->elevator->elevator_data;
1967
1968 bfqd->rq_in_driver--;
1969}
1970#endif
1971
1972static void bfq_remove_request(struct request_queue *q,
1973 struct request *rq)
1974{
1975 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1976 struct bfq_data *bfqd = bfqq->bfqd;
1977 const int sync = rq_is_sync(rq);
1978
1979 if (bfqq->next_rq == rq) {
1980 bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
1981 bfq_updated_next_req(bfqd, bfqq);
1982 }
1983
1984 if (rq->queuelist.prev != &rq->queuelist)
1985 list_del_init(&rq->queuelist);
1986 bfqq->queued[sync]--;
1987 bfqd->queued--;
1988 elv_rb_del(&bfqq->sort_list, rq);
1989
1990 elv_rqhash_del(q, rq);
1991 if (q->last_merge == rq)
1992 q->last_merge = NULL;
1993
1994 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
1995 bfqq->next_rq = NULL;
1996
1997 if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02001998 bfq_del_bfqq_busy(bfqd, bfqq, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -06001999 /*
2000 * bfqq emptied. In normal operation, when
2001 * bfqq is empty, bfqq->entity.service and
2002 * bfqq->entity.budget must contain,
2003 * respectively, the service received and the
2004 * budget used last time bfqq emptied. These
2005 * facts do not hold in this case, as at least
2006 * this last removal occurred while bfqq is
2007 * not in service. To avoid inconsistencies,
2008 * reset both bfqq->entity.service and
2009 * bfqq->entity.budget, if bfqq has still a
2010 * process that may issue I/O requests to it.
2011 */
2012 bfqq->entity.budget = bfqq->entity.service = 0;
2013 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02002014
2015 /*
2016 * Remove queue from request-position tree as it is empty.
2017 */
2018 if (bfqq->pos_root) {
2019 rb_erase(&bfqq->pos_node, bfqq->pos_root);
2020 bfqq->pos_root = NULL;
2021 }
Paolo Valente05e90282017-12-20 12:38:31 +01002022 } else {
Paolo Valente8cacc5a2019-03-12 09:59:30 +01002023 /* see comments on bfq_pos_tree_add_move() for the unlikely() */
2024 if (unlikely(!bfqd->nonrot_with_queueing))
2025 bfq_pos_tree_add_move(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002026 }
2027
2028 if (rq->cmd_flags & REQ_META)
2029 bfqq->meta_pending--;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002030
Paolo Valenteaee69d72017-04-19 08:29:02 -06002031}
2032
Christoph Hellwig14ccb662019-06-06 12:29:01 +02002033static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio,
2034 unsigned int nr_segs)
Paolo Valenteaee69d72017-04-19 08:29:02 -06002035{
2036 struct request_queue *q = hctx->queue;
2037 struct bfq_data *bfqd = q->elevator->elevator_data;
2038 struct request *free = NULL;
2039 /*
2040 * bfq_bic_lookup grabs the queue_lock: invoke it now and
2041 * store its return value for later use, to avoid nesting
2042 * queue_lock inside the bfqd->lock. We assume that the bic
2043 * returned by bfq_bic_lookup does not go away before
2044 * bfqd->lock is taken.
2045 */
2046 struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q);
2047 bool ret;
2048
2049 spin_lock_irq(&bfqd->lock);
2050
2051 if (bic)
2052 bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf));
2053 else
2054 bfqd->bio_bfqq = NULL;
2055 bfqd->bio_bic = bic;
2056
Christoph Hellwig14ccb662019-06-06 12:29:01 +02002057 ret = blk_mq_sched_try_merge(q, bio, nr_segs, &free);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002058
2059 if (free)
2060 blk_mq_free_request(free);
2061 spin_unlock_irq(&bfqd->lock);
2062
2063 return ret;
2064}
2065
2066static int bfq_request_merge(struct request_queue *q, struct request **req,
2067 struct bio *bio)
2068{
2069 struct bfq_data *bfqd = q->elevator->elevator_data;
2070 struct request *__rq;
2071
2072 __rq = bfq_find_rq_fmerge(bfqd, bio, q);
2073 if (__rq && elv_bio_merge_ok(__rq, bio)) {
2074 *req = __rq;
2075 return ELEVATOR_FRONT_MERGE;
2076 }
2077
2078 return ELEVATOR_NO_MERGE;
2079}
2080
Paolo Valente18e5a572018-05-04 19:17:01 +02002081static struct bfq_queue *bfq_init_rq(struct request *rq);
2082
Paolo Valenteaee69d72017-04-19 08:29:02 -06002083static void bfq_request_merged(struct request_queue *q, struct request *req,
2084 enum elv_merge type)
2085{
2086 if (type == ELEVATOR_FRONT_MERGE &&
2087 rb_prev(&req->rb_node) &&
2088 blk_rq_pos(req) <
2089 blk_rq_pos(container_of(rb_prev(&req->rb_node),
2090 struct request, rb_node))) {
Paolo Valente18e5a572018-05-04 19:17:01 +02002091 struct bfq_queue *bfqq = bfq_init_rq(req);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002092 struct bfq_data *bfqd = bfqq->bfqd;
2093 struct request *prev, *next_rq;
2094
2095 /* Reposition request in its sort_list */
2096 elv_rb_del(&bfqq->sort_list, req);
2097 elv_rb_add(&bfqq->sort_list, req);
2098
2099 /* Choose next request to be served for bfqq */
2100 prev = bfqq->next_rq;
2101 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
2102 bfqd->last_position);
2103 bfqq->next_rq = next_rq;
2104 /*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002105 * If next_rq changes, update both the queue's budget to
2106 * fit the new request and the queue's position in its
2107 * rq_pos_tree.
Paolo Valenteaee69d72017-04-19 08:29:02 -06002108 */
Arianna Avanzini36eca892017-04-12 18:23:16 +02002109 if (prev != bfqq->next_rq) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002110 bfq_updated_next_req(bfqd, bfqq);
Paolo Valente8cacc5a2019-03-12 09:59:30 +01002111 /*
2112 * See comments on bfq_pos_tree_add_move() for
2113 * the unlikely().
2114 */
2115 if (unlikely(!bfqd->nonrot_with_queueing))
2116 bfq_pos_tree_add_move(bfqd, bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002117 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06002118 }
2119}
2120
Paolo Valente8abfa4d2018-05-31 08:48:05 -06002121/*
2122 * This function is called to notify the scheduler that the requests
2123 * rq and 'next' have been merged, with 'next' going away. BFQ
2124 * exploits this hook to address the following issue: if 'next' has a
2125 * fifo_time lower that rq, then the fifo_time of rq must be set to
2126 * the value of 'next', to not forget the greater age of 'next'.
Paolo Valente8abfa4d2018-05-31 08:48:05 -06002127 *
2128 * NOTE: in this function we assume that rq is in a bfq_queue, basing
2129 * on that rq is picked from the hash table q->elevator->hash, which,
2130 * in its turn, is filled only with I/O requests present in
2131 * bfq_queues, while BFQ is in use for the request queue q. In fact,
2132 * the function that fills this hash table (elv_rqhash_add) is called
2133 * only by bfq_insert_request.
2134 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06002135static void bfq_requests_merged(struct request_queue *q, struct request *rq,
2136 struct request *next)
2137{
Paolo Valente18e5a572018-05-04 19:17:01 +02002138 struct bfq_queue *bfqq = bfq_init_rq(rq),
2139 *next_bfqq = bfq_init_rq(next);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002140
Paolo Valenteaee69d72017-04-19 08:29:02 -06002141 /*
2142 * If next and rq belong to the same bfq_queue and next is older
2143 * than rq, then reposition rq in the fifo (by substituting next
2144 * with rq). Otherwise, if next and rq belong to different
2145 * bfq_queues, never reposition rq: in fact, we would have to
2146 * reposition it with respect to next's position in its own fifo,
2147 * which would most certainly be too expensive with respect to
2148 * the benefits.
2149 */
2150 if (bfqq == next_bfqq &&
2151 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
2152 next->fifo_time < rq->fifo_time) {
2153 list_del_init(&rq->queuelist);
2154 list_replace_init(&next->queuelist, &rq->queuelist);
2155 rq->fifo_time = next->fifo_time;
2156 }
2157
2158 if (bfqq->next_rq == next)
2159 bfqq->next_rq = rq;
2160
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002161 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002162}
2163
Paolo Valente44e44a12017-04-12 18:23:12 +02002164/* Must be called with bfqq != NULL */
2165static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
2166{
Paolo Valentecfd69712017-04-12 18:23:15 +02002167 if (bfq_bfqq_busy(bfqq))
2168 bfqq->bfqd->wr_busy_queues--;
Paolo Valente44e44a12017-04-12 18:23:12 +02002169 bfqq->wr_coeff = 1;
2170 bfqq->wr_cur_max_time = 0;
Paolo Valente77b7dce2017-04-12 18:23:13 +02002171 bfqq->last_wr_start_finish = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02002172 /*
2173 * Trigger a weight change on the next invocation of
2174 * __bfq_entity_update_weight_prio.
2175 */
2176 bfqq->entity.prio_changed = 1;
2177}
2178
Paolo Valenteea25da42017-04-19 08:48:24 -06002179void bfq_end_wr_async_queues(struct bfq_data *bfqd,
2180 struct bfq_group *bfqg)
Paolo Valente44e44a12017-04-12 18:23:12 +02002181{
2182 int i, j;
2183
2184 for (i = 0; i < 2; i++)
2185 for (j = 0; j < IOPRIO_BE_NR; j++)
2186 if (bfqg->async_bfqq[i][j])
2187 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
2188 if (bfqg->async_idle_bfqq)
2189 bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
2190}
2191
2192static void bfq_end_wr(struct bfq_data *bfqd)
2193{
2194 struct bfq_queue *bfqq;
2195
2196 spin_lock_irq(&bfqd->lock);
2197
2198 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
2199 bfq_bfqq_end_wr(bfqq);
2200 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
2201 bfq_bfqq_end_wr(bfqq);
2202 bfq_end_wr_async(bfqd);
2203
2204 spin_unlock_irq(&bfqd->lock);
2205}
2206
Arianna Avanzini36eca892017-04-12 18:23:16 +02002207static sector_t bfq_io_struct_pos(void *io_struct, bool request)
2208{
2209 if (request)
2210 return blk_rq_pos(io_struct);
2211 else
2212 return ((struct bio *)io_struct)->bi_iter.bi_sector;
2213}
2214
2215static int bfq_rq_close_to_sector(void *io_struct, bool request,
2216 sector_t sector)
2217{
2218 return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
2219 BFQQ_CLOSE_THR;
2220}
2221
2222static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
2223 struct bfq_queue *bfqq,
2224 sector_t sector)
2225{
2226 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
2227 struct rb_node *parent, *node;
2228 struct bfq_queue *__bfqq;
2229
2230 if (RB_EMPTY_ROOT(root))
2231 return NULL;
2232
2233 /*
2234 * First, if we find a request starting at the end of the last
2235 * request, choose it.
2236 */
2237 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
2238 if (__bfqq)
2239 return __bfqq;
2240
2241 /*
2242 * If the exact sector wasn't found, the parent of the NULL leaf
2243 * will contain the closest sector (rq_pos_tree sorted by
2244 * next_request position).
2245 */
2246 __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
2247 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2248 return __bfqq;
2249
2250 if (blk_rq_pos(__bfqq->next_rq) < sector)
2251 node = rb_next(&__bfqq->pos_node);
2252 else
2253 node = rb_prev(&__bfqq->pos_node);
2254 if (!node)
2255 return NULL;
2256
2257 __bfqq = rb_entry(node, struct bfq_queue, pos_node);
2258 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2259 return __bfqq;
2260
2261 return NULL;
2262}
2263
2264static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
2265 struct bfq_queue *cur_bfqq,
2266 sector_t sector)
2267{
2268 struct bfq_queue *bfqq;
2269
2270 /*
2271 * We shall notice if some of the queues are cooperating,
2272 * e.g., working closely on the same area of the device. In
2273 * that case, we can group them together and: 1) don't waste
2274 * time idling, and 2) serve the union of their requests in
2275 * the best possible order for throughput.
2276 */
2277 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
2278 if (!bfqq || bfqq == cur_bfqq)
2279 return NULL;
2280
2281 return bfqq;
2282}
2283
2284static struct bfq_queue *
2285bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2286{
2287 int process_refs, new_process_refs;
2288 struct bfq_queue *__bfqq;
2289
2290 /*
2291 * If there are no process references on the new_bfqq, then it is
2292 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
2293 * may have dropped their last reference (not just their last process
2294 * reference).
2295 */
2296 if (!bfqq_process_refs(new_bfqq))
2297 return NULL;
2298
2299 /* Avoid a circular list and skip interim queue merges. */
2300 while ((__bfqq = new_bfqq->new_bfqq)) {
2301 if (__bfqq == bfqq)
2302 return NULL;
2303 new_bfqq = __bfqq;
2304 }
2305
2306 process_refs = bfqq_process_refs(bfqq);
2307 new_process_refs = bfqq_process_refs(new_bfqq);
2308 /*
2309 * If the process for the bfqq has gone away, there is no
2310 * sense in merging the queues.
2311 */
2312 if (process_refs == 0 || new_process_refs == 0)
2313 return NULL;
2314
2315 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
2316 new_bfqq->pid);
2317
2318 /*
2319 * Merging is just a redirection: the requests of the process
2320 * owning one of the two queues are redirected to the other queue.
2321 * The latter queue, in its turn, is set as shared if this is the
2322 * first time that the requests of some process are redirected to
2323 * it.
2324 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002325 * We redirect bfqq to new_bfqq and not the opposite, because
2326 * we are in the context of the process owning bfqq, thus we
2327 * have the io_cq of this process. So we can immediately
2328 * configure this io_cq to redirect the requests of the
2329 * process to new_bfqq. In contrast, the io_cq of new_bfqq is
2330 * not available any more (new_bfqq->bic == NULL).
Arianna Avanzini36eca892017-04-12 18:23:16 +02002331 *
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02002332 * Anyway, even in case new_bfqq coincides with the in-service
2333 * queue, redirecting requests the in-service queue is the
2334 * best option, as we feed the in-service queue with new
2335 * requests close to the last request served and, by doing so,
2336 * are likely to increase the throughput.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002337 */
2338 bfqq->new_bfqq = new_bfqq;
2339 new_bfqq->ref += process_refs;
2340 return new_bfqq;
2341}
2342
2343static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
2344 struct bfq_queue *new_bfqq)
2345{
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002346 if (bfq_too_late_for_merging(new_bfqq))
2347 return false;
2348
Arianna Avanzini36eca892017-04-12 18:23:16 +02002349 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
2350 (bfqq->ioprio_class != new_bfqq->ioprio_class))
2351 return false;
2352
2353 /*
2354 * If either of the queues has already been detected as seeky,
2355 * then merging it with the other queue is unlikely to lead to
2356 * sequential I/O.
2357 */
2358 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
2359 return false;
2360
2361 /*
2362 * Interleaved I/O is known to be done by (some) applications
2363 * only for reads, so it does not make sense to merge async
2364 * queues.
2365 */
2366 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
2367 return false;
2368
2369 return true;
2370}
2371
2372/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002373 * Attempt to schedule a merge of bfqq with the currently in-service
2374 * queue or with a close queue among the scheduled queues. Return
2375 * NULL if no merge was scheduled, a pointer to the shared bfq_queue
2376 * structure otherwise.
2377 *
2378 * The OOM queue is not allowed to participate to cooperation: in fact, since
2379 * the requests temporarily redirected to the OOM queue could be redirected
2380 * again to dedicated queues at any time, the state needed to correctly
2381 * handle merging with the OOM queue would be quite complex and expensive
2382 * to maintain. Besides, in such a critical condition as an out of memory,
2383 * the benefits of queue merging may be little relevant, or even negligible.
2384 *
Arianna Avanzini36eca892017-04-12 18:23:16 +02002385 * WARNING: queue merging may impair fairness among non-weight raised
2386 * queues, for at least two reasons: 1) the original weight of a
2387 * merged queue may change during the merged state, 2) even being the
2388 * weight the same, a merged queue may be bloated with many more
2389 * requests than the ones produced by its originally-associated
2390 * process.
2391 */
2392static struct bfq_queue *
2393bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2394 void *io_struct, bool request)
2395{
2396 struct bfq_queue *in_service_bfqq, *new_bfqq;
2397
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002398 /*
Paolo Valente8cacc5a2019-03-12 09:59:30 +01002399 * Do not perform queue merging if the device is non
2400 * rotational and performs internal queueing. In fact, such a
2401 * device reaches a high speed through internal parallelism
2402 * and pipelining. This means that, to reach a high
2403 * throughput, it must have many requests enqueued at the same
2404 * time. But, in this configuration, the internal scheduling
2405 * algorithm of the device does exactly the job of queue
2406 * merging: it reorders requests so as to obtain as much as
2407 * possible a sequential I/O pattern. As a consequence, with
2408 * the workload generated by processes doing interleaved I/O,
2409 * the throughput reached by the device is likely to be the
2410 * same, with and without queue merging.
2411 *
2412 * Disabling merging also provides a remarkable benefit in
2413 * terms of throughput. Merging tends to make many workloads
2414 * artificially more uneven, because of shared queues
2415 * remaining non empty for incomparably more time than
2416 * non-merged queues. This may accentuate workload
2417 * asymmetries. For example, if one of the queues in a set of
2418 * merged queues has a higher weight than a normal queue, then
2419 * the shared queue may inherit such a high weight and, by
2420 * staying almost always active, may force BFQ to perform I/O
2421 * plugging most of the time. This evidently makes it harder
2422 * for BFQ to let the device reach a high throughput.
2423 *
2424 * Finally, the likely() macro below is not used because one
2425 * of the two branches is more likely than the other, but to
2426 * have the code path after the following if() executed as
2427 * fast as possible for the case of a non rotational device
2428 * with queueing. We want it because this is the fastest kind
2429 * of device. On the opposite end, the likely() may lengthen
2430 * the execution time of BFQ for the case of slower devices
2431 * (rotational or at least without queueing). But in this case
2432 * the execution time of BFQ matters very little, if not at
2433 * all.
2434 */
2435 if (likely(bfqd->nonrot_with_queueing))
2436 return NULL;
2437
2438 /*
Paolo Valente7b8fa3b2017-12-20 12:38:33 +01002439 * Prevent bfqq from being merged if it has been created too
2440 * long ago. The idea is that true cooperating processes, and
2441 * thus their associated bfq_queues, are supposed to be
2442 * created shortly after each other. This is the case, e.g.,
2443 * for KVM/QEMU and dump I/O threads. Basing on this
2444 * assumption, the following filtering greatly reduces the
2445 * probability that two non-cooperating processes, which just
2446 * happen to do close I/O for some short time interval, have
2447 * their queues merged by mistake.
2448 */
2449 if (bfq_too_late_for_merging(bfqq))
2450 return NULL;
2451
Arianna Avanzini36eca892017-04-12 18:23:16 +02002452 if (bfqq->new_bfqq)
2453 return bfqq->new_bfqq;
2454
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002455 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
Arianna Avanzini36eca892017-04-12 18:23:16 +02002456 return NULL;
2457
2458 /* If there is only one backlogged queue, don't search. */
Paolo Valente73d58112019-01-29 12:06:29 +01002459 if (bfq_tot_busy_queues(bfqd) == 1)
Arianna Avanzini36eca892017-04-12 18:23:16 +02002460 return NULL;
2461
2462 in_service_bfqq = bfqd->in_service_queue;
2463
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002464 if (in_service_bfqq && in_service_bfqq != bfqq &&
2465 likely(in_service_bfqq != &bfqd->oom_bfqq) &&
Paolo Valente058fdec2019-01-29 12:06:38 +01002466 bfq_rq_close_to_sector(io_struct, request,
2467 bfqd->in_serv_last_pos) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002468 bfqq->entity.parent == in_service_bfqq->entity.parent &&
2469 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
2470 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
2471 if (new_bfqq)
2472 return new_bfqq;
2473 }
2474 /*
2475 * Check whether there is a cooperator among currently scheduled
2476 * queues. The only thing we need is that the bio/request is not
2477 * NULL, as we need it to establish whether a cooperator exists.
2478 */
Arianna Avanzini36eca892017-04-12 18:23:16 +02002479 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
2480 bfq_io_struct_pos(io_struct, request));
2481
Angelo Ruocco4403e4e2017-12-20 12:38:34 +01002482 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
Arianna Avanzini36eca892017-04-12 18:23:16 +02002483 bfq_may_be_close_cooperator(bfqq, new_bfqq))
2484 return bfq_setup_merge(bfqq, new_bfqq);
2485
2486 return NULL;
2487}
2488
2489static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
2490{
2491 struct bfq_io_cq *bic = bfqq->bic;
2492
2493 /*
2494 * If !bfqq->bic, the queue is already shared or its requests
2495 * have already been redirected to a shared queue; both idle window
2496 * and weight raising state have already been saved. Do nothing.
2497 */
2498 if (!bic)
2499 return;
2500
Francesco Pollicinofffca082019-03-12 09:59:34 +01002501 bic->saved_weight = bfqq->entity.orig_weight;
Arianna Avanzini36eca892017-04-12 18:23:16 +02002502 bic->saved_ttime = bfqq->ttime;
Paolo Valented5be3fe2017-08-04 07:35:10 +02002503 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002504 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002505 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
2506 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
Paolo Valente894df932017-09-21 11:04:02 +02002507 if (unlikely(bfq_bfqq_just_created(bfqq) &&
Angelo Ruocco1be6e8a2017-12-20 12:38:32 +01002508 !bfq_bfqq_in_large_burst(bfqq) &&
2509 bfqq->bfqd->low_latency)) {
Paolo Valente894df932017-09-21 11:04:02 +02002510 /*
2511 * bfqq being merged right after being created: bfqq
2512 * would have deserved interactive weight raising, but
2513 * did not make it to be set in a weight-raised state,
2514 * because of this early merge. Store directly the
2515 * weight-raising state that would have been assigned
2516 * to bfqq, so that to avoid that bfqq unjustly fails
2517 * to enjoy weight raising if split soon.
2518 */
2519 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
2520 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd);
2521 bic->saved_last_wr_start_finish = jiffies;
2522 } else {
2523 bic->saved_wr_coeff = bfqq->wr_coeff;
2524 bic->saved_wr_start_at_switch_to_srt =
2525 bfqq->wr_start_at_switch_to_srt;
2526 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
2527 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
2528 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02002529}
2530
Arianna Avanzini36eca892017-04-12 18:23:16 +02002531static void
2532bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
2533 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2534{
2535 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
2536 (unsigned long)new_bfqq->pid);
2537 /* Save weight raising and idle window of the merged queues */
2538 bfq_bfqq_save_state(bfqq);
2539 bfq_bfqq_save_state(new_bfqq);
2540 if (bfq_bfqq_IO_bound(bfqq))
2541 bfq_mark_bfqq_IO_bound(new_bfqq);
2542 bfq_clear_bfqq_IO_bound(bfqq);
2543
2544 /*
2545 * If bfqq is weight-raised, then let new_bfqq inherit
2546 * weight-raising. To reduce false positives, neglect the case
2547 * where bfqq has just been created, but has not yet made it
2548 * to be weight-raised (which may happen because EQM may merge
2549 * bfqq even before bfq_add_request is executed for the first
Arianna Avanzinie1b23242017-04-12 18:23:20 +02002550 * time for bfqq). Handling this case would however be very
2551 * easy, thanks to the flag just_created.
Arianna Avanzini36eca892017-04-12 18:23:16 +02002552 */
2553 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
2554 new_bfqq->wr_coeff = bfqq->wr_coeff;
2555 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
2556 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
2557 new_bfqq->wr_start_at_switch_to_srt =
2558 bfqq->wr_start_at_switch_to_srt;
2559 if (bfq_bfqq_busy(new_bfqq))
2560 bfqd->wr_busy_queues++;
2561 new_bfqq->entity.prio_changed = 1;
2562 }
2563
2564 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
2565 bfqq->wr_coeff = 1;
2566 bfqq->entity.prio_changed = 1;
2567 if (bfq_bfqq_busy(bfqq))
2568 bfqd->wr_busy_queues--;
2569 }
2570
2571 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
2572 bfqd->wr_busy_queues);
2573
2574 /*
Arianna Avanzini36eca892017-04-12 18:23:16 +02002575 * Merge queues (that is, let bic redirect its requests to new_bfqq)
2576 */
2577 bic_set_bfqq(bic, new_bfqq, 1);
2578 bfq_mark_bfqq_coop(new_bfqq);
2579 /*
2580 * new_bfqq now belongs to at least two bics (it is a shared queue):
2581 * set new_bfqq->bic to NULL. bfqq either:
2582 * - does not belong to any bic any more, and hence bfqq->bic must
2583 * be set to NULL, or
2584 * - is a queue whose owning bics have already been redirected to a
2585 * different queue, hence the queue is destined to not belong to
2586 * any bic soon and bfqq->bic is already NULL (therefore the next
2587 * assignment causes no harm).
2588 */
2589 new_bfqq->bic = NULL;
Francesco Pollicino1e664132019-03-12 09:59:33 +01002590 /*
2591 * If the queue is shared, the pid is the pid of one of the associated
2592 * processes. Which pid depends on the exact sequence of merge events
2593 * the queue underwent. So printing such a pid is useless and confusing
2594 * because it reports a random pid between those of the associated
2595 * processes.
2596 * We mark such a queue with a pid -1, and then print SHARED instead of
2597 * a pid in logging messages.
2598 */
2599 new_bfqq->pid = -1;
Arianna Avanzini36eca892017-04-12 18:23:16 +02002600 bfqq->bic = NULL;
2601 /* release process reference to bfqq */
2602 bfq_put_queue(bfqq);
2603}
2604
Paolo Valenteaee69d72017-04-19 08:29:02 -06002605static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2606 struct bio *bio)
2607{
2608 struct bfq_data *bfqd = q->elevator->elevator_data;
2609 bool is_sync = op_is_sync(bio->bi_opf);
Arianna Avanzini36eca892017-04-12 18:23:16 +02002610 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002611
2612 /*
2613 * Disallow merge of a sync bio into an async request.
2614 */
2615 if (is_sync && !rq_is_sync(rq))
2616 return false;
2617
2618 /*
2619 * Lookup the bfqq that this bio will be queued with. Allow
2620 * merge only if rq is queued there.
2621 */
2622 if (!bfqq)
2623 return false;
2624
Arianna Avanzini36eca892017-04-12 18:23:16 +02002625 /*
2626 * We take advantage of this function to perform an early merge
2627 * of the queues of possible cooperating processes.
2628 */
2629 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
2630 if (new_bfqq) {
2631 /*
2632 * bic still points to bfqq, then it has not yet been
2633 * redirected to some other bfq_queue, and a queue
Angelo Ruocco636b8fe2019-04-08 17:35:34 +02002634 * merge between bfqq and new_bfqq can be safely
2635 * fulfilled, i.e., bic can be redirected to new_bfqq
Arianna Avanzini36eca892017-04-12 18:23:16 +02002636 * and bfqq can be put.
2637 */
2638 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
2639 new_bfqq);
2640 /*
2641 * If we get here, bio will be queued into new_queue,
2642 * so use new_bfqq to decide whether bio and rq can be
2643 * merged.
2644 */
2645 bfqq = new_bfqq;
2646
2647 /*
2648 * Change also bqfd->bio_bfqq, as
2649 * bfqd->bio_bic now points to new_bfqq, and
2650 * this function may be invoked again (and then may
2651 * use again bqfd->bio_bfqq).
2652 */
2653 bfqd->bio_bfqq = bfqq;
2654 }
2655
Paolo Valenteaee69d72017-04-19 08:29:02 -06002656 return bfqq == RQ_BFQQ(rq);
2657}
2658
Paolo Valente44e44a12017-04-12 18:23:12 +02002659/*
2660 * Set the maximum time for the in-service queue to consume its
2661 * budget. This prevents seeky processes from lowering the throughput.
2662 * In practice, a time-slice service scheme is used with seeky
2663 * processes.
2664 */
2665static void bfq_set_budget_timeout(struct bfq_data *bfqd,
2666 struct bfq_queue *bfqq)
2667{
Paolo Valente77b7dce2017-04-12 18:23:13 +02002668 unsigned int timeout_coeff;
2669
2670 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
2671 timeout_coeff = 1;
2672 else
2673 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
2674
Paolo Valente44e44a12017-04-12 18:23:12 +02002675 bfqd->last_budget_start = ktime_get();
2676
2677 bfqq->budget_timeout = jiffies +
Paolo Valente77b7dce2017-04-12 18:23:13 +02002678 bfqd->bfq_timeout * timeout_coeff;
Paolo Valente44e44a12017-04-12 18:23:12 +02002679}
2680
Paolo Valenteaee69d72017-04-19 08:29:02 -06002681static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
2682 struct bfq_queue *bfqq)
2683{
2684 if (bfqq) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06002685 bfq_clear_bfqq_fifo_expire(bfqq);
2686
2687 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
2688
Paolo Valente77b7dce2017-04-12 18:23:13 +02002689 if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
2690 bfqq->wr_coeff > 1 &&
2691 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
2692 time_is_before_jiffies(bfqq->budget_timeout)) {
2693 /*
2694 * For soft real-time queues, move the start
2695 * of the weight-raising period forward by the
2696 * time the queue has not received any
2697 * service. Otherwise, a relatively long
2698 * service delay is likely to cause the
2699 * weight-raising period of the queue to end,
2700 * because of the short duration of the
2701 * weight-raising period of a soft real-time
2702 * queue. It is worth noting that this move
2703 * is not so dangerous for the other queues,
2704 * because soft real-time queues are not
2705 * greedy.
2706 *
2707 * To not add a further variable, we use the
2708 * overloaded field budget_timeout to
2709 * determine for how long the queue has not
2710 * received service, i.e., how much time has
2711 * elapsed since the queue expired. However,
2712 * this is a little imprecise, because
2713 * budget_timeout is set to jiffies if bfqq
2714 * not only expires, but also remains with no
2715 * request.
2716 */
2717 if (time_after(bfqq->budget_timeout,
2718 bfqq->last_wr_start_finish))
2719 bfqq->last_wr_start_finish +=
2720 jiffies - bfqq->budget_timeout;
2721 else
2722 bfqq->last_wr_start_finish = jiffies;
2723 }
2724
Paolo Valente44e44a12017-04-12 18:23:12 +02002725 bfq_set_budget_timeout(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002726 bfq_log_bfqq(bfqd, bfqq,
2727 "set_in_service_queue, cur-budget = %d",
2728 bfqq->entity.budget);
2729 }
2730
2731 bfqd->in_service_queue = bfqq;
2732}
2733
2734/*
2735 * Get and set a new queue for service.
2736 */
2737static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
2738{
2739 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
2740
2741 __bfq_set_in_service_queue(bfqd, bfqq);
2742 return bfqq;
2743}
2744
Paolo Valenteaee69d72017-04-19 08:29:02 -06002745static void bfq_arm_slice_timer(struct bfq_data *bfqd)
2746{
2747 struct bfq_queue *bfqq = bfqd->in_service_queue;
Paolo Valenteaee69d72017-04-19 08:29:02 -06002748 u32 sl;
2749
Paolo Valenteaee69d72017-04-19 08:29:02 -06002750 bfq_mark_bfqq_wait_request(bfqq);
2751
2752 /*
2753 * We don't want to idle for seeks, but we do want to allow
2754 * fair distribution of slice time for a process doing back-to-back
2755 * seeks. So allow a little bit of time for him to submit a new rq.
2756 */
2757 sl = bfqd->bfq_slice_idle;
2758 /*
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002759 * Unless the queue is being weight-raised or the scenario is
2760 * asymmetric, grant only minimum idle time if the queue
2761 * is seeky. A long idling is preserved for a weight-raised
2762 * queue, or, more in general, in an asymmetric scenario,
2763 * because a long idling is needed for guaranteeing to a queue
2764 * its reserved share of the throughput (in particular, it is
2765 * needed if the queue has a higher weight than some other
2766 * queue).
Paolo Valenteaee69d72017-04-19 08:29:02 -06002767 */
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02002768 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
Paolo Valentefb53ac62019-03-12 09:59:28 +01002769 !bfq_asymmetric_scenario(bfqd, bfqq))
Paolo Valenteaee69d72017-04-19 08:29:02 -06002770 sl = min_t(u64, sl, BFQ_MIN_TT);
Paolo Valente778c02a2019-03-12 09:59:27 +01002771 else if (bfqq->wr_coeff > 1)
2772 sl = max_t(u32, sl, 20ULL * NSEC_PER_MSEC);
Paolo Valenteaee69d72017-04-19 08:29:02 -06002773
2774 bfqd->last_idling_start = ktime_get();
Paolo Valente2341d6622019-03-12 09:59:29 +01002775 bfqd->last_idling_start_jiffies = jiffies;
2776
Paolo Valenteaee69d72017-04-19 08:29:02 -06002777 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
2778 HRTIMER_MODE_REL);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02002779 bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06002780}
2781
2782/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002783 * In autotuning mode, max_budget is dynamically recomputed as the
2784 * amount of sectors transferred in timeout at the estimated peak
2785 * rate. This enables BFQ to utilize a full timeslice with a full
2786 * budget, even if the in-service queue is served at peak rate. And
2787 * this maximises throughput with sequential workloads.
2788 */
2789static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
2790{
2791 return (u64)bfqd->peak_rate * USEC_PER_MSEC *
2792 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
2793}
2794
Paolo Valente44e44a12017-04-12 18:23:12 +02002795/*
2796 * Update parameters related to throughput and responsiveness, as a
2797 * function of the estimated peak rate. See comments on
Paolo Valentee24f1c22018-05-31 16:45:06 +02002798 * bfq_calc_max_budget(), and on the ref_wr_duration array.
Paolo Valente44e44a12017-04-12 18:23:12 +02002799 */
2800static void update_thr_responsiveness_params(struct bfq_data *bfqd)
2801{
Paolo Valentee24f1c22018-05-31 16:45:06 +02002802 if (bfqd->bfq_user_max_budget == 0) {
Paolo Valente44e44a12017-04-12 18:23:12 +02002803 bfqd->bfq_max_budget =
2804 bfq_calc_max_budget(bfqd);
Paolo Valentee24f1c22018-05-31 16:45:06 +02002805 bfq_log(bfqd, "new max_budget = %d", bfqd->bfq_max_budget);
Paolo Valente44e44a12017-04-12 18:23:12 +02002806 }
Paolo Valente44e44a12017-04-12 18:23:12 +02002807}
2808
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002809static void bfq_reset_rate_computation(struct bfq_data *bfqd,
2810 struct request *rq)
2811{
2812 if (rq != NULL) { /* new rq dispatch now, reset accordingly */
2813 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
2814 bfqd->peak_rate_samples = 1;
2815 bfqd->sequential_samples = 0;
2816 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
2817 blk_rq_sectors(rq);
2818 } else /* no new rq dispatched, just reset the number of samples */
2819 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
2820
2821 bfq_log(bfqd,
2822 "reset_rate_computation at end, sample %u/%u tot_sects %llu",
2823 bfqd->peak_rate_samples, bfqd->sequential_samples,
2824 bfqd->tot_sectors_dispatched);
2825}
2826
2827static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
2828{
2829 u32 rate, weight, divisor;
2830
2831 /*
2832 * For the convergence property to hold (see comments on
2833 * bfq_update_peak_rate()) and for the assessment to be
2834 * reliable, a minimum number of samples must be present, and
2835 * a minimum amount of time must have elapsed. If not so, do
2836 * not compute new rate. Just reset parameters, to get ready
2837 * for a new evaluation attempt.
2838 */
2839 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
2840 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
2841 goto reset_computation;
2842
2843 /*
2844 * If a new request completion has occurred after last
2845 * dispatch, then, to approximate the rate at which requests
2846 * have been served by the device, it is more precise to
2847 * extend the observation interval to the last completion.
2848 */
2849 bfqd->delta_from_first =
2850 max_t(u64, bfqd->delta_from_first,
2851 bfqd->last_completion - bfqd->first_dispatch);
2852
2853 /*
2854 * Rate computed in sects/usec, and not sects/nsec, for
2855 * precision issues.
2856 */
2857 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
2858 div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
2859
2860 /*
2861 * Peak rate not updated if:
2862 * - the percentage of sequential dispatches is below 3/4 of the
2863 * total, and rate is below the current estimated peak rate
2864 * - rate is unreasonably high (> 20M sectors/sec)
2865 */
2866 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
2867 rate <= bfqd->peak_rate) ||
2868 rate > 20<<BFQ_RATE_SHIFT)
2869 goto reset_computation;
2870
2871 /*
2872 * We have to update the peak rate, at last! To this purpose,
2873 * we use a low-pass filter. We compute the smoothing constant
2874 * of the filter as a function of the 'weight' of the new
2875 * measured rate.
2876 *
2877 * As can be seen in next formulas, we define this weight as a
2878 * quantity proportional to how sequential the workload is,
2879 * and to how long the observation time interval is.
2880 *
2881 * The weight runs from 0 to 8. The maximum value of the
2882 * weight, 8, yields the minimum value for the smoothing
2883 * constant. At this minimum value for the smoothing constant,
2884 * the measured rate contributes for half of the next value of
2885 * the estimated peak rate.
2886 *
2887 * So, the first step is to compute the weight as a function
2888 * of how sequential the workload is. Note that the weight
2889 * cannot reach 9, because bfqd->sequential_samples cannot
2890 * become equal to bfqd->peak_rate_samples, which, in its
2891 * turn, holds true because bfqd->sequential_samples is not
2892 * incremented for the first sample.
2893 */
2894 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
2895
2896 /*
2897 * Second step: further refine the weight as a function of the
2898 * duration of the observation interval.
2899 */
2900 weight = min_t(u32, 8,
2901 div_u64(weight * bfqd->delta_from_first,
2902 BFQ_RATE_REF_INTERVAL));
2903
2904 /*
2905 * Divisor ranging from 10, for minimum weight, to 2, for
2906 * maximum weight.
2907 */
2908 divisor = 10 - weight;
2909
2910 /*
2911 * Finally, update peak rate:
2912 *
2913 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
2914 */
2915 bfqd->peak_rate *= divisor-1;
2916 bfqd->peak_rate /= divisor;
2917 rate /= divisor; /* smoothing constant alpha = 1/divisor */
2918
2919 bfqd->peak_rate += rate;
Paolo Valentebc56e2c2018-03-26 16:06:24 +02002920
2921 /*
2922 * For a very slow device, bfqd->peak_rate can reach 0 (see
2923 * the minimum representable values reported in the comments
2924 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
2925 * divisions by zero where bfqd->peak_rate is used as a
2926 * divisor.
2927 */
2928 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
2929
Paolo Valente44e44a12017-04-12 18:23:12 +02002930 update_thr_responsiveness_params(bfqd);
Paolo Valenteab0e43e2017-04-12 18:23:10 +02002931
2932reset_computation:
2933 bfq_reset_rate_computation(bfqd, rq);
2934}
2935
2936/*
2937 * Update the read/write peak rate (the main quantity used for
2938 * auto-tuning, see update_thr_responsiveness_params()).
2939 *
2940 * It is not trivial to estimate the peak rate (correctly): because of
2941 * the presence of sw and hw queues between the scheduler and the
2942 * device components that finally serve I/O requests, it is hard to
2943 * say exactly when a given dispatched request is served inside the
2944 * device, and for how long. As a consequence, it is hard to know
2945 * precisely at what rate a given set of requests is actually served
2946 * by the device.
2947 *
2948 * On the opposite end, the dispatch time of any request is trivially
2949 * available, and, from this piece of information, the "dispatch rate"
2950 * of requests can be immediately computed. So, the idea in the next
2951 * function is to use what is known, namely request dispatch times
2952 * (plus, when useful, request completion times), to estimate what is
2953 * unknown, namely in-device request service rate.
2954 *
2955 * The main issue is that, because of the above facts, the rate at
2956 * which a certain set of requests is dispatched over a certain time
2957 * interval can vary greatly with respect to the rate at which the
2958 * same requests are then served. But, since the size of any
2959 * intermediate queue is limited, and the service scheme is lossless
2960 * (no request is silently dropped), the following obvious convergence
2961 * property holds: the number of requests dispatched MUST become
2962 * closer and closer to the number of requests completed as the
2963 * observation interval grows. This is the key property used in
2964 * the next function to estimate the peak service rate as a function
2965 * of the observed dispatch rate. The function assumes to be invoked
2966 * on every request dispatch.
2967 */
2968static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
2969{
2970 u64 now_ns = ktime_get_ns();
2971
2972 if (bfqd->peak_rate_samples == 0) { /* first dispatch */
2973 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
2974 bfqd->peak_rate_samples);
2975 bfq_reset_rate_computation(bfqd, rq);
2976 goto update_last_values; /* will add one sample */
2977 }
2978
2979 /*
2980 * Device idle for very long: the observation interval lasting
2981 * up to this dispatch cannot be a valid observation interval
2982 * for computing a new peak rate (similarly to the late-
2983 * completion event in bfq_completed_request()). Go to
2984 * update_rate_and_reset to have the following three steps
2985 * taken:
2986 * - close the observation interval at the last (previous)
2987 * request dispatch or completion
2988 * - compute rate, if possible, for that observation interval
2989 * - start a new observation interval with this dispatch
2990 */
2991 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
2992 bfqd->rq_in_driver == 0)
2993 goto update_rate_and_reset;
2994
2995 /* Update sampling information */
2996 bfqd->peak_rate_samples++;
2997
2998 if ((bfqd->rq_in_driver > 0 ||
2999 now_ns - bfqd->last_completion < BFQ_MIN_TT)
Paolo Valented87447d2019-01-29 12:06:33 +01003000 && !BFQ_RQ_SEEKY(bfqd, bfqd->last_position, rq))
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003001 bfqd->sequential_samples++;
3002
3003 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
3004
3005 /* Reset max observed rq size every 32 dispatches */
3006 if (likely(bfqd->peak_rate_samples % 32))
3007 bfqd->last_rq_max_size =
3008 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
3009 else
3010 bfqd->last_rq_max_size = blk_rq_sectors(rq);
3011
3012 bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
3013
3014 /* Target observation interval not yet reached, go on sampling */
3015 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
3016 goto update_last_values;
3017
3018update_rate_and_reset:
3019 bfq_update_rate_reset(bfqd, rq);
3020update_last_values:
3021 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
Paolo Valente058fdec2019-01-29 12:06:38 +01003022 if (RQ_BFQQ(rq) == bfqd->in_service_queue)
3023 bfqd->in_serv_last_pos = bfqd->last_position;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003024 bfqd->last_dispatch = now_ns;
3025}
3026
3027/*
Paolo Valenteaee69d72017-04-19 08:29:02 -06003028 * Remove request from internal lists.
3029 */
3030static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
3031{
3032 struct bfq_queue *bfqq = RQ_BFQQ(rq);
3033
3034 /*
3035 * For consistency, the next instruction should have been
3036 * executed after removing the request from the queue and
3037 * dispatching it. We execute instead this instruction before
3038 * bfq_remove_request() (and hence introduce a temporary
3039 * inconsistency), for efficiency. In fact, should this
3040 * dispatch occur for a non in-service bfqq, this anticipated
3041 * increment prevents two counters related to bfqq->dispatched
3042 * from risking to be, first, uselessly decremented, and then
3043 * incremented again when the (new) value of bfqq->dispatched
3044 * happens to be taken into account.
3045 */
3046 bfqq->dispatched++;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003047 bfq_update_peak_rate(q->elevator->elevator_data, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003048
3049 bfq_remove_request(q, rq);
3050}
3051
Paolo Valenteeed47d12019-04-10 10:38:33 +02003052static bool __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003053{
Arianna Avanzini36eca892017-04-12 18:23:16 +02003054 /*
3055 * If this bfqq is shared between multiple processes, check
3056 * to make sure that those processes are still issuing I/Os
3057 * within the mean seek distance. If not, it may be time to
3058 * break the queues apart again.
3059 */
3060 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
3061 bfq_mark_bfqq_split_coop(bfqq);
3062
Paolo Valente44e44a12017-04-12 18:23:12 +02003063 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
3064 if (bfqq->dispatched == 0)
3065 /*
3066 * Overloading budget_timeout field to store
3067 * the time at which the queue remains with no
3068 * backlog and no outstanding request; used by
3069 * the weight-raising mechanism.
3070 */
3071 bfqq->budget_timeout = jiffies;
3072
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003073 bfq_del_bfqq_busy(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02003074 } else {
Paolo Valente80294c32017-08-31 08:46:29 +02003075 bfq_requeue_bfqq(bfqd, bfqq, true);
Arianna Avanzini36eca892017-04-12 18:23:16 +02003076 /*
3077 * Resort priority tree of potential close cooperators.
Paolo Valente8cacc5a2019-03-12 09:59:30 +01003078 * See comments on bfq_pos_tree_add_move() for the unlikely().
Arianna Avanzini36eca892017-04-12 18:23:16 +02003079 */
Paolo Valente8cacc5a2019-03-12 09:59:30 +01003080 if (unlikely(!bfqd->nonrot_with_queueing))
3081 bfq_pos_tree_add_move(bfqd, bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02003082 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003083
3084 /*
3085 * All in-service entities must have been properly deactivated
3086 * or requeued before executing the next function, which
Paolo Valenteeed47d12019-04-10 10:38:33 +02003087 * resets all in-service entities as no more in service. This
3088 * may cause bfqq to be freed. If this happens, the next
3089 * function returns true.
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02003090 */
Paolo Valenteeed47d12019-04-10 10:38:33 +02003091 return __bfq_bfqd_reset_in_service(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003092}
3093
3094/**
3095 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
3096 * @bfqd: device data.
3097 * @bfqq: queue to update.
3098 * @reason: reason for expiration.
3099 *
3100 * Handle the feedback on @bfqq budget at queue expiration.
3101 * See the body for detailed comments.
3102 */
3103static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
3104 struct bfq_queue *bfqq,
3105 enum bfqq_expiration reason)
3106{
3107 struct request *next_rq;
3108 int budget, min_budget;
3109
Paolo Valenteaee69d72017-04-19 08:29:02 -06003110 min_budget = bfq_min_budget(bfqd);
3111
Paolo Valente44e44a12017-04-12 18:23:12 +02003112 if (bfqq->wr_coeff == 1)
3113 budget = bfqq->max_budget;
3114 else /*
3115 * Use a constant, low budget for weight-raised queues,
3116 * to help achieve a low latency. Keep it slightly higher
3117 * than the minimum possible budget, to cause a little
3118 * bit fewer expirations.
3119 */
3120 budget = 2 * min_budget;
3121
Paolo Valenteaee69d72017-04-19 08:29:02 -06003122 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
3123 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
3124 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
3125 budget, bfq_min_budget(bfqd));
3126 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
3127 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
3128
Paolo Valente44e44a12017-04-12 18:23:12 +02003129 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06003130 switch (reason) {
3131 /*
3132 * Caveat: in all the following cases we trade latency
3133 * for throughput.
3134 */
3135 case BFQQE_TOO_IDLE:
Paolo Valente54b60452017-04-12 18:23:09 +02003136 /*
3137 * This is the only case where we may reduce
3138 * the budget: if there is no request of the
3139 * process still waiting for completion, then
3140 * we assume (tentatively) that the timer has
3141 * expired because the batch of requests of
3142 * the process could have been served with a
3143 * smaller budget. Hence, betting that
3144 * process will behave in the same way when it
3145 * becomes backlogged again, we reduce its
3146 * next budget. As long as we guess right,
3147 * this budget cut reduces the latency
3148 * experienced by the process.
3149 *
3150 * However, if there are still outstanding
3151 * requests, then the process may have not yet
3152 * issued its next request just because it is
3153 * still waiting for the completion of some of
3154 * the still outstanding ones. So in this
3155 * subcase we do not reduce its budget, on the
3156 * contrary we increase it to possibly boost
3157 * the throughput, as discussed in the
3158 * comments to the BUDGET_TIMEOUT case.
3159 */
3160 if (bfqq->dispatched > 0) /* still outstanding reqs */
3161 budget = min(budget * 2, bfqd->bfq_max_budget);
3162 else {
3163 if (budget > 5 * min_budget)
3164 budget -= 4 * min_budget;
3165 else
3166 budget = min_budget;
3167 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06003168 break;
3169 case BFQQE_BUDGET_TIMEOUT:
Paolo Valente54b60452017-04-12 18:23:09 +02003170 /*
3171 * We double the budget here because it gives
3172 * the chance to boost the throughput if this
3173 * is not a seeky process (and has bumped into
3174 * this timeout because of, e.g., ZBR).
3175 */
3176 budget = min(budget * 2, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003177 break;
3178 case BFQQE_BUDGET_EXHAUSTED:
3179 /*
3180 * The process still has backlog, and did not
3181 * let either the budget timeout or the disk
3182 * idling timeout expire. Hence it is not
3183 * seeky, has a short thinktime and may be
3184 * happy with a higher budget too. So
3185 * definitely increase the budget of this good
3186 * candidate to boost the disk throughput.
3187 */
Paolo Valente54b60452017-04-12 18:23:09 +02003188 budget = min(budget * 4, bfqd->bfq_max_budget);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003189 break;
3190 case BFQQE_NO_MORE_REQUESTS:
3191 /*
3192 * For queues that expire for this reason, it
3193 * is particularly important to keep the
3194 * budget close to the actual service they
3195 * need. Doing so reduces the timestamp
3196 * misalignment problem described in the
3197 * comments in the body of
3198 * __bfq_activate_entity. In fact, suppose
3199 * that a queue systematically expires for
3200 * BFQQE_NO_MORE_REQUESTS and presents a
3201 * new request in time to enjoy timestamp
3202 * back-shifting. The larger the budget of the
3203 * queue is with respect to the service the
3204 * queue actually requests in each service
3205 * slot, the more times the queue can be
3206 * reactivated with the same virtual finish
3207 * time. It follows that, even if this finish
3208 * time is pushed to the system virtual time
3209 * to reduce the consequent timestamp
3210 * misalignment, the queue unjustly enjoys for
3211 * many re-activations a lower finish time
3212 * than all newly activated queues.
3213 *
3214 * The service needed by bfqq is measured
3215 * quite precisely by bfqq->entity.service.
3216 * Since bfqq does not enjoy device idling,
3217 * bfqq->entity.service is equal to the number
3218 * of sectors that the process associated with
3219 * bfqq requested to read/write before waiting
3220 * for request completions, or blocking for
3221 * other reasons.
3222 */
3223 budget = max_t(int, bfqq->entity.service, min_budget);
3224 break;
3225 default:
3226 return;
3227 }
Paolo Valente44e44a12017-04-12 18:23:12 +02003228 } else if (!bfq_bfqq_sync(bfqq)) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06003229 /*
3230 * Async queues get always the maximum possible
3231 * budget, as for them we do not care about latency
3232 * (in addition, their ability to dispatch is limited
3233 * by the charging factor).
3234 */
3235 budget = bfqd->bfq_max_budget;
3236 }
3237
3238 bfqq->max_budget = budget;
3239
3240 if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
3241 !bfqd->bfq_user_max_budget)
3242 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
3243
3244 /*
3245 * If there is still backlog, then assign a new budget, making
3246 * sure that it is large enough for the next request. Since
3247 * the finish time of bfqq must be kept in sync with the
3248 * budget, be sure to call __bfq_bfqq_expire() *after* this
3249 * update.
3250 *
3251 * If there is no backlog, then no need to update the budget;
3252 * it will be updated on the arrival of a new request.
3253 */
3254 next_rq = bfqq->next_rq;
3255 if (next_rq)
3256 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
3257 bfq_serv_to_charge(next_rq, bfqq));
3258
3259 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
3260 next_rq ? blk_rq_sectors(next_rq) : 0,
3261 bfqq->entity.budget);
3262}
3263
Paolo Valenteaee69d72017-04-19 08:29:02 -06003264/*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003265 * Return true if the process associated with bfqq is "slow". The slow
3266 * flag is used, in addition to the budget timeout, to reduce the
3267 * amount of service provided to seeky processes, and thus reduce
3268 * their chances to lower the throughput. More details in the comments
3269 * on the function bfq_bfqq_expire().
3270 *
3271 * An important observation is in order: as discussed in the comments
3272 * on the function bfq_update_peak_rate(), with devices with internal
3273 * queues, it is hard if ever possible to know when and for how long
3274 * an I/O request is processed by the device (apart from the trivial
3275 * I/O pattern where a new request is dispatched only after the
3276 * previous one has been completed). This makes it hard to evaluate
3277 * the real rate at which the I/O requests of each bfq_queue are
3278 * served. In fact, for an I/O scheduler like BFQ, serving a
3279 * bfq_queue means just dispatching its requests during its service
3280 * slot (i.e., until the budget of the queue is exhausted, or the
3281 * queue remains idle, or, finally, a timeout fires). But, during the
3282 * service slot of a bfq_queue, around 100 ms at most, the device may
3283 * be even still processing requests of bfq_queues served in previous
3284 * service slots. On the opposite end, the requests of the in-service
3285 * bfq_queue may be completed after the service slot of the queue
3286 * finishes.
3287 *
3288 * Anyway, unless more sophisticated solutions are used
3289 * (where possible), the sum of the sizes of the requests dispatched
3290 * during the service slot of a bfq_queue is probably the only
3291 * approximation available for the service received by the bfq_queue
3292 * during its service slot. And this sum is the quantity used in this
3293 * function to evaluate the I/O speed of a process.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003294 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003295static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
3296 bool compensate, enum bfqq_expiration reason,
3297 unsigned long *delta_ms)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003298{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003299 ktime_t delta_ktime;
3300 u32 delta_usecs;
3301 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
Paolo Valenteaee69d72017-04-19 08:29:02 -06003302
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003303 if (!bfq_bfqq_sync(bfqq))
Paolo Valenteaee69d72017-04-19 08:29:02 -06003304 return false;
3305
3306 if (compensate)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003307 delta_ktime = bfqd->last_idling_start;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003308 else
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003309 delta_ktime = ktime_get();
3310 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
3311 delta_usecs = ktime_to_us(delta_ktime);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003312
3313 /* don't use too short time intervals */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003314 if (delta_usecs < 1000) {
3315 if (blk_queue_nonrot(bfqd->queue))
3316 /*
3317 * give same worst-case guarantees as idling
3318 * for seeky
3319 */
3320 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
3321 else /* charge at least one seek */
3322 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003323
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003324 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003325 }
3326
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003327 *delta_ms = delta_usecs / USEC_PER_MSEC;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003328
3329 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003330 * Use only long (> 20ms) intervals to filter out excessive
3331 * spikes in service rate estimation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003332 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003333 if (delta_usecs > 20000) {
3334 /*
3335 * Caveat for rotational devices: processes doing I/O
3336 * in the slower disk zones tend to be slow(er) even
3337 * if not seeky. In this respect, the estimated peak
3338 * rate is likely to be an average over the disk
3339 * surface. Accordingly, to not be too harsh with
3340 * unlucky processes, a process is deemed slow only if
3341 * its rate has been lower than half of the estimated
3342 * peak rate.
3343 */
3344 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
3345 }
3346
3347 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
3348
3349 return slow;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003350}
3351
3352/*
Paolo Valente77b7dce2017-04-12 18:23:13 +02003353 * To be deemed as soft real-time, an application must meet two
3354 * requirements. First, the application must not require an average
3355 * bandwidth higher than the approximate bandwidth required to playback or
3356 * record a compressed high-definition video.
3357 * The next function is invoked on the completion of the last request of a
3358 * batch, to compute the next-start time instant, soft_rt_next_start, such
3359 * that, if the next request of the application does not arrive before
3360 * soft_rt_next_start, then the above requirement on the bandwidth is met.
3361 *
3362 * The second requirement is that the request pattern of the application is
3363 * isochronous, i.e., that, after issuing a request or a batch of requests,
3364 * the application stops issuing new requests until all its pending requests
3365 * have been completed. After that, the application may issue a new batch,
3366 * and so on.
3367 * For this reason the next function is invoked to compute
3368 * soft_rt_next_start only for applications that meet this requirement,
3369 * whereas soft_rt_next_start is set to infinity for applications that do
3370 * not.
3371 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003372 * Unfortunately, even a greedy (i.e., I/O-bound) application may
3373 * happen to meet, occasionally or systematically, both the above
3374 * bandwidth and isochrony requirements. This may happen at least in
3375 * the following circumstances. First, if the CPU load is high. The
3376 * application may stop issuing requests while the CPUs are busy
3377 * serving other processes, then restart, then stop again for a while,
3378 * and so on. The other circumstances are related to the storage
3379 * device: the storage device is highly loaded or reaches a low-enough
3380 * throughput with the I/O of the application (e.g., because the I/O
3381 * is random and/or the device is slow). In all these cases, the
3382 * I/O of the application may be simply slowed down enough to meet
3383 * the bandwidth and isochrony requirements. To reduce the probability
3384 * that greedy applications are deemed as soft real-time in these
3385 * corner cases, a further rule is used in the computation of
3386 * soft_rt_next_start: the return value of this function is forced to
3387 * be higher than the maximum between the following two quantities.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003388 *
Paolo Valentea34b0242017-12-15 07:23:12 +01003389 * (a) Current time plus: (1) the maximum time for which the arrival
3390 * of a request is waited for when a sync queue becomes idle,
3391 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
3392 * postpone for a moment the reason for adding a few extra
3393 * jiffies; we get back to it after next item (b). Lower-bounding
3394 * the return value of this function with the current time plus
3395 * bfqd->bfq_slice_idle tends to filter out greedy applications,
3396 * because the latter issue their next request as soon as possible
3397 * after the last one has been completed. In contrast, a soft
3398 * real-time application spends some time processing data, after a
3399 * batch of its requests has been completed.
3400 *
3401 * (b) Current value of bfqq->soft_rt_next_start. As pointed out
3402 * above, greedy applications may happen to meet both the
3403 * bandwidth and isochrony requirements under heavy CPU or
3404 * storage-device load. In more detail, in these scenarios, these
3405 * applications happen, only for limited time periods, to do I/O
3406 * slowly enough to meet all the requirements described so far,
3407 * including the filtering in above item (a). These slow-speed
3408 * time intervals are usually interspersed between other time
3409 * intervals during which these applications do I/O at a very high
3410 * speed. Fortunately, exactly because of the high speed of the
3411 * I/O in the high-speed intervals, the values returned by this
3412 * function happen to be so high, near the end of any such
3413 * high-speed interval, to be likely to fall *after* the end of
3414 * the low-speed time interval that follows. These high values are
3415 * stored in bfqq->soft_rt_next_start after each invocation of
3416 * this function. As a consequence, if the last value of
3417 * bfqq->soft_rt_next_start is constantly used to lower-bound the
3418 * next value that this function may return, then, from the very
3419 * beginning of a low-speed interval, bfqq->soft_rt_next_start is
3420 * likely to be constantly kept so high that any I/O request
3421 * issued during the low-speed interval is considered as arriving
3422 * to soon for the application to be deemed as soft
3423 * real-time. Then, in the high-speed interval that follows, the
3424 * application will not be deemed as soft real-time, just because
3425 * it will do I/O at a high speed. And so on.
3426 *
3427 * Getting back to the filtering in item (a), in the following two
3428 * cases this filtering might be easily passed by a greedy
3429 * application, if the reference quantity was just
3430 * bfqd->bfq_slice_idle:
3431 * 1) HZ is so low that the duration of a jiffy is comparable to or
3432 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
3433 * devices with HZ=100. The time granularity may be so coarse
3434 * that the approximation, in jiffies, of bfqd->bfq_slice_idle
3435 * is rather lower than the exact value.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003436 * 2) jiffies, instead of increasing at a constant rate, may stop increasing
3437 * for a while, then suddenly 'jump' by several units to recover the lost
3438 * increments. This seems to happen, e.g., inside virtual machines.
Paolo Valentea34b0242017-12-15 07:23:12 +01003439 * To address this issue, in the filtering in (a) we do not use as a
3440 * reference time interval just bfqd->bfq_slice_idle, but
3441 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
3442 * minimum number of jiffies for which the filter seems to be quite
3443 * precise also in embedded systems and KVM/QEMU virtual machines.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003444 */
3445static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
3446 struct bfq_queue *bfqq)
3447{
Paolo Valentea34b0242017-12-15 07:23:12 +01003448 return max3(bfqq->soft_rt_next_start,
3449 bfqq->last_idle_bklogged +
3450 HZ * bfqq->service_from_backlogged /
3451 bfqd->bfq_wr_max_softrt_rate,
3452 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
Paolo Valente77b7dce2017-04-12 18:23:13 +02003453}
3454
Paolo Valenteaee69d72017-04-19 08:29:02 -06003455/**
3456 * bfq_bfqq_expire - expire a queue.
3457 * @bfqd: device owning the queue.
3458 * @bfqq: the queue to expire.
3459 * @compensate: if true, compensate for the time spent idling.
3460 * @reason: the reason causing the expiration.
3461 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003462 * If the process associated with bfqq does slow I/O (e.g., because it
3463 * issues random requests), we charge bfqq with the time it has been
3464 * in service instead of the service it has received (see
3465 * bfq_bfqq_charge_time for details on how this goal is achieved). As
3466 * a consequence, bfqq will typically get higher timestamps upon
3467 * reactivation, and hence it will be rescheduled as if it had
3468 * received more service than what it has actually received. In the
3469 * end, bfqq receives less service in proportion to how slowly its
3470 * associated process consumes its budgets (and hence how seriously it
3471 * tends to lower the throughput). In addition, this time-charging
3472 * strategy guarantees time fairness among slow processes. In
3473 * contrast, if the process associated with bfqq is not slow, we
3474 * charge bfqq exactly with the service it has received.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003475 *
Paolo Valentec074170e2017-04-12 18:23:11 +02003476 * Charging time to the first type of queues and the exact service to
3477 * the other has the effect of using the WF2Q+ policy to schedule the
3478 * former on a timeslice basis, without violating service domain
3479 * guarantees among the latter.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003480 */
Paolo Valenteea25da42017-04-19 08:48:24 -06003481void bfq_bfqq_expire(struct bfq_data *bfqd,
3482 struct bfq_queue *bfqq,
3483 bool compensate,
3484 enum bfqq_expiration reason)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003485{
3486 bool slow;
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003487 unsigned long delta = 0;
3488 struct bfq_entity *entity = &bfqq->entity;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003489
3490 /*
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003491 * Check whether the process is slow (see bfq_bfqq_is_slow).
Paolo Valenteaee69d72017-04-19 08:29:02 -06003492 */
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003493 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003494
3495 /*
Paolo Valentec074170e2017-04-12 18:23:11 +02003496 * As above explained, charge slow (typically seeky) and
3497 * timed-out queues with the time and not the service
3498 * received, to favor sequential workloads.
3499 *
3500 * Processes doing I/O in the slower disk zones will tend to
3501 * be slow(er) even if not seeky. Therefore, since the
3502 * estimated peak rate is actually an average over the disk
3503 * surface, these processes may timeout just for bad luck. To
3504 * avoid punishing them, do not charge time to processes that
3505 * succeeded in consuming at least 2/3 of their budget. This
3506 * allows BFQ to preserve enough elasticity to still perform
3507 * bandwidth, and not time, distribution with little unlucky
3508 * or quasi-sequential processes.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003509 */
Paolo Valente44e44a12017-04-12 18:23:12 +02003510 if (bfqq->wr_coeff == 1 &&
3511 (slow ||
3512 (reason == BFQQE_BUDGET_TIMEOUT &&
3513 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
Paolo Valentec074170e2017-04-12 18:23:11 +02003514 bfq_bfqq_charge_time(bfqd, bfqq, delta);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003515
3516 if (reason == BFQQE_TOO_IDLE &&
Paolo Valenteab0e43e2017-04-12 18:23:10 +02003517 entity->service <= 2 * entity->budget / 10)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003518 bfq_clear_bfqq_IO_bound(bfqq);
3519
Paolo Valente44e44a12017-04-12 18:23:12 +02003520 if (bfqd->low_latency && bfqq->wr_coeff == 1)
3521 bfqq->last_wr_start_finish = jiffies;
3522
Paolo Valente77b7dce2017-04-12 18:23:13 +02003523 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
3524 RB_EMPTY_ROOT(&bfqq->sort_list)) {
3525 /*
3526 * If we get here, and there are no outstanding
3527 * requests, then the request pattern is isochronous
3528 * (see the comments on the function
3529 * bfq_bfqq_softrt_next_start()). Thus we can compute
Paolo Valente20cd3242019-01-29 12:06:25 +01003530 * soft_rt_next_start. And we do it, unless bfqq is in
3531 * interactive weight raising. We do not do it in the
3532 * latter subcase, for the following reason. bfqq may
3533 * be conveying the I/O needed to load a soft
3534 * real-time application. Such an application will
3535 * actually exhibit a soft real-time I/O pattern after
3536 * it finally starts doing its job. But, if
3537 * soft_rt_next_start is computed here for an
3538 * interactive bfqq, and bfqq had received a lot of
3539 * service before remaining with no outstanding
3540 * request (likely to happen on a fast device), then
3541 * soft_rt_next_start would be assigned such a high
3542 * value that, for a very long time, bfqq would be
3543 * prevented from being possibly considered as soft
3544 * real time.
3545 *
3546 * If, instead, the queue still has outstanding
3547 * requests, then we have to wait for the completion
3548 * of all the outstanding requests to discover whether
3549 * the request pattern is actually isochronous.
Paolo Valente77b7dce2017-04-12 18:23:13 +02003550 */
Paolo Valente20cd3242019-01-29 12:06:25 +01003551 if (bfqq->dispatched == 0 &&
3552 bfqq->wr_coeff != bfqd->bfq_wr_coeff)
Paolo Valente77b7dce2017-04-12 18:23:13 +02003553 bfqq->soft_rt_next_start =
3554 bfq_bfqq_softrt_next_start(bfqd, bfqq);
Paolo Valente20cd3242019-01-29 12:06:25 +01003555 else if (bfqq->dispatched > 0) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02003556 /*
Paolo Valente77b7dce2017-04-12 18:23:13 +02003557 * Schedule an update of soft_rt_next_start to when
3558 * the task may be discovered to be isochronous.
3559 */
3560 bfq_mark_bfqq_softrt_update(bfqq);
3561 }
3562 }
3563
Paolo Valenteaee69d72017-04-19 08:29:02 -06003564 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02003565 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
3566 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06003567
3568 /*
Paolo Valente2341d6622019-03-12 09:59:29 +01003569 * bfqq expired, so no total service time needs to be computed
3570 * any longer: reset state machine for measuring total service
3571 * times.
3572 */
3573 bfqd->rqs_injected = bfqd->wait_dispatch = false;
3574 bfqd->waited_rq = NULL;
3575
3576 /*
Paolo Valenteaee69d72017-04-19 08:29:02 -06003577 * Increase, decrease or leave budget unchanged according to
3578 * reason.
3579 */
3580 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
Paolo Valenteeed47d12019-04-10 10:38:33 +02003581 if (__bfq_bfqq_expire(bfqd, bfqq))
3582 /* bfqq is gone, no more actions on it */
Paolo Valente9fae8dd2018-06-25 21:55:36 +02003583 return;
3584
Paolo Valenteaee69d72017-04-19 08:29:02 -06003585 /* mark bfqq as waiting a request only if a bic still points to it */
Paolo Valente9fae8dd2018-06-25 21:55:36 +02003586 if (!bfq_bfqq_busy(bfqq) &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06003587 reason != BFQQE_BUDGET_TIMEOUT &&
Paolo Valente9fae8dd2018-06-25 21:55:36 +02003588 reason != BFQQE_BUDGET_EXHAUSTED) {
Paolo Valenteaee69d72017-04-19 08:29:02 -06003589 bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
Paolo Valente9fae8dd2018-06-25 21:55:36 +02003590 /*
3591 * Not setting service to 0, because, if the next rq
3592 * arrives in time, the queue will go on receiving
3593 * service with this same budget (as if it never expired)
3594 */
3595 } else
3596 entity->service = 0;
Paolo Valente8a511ba2018-08-16 18:51:15 +02003597
3598 /*
3599 * Reset the received-service counter for every parent entity.
3600 * Differently from what happens with bfqq->entity.service,
3601 * the resetting of this counter never needs to be postponed
3602 * for parent entities. In fact, in case bfqq may have a
3603 * chance to go on being served using the last, partially
3604 * consumed budget, bfqq->entity.service needs to be kept,
3605 * because if bfqq then actually goes on being served using
3606 * the same budget, the last value of bfqq->entity.service is
3607 * needed to properly decrement bfqq->entity.budget by the
3608 * portion already consumed. In contrast, it is not necessary
3609 * to keep entity->service for parent entities too, because
3610 * the bubble up of the new value of bfqq->entity.budget will
3611 * make sure that the budgets of parent entities are correct,
3612 * even in case bfqq and thus parent entities go on receiving
3613 * service with the same budget.
3614 */
3615 entity = entity->parent;
3616 for_each_entity(entity)
3617 entity->service = 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003618}
3619
3620/*
3621 * Budget timeout is not implemented through a dedicated timer, but
3622 * just checked on request arrivals and completions, as well as on
3623 * idle timer expirations.
3624 */
3625static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
3626{
Paolo Valente44e44a12017-04-12 18:23:12 +02003627 return time_is_before_eq_jiffies(bfqq->budget_timeout);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003628}
3629
3630/*
3631 * If we expire a queue that is actively waiting (i.e., with the
3632 * device idled) for the arrival of a new request, then we may incur
3633 * the timestamp misalignment problem described in the body of the
3634 * function __bfq_activate_entity. Hence we return true only if this
3635 * condition does not hold, or if the queue is slow enough to deserve
3636 * only to be kicked off for preserving a high throughput.
3637 */
3638static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
3639{
3640 bfq_log_bfqq(bfqq->bfqd, bfqq,
3641 "may_budget_timeout: wait_request %d left %d timeout %d",
3642 bfq_bfqq_wait_request(bfqq),
3643 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
3644 bfq_bfqq_budget_timeout(bfqq));
3645
3646 return (!bfq_bfqq_wait_request(bfqq) ||
3647 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
3648 &&
3649 bfq_bfqq_budget_timeout(bfqq);
3650}
3651
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003652static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd,
3653 struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06003654{
Paolo Valenteedaf9422017-08-04 07:35:11 +02003655 bool rot_without_queueing =
3656 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
3657 bfqq_sequential_and_IO_bound,
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003658 idling_boosts_thr;
Paolo Valented5be3fe2017-08-04 07:35:10 +02003659
Paolo Valenteedaf9422017-08-04 07:35:11 +02003660 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
3661 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
3662
Paolo Valented5be3fe2017-08-04 07:35:10 +02003663 /*
Paolo Valente44e44a12017-04-12 18:23:12 +02003664 * The next variable takes into account the cases where idling
3665 * boosts the throughput.
3666 *
Paolo Valentee01eff02017-04-12 18:23:19 +02003667 * The value of the variable is computed considering, first, that
3668 * idling is virtually always beneficial for the throughput if:
Paolo Valenteedaf9422017-08-04 07:35:11 +02003669 * (a) the device is not NCQ-capable and rotational, or
3670 * (b) regardless of the presence of NCQ, the device is rotational and
3671 * the request pattern for bfqq is I/O-bound and sequential, or
3672 * (c) regardless of whether it is rotational, the device is
3673 * not NCQ-capable and the request pattern for bfqq is
3674 * I/O-bound and sequential.
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003675 *
3676 * Secondly, and in contrast to the above item (b), idling an
3677 * NCQ-capable flash-based device would not boost the
Paolo Valentee01eff02017-04-12 18:23:19 +02003678 * throughput even with sequential I/O; rather it would lower
Paolo Valentebf2b79e2017-04-12 18:23:18 +02003679 * the throughput in proportion to how fast the device
3680 * is. Accordingly, the next variable is true if any of the
Paolo Valenteedaf9422017-08-04 07:35:11 +02003681 * above conditions (a), (b) or (c) is true, and, in
3682 * particular, happens to be false if bfqd is an NCQ-capable
3683 * flash-based device.
Paolo Valenteaee69d72017-04-19 08:29:02 -06003684 */
Paolo Valenteedaf9422017-08-04 07:35:11 +02003685 idling_boosts_thr = rot_without_queueing ||
3686 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
3687 bfqq_sequential_and_IO_bound);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003688
3689 /*
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003690 * The return value of this function is equal to that of
Paolo Valentecfd69712017-04-12 18:23:15 +02003691 * idling_boosts_thr, unless a special case holds. In this
3692 * special case, described below, idling may cause problems to
3693 * weight-raised queues.
3694 *
3695 * When the request pool is saturated (e.g., in the presence
3696 * of write hogs), if the processes associated with
3697 * non-weight-raised queues ask for requests at a lower rate,
3698 * then processes associated with weight-raised queues have a
3699 * higher probability to get a request from the pool
3700 * immediately (or at least soon) when they need one. Thus
3701 * they have a higher probability to actually get a fraction
3702 * of the device throughput proportional to their high
3703 * weight. This is especially true with NCQ-capable drives,
3704 * which enqueue several requests in advance, and further
3705 * reorder internally-queued requests.
3706 *
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003707 * For this reason, we force to false the return value if
3708 * there are weight-raised busy queues. In this case, and if
3709 * bfqq is not weight-raised, this guarantees that the device
3710 * is not idled for bfqq (if, instead, bfqq is weight-raised,
3711 * then idling will be guaranteed by another variable, see
3712 * below). Combined with the timestamping rules of BFQ (see
3713 * [1] for details), this behavior causes bfqq, and hence any
3714 * sync non-weight-raised queue, to get a lower number of
3715 * requests served, and thus to ask for a lower number of
3716 * requests from the request pool, before the busy
3717 * weight-raised queues get served again. This often mitigates
3718 * starvation problems in the presence of heavy write
3719 * workloads and NCQ, thereby guaranteeing a higher
3720 * application and system responsiveness in these hostile
3721 * scenarios.
Paolo Valentecfd69712017-04-12 18:23:15 +02003722 */
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003723 return idling_boosts_thr &&
Paolo Valentecfd69712017-04-12 18:23:15 +02003724 bfqd->wr_busy_queues == 0;
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003725}
Paolo Valentecfd69712017-04-12 18:23:15 +02003726
Paolo Valente530c4cb2019-01-29 12:06:32 +01003727/*
Paolo Valentefb53ac62019-03-12 09:59:28 +01003728 * There is a case where idling does not have to be performed for
3729 * throughput concerns, but to preserve the throughput share of
3730 * the process associated with bfqq.
Paolo Valente530c4cb2019-01-29 12:06:32 +01003731 *
3732 * To introduce this case, we can note that allowing the drive
3733 * to enqueue more than one request at a time, and hence
3734 * delegating de facto final scheduling decisions to the
3735 * drive's internal scheduler, entails loss of control on the
3736 * actual request service order. In particular, the critical
3737 * situation is when requests from different processes happen
3738 * to be present, at the same time, in the internal queue(s)
3739 * of the drive. In such a situation, the drive, by deciding
3740 * the service order of the internally-queued requests, does
3741 * determine also the actual throughput distribution among
3742 * these processes. But the drive typically has no notion or
3743 * concern about per-process throughput distribution, and
3744 * makes its decisions only on a per-request basis. Therefore,
3745 * the service distribution enforced by the drive's internal
Paolo Valentefb53ac62019-03-12 09:59:28 +01003746 * scheduler is likely to coincide with the desired throughput
3747 * distribution only in a completely symmetric, or favorably
3748 * skewed scenario where:
3749 * (i-a) each of these processes must get the same throughput as
3750 * the others,
3751 * (i-b) in case (i-a) does not hold, it holds that the process
3752 * associated with bfqq must receive a lower or equal
3753 * throughput than any of the other processes;
3754 * (ii) the I/O of each process has the same properties, in
3755 * terms of locality (sequential or random), direction
3756 * (reads or writes), request sizes, greediness
3757 * (from I/O-bound to sporadic), and so on;
3758
3759 * In fact, in such a scenario, the drive tends to treat the requests
3760 * of each process in about the same way as the requests of the
3761 * others, and thus to provide each of these processes with about the
3762 * same throughput. This is exactly the desired throughput
3763 * distribution if (i-a) holds, or, if (i-b) holds instead, this is an
3764 * even more convenient distribution for (the process associated with)
3765 * bfqq.
Paolo Valente530c4cb2019-01-29 12:06:32 +01003766 *
Paolo Valentefb53ac62019-03-12 09:59:28 +01003767 * In contrast, in any asymmetric or unfavorable scenario, device
3768 * idling (I/O-dispatch plugging) is certainly needed to guarantee
3769 * that bfqq receives its assigned fraction of the device throughput
3770 * (see [1] for details).
3771 *
3772 * The problem is that idling may significantly reduce throughput with
3773 * certain combinations of types of I/O and devices. An important
3774 * example is sync random I/O on flash storage with command
3775 * queueing. So, unless bfqq falls in cases where idling also boosts
3776 * throughput, it is important to check conditions (i-a), i(-b) and
3777 * (ii) accurately, so as to avoid idling when not strictly needed for
3778 * service guarantees.
3779 *
3780 * Unfortunately, it is extremely difficult to thoroughly check
3781 * condition (ii). And, in case there are active groups, it becomes
3782 * very difficult to check conditions (i-a) and (i-b) too. In fact,
3783 * if there are active groups, then, for conditions (i-a) or (i-b) to
3784 * become false 'indirectly', it is enough that an active group
3785 * contains more active processes or sub-groups than some other active
3786 * group. More precisely, for conditions (i-a) or (i-b) to become
3787 * false because of such a group, it is not even necessary that the
3788 * group is (still) active: it is sufficient that, even if the group
3789 * has become inactive, some of its descendant processes still have
3790 * some request already dispatched but still waiting for
3791 * completion. In fact, requests have still to be guaranteed their
3792 * share of the throughput even after being dispatched. In this
3793 * respect, it is easy to show that, if a group frequently becomes
3794 * inactive while still having in-flight requests, and if, when this
3795 * happens, the group is not considered in the calculation of whether
3796 * the scenario is asymmetric, then the group may fail to be
3797 * guaranteed its fair share of the throughput (basically because
3798 * idling may not be performed for the descendant processes of the
3799 * group, but it had to be). We address this issue with the following
3800 * bi-modal behavior, implemented in the function
3801 * bfq_asymmetric_scenario().
Paolo Valente530c4cb2019-01-29 12:06:32 +01003802 *
3803 * If there are groups with requests waiting for completion
3804 * (as commented above, some of these groups may even be
3805 * already inactive), then the scenario is tagged as
3806 * asymmetric, conservatively, without checking any of the
Paolo Valentefb53ac62019-03-12 09:59:28 +01003807 * conditions (i-a), (i-b) or (ii). So the device is idled for bfqq.
Paolo Valente530c4cb2019-01-29 12:06:32 +01003808 * This behavior matches also the fact that groups are created
3809 * exactly if controlling I/O is a primary concern (to
3810 * preserve bandwidth and latency guarantees).
3811 *
Paolo Valentefb53ac62019-03-12 09:59:28 +01003812 * On the opposite end, if there are no groups with requests waiting
3813 * for completion, then only conditions (i-a) and (i-b) are actually
3814 * controlled, i.e., provided that conditions (i-a) or (i-b) holds,
3815 * idling is not performed, regardless of whether condition (ii)
3816 * holds. In other words, only if conditions (i-a) and (i-b) do not
3817 * hold, then idling is allowed, and the device tends to be prevented
3818 * from queueing many requests, possibly of several processes. Since
3819 * there are no groups with requests waiting for completion, then, to
3820 * control conditions (i-a) and (i-b) it is enough to check just
3821 * whether all the queues with requests waiting for completion also
3822 * have the same weight.
Paolo Valente530c4cb2019-01-29 12:06:32 +01003823 *
3824 * Not checking condition (ii) evidently exposes bfqq to the
3825 * risk of getting less throughput than its fair share.
3826 * However, for queues with the same weight, a further
3827 * mechanism, preemption, mitigates or even eliminates this
3828 * problem. And it does so without consequences on overall
3829 * throughput. This mechanism and its benefits are explained
3830 * in the next three paragraphs.
3831 *
3832 * Even if a queue, say Q, is expired when it remains idle, Q
3833 * can still preempt the new in-service queue if the next
3834 * request of Q arrives soon (see the comments on
3835 * bfq_bfqq_update_budg_for_activation). If all queues and
3836 * groups have the same weight, this form of preemption,
3837 * combined with the hole-recovery heuristic described in the
3838 * comments on function bfq_bfqq_update_budg_for_activation,
3839 * are enough to preserve a correct bandwidth distribution in
3840 * the mid term, even without idling. In fact, even if not
3841 * idling allows the internal queues of the device to contain
3842 * many requests, and thus to reorder requests, we can rather
3843 * safely assume that the internal scheduler still preserves a
3844 * minimum of mid-term fairness.
3845 *
3846 * More precisely, this preemption-based, idleless approach
3847 * provides fairness in terms of IOPS, and not sectors per
3848 * second. This can be seen with a simple example. Suppose
3849 * that there are two queues with the same weight, but that
3850 * the first queue receives requests of 8 sectors, while the
3851 * second queue receives requests of 1024 sectors. In
3852 * addition, suppose that each of the two queues contains at
3853 * most one request at a time, which implies that each queue
3854 * always remains idle after it is served. Finally, after
3855 * remaining idle, each queue receives very quickly a new
3856 * request. It follows that the two queues are served
3857 * alternatively, preempting each other if needed. This
3858 * implies that, although both queues have the same weight,
3859 * the queue with large requests receives a service that is
3860 * 1024/8 times as high as the service received by the other
3861 * queue.
3862 *
3863 * The motivation for using preemption instead of idling (for
3864 * queues with the same weight) is that, by not idling,
3865 * service guarantees are preserved (completely or at least in
3866 * part) without minimally sacrificing throughput. And, if
3867 * there is no active group, then the primary expectation for
3868 * this device is probably a high throughput.
3869 *
3870 * We are now left only with explaining the additional
3871 * compound condition that is checked below for deciding
3872 * whether the scenario is asymmetric. To explain this
3873 * compound condition, we need to add that the function
Paolo Valentefb53ac62019-03-12 09:59:28 +01003874 * bfq_asymmetric_scenario checks the weights of only
Paolo Valente530c4cb2019-01-29 12:06:32 +01003875 * non-weight-raised queues, for efficiency reasons (see
3876 * comments on bfq_weights_tree_add()). Then the fact that
3877 * bfqq is weight-raised is checked explicitly here. More
3878 * precisely, the compound condition below takes into account
3879 * also the fact that, even if bfqq is being weight-raised,
3880 * the scenario is still symmetric if all queues with requests
3881 * waiting for completion happen to be
3882 * weight-raised. Actually, we should be even more precise
3883 * here, and differentiate between interactive weight raising
3884 * and soft real-time weight raising.
3885 *
3886 * As a side note, it is worth considering that the above
3887 * device-idling countermeasures may however fail in the
3888 * following unlucky scenario: if idling is (correctly)
3889 * disabled in a time period during which all symmetry
3890 * sub-conditions hold, and hence the device is allowed to
3891 * enqueue many requests, but at some later point in time some
3892 * sub-condition stops to hold, then it may become impossible
3893 * to let requests be served in the desired order until all
3894 * the requests already queued in the device have been served.
3895 */
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003896static bool idling_needed_for_service_guarantees(struct bfq_data *bfqd,
3897 struct bfq_queue *bfqq)
3898{
Paolo Valente530c4cb2019-01-29 12:06:32 +01003899 return (bfqq->wr_coeff > 1 &&
3900 bfqd->wr_busy_queues <
3901 bfq_tot_busy_queues(bfqd)) ||
Paolo Valentefb53ac62019-03-12 09:59:28 +01003902 bfq_asymmetric_scenario(bfqd, bfqq);
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003903}
3904
3905/*
3906 * For a queue that becomes empty, device idling is allowed only if
3907 * this function returns true for that queue. As a consequence, since
3908 * device idling plays a critical role for both throughput boosting
3909 * and service guarantees, the return value of this function plays a
3910 * critical role as well.
3911 *
3912 * In a nutshell, this function returns true only if idling is
3913 * beneficial for throughput or, even if detrimental for throughput,
3914 * idling is however necessary to preserve service guarantees (low
3915 * latency, desired throughput distribution, ...). In particular, on
3916 * NCQ-capable devices, this function tries to return false, so as to
3917 * help keep the drives' internal queues full, whenever this helps the
3918 * device boost the throughput without causing any service-guarantee
3919 * issue.
3920 *
3921 * Most of the issues taken into account to get the return value of
3922 * this function are not trivial. We discuss these issues in the two
3923 * functions providing the main pieces of information needed by this
3924 * function.
3925 */
3926static bool bfq_better_to_idle(struct bfq_queue *bfqq)
3927{
3928 struct bfq_data *bfqd = bfqq->bfqd;
3929 bool idling_boosts_thr_with_no_issue, idling_needed_for_service_guar;
3930
3931 if (unlikely(bfqd->strict_guarantees))
3932 return true;
Arianna Avanzinie1b23242017-04-12 18:23:20 +02003933
3934 /*
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003935 * Idling is performed only if slice_idle > 0. In addition, we
3936 * do not idle if
3937 * (a) bfqq is async
3938 * (b) bfqq is in the idle io prio class: in this case we do
3939 * not idle because we want to minimize the bandwidth that
3940 * queues in this class can steal to higher-priority queues
3941 */
3942 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
3943 bfq_class_idle(bfqq))
3944 return false;
3945
3946 idling_boosts_thr_with_no_issue =
3947 idling_boosts_thr_without_issues(bfqd, bfqq);
3948
3949 idling_needed_for_service_guar =
3950 idling_needed_for_service_guarantees(bfqd, bfqq);
3951
3952 /*
3953 * We have now the two components we need to compute the
Paolo Valented5be3fe2017-08-04 07:35:10 +02003954 * return value of the function, which is true only if idling
3955 * either boosts the throughput (without issues), or is
3956 * necessary to preserve service guarantees.
Paolo Valente44e44a12017-04-12 18:23:12 +02003957 */
Paolo Valente05c2f5c2019-01-29 12:06:30 +01003958 return idling_boosts_thr_with_no_issue ||
3959 idling_needed_for_service_guar;
Paolo Valenteaee69d72017-04-19 08:29:02 -06003960}
3961
3962/*
Paolo Valente277a4a92018-06-25 21:55:37 +02003963 * If the in-service queue is empty but the function bfq_better_to_idle
Paolo Valenteaee69d72017-04-19 08:29:02 -06003964 * returns true, then:
3965 * 1) the queue must remain in service and cannot be expired, and
3966 * 2) the device must be idled to wait for the possible arrival of a new
3967 * request for the queue.
Paolo Valente277a4a92018-06-25 21:55:37 +02003968 * See the comments on the function bfq_better_to_idle for the reasons
Paolo Valenteaee69d72017-04-19 08:29:02 -06003969 * why performing device idling is the best choice to boost the throughput
Paolo Valente277a4a92018-06-25 21:55:37 +02003970 * and preserve service guarantees when bfq_better_to_idle itself
Paolo Valenteaee69d72017-04-19 08:29:02 -06003971 * returns true.
3972 */
3973static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
3974{
Paolo Valente277a4a92018-06-25 21:55:37 +02003975 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_better_to_idle(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06003976}
3977
Paolo Valente2341d6622019-03-12 09:59:29 +01003978/*
3979 * This function chooses the queue from which to pick the next extra
3980 * I/O request to inject, if it finds a compatible queue. See the
3981 * comments on bfq_update_inject_limit() for details on the injection
3982 * mechanism, and for the definitions of the quantities mentioned
3983 * below.
3984 */
3985static struct bfq_queue *
3986bfq_choose_bfqq_for_injection(struct bfq_data *bfqd)
Paolo Valented0edc242018-09-14 16:23:08 +02003987{
Paolo Valente2341d6622019-03-12 09:59:29 +01003988 struct bfq_queue *bfqq, *in_serv_bfqq = bfqd->in_service_queue;
3989 unsigned int limit = in_serv_bfqq->inject_limit;
3990 /*
3991 * If
3992 * - bfqq is not weight-raised and therefore does not carry
3993 * time-critical I/O,
3994 * or
3995 * - regardless of whether bfqq is weight-raised, bfqq has
3996 * however a long think time, during which it can absorb the
3997 * effect of an appropriate number of extra I/O requests
3998 * from other queues (see bfq_update_inject_limit for
3999 * details on the computation of this number);
4000 * then injection can be performed without restrictions.
4001 */
4002 bool in_serv_always_inject = in_serv_bfqq->wr_coeff == 1 ||
4003 !bfq_bfqq_has_short_ttime(in_serv_bfqq);
Paolo Valented0edc242018-09-14 16:23:08 +02004004
4005 /*
Paolo Valente2341d6622019-03-12 09:59:29 +01004006 * If
4007 * - the baseline total service time could not be sampled yet,
4008 * so the inject limit happens to be still 0, and
4009 * - a lot of time has elapsed since the plugging of I/O
4010 * dispatching started, so drive speed is being wasted
4011 * significantly;
4012 * then temporarily raise inject limit to one request.
4013 */
4014 if (limit == 0 && in_serv_bfqq->last_serv_time_ns == 0 &&
4015 bfq_bfqq_wait_request(in_serv_bfqq) &&
4016 time_is_before_eq_jiffies(bfqd->last_idling_start_jiffies +
4017 bfqd->bfq_slice_idle)
4018 )
4019 limit = 1;
4020
4021 if (bfqd->rq_in_driver >= limit)
4022 return NULL;
4023
4024 /*
4025 * Linear search of the source queue for injection; but, with
4026 * a high probability, very few steps are needed to find a
4027 * candidate queue, i.e., a queue with enough budget left for
4028 * its next request. In fact:
Paolo Valented0edc242018-09-14 16:23:08 +02004029 * - BFQ dynamically updates the budget of every queue so as
4030 * to accommodate the expected backlog of the queue;
4031 * - if a queue gets all its requests dispatched as injected
4032 * service, then the queue is removed from the active list
Paolo Valente2341d6622019-03-12 09:59:29 +01004033 * (and re-added only if it gets new requests, but then it
4034 * is assigned again enough budget for its new backlog).
Paolo Valented0edc242018-09-14 16:23:08 +02004035 */
4036 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
4037 if (!RB_EMPTY_ROOT(&bfqq->sort_list) &&
Paolo Valente2341d6622019-03-12 09:59:29 +01004038 (in_serv_always_inject || bfqq->wr_coeff > 1) &&
Paolo Valented0edc242018-09-14 16:23:08 +02004039 bfq_serv_to_charge(bfqq->next_rq, bfqq) <=
Paolo Valente2341d6622019-03-12 09:59:29 +01004040 bfq_bfqq_budget_left(bfqq)) {
4041 /*
4042 * Allow for only one large in-flight request
4043 * on non-rotational devices, for the
4044 * following reason. On non-rotationl drives,
4045 * large requests take much longer than
4046 * smaller requests to be served. In addition,
4047 * the drive prefers to serve large requests
4048 * w.r.t. to small ones, if it can choose. So,
4049 * having more than one large requests queued
4050 * in the drive may easily make the next first
4051 * request of the in-service queue wait for so
4052 * long to break bfqq's service guarantees. On
4053 * the bright side, large requests let the
4054 * drive reach a very high throughput, even if
4055 * there is only one in-flight large request
4056 * at a time.
4057 */
4058 if (blk_queue_nonrot(bfqd->queue) &&
4059 blk_rq_sectors(bfqq->next_rq) >=
4060 BFQQ_SECT_THR_NONROT)
4061 limit = min_t(unsigned int, 1, limit);
4062 else
4063 limit = in_serv_bfqq->inject_limit;
4064
4065 if (bfqd->rq_in_driver < limit) {
4066 bfqd->rqs_injected = true;
4067 return bfqq;
4068 }
4069 }
Paolo Valented0edc242018-09-14 16:23:08 +02004070
4071 return NULL;
4072}
4073
Paolo Valenteaee69d72017-04-19 08:29:02 -06004074/*
4075 * Select a queue for service. If we have a current queue in service,
4076 * check whether to continue servicing it, or retrieve and set a new one.
4077 */
4078static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
4079{
4080 struct bfq_queue *bfqq;
4081 struct request *next_rq;
4082 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
4083
4084 bfqq = bfqd->in_service_queue;
4085 if (!bfqq)
4086 goto new_queue;
4087
4088 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
4089
Paolo Valente4420b092018-06-25 21:55:35 +02004090 /*
4091 * Do not expire bfqq for budget timeout if bfqq may be about
4092 * to enjoy device idling. The reason why, in this case, we
4093 * prevent bfqq from expiring is the same as in the comments
4094 * on the case where bfq_bfqq_must_idle() returns true, in
4095 * bfq_completed_request().
4096 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004097 if (bfq_may_expire_for_budg_timeout(bfqq) &&
Paolo Valenteaee69d72017-04-19 08:29:02 -06004098 !bfq_bfqq_must_idle(bfqq))
4099 goto expire;
4100
4101check_queue:
4102 /*
4103 * This loop is rarely executed more than once. Even when it
4104 * happens, it is much more convenient to re-execute this loop
4105 * than to return NULL and trigger a new dispatch to get a
4106 * request served.
4107 */
4108 next_rq = bfqq->next_rq;
4109 /*
4110 * If bfqq has requests queued and it has enough budget left to
4111 * serve them, keep the queue, otherwise expire it.
4112 */
4113 if (next_rq) {
4114 if (bfq_serv_to_charge(next_rq, bfqq) >
4115 bfq_bfqq_budget_left(bfqq)) {
4116 /*
4117 * Expire the queue for budget exhaustion,
4118 * which makes sure that the next budget is
4119 * enough to serve the next request, even if
4120 * it comes from the fifo expired path.
4121 */
4122 reason = BFQQE_BUDGET_EXHAUSTED;
4123 goto expire;
4124 } else {
4125 /*
4126 * The idle timer may be pending because we may
4127 * not disable disk idling even when a new request
4128 * arrives.
4129 */
4130 if (bfq_bfqq_wait_request(bfqq)) {
4131 /*
4132 * If we get here: 1) at least a new request
4133 * has arrived but we have not disabled the
4134 * timer because the request was too small,
4135 * 2) then the block layer has unplugged
4136 * the device, causing the dispatch to be
4137 * invoked.
4138 *
4139 * Since the device is unplugged, now the
4140 * requests are probably large enough to
4141 * provide a reasonable throughput.
4142 * So we disable idling.
4143 */
4144 bfq_clear_bfqq_wait_request(bfqq);
4145 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
4146 }
4147 goto keep_queue;
4148 }
4149 }
4150
4151 /*
4152 * No requests pending. However, if the in-service queue is idling
4153 * for a new request, or has requests waiting for a completion and
4154 * may idle after their completion, then keep it anyway.
Paolo Valented0edc242018-09-14 16:23:08 +02004155 *
Paolo Valente2341d6622019-03-12 09:59:29 +01004156 * Yet, inject service from other queues if it boosts
4157 * throughput and is possible.
Paolo Valenteaee69d72017-04-19 08:29:02 -06004158 */
4159 if (bfq_bfqq_wait_request(bfqq) ||
Paolo Valente277a4a92018-06-25 21:55:37 +02004160 (bfqq->dispatched != 0 && bfq_better_to_idle(bfqq))) {
Paolo Valente2341d6622019-03-12 09:59:29 +01004161 struct bfq_queue *async_bfqq =
4162 bfqq->bic && bfqq->bic->bfqq[0] &&
4163 bfq_bfqq_busy(bfqq->bic->bfqq[0]) ?
4164 bfqq->bic->bfqq[0] : NULL;
4165
4166 /*
4167 * If the process associated with bfqq has also async
4168 * I/O pending, then inject it
4169 * unconditionally. Injecting I/O from the same
4170 * process can cause no harm to the process. On the
4171 * contrary, it can only increase bandwidth and reduce
4172 * latency for the process.
4173 */
4174 if (async_bfqq &&
4175 icq_to_bic(async_bfqq->next_rq->elv.icq) == bfqq->bic &&
4176 bfq_serv_to_charge(async_bfqq->next_rq, async_bfqq) <=
4177 bfq_bfqq_budget_left(async_bfqq))
4178 bfqq = bfqq->bic->bfqq[0];
4179 else if (!idling_boosts_thr_without_issues(bfqd, bfqq) &&
4180 (bfqq->wr_coeff == 1 || bfqd->wr_busy_queues > 1 ||
4181 !bfq_bfqq_has_short_ttime(bfqq)))
Paolo Valented0edc242018-09-14 16:23:08 +02004182 bfqq = bfq_choose_bfqq_for_injection(bfqd);
4183 else
4184 bfqq = NULL;
4185
Paolo Valenteaee69d72017-04-19 08:29:02 -06004186 goto keep_queue;
4187 }
4188
4189 reason = BFQQE_NO_MORE_REQUESTS;
4190expire:
4191 bfq_bfqq_expire(bfqd, bfqq, false, reason);
4192new_queue:
4193 bfqq = bfq_set_in_service_queue(bfqd);
4194 if (bfqq) {
4195 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
4196 goto check_queue;
4197 }
4198keep_queue:
4199 if (bfqq)
4200 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
4201 else
4202 bfq_log(bfqd, "select_queue: no queue returned");
4203
4204 return bfqq;
4205}
4206
Paolo Valente44e44a12017-04-12 18:23:12 +02004207static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4208{
4209 struct bfq_entity *entity = &bfqq->entity;
4210
4211 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
4212 bfq_log_bfqq(bfqd, bfqq,
4213 "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
4214 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
4215 jiffies_to_msecs(bfqq->wr_cur_max_time),
4216 bfqq->wr_coeff,
4217 bfqq->entity.weight, bfqq->entity.orig_weight);
4218
4219 if (entity->prio_changed)
4220 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
4221
4222 /*
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004223 * If the queue was activated in a burst, or too much
4224 * time has elapsed from the beginning of this
4225 * weight-raising period, then end weight raising.
Paolo Valente44e44a12017-04-12 18:23:12 +02004226 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004227 if (bfq_bfqq_in_large_burst(bfqq))
4228 bfq_bfqq_end_wr(bfqq);
4229 else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
4230 bfqq->wr_cur_max_time)) {
Paolo Valente77b7dce2017-04-12 18:23:13 +02004231 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
4232 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004233 bfq_wr_duration(bfqd)))
Paolo Valente77b7dce2017-04-12 18:23:13 +02004234 bfq_bfqq_end_wr(bfqq);
4235 else {
Paolo Valente3e2bdd62017-09-21 11:04:01 +02004236 switch_back_to_interactive_wr(bfqq, bfqd);
Paolo Valente77b7dce2017-04-12 18:23:13 +02004237 bfqq->entity.prio_changed = 1;
4238 }
Paolo Valente44e44a12017-04-12 18:23:12 +02004239 }
Paolo Valente8a8747d2018-01-13 12:05:18 +01004240 if (bfqq->wr_coeff > 1 &&
4241 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
4242 bfqq->service_from_wr > max_service_from_wr) {
4243 /* see comments on max_service_from_wr */
4244 bfq_bfqq_end_wr(bfqq);
4245 }
Paolo Valente44e44a12017-04-12 18:23:12 +02004246 }
Paolo Valente431b17f2017-07-03 10:00:10 +02004247 /*
4248 * To improve latency (for this or other queues), immediately
4249 * update weight both if it must be raised and if it must be
4250 * lowered. Since, entity may be on some active tree here, and
4251 * might have a pending change of its ioprio class, invoke
4252 * next function with the last parameter unset (see the
4253 * comments on the function).
4254 */
Paolo Valente44e44a12017-04-12 18:23:12 +02004255 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
Paolo Valente431b17f2017-07-03 10:00:10 +02004256 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
4257 entity, false);
Paolo Valente44e44a12017-04-12 18:23:12 +02004258}
4259
Paolo Valenteaee69d72017-04-19 08:29:02 -06004260/*
4261 * Dispatch next request from bfqq.
4262 */
4263static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
4264 struct bfq_queue *bfqq)
4265{
4266 struct request *rq = bfqq->next_rq;
4267 unsigned long service_to_charge;
4268
4269 service_to_charge = bfq_serv_to_charge(rq, bfqq);
4270
4271 bfq_bfqq_served(bfqq, service_to_charge);
4272
Paolo Valente2341d6622019-03-12 09:59:29 +01004273 if (bfqq == bfqd->in_service_queue && bfqd->wait_dispatch) {
4274 bfqd->wait_dispatch = false;
4275 bfqd->waited_rq = rq;
4276 }
4277
Paolo Valenteaee69d72017-04-19 08:29:02 -06004278 bfq_dispatch_remove(bfqd->queue, rq);
4279
Paolo Valente2341d6622019-03-12 09:59:29 +01004280 if (bfqq != bfqd->in_service_queue)
Paolo Valented0edc242018-09-14 16:23:08 +02004281 goto return_rq;
Paolo Valented0edc242018-09-14 16:23:08 +02004282
Paolo Valente44e44a12017-04-12 18:23:12 +02004283 /*
4284 * If weight raising has to terminate for bfqq, then next
4285 * function causes an immediate update of bfqq's weight,
4286 * without waiting for next activation. As a consequence, on
4287 * expiration, bfqq will be timestamped as if has never been
4288 * weight-raised during this service slot, even if it has
4289 * received part or even most of the service as a
4290 * weight-raised queue. This inflates bfqq's timestamps, which
4291 * is beneficial, as bfqq is then more willing to leave the
4292 * device immediately to possible other weight-raised queues.
4293 */
4294 bfq_update_wr_data(bfqd, bfqq);
4295
Paolo Valenteaee69d72017-04-19 08:29:02 -06004296 /*
4297 * Expire bfqq, pretending that its budget expired, if bfqq
4298 * belongs to CLASS_IDLE and other queues are waiting for
4299 * service.
4300 */
Paolo Valente73d58112019-01-29 12:06:29 +01004301 if (!(bfq_tot_busy_queues(bfqd) > 1 && bfq_class_idle(bfqq)))
Paolo Valented0edc242018-09-14 16:23:08 +02004302 goto return_rq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004303
Paolo Valenteaee69d72017-04-19 08:29:02 -06004304 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
Paolo Valented0edc242018-09-14 16:23:08 +02004305
4306return_rq:
Paolo Valenteaee69d72017-04-19 08:29:02 -06004307 return rq;
4308}
4309
4310static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
4311{
4312 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4313
4314 /*
4315 * Avoiding lock: a race on bfqd->busy_queues should cause at
4316 * most a call to dispatch for nothing
4317 */
4318 return !list_empty_careful(&bfqd->dispatch) ||
Paolo Valente73d58112019-01-29 12:06:29 +01004319 bfq_tot_busy_queues(bfqd) > 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004320}
4321
4322static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
4323{
4324 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4325 struct request *rq = NULL;
4326 struct bfq_queue *bfqq = NULL;
4327
4328 if (!list_empty(&bfqd->dispatch)) {
4329 rq = list_first_entry(&bfqd->dispatch, struct request,
4330 queuelist);
4331 list_del_init(&rq->queuelist);
4332
4333 bfqq = RQ_BFQQ(rq);
4334
4335 if (bfqq) {
4336 /*
4337 * Increment counters here, because this
4338 * dispatch does not follow the standard
4339 * dispatch flow (where counters are
4340 * incremented)
4341 */
4342 bfqq->dispatched++;
4343
4344 goto inc_in_driver_start_rq;
4345 }
4346
4347 /*
Paolo Valentea7877392018-02-07 22:19:20 +01004348 * We exploit the bfq_finish_requeue_request hook to
4349 * decrement rq_in_driver, but
4350 * bfq_finish_requeue_request will not be invoked on
4351 * this request. So, to avoid unbalance, just start
4352 * this request, without incrementing rq_in_driver. As
4353 * a negative consequence, rq_in_driver is deceptively
4354 * lower than it should be while this request is in
4355 * service. This may cause bfq_schedule_dispatch to be
4356 * invoked uselessly.
Paolo Valenteaee69d72017-04-19 08:29:02 -06004357 *
4358 * As for implementing an exact solution, the
Paolo Valentea7877392018-02-07 22:19:20 +01004359 * bfq_finish_requeue_request hook, if defined, is
4360 * probably invoked also on this request. So, by
4361 * exploiting this hook, we could 1) increment
4362 * rq_in_driver here, and 2) decrement it in
4363 * bfq_finish_requeue_request. Such a solution would
4364 * let the value of the counter be always accurate,
4365 * but it would entail using an extra interface
4366 * function. This cost seems higher than the benefit,
4367 * being the frequency of non-elevator-private
Paolo Valenteaee69d72017-04-19 08:29:02 -06004368 * requests very low.
4369 */
4370 goto start_rq;
4371 }
4372
Paolo Valente73d58112019-01-29 12:06:29 +01004373 bfq_log(bfqd, "dispatch requests: %d busy queues",
4374 bfq_tot_busy_queues(bfqd));
Paolo Valenteaee69d72017-04-19 08:29:02 -06004375
Paolo Valente73d58112019-01-29 12:06:29 +01004376 if (bfq_tot_busy_queues(bfqd) == 0)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004377 goto exit;
4378
4379 /*
4380 * Force device to serve one request at a time if
4381 * strict_guarantees is true. Forcing this service scheme is
4382 * currently the ONLY way to guarantee that the request
4383 * service order enforced by the scheduler is respected by a
4384 * queueing device. Otherwise the device is free even to make
4385 * some unlucky request wait for as long as the device
4386 * wishes.
4387 *
4388 * Of course, serving one request at at time may cause loss of
4389 * throughput.
4390 */
4391 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
4392 goto exit;
4393
4394 bfqq = bfq_select_queue(bfqd);
4395 if (!bfqq)
4396 goto exit;
4397
4398 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
4399
4400 if (rq) {
4401inc_in_driver_start_rq:
4402 bfqd->rq_in_driver++;
4403start_rq:
4404 rq->rq_flags |= RQF_STARTED;
4405 }
4406exit:
4407 return rq;
4408}
4409
Christoph Hellwig8060c472019-06-06 12:26:24 +02004410#ifdef CONFIG_BFQ_CGROUP_DEBUG
Paolo Valente9b25bd02017-12-04 11:42:05 +01004411static void bfq_update_dispatch_stats(struct request_queue *q,
4412 struct request *rq,
4413 struct bfq_queue *in_serv_queue,
4414 bool idle_timer_disabled)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004415{
Paolo Valente9b25bd02017-12-04 11:42:05 +01004416 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004417
Paolo Valente24bfd192017-11-13 07:34:09 +01004418 if (!idle_timer_disabled && !bfqq)
Paolo Valente9b25bd02017-12-04 11:42:05 +01004419 return;
Paolo Valente24bfd192017-11-13 07:34:09 +01004420
4421 /*
4422 * rq and bfqq are guaranteed to exist until this function
4423 * ends, for the following reasons. First, rq can be
4424 * dispatched to the device, and then can be completed and
4425 * freed, only after this function ends. Second, rq cannot be
4426 * merged (and thus freed because of a merge) any longer,
4427 * because it has already started. Thus rq cannot be freed
4428 * before this function ends, and, since rq has a reference to
4429 * bfqq, the same guarantee holds for bfqq too.
4430 *
4431 * In addition, the following queue lock guarantees that
4432 * bfqq_group(bfqq) exists as well.
4433 */
Christoph Hellwig0d945c12018-11-15 12:17:28 -07004434 spin_lock_irq(&q->queue_lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01004435 if (idle_timer_disabled)
4436 /*
4437 * Since the idle timer has been disabled,
4438 * in_serv_queue contained some request when
4439 * __bfq_dispatch_request was invoked above, which
4440 * implies that rq was picked exactly from
4441 * in_serv_queue. Thus in_serv_queue == bfqq, and is
4442 * therefore guaranteed to exist because of the above
4443 * arguments.
4444 */
4445 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
4446 if (bfqq) {
4447 struct bfq_group *bfqg = bfqq_group(bfqq);
4448
4449 bfqg_stats_update_avg_queue_size(bfqg);
4450 bfqg_stats_set_start_empty_time(bfqg);
4451 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
4452 }
Christoph Hellwig0d945c12018-11-15 12:17:28 -07004453 spin_unlock_irq(&q->queue_lock);
Paolo Valente9b25bd02017-12-04 11:42:05 +01004454}
4455#else
4456static inline void bfq_update_dispatch_stats(struct request_queue *q,
4457 struct request *rq,
4458 struct bfq_queue *in_serv_queue,
4459 bool idle_timer_disabled) {}
Christoph Hellwig8060c472019-06-06 12:26:24 +02004460#endif /* CONFIG_BFQ_CGROUP_DEBUG */
Paolo Valente24bfd192017-11-13 07:34:09 +01004461
Paolo Valente9b25bd02017-12-04 11:42:05 +01004462static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
4463{
4464 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4465 struct request *rq;
4466 struct bfq_queue *in_serv_queue;
4467 bool waiting_rq, idle_timer_disabled;
4468
4469 spin_lock_irq(&bfqd->lock);
4470
4471 in_serv_queue = bfqd->in_service_queue;
4472 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
4473
4474 rq = __bfq_dispatch_request(hctx);
4475
4476 idle_timer_disabled =
4477 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
4478
4479 spin_unlock_irq(&bfqd->lock);
4480
4481 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue,
4482 idle_timer_disabled);
4483
Paolo Valenteaee69d72017-04-19 08:29:02 -06004484 return rq;
4485}
4486
4487/*
4488 * Task holds one reference to the queue, dropped when task exits. Each rq
4489 * in-flight on this queue also holds a reference, dropped when rq is freed.
4490 *
4491 * Scheduler lock must be held here. Recall not to use bfqq after calling
4492 * this function on it.
4493 */
Paolo Valenteea25da42017-04-19 08:48:24 -06004494void bfq_put_queue(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004495{
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004496#ifdef CONFIG_BFQ_GROUP_IOSCHED
4497 struct bfq_group *bfqg = bfqq_group(bfqq);
4498#endif
4499
Paolo Valenteaee69d72017-04-19 08:29:02 -06004500 if (bfqq->bfqd)
4501 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
4502 bfqq, bfqq->ref);
4503
4504 bfqq->ref--;
4505 if (bfqq->ref)
4506 return;
4507
Paolo Valente99fead82017-10-09 13:11:23 +02004508 if (!hlist_unhashed(&bfqq->burst_list_node)) {
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004509 hlist_del_init(&bfqq->burst_list_node);
Paolo Valente99fead82017-10-09 13:11:23 +02004510 /*
4511 * Decrement also burst size after the removal, if the
4512 * process associated with bfqq is exiting, and thus
4513 * does not contribute to the burst any longer. This
4514 * decrement helps filter out false positives of large
4515 * bursts, when some short-lived process (often due to
4516 * the execution of commands by some service) happens
4517 * to start and exit while a complex application is
4518 * starting, and thus spawning several processes that
4519 * do I/O (and that *must not* be treated as a large
4520 * burst, see comments on bfq_handle_burst).
4521 *
4522 * In particular, the decrement is performed only if:
4523 * 1) bfqq is not a merged queue, because, if it is,
4524 * then this free of bfqq is not triggered by the exit
4525 * of the process bfqq is associated with, but exactly
4526 * by the fact that bfqq has just been merged.
4527 * 2) burst_size is greater than 0, to handle
4528 * unbalanced decrements. Unbalanced decrements may
4529 * happen in te following case: bfqq is inserted into
4530 * the current burst list--without incrementing
4531 * bust_size--because of a split, but the current
4532 * burst list is not the burst list bfqq belonged to
4533 * (see comments on the case of a split in
4534 * bfq_set_request).
4535 */
4536 if (bfqq->bic && bfqq->bfqd->burst_size > 0)
4537 bfqq->bfqd->burst_size--;
Paolo Valente7cb04002017-09-21 11:04:03 +02004538 }
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004539
Paolo Valenteaee69d72017-04-19 08:29:02 -06004540 kmem_cache_free(bfq_pool, bfqq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004541#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente8f9bebc2017-06-05 10:11:15 +02004542 bfqg_and_blkg_put(bfqg);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004543#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06004544}
4545
Arianna Avanzini36eca892017-04-12 18:23:16 +02004546static void bfq_put_cooperator(struct bfq_queue *bfqq)
4547{
4548 struct bfq_queue *__bfqq, *next;
4549
4550 /*
4551 * If this queue was scheduled to merge with another queue, be
4552 * sure to drop the reference taken on that queue (and others in
4553 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
4554 */
4555 __bfqq = bfqq->new_bfqq;
4556 while (__bfqq) {
4557 if (__bfqq == bfqq)
4558 break;
4559 next = __bfqq->new_bfqq;
4560 bfq_put_queue(__bfqq);
4561 __bfqq = next;
4562 }
4563}
4564
Paolo Valenteaee69d72017-04-19 08:29:02 -06004565static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4566{
4567 if (bfqq == bfqd->in_service_queue) {
4568 __bfq_bfqq_expire(bfqd, bfqq);
4569 bfq_schedule_dispatch(bfqd);
4570 }
4571
4572 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
4573
Arianna Avanzini36eca892017-04-12 18:23:16 +02004574 bfq_put_cooperator(bfqq);
4575
Paolo Valenteaee69d72017-04-19 08:29:02 -06004576 bfq_put_queue(bfqq); /* release process reference */
4577}
4578
4579static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
4580{
4581 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4582 struct bfq_data *bfqd;
4583
4584 if (bfqq)
4585 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
4586
4587 if (bfqq && bfqd) {
4588 unsigned long flags;
4589
4590 spin_lock_irqsave(&bfqd->lock, flags);
4591 bfq_exit_bfqq(bfqd, bfqq);
4592 bic_set_bfqq(bic, NULL, is_sync);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02004593 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004594 }
4595}
4596
4597static void bfq_exit_icq(struct io_cq *icq)
4598{
4599 struct bfq_io_cq *bic = icq_to_bic(icq);
4600
4601 bfq_exit_icq_bfqq(bic, true);
4602 bfq_exit_icq_bfqq(bic, false);
4603}
4604
4605/*
4606 * Update the entity prio values; note that the new values will not
4607 * be used until the next (re)activation.
4608 */
4609static void
4610bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
4611{
4612 struct task_struct *tsk = current;
4613 int ioprio_class;
4614 struct bfq_data *bfqd = bfqq->bfqd;
4615
4616 if (!bfqd)
4617 return;
4618
4619 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4620 switch (ioprio_class) {
4621 default:
4622 dev_err(bfqq->bfqd->queue->backing_dev_info->dev,
4623 "bfq: bad prio class %d\n", ioprio_class);
Bart Van Asschefa393d12017-08-30 11:42:07 -07004624 /* fall through */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004625 case IOPRIO_CLASS_NONE:
4626 /*
4627 * No prio set, inherit CPU scheduling settings.
4628 */
4629 bfqq->new_ioprio = task_nice_ioprio(tsk);
4630 bfqq->new_ioprio_class = task_nice_ioclass(tsk);
4631 break;
4632 case IOPRIO_CLASS_RT:
4633 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4634 bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
4635 break;
4636 case IOPRIO_CLASS_BE:
4637 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4638 bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
4639 break;
4640 case IOPRIO_CLASS_IDLE:
4641 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
4642 bfqq->new_ioprio = 7;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004643 break;
4644 }
4645
4646 if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
4647 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
4648 bfqq->new_ioprio);
4649 bfqq->new_ioprio = IOPRIO_BE_NR;
4650 }
4651
4652 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
4653 bfqq->entity.prio_changed = 1;
4654}
4655
Paolo Valenteea25da42017-04-19 08:48:24 -06004656static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4657 struct bio *bio, bool is_sync,
4658 struct bfq_io_cq *bic);
4659
Paolo Valenteaee69d72017-04-19 08:29:02 -06004660static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
4661{
4662 struct bfq_data *bfqd = bic_to_bfqd(bic);
4663 struct bfq_queue *bfqq;
4664 int ioprio = bic->icq.ioc->ioprio;
4665
4666 /*
4667 * This condition may trigger on a newly created bic, be sure to
4668 * drop the lock before returning.
4669 */
4670 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
4671 return;
4672
4673 bic->ioprio = ioprio;
4674
4675 bfqq = bic_to_bfqq(bic, false);
4676 if (bfqq) {
4677 /* release process reference on this queue */
4678 bfq_put_queue(bfqq);
4679 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
4680 bic_set_bfqq(bic, bfqq, false);
4681 }
4682
4683 bfqq = bic_to_bfqq(bic, true);
4684 if (bfqq)
4685 bfq_set_next_ioprio_data(bfqq, bic);
4686}
4687
4688static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4689 struct bfq_io_cq *bic, pid_t pid, int is_sync)
4690{
4691 RB_CLEAR_NODE(&bfqq->entity.rb_node);
4692 INIT_LIST_HEAD(&bfqq->fifo);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004693 INIT_HLIST_NODE(&bfqq->burst_list_node);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004694
4695 bfqq->ref = 0;
4696 bfqq->bfqd = bfqd;
4697
4698 if (bic)
4699 bfq_set_next_ioprio_data(bfqq, bic);
4700
4701 if (is_sync) {
Paolo Valented5be3fe2017-08-04 07:35:10 +02004702 /*
4703 * No need to mark as has_short_ttime if in
4704 * idle_class, because no device idling is performed
4705 * for queues in idle class
4706 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004707 if (!bfq_class_idle(bfqq))
Paolo Valented5be3fe2017-08-04 07:35:10 +02004708 /* tentatively mark as has_short_ttime */
4709 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004710 bfq_mark_bfqq_sync(bfqq);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02004711 bfq_mark_bfqq_just_created(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004712 } else
4713 bfq_clear_bfqq_sync(bfqq);
4714
4715 /* set end request to minus infinity from now */
4716 bfqq->ttime.last_end_request = ktime_get_ns() + 1;
4717
4718 bfq_mark_bfqq_IO_bound(bfqq);
4719
4720 bfqq->pid = pid;
4721
4722 /* Tentative initial value to trade off between thr and lat */
Paolo Valente54b60452017-04-12 18:23:09 +02004723 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004724 bfqq->budget_timeout = bfq_smallest_from_now();
Paolo Valenteaee69d72017-04-19 08:29:02 -06004725
Paolo Valente44e44a12017-04-12 18:23:12 +02004726 bfqq->wr_coeff = 1;
Arianna Avanzini36eca892017-04-12 18:23:16 +02004727 bfqq->last_wr_start_finish = jiffies;
Paolo Valente77b7dce2017-04-12 18:23:13 +02004728 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
Arianna Avanzini36eca892017-04-12 18:23:16 +02004729 bfqq->split_time = bfq_smallest_from_now();
Paolo Valente77b7dce2017-04-12 18:23:13 +02004730
4731 /*
Paolo Valentea34b0242017-12-15 07:23:12 +01004732 * To not forget the possibly high bandwidth consumed by a
4733 * process/queue in the recent past,
4734 * bfq_bfqq_softrt_next_start() returns a value at least equal
4735 * to the current value of bfqq->soft_rt_next_start (see
4736 * comments on bfq_bfqq_softrt_next_start). Set
4737 * soft_rt_next_start to now, to mean that bfqq has consumed
4738 * no bandwidth so far.
Paolo Valente77b7dce2017-04-12 18:23:13 +02004739 */
Paolo Valentea34b0242017-12-15 07:23:12 +01004740 bfqq->soft_rt_next_start = jiffies;
Paolo Valente44e44a12017-04-12 18:23:12 +02004741
Paolo Valenteaee69d72017-04-19 08:29:02 -06004742 /* first request is almost certainly seeky */
4743 bfqq->seek_history = 1;
4744}
4745
4746static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004747 struct bfq_group *bfqg,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004748 int ioprio_class, int ioprio)
4749{
4750 switch (ioprio_class) {
4751 case IOPRIO_CLASS_RT:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004752 return &bfqg->async_bfqq[0][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004753 case IOPRIO_CLASS_NONE:
4754 ioprio = IOPRIO_NORM;
4755 /* fall through */
4756 case IOPRIO_CLASS_BE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004757 return &bfqg->async_bfqq[1][ioprio];
Paolo Valenteaee69d72017-04-19 08:29:02 -06004758 case IOPRIO_CLASS_IDLE:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004759 return &bfqg->async_idle_bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004760 default:
4761 return NULL;
4762 }
4763}
4764
4765static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
4766 struct bio *bio, bool is_sync,
4767 struct bfq_io_cq *bic)
4768{
4769 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4770 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4771 struct bfq_queue **async_bfqq = NULL;
4772 struct bfq_queue *bfqq;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004773 struct bfq_group *bfqg;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004774
4775 rcu_read_lock();
4776
Dennis Zhou0fe061b2018-12-05 12:10:26 -05004777 bfqg = bfq_find_set_group(bfqd, __bio_blkcg(bio));
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004778 if (!bfqg) {
4779 bfqq = &bfqd->oom_bfqq;
4780 goto out;
4781 }
4782
Paolo Valenteaee69d72017-04-19 08:29:02 -06004783 if (!is_sync) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004784 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
Paolo Valenteaee69d72017-04-19 08:29:02 -06004785 ioprio);
4786 bfqq = *async_bfqq;
4787 if (bfqq)
4788 goto out;
4789 }
4790
4791 bfqq = kmem_cache_alloc_node(bfq_pool,
4792 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
4793 bfqd->queue->node);
4794
4795 if (bfqq) {
4796 bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
4797 is_sync);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004798 bfq_init_entity(&bfqq->entity, bfqg);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004799 bfq_log_bfqq(bfqd, bfqq, "allocated");
4800 } else {
4801 bfqq = &bfqd->oom_bfqq;
4802 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
4803 goto out;
4804 }
4805
4806 /*
4807 * Pin the queue now that it's allocated, scheduler exit will
4808 * prune it.
4809 */
4810 if (async_bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02004811 bfqq->ref++; /*
4812 * Extra group reference, w.r.t. sync
4813 * queue. This extra reference is removed
4814 * only if bfqq->bfqg disappears, to
4815 * guarantee that this queue is not freed
4816 * until its group goes away.
4817 */
4818 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
Paolo Valenteaee69d72017-04-19 08:29:02 -06004819 bfqq, bfqq->ref);
4820 *async_bfqq = bfqq;
4821 }
4822
4823out:
4824 bfqq->ref++; /* get a process reference to this queue */
4825 bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
4826 rcu_read_unlock();
4827 return bfqq;
4828}
4829
4830static void bfq_update_io_thinktime(struct bfq_data *bfqd,
4831 struct bfq_queue *bfqq)
4832{
4833 struct bfq_ttime *ttime = &bfqq->ttime;
4834 u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
4835
4836 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
4837
4838 ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
4839 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
4840 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
4841 ttime->ttime_samples);
4842}
4843
4844static void
4845bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4846 struct request *rq)
4847{
Paolo Valenteaee69d72017-04-19 08:29:02 -06004848 bfqq->seek_history <<= 1;
Paolo Valented87447d2019-01-29 12:06:33 +01004849 bfqq->seek_history |= BFQ_RQ_SEEKY(bfqd, bfqq->last_request_pos, rq);
Paolo Valente7074f072019-03-12 09:59:31 +01004850
4851 if (bfqq->wr_coeff > 1 &&
4852 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
4853 BFQQ_TOTALLY_SEEKY(bfqq))
4854 bfq_bfqq_end_wr(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004855}
4856
Paolo Valented5be3fe2017-08-04 07:35:10 +02004857static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
4858 struct bfq_queue *bfqq,
4859 struct bfq_io_cq *bic)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004860{
Paolo Valente766d6142019-06-25 07:12:43 +02004861 bool has_short_ttime = true, state_changed;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004862
Paolo Valented5be3fe2017-08-04 07:35:10 +02004863 /*
4864 * No need to update has_short_ttime if bfqq is async or in
4865 * idle io prio class, or if bfq_slice_idle is zero, because
4866 * no device idling is performed for bfqq in this case.
4867 */
4868 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
4869 bfqd->bfq_slice_idle == 0)
Paolo Valenteaee69d72017-04-19 08:29:02 -06004870 return;
4871
Arianna Avanzini36eca892017-04-12 18:23:16 +02004872 /* Idle window just restored, statistics are meaningless. */
4873 if (time_is_after_eq_jiffies(bfqq->split_time +
4874 bfqd->bfq_wr_min_idle_time))
4875 return;
4876
Paolo Valented5be3fe2017-08-04 07:35:10 +02004877 /* Think time is infinite if no process is linked to
4878 * bfqq. Otherwise check average think time to
4879 * decide whether to mark as has_short_ttime
4880 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06004881 if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
Paolo Valented5be3fe2017-08-04 07:35:10 +02004882 (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
4883 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
4884 has_short_ttime = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06004885
Paolo Valente766d6142019-06-25 07:12:43 +02004886 state_changed = has_short_ttime != bfq_bfqq_has_short_ttime(bfqq);
Paolo Valented5be3fe2017-08-04 07:35:10 +02004887
4888 if (has_short_ttime)
4889 bfq_mark_bfqq_has_short_ttime(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004890 else
Paolo Valented5be3fe2017-08-04 07:35:10 +02004891 bfq_clear_bfqq_has_short_ttime(bfqq);
Paolo Valente766d6142019-06-25 07:12:43 +02004892
4893 /*
4894 * Until the base value for the total service time gets
4895 * finally computed for bfqq, the inject limit does depend on
4896 * the think-time state (short|long). In particular, the limit
4897 * is 0 or 1 if the think time is deemed, respectively, as
4898 * short or long (details in the comments in
4899 * bfq_update_inject_limit()). Accordingly, the next
4900 * instructions reset the inject limit if the think-time state
4901 * has changed and the above base value is still to be
4902 * computed.
4903 *
4904 * However, the reset is performed only if more than 100 ms
4905 * have elapsed since the last update of the inject limit, or
4906 * (inclusive) if the change is from short to long think
4907 * time. The reason for this waiting is as follows.
4908 *
4909 * bfqq may have a long think time because of a
4910 * synchronization with some other queue, i.e., because the
4911 * I/O of some other queue may need to be completed for bfqq
4912 * to receive new I/O. This happens, e.g., if bfqq is
4913 * associated with a process that does some sync. A sync
4914 * generates extra blocking I/O, which must be completed
4915 * before the process associated with bfqq can go on with its
4916 * I/O.
4917 *
4918 * If such a synchronization is actually in place, then,
4919 * without injection on bfqq, the blocking I/O cannot happen
4920 * to served while bfqq is in service. As a consequence, if
4921 * bfqq is granted I/O-dispatch-plugging, then bfqq remains
4922 * empty, and no I/O is dispatched, until the idle timeout
4923 * fires. This is likely to result in lower bandwidth and
4924 * higher latencies for bfqq, and in a severe loss of total
4925 * throughput.
4926 *
4927 * On the opposite end, a non-zero inject limit may allow the
4928 * I/O that blocks bfqq to be executed soon, and therefore
4929 * bfqq to receive new I/O soon. But, if this actually
4930 * happens, then the next think-time sample for bfqq may be
4931 * very low. This in turn may cause bfqq's think time to be
4932 * deemed short. Without the 100 ms barrier, this new state
4933 * change would cause the body of the next if to be executed
4934 * immediately. But this would set to 0 the inject
4935 * limit. Without injection, the blocking I/O would cause the
4936 * think time of bfqq to become long again, and therefore the
4937 * inject limit to be raised again, and so on. The only effect
4938 * of such a steady oscillation between the two think-time
4939 * states would be to prevent effective injection on bfqq.
4940 *
4941 * In contrast, if the inject limit is not reset during such a
4942 * long time interval as 100 ms, then the number of short
4943 * think time samples can grow significantly before the reset
4944 * is allowed. As a consequence, the think time state can
4945 * become stable before the reset. There will be no state
4946 * change when the 100 ms elapse, and therefore no reset of
4947 * the inject limit. The inject limit remains steadily equal
4948 * to 1 both during and after the 100 ms. So injection can be
4949 * performed at all times, and throughput gets boosted.
4950 *
4951 * An inject limit equal to 1 is however in conflict, in
4952 * general, with the fact that the think time of bfqq is
4953 * short, because injection may be likely to delay bfqq's I/O
4954 * (as explained in the comments in
4955 * bfq_update_inject_limit()). But this does not happen in
4956 * this special case, because bfqq's low think time is due to
4957 * an effective handling of a synchronization, through
4958 * injection. In this special case, bfqq's I/O does not get
4959 * delayed by injection; on the contrary, bfqq's I/O is
4960 * brought forward, because it is not blocked for
4961 * milliseconds.
4962 *
4963 * In addition, during the 100 ms, the base value for the
4964 * total service time is likely to get finally computed,
4965 * freeing the inject limit from its relation with the think
4966 * time.
4967 */
4968 if (state_changed && bfqq->last_serv_time_ns == 0 &&
4969 (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
4970 msecs_to_jiffies(100)) ||
4971 !has_short_ttime))
4972 bfq_reset_inject_limit(bfqd, bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004973}
4974
4975/*
4976 * Called when a new fs request (rq) is added to bfqq. Check if there's
4977 * something we should do about it.
4978 */
4979static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
4980 struct request *rq)
4981{
4982 struct bfq_io_cq *bic = RQ_BIC(rq);
4983
4984 if (rq->cmd_flags & REQ_META)
4985 bfqq->meta_pending++;
4986
4987 bfq_update_io_thinktime(bfqd, bfqq);
Paolo Valented5be3fe2017-08-04 07:35:10 +02004988 bfq_update_has_short_ttime(bfqd, bfqq, bic);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004989 bfq_update_io_seektime(bfqd, bfqq, rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06004990
4991 bfq_log_bfqq(bfqd, bfqq,
Paolo Valented5be3fe2017-08-04 07:35:10 +02004992 "rq_enqueued: has_short_ttime=%d (seeky %d)",
4993 bfq_bfqq_has_short_ttime(bfqq), BFQQ_SEEKY(bfqq));
Paolo Valenteaee69d72017-04-19 08:29:02 -06004994
4995 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4996
4997 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
4998 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
4999 blk_rq_sectors(rq) < 32;
5000 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
5001
5002 /*
Paolo Valenteac8b0cb2019-01-29 12:06:31 +01005003 * There is just this request queued: if
5004 * - the request is small, and
5005 * - we are idling to boost throughput, and
5006 * - the queue is not to be expired,
5007 * then just exit.
Paolo Valenteaee69d72017-04-19 08:29:02 -06005008 *
5009 * In this way, if the device is being idled to wait
5010 * for a new request from the in-service queue, we
5011 * avoid unplugging the device and committing the
Paolo Valenteac8b0cb2019-01-29 12:06:31 +01005012 * device to serve just a small request. In contrast
5013 * we wait for the block layer to decide when to
5014 * unplug the device: hopefully, new requests will be
5015 * merged to this one quickly, then the device will be
5016 * unplugged and larger requests will be dispatched.
Paolo Valenteaee69d72017-04-19 08:29:02 -06005017 */
Paolo Valenteac8b0cb2019-01-29 12:06:31 +01005018 if (small_req && idling_boosts_thr_without_issues(bfqd, bfqq) &&
5019 !budget_timeout)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005020 return;
5021
5022 /*
Paolo Valenteac8b0cb2019-01-29 12:06:31 +01005023 * A large enough request arrived, or idling is being
5024 * performed to preserve service guarantees, or
5025 * finally the queue is to be expired: in all these
5026 * cases disk idling is to be stopped, so clear
5027 * wait_request flag and reset timer.
Paolo Valenteaee69d72017-04-19 08:29:02 -06005028 */
5029 bfq_clear_bfqq_wait_request(bfqq);
5030 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
5031
5032 /*
5033 * The queue is not empty, because a new request just
5034 * arrived. Hence we can safely expire the queue, in
5035 * case of budget timeout, without risking that the
5036 * timestamps of the queue are not updated correctly.
5037 * See [1] for more details.
5038 */
5039 if (budget_timeout)
5040 bfq_bfqq_expire(bfqd, bfqq, false,
5041 BFQQE_BUDGET_TIMEOUT);
5042 }
5043}
5044
Paolo Valente24bfd192017-11-13 07:34:09 +01005045/* returns true if it causes the idle timer to be disabled */
5046static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005047{
Arianna Avanzini36eca892017-04-12 18:23:16 +02005048 struct bfq_queue *bfqq = RQ_BFQQ(rq),
5049 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
Paolo Valente24bfd192017-11-13 07:34:09 +01005050 bool waiting, idle_timer_disabled = false;
Arianna Avanzini36eca892017-04-12 18:23:16 +02005051
5052 if (new_bfqq) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02005053 /*
5054 * Release the request's reference to the old bfqq
5055 * and make sure one is taken to the shared queue.
5056 */
5057 new_bfqq->allocated++;
5058 bfqq->allocated--;
5059 new_bfqq->ref++;
5060 /*
5061 * If the bic associated with the process
5062 * issuing this request still points to bfqq
5063 * (and thus has not been already redirected
5064 * to new_bfqq or even some other bfq_queue),
5065 * then complete the merge and redirect it to
5066 * new_bfqq.
5067 */
5068 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
5069 bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
5070 bfqq, new_bfqq);
Paolo Valente894df932017-09-21 11:04:02 +02005071
5072 bfq_clear_bfqq_just_created(bfqq);
Arianna Avanzini36eca892017-04-12 18:23:16 +02005073 /*
5074 * rq is about to be enqueued into new_bfqq,
5075 * release rq reference on bfqq
5076 */
5077 bfq_put_queue(bfqq);
5078 rq->elv.priv[1] = new_bfqq;
5079 bfqq = new_bfqq;
5080 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06005081
Paolo Valente24bfd192017-11-13 07:34:09 +01005082 waiting = bfqq && bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005083 bfq_add_request(rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01005084 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005085
5086 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
5087 list_add_tail(&rq->queuelist, &bfqq->fifo);
5088
5089 bfq_rq_enqueued(bfqd, bfqq, rq);
Paolo Valente24bfd192017-11-13 07:34:09 +01005090
5091 return idle_timer_disabled;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005092}
5093
Christoph Hellwig8060c472019-06-06 12:26:24 +02005094#ifdef CONFIG_BFQ_CGROUP_DEBUG
Paolo Valente9b25bd02017-12-04 11:42:05 +01005095static void bfq_update_insert_stats(struct request_queue *q,
5096 struct bfq_queue *bfqq,
5097 bool idle_timer_disabled,
5098 unsigned int cmd_flags)
5099{
5100 if (!bfqq)
5101 return;
5102
5103 /*
5104 * bfqq still exists, because it can disappear only after
5105 * either it is merged with another queue, or the process it
5106 * is associated with exits. But both actions must be taken by
5107 * the same process currently executing this flow of
5108 * instructions.
5109 *
5110 * In addition, the following queue lock guarantees that
5111 * bfqq_group(bfqq) exists as well.
5112 */
Christoph Hellwig0d945c12018-11-15 12:17:28 -07005113 spin_lock_irq(&q->queue_lock);
Paolo Valente9b25bd02017-12-04 11:42:05 +01005114 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
5115 if (idle_timer_disabled)
5116 bfqg_stats_update_idle_time(bfqq_group(bfqq));
Christoph Hellwig0d945c12018-11-15 12:17:28 -07005117 spin_unlock_irq(&q->queue_lock);
Paolo Valente9b25bd02017-12-04 11:42:05 +01005118}
5119#else
5120static inline void bfq_update_insert_stats(struct request_queue *q,
5121 struct bfq_queue *bfqq,
5122 bool idle_timer_disabled,
5123 unsigned int cmd_flags) {}
Christoph Hellwig8060c472019-06-06 12:26:24 +02005124#endif /* CONFIG_BFQ_CGROUP_DEBUG */
Paolo Valente9b25bd02017-12-04 11:42:05 +01005125
Paolo Valenteaee69d72017-04-19 08:29:02 -06005126static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
5127 bool at_head)
5128{
5129 struct request_queue *q = hctx->queue;
5130 struct bfq_data *bfqd = q->elevator->elevator_data;
Paolo Valente18e5a572018-05-04 19:17:01 +02005131 struct bfq_queue *bfqq;
Paolo Valente24bfd192017-11-13 07:34:09 +01005132 bool idle_timer_disabled = false;
5133 unsigned int cmd_flags;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005134
5135 spin_lock_irq(&bfqd->lock);
5136 if (blk_mq_sched_try_insert_merge(q, rq)) {
5137 spin_unlock_irq(&bfqd->lock);
5138 return;
5139 }
5140
5141 spin_unlock_irq(&bfqd->lock);
5142
5143 blk_mq_sched_request_inserted(rq);
5144
5145 spin_lock_irq(&bfqd->lock);
Paolo Valente18e5a572018-05-04 19:17:01 +02005146 bfqq = bfq_init_rq(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005147 if (at_head || blk_rq_is_passthrough(rq)) {
5148 if (at_head)
5149 list_add(&rq->queuelist, &bfqd->dispatch);
5150 else
5151 list_add_tail(&rq->queuelist, &bfqd->dispatch);
Paolo Valente18e5a572018-05-04 19:17:01 +02005152 } else { /* bfqq is assumed to be non null here */
Paolo Valente24bfd192017-11-13 07:34:09 +01005153 idle_timer_disabled = __bfq_insert_request(bfqd, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01005154 /*
5155 * Update bfqq, because, if a queue merge has occurred
5156 * in __bfq_insert_request, then rq has been
5157 * redirected into a new queue.
5158 */
5159 bfqq = RQ_BFQQ(rq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005160
5161 if (rq_mergeable(rq)) {
5162 elv_rqhash_add(q, rq);
5163 if (!q->last_merge)
5164 q->last_merge = rq;
5165 }
5166 }
5167
Paolo Valente24bfd192017-11-13 07:34:09 +01005168 /*
5169 * Cache cmd_flags before releasing scheduler lock, because rq
5170 * may disappear afterwards (for example, because of a request
5171 * merge).
5172 */
5173 cmd_flags = rq->cmd_flags;
Paolo Valente9b25bd02017-12-04 11:42:05 +01005174
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005175 spin_unlock_irq(&bfqd->lock);
Paolo Valente24bfd192017-11-13 07:34:09 +01005176
Paolo Valente9b25bd02017-12-04 11:42:05 +01005177 bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
5178 cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005179}
5180
5181static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
5182 struct list_head *list, bool at_head)
5183{
5184 while (!list_empty(list)) {
5185 struct request *rq;
5186
5187 rq = list_first_entry(list, struct request, queuelist);
5188 list_del_init(&rq->queuelist);
5189 bfq_insert_request(hctx, rq, at_head);
5190 }
5191}
5192
5193static void bfq_update_hw_tag(struct bfq_data *bfqd)
5194{
Paolo Valenteb3c34982019-01-29 12:06:36 +01005195 struct bfq_queue *bfqq = bfqd->in_service_queue;
5196
Paolo Valenteaee69d72017-04-19 08:29:02 -06005197 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
5198 bfqd->rq_in_driver);
5199
5200 if (bfqd->hw_tag == 1)
5201 return;
5202
5203 /*
5204 * This sample is valid if the number of outstanding requests
5205 * is large enough to allow a queueing behavior. Note that the
5206 * sum is not exact, as it's not taking into account deactivated
5207 * requests.
5208 */
Paolo Valentea3c92562019-01-29 12:06:35 +01005209 if (bfqd->rq_in_driver + bfqd->queued <= BFQ_HW_QUEUE_THRESHOLD)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005210 return;
5211
Paolo Valenteb3c34982019-01-29 12:06:36 +01005212 /*
5213 * If active queue hasn't enough requests and can idle, bfq might not
5214 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
5215 * case
5216 */
5217 if (bfqq && bfq_bfqq_has_short_ttime(bfqq) &&
5218 bfqq->dispatched + bfqq->queued[0] + bfqq->queued[1] <
5219 BFQ_HW_QUEUE_THRESHOLD &&
5220 bfqd->rq_in_driver < BFQ_HW_QUEUE_THRESHOLD)
5221 return;
5222
Paolo Valenteaee69d72017-04-19 08:29:02 -06005223 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
5224 return;
5225
5226 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
5227 bfqd->max_rq_in_driver = 0;
5228 bfqd->hw_tag_samples = 0;
Paolo Valente8cacc5a2019-03-12 09:59:30 +01005229
5230 bfqd->nonrot_with_queueing =
5231 blk_queue_nonrot(bfqd->queue) && bfqd->hw_tag;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005232}
5233
5234static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
5235{
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005236 u64 now_ns;
5237 u32 delta_us;
5238
Paolo Valenteaee69d72017-04-19 08:29:02 -06005239 bfq_update_hw_tag(bfqd);
5240
5241 bfqd->rq_in_driver--;
5242 bfqq->dispatched--;
5243
Paolo Valente44e44a12017-04-12 18:23:12 +02005244 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
5245 /*
5246 * Set budget_timeout (which we overload to store the
5247 * time at which the queue remains with no backlog and
5248 * no outstanding request; used by the weight-raising
5249 * mechanism).
5250 */
5251 bfqq->budget_timeout = jiffies;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02005252
Paolo Valente04715592018-06-25 21:55:34 +02005253 bfq_weights_tree_remove(bfqd, bfqq);
Paolo Valente44e44a12017-04-12 18:23:12 +02005254 }
5255
Paolo Valenteab0e43e2017-04-12 18:23:10 +02005256 now_ns = ktime_get_ns();
5257
5258 bfqq->ttime.last_end_request = now_ns;
5259
5260 /*
5261 * Using us instead of ns, to get a reasonable precision in
5262 * computing rate in next check.
5263 */
5264 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
5265
5266 /*
5267 * If the request took rather long to complete, and, according
5268 * to the maximum request size recorded, this completion latency
5269 * implies that the request was certainly served at a very low
5270 * rate (less than 1M sectors/sec), then the whole observation
5271 * interval that lasts up to this time instant cannot be a
5272 * valid time interval for computing a new peak rate. Invoke
5273 * bfq_update_rate_reset to have the following three steps
5274 * taken:
5275 * - close the observation interval at the last (previous)
5276 * request dispatch or completion
5277 * - compute rate, if possible, for that observation interval
5278 * - reset to zero samples, which will trigger a proper
5279 * re-initialization of the observation interval on next
5280 * dispatch
5281 */
5282 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
5283 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
5284 1UL<<(BFQ_RATE_SHIFT - 10))
5285 bfq_update_rate_reset(bfqd, NULL);
5286 bfqd->last_completion = now_ns;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005287
5288 /*
Paolo Valente77b7dce2017-04-12 18:23:13 +02005289 * If we are waiting to discover whether the request pattern
5290 * of the task associated with the queue is actually
5291 * isochronous, and both requisites for this condition to hold
5292 * are now satisfied, then compute soft_rt_next_start (see the
5293 * comments on the function bfq_bfqq_softrt_next_start()). We
Paolo Valente20cd3242019-01-29 12:06:25 +01005294 * do not compute soft_rt_next_start if bfqq is in interactive
5295 * weight raising (see the comments in bfq_bfqq_expire() for
5296 * an explanation). We schedule this delayed update when bfqq
5297 * expires, if it still has in-flight requests.
Paolo Valente77b7dce2017-04-12 18:23:13 +02005298 */
5299 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
Paolo Valente20cd3242019-01-29 12:06:25 +01005300 RB_EMPTY_ROOT(&bfqq->sort_list) &&
5301 bfqq->wr_coeff != bfqd->bfq_wr_coeff)
Paolo Valente77b7dce2017-04-12 18:23:13 +02005302 bfqq->soft_rt_next_start =
5303 bfq_bfqq_softrt_next_start(bfqd, bfqq);
5304
5305 /*
Paolo Valenteaee69d72017-04-19 08:29:02 -06005306 * If this is the in-service queue, check if it needs to be expired,
5307 * or if we want to idle in case it has no pending requests.
5308 */
5309 if (bfqd->in_service_queue == bfqq) {
Paolo Valente4420b092018-06-25 21:55:35 +02005310 if (bfq_bfqq_must_idle(bfqq)) {
5311 if (bfqq->dispatched == 0)
5312 bfq_arm_slice_timer(bfqd);
5313 /*
5314 * If we get here, we do not expire bfqq, even
5315 * if bfqq was in budget timeout or had no
5316 * more requests (as controlled in the next
5317 * conditional instructions). The reason for
5318 * not expiring bfqq is as follows.
5319 *
5320 * Here bfqq->dispatched > 0 holds, but
5321 * bfq_bfqq_must_idle() returned true. This
5322 * implies that, even if no request arrives
5323 * for bfqq before bfqq->dispatched reaches 0,
5324 * bfqq will, however, not be expired on the
5325 * completion event that causes bfqq->dispatch
5326 * to reach zero. In contrast, on this event,
5327 * bfqq will start enjoying device idling
5328 * (I/O-dispatch plugging).
5329 *
5330 * But, if we expired bfqq here, bfqq would
5331 * not have the chance to enjoy device idling
5332 * when bfqq->dispatched finally reaches
5333 * zero. This would expose bfqq to violation
5334 * of its reserved service guarantees.
5335 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06005336 return;
5337 } else if (bfq_may_expire_for_budg_timeout(bfqq))
5338 bfq_bfqq_expire(bfqd, bfqq, false,
5339 BFQQE_BUDGET_TIMEOUT);
5340 else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
5341 (bfqq->dispatched == 0 ||
Paolo Valente277a4a92018-06-25 21:55:37 +02005342 !bfq_better_to_idle(bfqq)))
Paolo Valenteaee69d72017-04-19 08:29:02 -06005343 bfq_bfqq_expire(bfqd, bfqq, false,
5344 BFQQE_NO_MORE_REQUESTS);
5345 }
Hou Tao3f7cb4f2017-07-11 21:58:15 +08005346
5347 if (!bfqd->rq_in_driver)
5348 bfq_schedule_dispatch(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005349}
5350
Paolo Valentea7877392018-02-07 22:19:20 +01005351static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005352{
5353 bfqq->allocated--;
5354
5355 bfq_put_queue(bfqq);
5356}
5357
Paolo Valentea7877392018-02-07 22:19:20 +01005358/*
Paolo Valente2341d6622019-03-12 09:59:29 +01005359 * The processes associated with bfqq may happen to generate their
5360 * cumulative I/O at a lower rate than the rate at which the device
5361 * could serve the same I/O. This is rather probable, e.g., if only
5362 * one process is associated with bfqq and the device is an SSD. It
5363 * results in bfqq becoming often empty while in service. In this
5364 * respect, if BFQ is allowed to switch to another queue when bfqq
5365 * remains empty, then the device goes on being fed with I/O requests,
5366 * and the throughput is not affected. In contrast, if BFQ is not
5367 * allowed to switch to another queue---because bfqq is sync and
5368 * I/O-dispatch needs to be plugged while bfqq is temporarily
5369 * empty---then, during the service of bfqq, there will be frequent
5370 * "service holes", i.e., time intervals during which bfqq gets empty
5371 * and the device can only consume the I/O already queued in its
5372 * hardware queues. During service holes, the device may even get to
5373 * remaining idle. In the end, during the service of bfqq, the device
5374 * is driven at a lower speed than the one it can reach with the kind
5375 * of I/O flowing through bfqq.
5376 *
5377 * To counter this loss of throughput, BFQ implements a "request
5378 * injection mechanism", which tries to fill the above service holes
5379 * with I/O requests taken from other queues. The hard part in this
5380 * mechanism is finding the right amount of I/O to inject, so as to
5381 * both boost throughput and not break bfqq's bandwidth and latency
5382 * guarantees. In this respect, the mechanism maintains a per-queue
5383 * inject limit, computed as below. While bfqq is empty, the injection
5384 * mechanism dispatches extra I/O requests only until the total number
5385 * of I/O requests in flight---i.e., already dispatched but not yet
5386 * completed---remains lower than this limit.
5387 *
5388 * A first definition comes in handy to introduce the algorithm by
5389 * which the inject limit is computed. We define as first request for
5390 * bfqq, an I/O request for bfqq that arrives while bfqq is in
5391 * service, and causes bfqq to switch from empty to non-empty. The
5392 * algorithm updates the limit as a function of the effect of
5393 * injection on the service times of only the first requests of
5394 * bfqq. The reason for this restriction is that these are the
5395 * requests whose service time is affected most, because they are the
5396 * first to arrive after injection possibly occurred.
5397 *
5398 * To evaluate the effect of injection, the algorithm measures the
5399 * "total service time" of first requests. We define as total service
5400 * time of an I/O request, the time that elapses since when the
5401 * request is enqueued into bfqq, to when it is completed. This
5402 * quantity allows the whole effect of injection to be measured. It is
5403 * easy to see why. Suppose that some requests of other queues are
5404 * actually injected while bfqq is empty, and that a new request R
5405 * then arrives for bfqq. If the device does start to serve all or
5406 * part of the injected requests during the service hole, then,
5407 * because of this extra service, it may delay the next invocation of
5408 * the dispatch hook of BFQ. Then, even after R gets eventually
5409 * dispatched, the device may delay the actual service of R if it is
5410 * still busy serving the extra requests, or if it decides to serve,
5411 * before R, some extra request still present in its queues. As a
5412 * conclusion, the cumulative extra delay caused by injection can be
5413 * easily evaluated by just comparing the total service time of first
5414 * requests with and without injection.
5415 *
5416 * The limit-update algorithm works as follows. On the arrival of a
5417 * first request of bfqq, the algorithm measures the total time of the
5418 * request only if one of the three cases below holds, and, for each
5419 * case, it updates the limit as described below:
5420 *
5421 * (1) If there is no in-flight request. This gives a baseline for the
5422 * total service time of the requests of bfqq. If the baseline has
5423 * not been computed yet, then, after computing it, the limit is
5424 * set to 1, to start boosting throughput, and to prepare the
5425 * ground for the next case. If the baseline has already been
5426 * computed, then it is updated, in case it results to be lower
5427 * than the previous value.
5428 *
5429 * (2) If the limit is higher than 0 and there are in-flight
5430 * requests. By comparing the total service time in this case with
5431 * the above baseline, it is possible to know at which extent the
5432 * current value of the limit is inflating the total service
5433 * time. If the inflation is below a certain threshold, then bfqq
5434 * is assumed to be suffering from no perceivable loss of its
5435 * service guarantees, and the limit is even tentatively
5436 * increased. If the inflation is above the threshold, then the
5437 * limit is decreased. Due to the lack of any hysteresis, this
5438 * logic makes the limit oscillate even in steady workload
5439 * conditions. Yet we opted for it, because it is fast in reaching
5440 * the best value for the limit, as a function of the current I/O
5441 * workload. To reduce oscillations, this step is disabled for a
5442 * short time interval after the limit happens to be decreased.
5443 *
5444 * (3) Periodically, after resetting the limit, to make sure that the
5445 * limit eventually drops in case the workload changes. This is
5446 * needed because, after the limit has gone safely up for a
5447 * certain workload, it is impossible to guess whether the
5448 * baseline total service time may have changed, without measuring
5449 * it again without injection. A more effective version of this
5450 * step might be to just sample the baseline, by interrupting
5451 * injection only once, and then to reset/lower the limit only if
5452 * the total service time with the current limit does happen to be
5453 * too large.
5454 *
5455 * More details on each step are provided in the comments on the
5456 * pieces of code that implement these steps: the branch handling the
5457 * transition from empty to non empty in bfq_add_request(), the branch
5458 * handling injection in bfq_select_queue(), and the function
5459 * bfq_choose_bfqq_for_injection(). These comments also explain some
5460 * exceptions, made by the injection mechanism in some special cases.
5461 */
5462static void bfq_update_inject_limit(struct bfq_data *bfqd,
5463 struct bfq_queue *bfqq)
5464{
5465 u64 tot_time_ns = ktime_get_ns() - bfqd->last_empty_occupied_ns;
5466 unsigned int old_limit = bfqq->inject_limit;
5467
5468 if (bfqq->last_serv_time_ns > 0) {
5469 u64 threshold = (bfqq->last_serv_time_ns * 3)>>1;
5470
5471 if (tot_time_ns >= threshold && old_limit > 0) {
5472 bfqq->inject_limit--;
5473 bfqq->decrease_time_jif = jiffies;
5474 } else if (tot_time_ns < threshold &&
5475 old_limit < bfqd->max_rq_in_driver<<1)
5476 bfqq->inject_limit++;
5477 }
5478
5479 /*
5480 * Either we still have to compute the base value for the
5481 * total service time, and there seem to be the right
5482 * conditions to do it, or we can lower the last base value
5483 * computed.
Paolo Valentedb599f92019-06-25 07:12:44 +02005484 *
5485 * NOTE: (bfqd->rq_in_driver == 1) means that there is no I/O
5486 * request in flight, because this function is in the code
5487 * path that handles the completion of a request of bfqq, and,
5488 * in particular, this function is executed before
5489 * bfqd->rq_in_driver is decremented in such a code path.
Paolo Valente2341d6622019-03-12 09:59:29 +01005490 */
Paolo Valentedb599f92019-06-25 07:12:44 +02005491 if ((bfqq->last_serv_time_ns == 0 && bfqd->rq_in_driver == 1) ||
Paolo Valente2341d6622019-03-12 09:59:29 +01005492 tot_time_ns < bfqq->last_serv_time_ns) {
5493 bfqq->last_serv_time_ns = tot_time_ns;
5494 /*
5495 * Now we certainly have a base value: make sure we
5496 * start trying injection.
5497 */
5498 bfqq->inject_limit = max_t(unsigned int, 1, old_limit);
5499 }
5500
5501 /* update complete, not waiting for any request completion any longer */
5502 bfqd->waited_rq = NULL;
5503}
5504
5505/*
Paolo Valentea7877392018-02-07 22:19:20 +01005506 * Handle either a requeue or a finish for rq. The things to do are
5507 * the same in both cases: all references to rq are to be dropped. In
5508 * particular, rq is considered completed from the point of view of
5509 * the scheduler.
5510 */
5511static void bfq_finish_requeue_request(struct request *rq)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005512{
Paolo Valentea7877392018-02-07 22:19:20 +01005513 struct bfq_queue *bfqq = RQ_BFQQ(rq);
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005514 struct bfq_data *bfqd;
5515
Paolo Valentea7877392018-02-07 22:19:20 +01005516 /*
5517 * Requeue and finish hooks are invoked in blk-mq without
5518 * checking whether the involved request is actually still
5519 * referenced in the scheduler. To handle this fact, the
5520 * following two checks make this function exit in case of
5521 * spurious invocations, for which there is nothing to do.
5522 *
5523 * First, check whether rq has nothing to do with an elevator.
5524 */
5525 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV)))
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005526 return;
5527
Paolo Valentea7877392018-02-07 22:19:20 +01005528 /*
5529 * rq either is not associated with any icq, or is an already
5530 * requeued request that has not (yet) been re-inserted into
5531 * a bfq_queue.
5532 */
5533 if (!rq->elv.icq || !bfqq)
5534 return;
5535
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005536 bfqd = bfqq->bfqd;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005537
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005538 if (rq->rq_flags & RQF_STARTED)
5539 bfqg_stats_update_completion(bfqq_group(bfqq),
Omar Sandoval522a7772018-05-09 02:08:53 -07005540 rq->start_time_ns,
5541 rq->io_start_time_ns,
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005542 rq->cmd_flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005543
5544 if (likely(rq->rq_flags & RQF_STARTED)) {
5545 unsigned long flags;
5546
5547 spin_lock_irqsave(&bfqd->lock, flags);
5548
Paolo Valente2341d6622019-03-12 09:59:29 +01005549 if (rq == bfqd->waited_rq)
5550 bfq_update_inject_limit(bfqd, bfqq);
5551
Paolo Valenteaee69d72017-04-19 08:29:02 -06005552 bfq_completed_request(bfqq, bfqd);
Paolo Valentea7877392018-02-07 22:19:20 +01005553 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005554
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005555 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005556 } else {
5557 /*
5558 * Request rq may be still/already in the scheduler,
Paolo Valentea7877392018-02-07 22:19:20 +01005559 * in which case we need to remove it (this should
5560 * never happen in case of requeue). And we cannot
Paolo Valenteaee69d72017-04-19 08:29:02 -06005561 * defer such a check and removal, to avoid
5562 * inconsistencies in the time interval from the end
5563 * of this function to the start of the deferred work.
5564 * This situation seems to occur only in process
5565 * context, as a consequence of a merge. In the
5566 * current version of the code, this implies that the
5567 * lock is held.
5568 */
5569
Luca Miccio614822f2017-11-13 07:34:08 +01005570 if (!RB_EMPTY_NODE(&rq->rb_node)) {
Christoph Hellwig7b9e9362017-06-16 18:15:21 +02005571 bfq_remove_request(rq->q, rq);
Luca Miccio614822f2017-11-13 07:34:08 +01005572 bfqg_stats_update_io_remove(bfqq_group(bfqq),
5573 rq->cmd_flags);
5574 }
Paolo Valentea7877392018-02-07 22:19:20 +01005575 bfq_finish_requeue_request_body(bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005576 }
5577
Paolo Valentea7877392018-02-07 22:19:20 +01005578 /*
5579 * Reset private fields. In case of a requeue, this allows
5580 * this function to correctly do nothing if it is spuriously
5581 * invoked again on this same request (see the check at the
5582 * beginning of the function). Probably, a better general
5583 * design would be to prevent blk-mq from invoking the requeue
5584 * or finish hooks of an elevator, for a request that is not
5585 * referred by that elevator.
5586 *
5587 * Resetting the following fields would break the
5588 * request-insertion logic if rq is re-inserted into a bfq
5589 * internal queue, without a re-preparation. Here we assume
5590 * that re-insertions of requeued requests, without
5591 * re-preparation, can happen only for pass_through or at_head
5592 * requests (which are not re-inserted into bfq internal
5593 * queues).
5594 */
Paolo Valenteaee69d72017-04-19 08:29:02 -06005595 rq->elv.priv[0] = NULL;
5596 rq->elv.priv[1] = NULL;
5597}
5598
5599/*
Arianna Avanzini36eca892017-04-12 18:23:16 +02005600 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
5601 * was the last process referring to that bfqq.
5602 */
5603static struct bfq_queue *
5604bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
5605{
5606 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
5607
5608 if (bfqq_process_refs(bfqq) == 1) {
5609 bfqq->pid = current->pid;
5610 bfq_clear_bfqq_coop(bfqq);
5611 bfq_clear_bfqq_split_coop(bfqq);
5612 return bfqq;
5613 }
5614
5615 bic_set_bfqq(bic, NULL, 1);
5616
5617 bfq_put_cooperator(bfqq);
5618
5619 bfq_put_queue(bfqq);
5620 return NULL;
5621}
5622
5623static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
5624 struct bfq_io_cq *bic,
5625 struct bio *bio,
5626 bool split, bool is_sync,
5627 bool *new_queue)
5628{
5629 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
5630
5631 if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
5632 return bfqq;
5633
5634 if (new_queue)
5635 *new_queue = true;
5636
5637 if (bfqq)
5638 bfq_put_queue(bfqq);
5639 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
5640
5641 bic_set_bfqq(bic, bfqq, is_sync);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005642 if (split && is_sync) {
5643 if ((bic->was_in_burst_list && bfqd->large_burst) ||
5644 bic->saved_in_large_burst)
5645 bfq_mark_bfqq_in_large_burst(bfqq);
5646 else {
5647 bfq_clear_bfqq_in_large_burst(bfqq);
5648 if (bic->was_in_burst_list)
Paolo Valente99fead82017-10-09 13:11:23 +02005649 /*
5650 * If bfqq was in the current
5651 * burst list before being
5652 * merged, then we have to add
5653 * it back. And we do not need
5654 * to increase burst_size, as
5655 * we did not decrement
5656 * burst_size when we removed
5657 * bfqq from the burst list as
5658 * a consequence of a merge
5659 * (see comments in
5660 * bfq_put_queue). In this
5661 * respect, it would be rather
5662 * costly to know whether the
5663 * current burst list is still
5664 * the same burst list from
5665 * which bfqq was removed on
5666 * the merge. To avoid this
5667 * cost, if bfqq was in a
5668 * burst list, then we add
5669 * bfqq to the current burst
5670 * list without any further
5671 * check. This can cause
5672 * inappropriate insertions,
5673 * but rarely enough to not
5674 * harm the detection of large
5675 * bursts significantly.
5676 */
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005677 hlist_add_head(&bfqq->burst_list_node,
5678 &bfqd->burst_list);
5679 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02005680 bfqq->split_time = jiffies;
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005681 }
Arianna Avanzini36eca892017-04-12 18:23:16 +02005682
5683 return bfqq;
5684}
5685
5686/*
Paolo Valente18e5a572018-05-04 19:17:01 +02005687 * Only reset private fields. The actual request preparation will be
5688 * performed by bfq_init_rq, when rq is either inserted or merged. See
5689 * comments on bfq_init_rq for the reason behind this delayed
5690 * preparation.
Paolo Valenteaee69d72017-04-19 08:29:02 -06005691 */
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005692static void bfq_prepare_request(struct request *rq, struct bio *bio)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005693{
Paolo Valente18e5a572018-05-04 19:17:01 +02005694 /*
5695 * Regardless of whether we have an icq attached, we have to
5696 * clear the scheduler pointers, as they might point to
5697 * previously allocated bic/bfqq structs.
5698 */
5699 rq->elv.priv[0] = rq->elv.priv[1] = NULL;
5700}
5701
5702/*
5703 * If needed, init rq, allocate bfq data structures associated with
5704 * rq, and increment reference counters in the destination bfq_queue
5705 * for rq. Return the destination bfq_queue for rq, or NULL is rq is
5706 * not associated with any bfq_queue.
5707 *
5708 * This function is invoked by the functions that perform rq insertion
5709 * or merging. One may have expected the above preparation operations
5710 * to be performed in bfq_prepare_request, and not delayed to when rq
5711 * is inserted or merged. The rationale behind this delayed
5712 * preparation is that, after the prepare_request hook is invoked for
5713 * rq, rq may still be transformed into a request with no icq, i.e., a
5714 * request not associated with any queue. No bfq hook is invoked to
Angelo Ruocco636b8fe2019-04-08 17:35:34 +02005715 * signal this transformation. As a consequence, should these
Paolo Valente18e5a572018-05-04 19:17:01 +02005716 * preparation operations be performed when the prepare_request hook
5717 * is invoked, and should rq be transformed one moment later, bfq
5718 * would end up in an inconsistent state, because it would have
5719 * incremented some queue counters for an rq destined to
5720 * transformation, without any chance to correctly lower these
5721 * counters back. In contrast, no transformation can still happen for
5722 * rq after rq has been inserted or merged. So, it is safe to execute
5723 * these preparation operations when rq is finally inserted or merged.
5724 */
5725static struct bfq_queue *bfq_init_rq(struct request *rq)
5726{
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02005727 struct request_queue *q = rq->q;
Paolo Valente18e5a572018-05-04 19:17:01 +02005728 struct bio *bio = rq->bio;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005729 struct bfq_data *bfqd = q->elevator->elevator_data;
Christoph Hellwig9f210732017-06-16 18:15:24 +02005730 struct bfq_io_cq *bic;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005731 const int is_sync = rq_is_sync(rq);
5732 struct bfq_queue *bfqq;
Arianna Avanzini36eca892017-04-12 18:23:16 +02005733 bool new_queue = false;
Paolo Valente13c931b2017-06-27 12:30:47 -06005734 bool bfqq_already_existing = false, split = false;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005735
Paolo Valente18e5a572018-05-04 19:17:01 +02005736 if (unlikely(!rq->elv.icq))
5737 return NULL;
5738
Jens Axboe72961c42018-04-17 17:08:52 -06005739 /*
Paolo Valente18e5a572018-05-04 19:17:01 +02005740 * Assuming that elv.priv[1] is set only if everything is set
5741 * for this rq. This holds true, because this function is
5742 * invoked only for insertion or merging, and, after such
5743 * events, a request cannot be manipulated any longer before
5744 * being removed from bfq.
Jens Axboe72961c42018-04-17 17:08:52 -06005745 */
Paolo Valente18e5a572018-05-04 19:17:01 +02005746 if (rq->elv.priv[1])
5747 return rq->elv.priv[1];
Jens Axboe72961c42018-04-17 17:08:52 -06005748
Christoph Hellwig9f210732017-06-16 18:15:24 +02005749 bic = icq_to_bic(rq->elv.icq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005750
Colin Ian King8c9ff1a2017-04-20 15:07:18 +01005751 bfq_check_ioprio_change(bic, bio);
5752
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005753 bfq_bic_update_cgroup(bic, bio);
5754
Arianna Avanzini36eca892017-04-12 18:23:16 +02005755 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
5756 &new_queue);
5757
5758 if (likely(!new_queue)) {
5759 /* If the queue was seeky for too long, break it apart. */
5760 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
5761 bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005762
5763 /* Update bic before losing reference to bfqq */
5764 if (bfq_bfqq_in_large_burst(bfqq))
5765 bic->saved_in_large_burst = true;
5766
Arianna Avanzini36eca892017-04-12 18:23:16 +02005767 bfqq = bfq_split_bfqq(bic, bfqq);
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005768 split = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02005769
5770 if (!bfqq)
5771 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
5772 true, is_sync,
5773 NULL);
Paolo Valente13c931b2017-06-27 12:30:47 -06005774 else
5775 bfqq_already_existing = true;
Arianna Avanzini36eca892017-04-12 18:23:16 +02005776 }
Paolo Valenteaee69d72017-04-19 08:29:02 -06005777 }
5778
5779 bfqq->allocated++;
5780 bfqq->ref++;
5781 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
5782 rq, bfqq, bfqq->ref);
5783
5784 rq->elv.priv[0] = bic;
5785 rq->elv.priv[1] = bfqq;
5786
Arianna Avanzini36eca892017-04-12 18:23:16 +02005787 /*
5788 * If a bfq_queue has only one process reference, it is owned
5789 * by only this bic: we can then set bfqq->bic = bic. in
5790 * addition, if the queue has also just been split, we have to
5791 * resume its state.
5792 */
5793 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
5794 bfqq->bic = bic;
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005795 if (split) {
Arianna Avanzini36eca892017-04-12 18:23:16 +02005796 /*
5797 * The queue has just been split from a shared
5798 * queue: restore the idle window and the
5799 * possible weight raising period.
5800 */
Paolo Valente13c931b2017-06-27 12:30:47 -06005801 bfq_bfqq_resume_state(bfqq, bfqd, bic,
5802 bfqq_already_existing);
Arianna Avanzini36eca892017-04-12 18:23:16 +02005803 }
5804 }
5805
Paolo Valente84a74682019-03-12 09:59:32 +01005806 /*
5807 * Consider bfqq as possibly belonging to a burst of newly
5808 * created queues only if:
5809 * 1) A burst is actually happening (bfqd->burst_size > 0)
5810 * or
5811 * 2) There is no other active queue. In fact, if, in
5812 * contrast, there are active queues not belonging to the
5813 * possible burst bfqq may belong to, then there is no gain
5814 * in considering bfqq as belonging to a burst, and
5815 * therefore in not weight-raising bfqq. See comments on
5816 * bfq_handle_burst().
5817 *
5818 * This filtering also helps eliminating false positives,
5819 * occurring when bfqq does not belong to an actual large
5820 * burst, but some background task (e.g., a service) happens
5821 * to trigger the creation of new queues very close to when
5822 * bfqq and its possible companion queues are created. See
5823 * comments on bfq_handle_burst() for further details also on
5824 * this issue.
5825 */
5826 if (unlikely(bfq_bfqq_just_created(bfqq) &&
5827 (bfqd->burst_size > 0 ||
5828 bfq_tot_busy_queues(bfqd) == 0)))
Arianna Avanzinie1b23242017-04-12 18:23:20 +02005829 bfq_handle_burst(bfqd, bfqq);
5830
Paolo Valente18e5a572018-05-04 19:17:01 +02005831 return bfqq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06005832}
5833
5834static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
5835{
5836 struct bfq_data *bfqd = bfqq->bfqd;
5837 enum bfqq_expiration reason;
5838 unsigned long flags;
5839
5840 spin_lock_irqsave(&bfqd->lock, flags);
5841 bfq_clear_bfqq_wait_request(bfqq);
5842
5843 if (bfqq != bfqd->in_service_queue) {
5844 spin_unlock_irqrestore(&bfqd->lock, flags);
5845 return;
5846 }
5847
5848 if (bfq_bfqq_budget_timeout(bfqq))
5849 /*
5850 * Also here the queue can be safely expired
5851 * for budget timeout without wasting
5852 * guarantees
5853 */
5854 reason = BFQQE_BUDGET_TIMEOUT;
5855 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
5856 /*
5857 * The queue may not be empty upon timer expiration,
5858 * because we may not disable the timer when the
5859 * first request of the in-service queue arrives
5860 * during disk idling.
5861 */
5862 reason = BFQQE_TOO_IDLE;
5863 else
5864 goto schedule_dispatch;
5865
5866 bfq_bfqq_expire(bfqd, bfqq, true, reason);
5867
5868schedule_dispatch:
Paolo Valente6fa3e8d2017-04-12 18:23:21 +02005869 spin_unlock_irqrestore(&bfqd->lock, flags);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005870 bfq_schedule_dispatch(bfqd);
5871}
5872
5873/*
5874 * Handler of the expiration of the timer running if the in-service queue
5875 * is idling inside its time slice.
5876 */
5877static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
5878{
5879 struct bfq_data *bfqd = container_of(timer, struct bfq_data,
5880 idle_slice_timer);
5881 struct bfq_queue *bfqq = bfqd->in_service_queue;
5882
5883 /*
5884 * Theoretical race here: the in-service queue can be NULL or
5885 * different from the queue that was idling if a new request
5886 * arrives for the current queue and there is a full dispatch
5887 * cycle that changes the in-service queue. This can hardly
5888 * happen, but in the worst case we just expire a queue too
5889 * early.
5890 */
5891 if (bfqq)
5892 bfq_idle_slice_timer_body(bfqq);
5893
5894 return HRTIMER_NORESTART;
5895}
5896
5897static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
5898 struct bfq_queue **bfqq_ptr)
5899{
5900 struct bfq_queue *bfqq = *bfqq_ptr;
5901
5902 bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
5903 if (bfqq) {
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005904 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
5905
Paolo Valenteaee69d72017-04-19 08:29:02 -06005906 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
5907 bfqq, bfqq->ref);
5908 bfq_put_queue(bfqq);
5909 *bfqq_ptr = NULL;
5910 }
5911}
5912
5913/*
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005914 * Release all the bfqg references to its async queues. If we are
5915 * deallocating the group these queues may still contain requests, so
5916 * we reparent them to the root cgroup (i.e., the only one that will
5917 * exist for sure until all the requests on a device are gone).
Paolo Valenteaee69d72017-04-19 08:29:02 -06005918 */
Paolo Valenteea25da42017-04-19 08:48:24 -06005919void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
Paolo Valenteaee69d72017-04-19 08:29:02 -06005920{
5921 int i, j;
5922
5923 for (i = 0; i < 2; i++)
5924 for (j = 0; j < IOPRIO_BE_NR; j++)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005925 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005926
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02005927 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
Paolo Valenteaee69d72017-04-19 08:29:02 -06005928}
5929
Jens Axboef0635b82018-05-09 13:27:21 -06005930/*
5931 * See the comments on bfq_limit_depth for the purpose of
Jens Axboe483b7bf2018-05-09 15:26:55 -06005932 * the depths set in the function. Return minimum shallow depth we'll use.
Jens Axboef0635b82018-05-09 13:27:21 -06005933 */
Jens Axboe483b7bf2018-05-09 15:26:55 -06005934static unsigned int bfq_update_depths(struct bfq_data *bfqd,
5935 struct sbitmap_queue *bt)
Jens Axboef0635b82018-05-09 13:27:21 -06005936{
Jens Axboe483b7bf2018-05-09 15:26:55 -06005937 unsigned int i, j, min_shallow = UINT_MAX;
5938
Jens Axboef0635b82018-05-09 13:27:21 -06005939 /*
5940 * In-word depths if no bfq_queue is being weight-raised:
5941 * leaving 25% of tags only for sync reads.
5942 *
5943 * In next formulas, right-shift the value
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005944 * (1U<<bt->sb.shift), instead of computing directly
5945 * (1U<<(bt->sb.shift - something)), to be robust against
5946 * any possible value of bt->sb.shift, without having to
Jens Axboef0635b82018-05-09 13:27:21 -06005947 * limit 'something'.
5948 */
5949 /* no more than 50% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005950 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005951 /*
5952 * no more than 75% of tags for sync writes (25% extra tags
5953 * w.r.t. async I/O, to prevent async I/O from starving sync
5954 * writes)
5955 */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005956 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005957
5958 /*
5959 * In-word depths in case some bfq_queue is being weight-
5960 * raised: leaving ~63% of tags for sync reads. This is the
5961 * highest percentage for which, in our tests, application
5962 * start-up times didn't suffer from any regression due to tag
5963 * shortage.
5964 */
5965 /* no more than ~18% of tags for async I/O */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005966 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U);
Jens Axboef0635b82018-05-09 13:27:21 -06005967 /* no more than ~37% of tags for sync writes (~20% extra tags) */
Jens Axboebd7d4ef2018-05-09 15:25:22 -06005968 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U);
Jens Axboe483b7bf2018-05-09 15:26:55 -06005969
5970 for (i = 0; i < 2; i++)
5971 for (j = 0; j < 2; j++)
5972 min_shallow = min(min_shallow, bfqd->word_depths[i][j]);
5973
5974 return min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005975}
5976
Jens Axboe77f1e0a2019-01-18 10:34:16 -07005977static void bfq_depth_updated(struct blk_mq_hw_ctx *hctx)
Jens Axboef0635b82018-05-09 13:27:21 -06005978{
5979 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
5980 struct blk_mq_tags *tags = hctx->sched_tags;
Jens Axboe483b7bf2018-05-09 15:26:55 -06005981 unsigned int min_shallow;
Jens Axboef0635b82018-05-09 13:27:21 -06005982
Jens Axboe483b7bf2018-05-09 15:26:55 -06005983 min_shallow = bfq_update_depths(bfqd, &tags->bitmap_tags);
5984 sbitmap_queue_min_shallow_depth(&tags->bitmap_tags, min_shallow);
Jens Axboe77f1e0a2019-01-18 10:34:16 -07005985}
5986
5987static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index)
5988{
5989 bfq_depth_updated(hctx);
Jens Axboef0635b82018-05-09 13:27:21 -06005990 return 0;
5991}
5992
Paolo Valenteaee69d72017-04-19 08:29:02 -06005993static void bfq_exit_queue(struct elevator_queue *e)
5994{
5995 struct bfq_data *bfqd = e->elevator_data;
5996 struct bfq_queue *bfqq, *n;
5997
5998 hrtimer_cancel(&bfqd->idle_slice_timer);
5999
6000 spin_lock_irq(&bfqd->lock);
6001 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006002 bfq_deactivate_bfqq(bfqd, bfqq, false, false);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006003 spin_unlock_irq(&bfqd->lock);
6004
6005 hrtimer_cancel(&bfqd->idle_slice_timer);
6006
Jens Axboe8abef102018-01-09 12:20:51 -07006007#ifdef CONFIG_BFQ_GROUP_IOSCHED
Paolo Valente0d52af52018-01-09 10:27:59 +01006008 /* release oom-queue reference to root group */
6009 bfqg_and_blkg_put(bfqd->root_group);
6010
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006011 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
6012#else
6013 spin_lock_irq(&bfqd->lock);
6014 bfq_put_async_queues(bfqd, bfqd->root_group);
6015 kfree(bfqd->root_group);
6016 spin_unlock_irq(&bfqd->lock);
6017#endif
6018
Paolo Valenteaee69d72017-04-19 08:29:02 -06006019 kfree(bfqd);
6020}
6021
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006022static void bfq_init_root_group(struct bfq_group *root_group,
6023 struct bfq_data *bfqd)
6024{
6025 int i;
6026
6027#ifdef CONFIG_BFQ_GROUP_IOSCHED
6028 root_group->entity.parent = NULL;
6029 root_group->my_entity = NULL;
6030 root_group->bfqd = bfqd;
6031#endif
Arianna Avanzini36eca892017-04-12 18:23:16 +02006032 root_group->rq_pos_tree = RB_ROOT;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006033 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
6034 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
6035 root_group->sched_data.bfq_class_idle_last_service = jiffies;
6036}
6037
Paolo Valenteaee69d72017-04-19 08:29:02 -06006038static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
6039{
6040 struct bfq_data *bfqd;
6041 struct elevator_queue *eq;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006042
6043 eq = elevator_alloc(q, e);
6044 if (!eq)
6045 return -ENOMEM;
6046
6047 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
6048 if (!bfqd) {
6049 kobject_put(&eq->kobj);
6050 return -ENOMEM;
6051 }
6052 eq->elevator_data = bfqd;
6053
Christoph Hellwig0d945c12018-11-15 12:17:28 -07006054 spin_lock_irq(&q->queue_lock);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006055 q->elevator = eq;
Christoph Hellwig0d945c12018-11-15 12:17:28 -07006056 spin_unlock_irq(&q->queue_lock);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006057
Paolo Valenteaee69d72017-04-19 08:29:02 -06006058 /*
6059 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
6060 * Grab a permanent reference to it, so that the normal code flow
6061 * will not attempt to free it.
6062 */
6063 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
6064 bfqd->oom_bfqq.ref++;
6065 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
6066 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
6067 bfqd->oom_bfqq.entity.new_weight =
6068 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02006069
6070 /* oom_bfqq does not participate to bursts */
6071 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
6072
Paolo Valenteaee69d72017-04-19 08:29:02 -06006073 /*
6074 * Trigger weight initialization, according to ioprio, at the
6075 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
6076 * class won't be changed any more.
6077 */
6078 bfqd->oom_bfqq.entity.prio_changed = 1;
6079
6080 bfqd->queue = q;
6081
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006082 INIT_LIST_HEAD(&bfqd->dispatch);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006083
6084 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
6085 HRTIMER_MODE_REL);
6086 bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
6087
Paolo Valentefb53ac62019-03-12 09:59:28 +01006088 bfqd->queue_weights_tree = RB_ROOT_CACHED;
Paolo Valenteba7aeae2018-12-06 19:18:18 +01006089 bfqd->num_groups_with_pending_reqs = 0;
Arianna Avanzini1de0c4c2017-04-12 18:23:17 +02006090
Paolo Valenteaee69d72017-04-19 08:29:02 -06006091 INIT_LIST_HEAD(&bfqd->active_list);
6092 INIT_LIST_HEAD(&bfqd->idle_list);
Arianna Avanzinie1b23242017-04-12 18:23:20 +02006093 INIT_HLIST_HEAD(&bfqd->burst_list);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006094
6095 bfqd->hw_tag = -1;
Paolo Valente8cacc5a2019-03-12 09:59:30 +01006096 bfqd->nonrot_with_queueing = blk_queue_nonrot(bfqd->queue);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006097
6098 bfqd->bfq_max_budget = bfq_default_max_budget;
6099
6100 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
6101 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
6102 bfqd->bfq_back_max = bfq_back_max;
6103 bfqd->bfq_back_penalty = bfq_back_penalty;
6104 bfqd->bfq_slice_idle = bfq_slice_idle;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006105 bfqd->bfq_timeout = bfq_timeout;
6106
6107 bfqd->bfq_requests_within_timer = 120;
6108
Arianna Avanzinie1b23242017-04-12 18:23:20 +02006109 bfqd->bfq_large_burst_thresh = 8;
6110 bfqd->bfq_burst_interval = msecs_to_jiffies(180);
6111
Paolo Valente44e44a12017-04-12 18:23:12 +02006112 bfqd->low_latency = true;
6113
6114 /*
6115 * Trade-off between responsiveness and fairness.
6116 */
6117 bfqd->bfq_wr_coeff = 30;
Paolo Valente77b7dce2017-04-12 18:23:13 +02006118 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
Paolo Valente44e44a12017-04-12 18:23:12 +02006119 bfqd->bfq_wr_max_time = 0;
6120 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
6121 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
Paolo Valente77b7dce2017-04-12 18:23:13 +02006122 bfqd->bfq_wr_max_softrt_rate = 7000; /*
6123 * Approximate rate required
6124 * to playback or record a
6125 * high-definition compressed
6126 * video.
6127 */
Paolo Valentecfd69712017-04-12 18:23:15 +02006128 bfqd->wr_busy_queues = 0;
Paolo Valente44e44a12017-04-12 18:23:12 +02006129
6130 /*
Paolo Valentee24f1c22018-05-31 16:45:06 +02006131 * Begin by assuming, optimistically, that the device peak
6132 * rate is equal to 2/3 of the highest reference rate.
Paolo Valente44e44a12017-04-12 18:23:12 +02006133 */
Paolo Valentee24f1c22018-05-31 16:45:06 +02006134 bfqd->rate_dur_prod = ref_rate[blk_queue_nonrot(bfqd->queue)] *
6135 ref_wr_duration[blk_queue_nonrot(bfqd->queue)];
6136 bfqd->peak_rate = ref_rate[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
Paolo Valente44e44a12017-04-12 18:23:12 +02006137
Paolo Valenteaee69d72017-04-19 08:29:02 -06006138 spin_lock_init(&bfqd->lock);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006139
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006140 /*
6141 * The invocation of the next bfq_create_group_hierarchy
6142 * function is the head of a chain of function calls
6143 * (bfq_create_group_hierarchy->blkcg_activate_policy->
6144 * blk_mq_freeze_queue) that may lead to the invocation of the
6145 * has_work hook function. For this reason,
6146 * bfq_create_group_hierarchy is invoked only after all
6147 * scheduler data has been initialized, apart from the fields
6148 * that can be initialized only after invoking
6149 * bfq_create_group_hierarchy. This, in particular, enables
6150 * has_work to correctly return false. Of course, to avoid
6151 * other inconsistencies, the blk-mq stack must then refrain
6152 * from invoking further scheduler hooks before this init
6153 * function is finished.
6154 */
6155 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
6156 if (!bfqd->root_group)
6157 goto out_free;
6158 bfq_init_root_group(bfqd->root_group, bfqd);
6159 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
6160
Luca Micciob5dc5d42017-10-09 16:27:21 +02006161 wbt_disable_default(q);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006162 return 0;
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006163
6164out_free:
6165 kfree(bfqd);
6166 kobject_put(&eq->kobj);
6167 return -ENOMEM;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006168}
6169
6170static void bfq_slab_kill(void)
6171{
6172 kmem_cache_destroy(bfq_pool);
6173}
6174
6175static int __init bfq_slab_setup(void)
6176{
6177 bfq_pool = KMEM_CACHE(bfq_queue, 0);
6178 if (!bfq_pool)
6179 return -ENOMEM;
6180 return 0;
6181}
6182
6183static ssize_t bfq_var_show(unsigned int var, char *page)
6184{
6185 return sprintf(page, "%u\n", var);
6186}
6187
Bart Van Assche2f791362017-08-30 11:42:09 -07006188static int bfq_var_store(unsigned long *var, const char *page)
Paolo Valenteaee69d72017-04-19 08:29:02 -06006189{
6190 unsigned long new_val;
6191 int ret = kstrtoul(page, 10, &new_val);
6192
Bart Van Assche2f791362017-08-30 11:42:09 -07006193 if (ret)
6194 return ret;
6195 *var = new_val;
6196 return 0;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006197}
6198
6199#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
6200static ssize_t __FUNC(struct elevator_queue *e, char *page) \
6201{ \
6202 struct bfq_data *bfqd = e->elevator_data; \
6203 u64 __data = __VAR; \
6204 if (__CONV == 1) \
6205 __data = jiffies_to_msecs(__data); \
6206 else if (__CONV == 2) \
6207 __data = div_u64(__data, NSEC_PER_MSEC); \
6208 return bfq_var_show(__data, (page)); \
6209}
6210SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
6211SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
6212SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
6213SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
6214SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
6215SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
6216SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
6217SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
Paolo Valente44e44a12017-04-12 18:23:12 +02006218SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006219#undef SHOW_FUNCTION
6220
6221#define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
6222static ssize_t __FUNC(struct elevator_queue *e, char *page) \
6223{ \
6224 struct bfq_data *bfqd = e->elevator_data; \
6225 u64 __data = __VAR; \
6226 __data = div_u64(__data, NSEC_PER_USEC); \
6227 return bfq_var_show(__data, (page)); \
6228}
6229USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
6230#undef USEC_SHOW_FUNCTION
6231
6232#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
6233static ssize_t \
6234__FUNC(struct elevator_queue *e, const char *page, size_t count) \
6235{ \
6236 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07006237 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07006238 int ret; \
6239 \
6240 ret = bfq_var_store(&__data, (page)); \
6241 if (ret) \
6242 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07006243 if (__data < __min) \
6244 __data = __min; \
6245 else if (__data > __max) \
6246 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06006247 if (__CONV == 1) \
6248 *(__PTR) = msecs_to_jiffies(__data); \
6249 else if (__CONV == 2) \
6250 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
6251 else \
6252 *(__PTR) = __data; \
weiping zhang235f8da2017-08-25 01:11:33 +08006253 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06006254}
6255STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
6256 INT_MAX, 2);
6257STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
6258 INT_MAX, 2);
6259STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
6260STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
6261 INT_MAX, 0);
6262STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
6263#undef STORE_FUNCTION
6264
6265#define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
6266static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
6267{ \
6268 struct bfq_data *bfqd = e->elevator_data; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07006269 unsigned long __data, __min = (MIN), __max = (MAX); \
Bart Van Assche2f791362017-08-30 11:42:09 -07006270 int ret; \
6271 \
6272 ret = bfq_var_store(&__data, (page)); \
6273 if (ret) \
6274 return ret; \
Bart Van Assche1530486c2017-08-30 11:42:10 -07006275 if (__data < __min) \
6276 __data = __min; \
6277 else if (__data > __max) \
6278 __data = __max; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06006279 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
weiping zhang235f8da2017-08-25 01:11:33 +08006280 return count; \
Paolo Valenteaee69d72017-04-19 08:29:02 -06006281}
6282USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
6283 UINT_MAX);
6284#undef USEC_STORE_FUNCTION
6285
Paolo Valenteaee69d72017-04-19 08:29:02 -06006286static ssize_t bfq_max_budget_store(struct elevator_queue *e,
6287 const char *page, size_t count)
6288{
6289 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07006290 unsigned long __data;
6291 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08006292
Bart Van Assche2f791362017-08-30 11:42:09 -07006293 ret = bfq_var_store(&__data, (page));
6294 if (ret)
6295 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006296
6297 if (__data == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02006298 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006299 else {
6300 if (__data > INT_MAX)
6301 __data = INT_MAX;
6302 bfqd->bfq_max_budget = __data;
6303 }
6304
6305 bfqd->bfq_user_max_budget = __data;
6306
weiping zhang235f8da2017-08-25 01:11:33 +08006307 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006308}
6309
6310/*
6311 * Leaving this name to preserve name compatibility with cfq
6312 * parameters, but this timeout is used for both sync and async.
6313 */
6314static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
6315 const char *page, size_t count)
6316{
6317 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07006318 unsigned long __data;
6319 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08006320
Bart Van Assche2f791362017-08-30 11:42:09 -07006321 ret = bfq_var_store(&__data, (page));
6322 if (ret)
6323 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006324
6325 if (__data < 1)
6326 __data = 1;
6327 else if (__data > INT_MAX)
6328 __data = INT_MAX;
6329
6330 bfqd->bfq_timeout = msecs_to_jiffies(__data);
6331 if (bfqd->bfq_user_max_budget == 0)
Paolo Valenteab0e43e2017-04-12 18:23:10 +02006332 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
Paolo Valenteaee69d72017-04-19 08:29:02 -06006333
weiping zhang235f8da2017-08-25 01:11:33 +08006334 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006335}
6336
6337static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
6338 const char *page, size_t count)
6339{
6340 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07006341 unsigned long __data;
6342 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08006343
Bart Van Assche2f791362017-08-30 11:42:09 -07006344 ret = bfq_var_store(&__data, (page));
6345 if (ret)
6346 return ret;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006347
6348 if (__data > 1)
6349 __data = 1;
6350 if (!bfqd->strict_guarantees && __data == 1
6351 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
6352 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
6353
6354 bfqd->strict_guarantees = __data;
6355
weiping zhang235f8da2017-08-25 01:11:33 +08006356 return count;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006357}
6358
Paolo Valente44e44a12017-04-12 18:23:12 +02006359static ssize_t bfq_low_latency_store(struct elevator_queue *e,
6360 const char *page, size_t count)
6361{
6362 struct bfq_data *bfqd = e->elevator_data;
Bart Van Assche2f791362017-08-30 11:42:09 -07006363 unsigned long __data;
6364 int ret;
weiping zhang235f8da2017-08-25 01:11:33 +08006365
Bart Van Assche2f791362017-08-30 11:42:09 -07006366 ret = bfq_var_store(&__data, (page));
6367 if (ret)
6368 return ret;
Paolo Valente44e44a12017-04-12 18:23:12 +02006369
6370 if (__data > 1)
6371 __data = 1;
6372 if (__data == 0 && bfqd->low_latency != 0)
6373 bfq_end_wr(bfqd);
6374 bfqd->low_latency = __data;
6375
weiping zhang235f8da2017-08-25 01:11:33 +08006376 return count;
Paolo Valente44e44a12017-04-12 18:23:12 +02006377}
6378
Paolo Valenteaee69d72017-04-19 08:29:02 -06006379#define BFQ_ATTR(name) \
6380 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
6381
6382static struct elv_fs_entry bfq_attrs[] = {
6383 BFQ_ATTR(fifo_expire_sync),
6384 BFQ_ATTR(fifo_expire_async),
6385 BFQ_ATTR(back_seek_max),
6386 BFQ_ATTR(back_seek_penalty),
6387 BFQ_ATTR(slice_idle),
6388 BFQ_ATTR(slice_idle_us),
6389 BFQ_ATTR(max_budget),
6390 BFQ_ATTR(timeout_sync),
6391 BFQ_ATTR(strict_guarantees),
Paolo Valente44e44a12017-04-12 18:23:12 +02006392 BFQ_ATTR(low_latency),
Paolo Valenteaee69d72017-04-19 08:29:02 -06006393 __ATTR_NULL
6394};
6395
6396static struct elevator_type iosched_bfq_mq = {
Jens Axboef9cd4bf2018-11-01 16:41:41 -06006397 .ops = {
Paolo Valentea52a69e2018-01-13 12:05:17 +01006398 .limit_depth = bfq_limit_depth,
Christoph Hellwig5bbf4e52017-06-16 18:15:26 +02006399 .prepare_request = bfq_prepare_request,
Paolo Valentea7877392018-02-07 22:19:20 +01006400 .requeue_request = bfq_finish_requeue_request,
6401 .finish_request = bfq_finish_requeue_request,
Paolo Valenteaee69d72017-04-19 08:29:02 -06006402 .exit_icq = bfq_exit_icq,
6403 .insert_requests = bfq_insert_requests,
6404 .dispatch_request = bfq_dispatch_request,
6405 .next_request = elv_rb_latter_request,
6406 .former_request = elv_rb_former_request,
6407 .allow_merge = bfq_allow_bio_merge,
6408 .bio_merge = bfq_bio_merge,
6409 .request_merge = bfq_request_merge,
6410 .requests_merged = bfq_requests_merged,
6411 .request_merged = bfq_request_merged,
6412 .has_work = bfq_has_work,
Jens Axboe77f1e0a2019-01-18 10:34:16 -07006413 .depth_updated = bfq_depth_updated,
Jens Axboef0635b82018-05-09 13:27:21 -06006414 .init_hctx = bfq_init_hctx,
Paolo Valenteaee69d72017-04-19 08:29:02 -06006415 .init_sched = bfq_init_queue,
6416 .exit_sched = bfq_exit_queue,
6417 },
6418
Paolo Valenteaee69d72017-04-19 08:29:02 -06006419 .icq_size = sizeof(struct bfq_io_cq),
6420 .icq_align = __alignof__(struct bfq_io_cq),
6421 .elevator_attrs = bfq_attrs,
6422 .elevator_name = "bfq",
6423 .elevator_owner = THIS_MODULE,
6424};
Ben Hutchings26b4cf22017-08-13 18:02:19 +01006425MODULE_ALIAS("bfq-iosched");
Paolo Valenteaee69d72017-04-19 08:29:02 -06006426
6427static int __init bfq_init(void)
6428{
6429 int ret;
6430
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006431#ifdef CONFIG_BFQ_GROUP_IOSCHED
6432 ret = blkcg_policy_register(&blkcg_policy_bfq);
6433 if (ret)
6434 return ret;
6435#endif
6436
Paolo Valenteaee69d72017-04-19 08:29:02 -06006437 ret = -ENOMEM;
6438 if (bfq_slab_setup())
6439 goto err_pol_unreg;
6440
Paolo Valente44e44a12017-04-12 18:23:12 +02006441 /*
6442 * Times to load large popular applications for the typical
6443 * systems installed on the reference devices (see the
Paolo Valentee24f1c22018-05-31 16:45:06 +02006444 * comments before the definition of the next
6445 * array). Actually, we use slightly lower values, as the
Paolo Valente44e44a12017-04-12 18:23:12 +02006446 * estimated peak rate tends to be smaller than the actual
6447 * peak rate. The reason for this last fact is that estimates
6448 * are computed over much shorter time intervals than the long
6449 * intervals typically used for benchmarking. Why? First, to
6450 * adapt more quickly to variations. Second, because an I/O
6451 * scheduler cannot rely on a peak-rate-evaluation workload to
6452 * be run for a long time.
6453 */
Paolo Valentee24f1c22018-05-31 16:45:06 +02006454 ref_wr_duration[0] = msecs_to_jiffies(7000); /* actually 8 sec */
6455 ref_wr_duration[1] = msecs_to_jiffies(2500); /* actually 3 sec */
Paolo Valente44e44a12017-04-12 18:23:12 +02006456
Paolo Valenteaee69d72017-04-19 08:29:02 -06006457 ret = elv_register(&iosched_bfq_mq);
6458 if (ret)
weiping zhang37dcd652017-08-19 00:37:20 +08006459 goto slab_kill;
Paolo Valenteaee69d72017-04-19 08:29:02 -06006460
6461 return 0;
6462
weiping zhang37dcd652017-08-19 00:37:20 +08006463slab_kill:
6464 bfq_slab_kill();
Paolo Valenteaee69d72017-04-19 08:29:02 -06006465err_pol_unreg:
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006466#ifdef CONFIG_BFQ_GROUP_IOSCHED
6467 blkcg_policy_unregister(&blkcg_policy_bfq);
6468#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06006469 return ret;
6470}
6471
6472static void __exit bfq_exit(void)
6473{
6474 elv_unregister(&iosched_bfq_mq);
Arianna Avanzinie21b7a02017-04-12 18:23:08 +02006475#ifdef CONFIG_BFQ_GROUP_IOSCHED
6476 blkcg_policy_unregister(&blkcg_policy_bfq);
6477#endif
Paolo Valenteaee69d72017-04-19 08:29:02 -06006478 bfq_slab_kill();
6479}
6480
6481module_init(bfq_init);
6482module_exit(bfq_exit);
6483
6484MODULE_AUTHOR("Paolo Valente");
6485MODULE_LICENSE("GPL");
6486MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");