block, bfq: get a ref to a group when adding it to a service tree
[linux-block.git] / block / bfq-iosched.c
CommitLineData
a497ee34 1// SPDX-License-Identifier: GPL-2.0-or-later
aee69d78
PV
2/*
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 *
aee69d78
PV
16 * 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
898bd37a 20 * limitations can be found in Documentation/block/bfq-iosched.rst.
aee69d78
PV
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
4029eef1
PV
43 * 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
aee69d78
PV
76 * 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 *
43c1b3d6
PV
80 * 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 *
4029eef1
PV
85 * 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+.
aee69d78
PV
93 *
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>
e21b7a0b 119#include <linux/cgroup.h>
aee69d78
PV
120#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"
ea25da48 131#include "bfq-iosched.h"
b5dc5d4d 132#include "blk-wbt.h"
aee69d78 133
ea25da48
PV
134#define BFQ_BFQQ_FNS(name) \
135void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \
136{ \
137 __set_bit(BFQQF_##name, &(bfqq)->flags); \
138} \
139void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \
140{ \
141 __clear_bit(BFQQF_##name, &(bfqq)->flags); \
142} \
143int bfq_bfqq_##name(const struct bfq_queue *bfqq) \
144{ \
145 return test_bit(BFQQF_##name, &(bfqq)->flags); \
44e44a1b
PV
146}
147
ea25da48
PV
148BFQ_BFQQ_FNS(just_created);
149BFQ_BFQQ_FNS(busy);
150BFQ_BFQQ_FNS(wait_request);
151BFQ_BFQQ_FNS(non_blocking_wait_rq);
152BFQ_BFQQ_FNS(fifo_expire);
d5be3fef 153BFQ_BFQQ_FNS(has_short_ttime);
ea25da48
PV
154BFQ_BFQQ_FNS(sync);
155BFQ_BFQQ_FNS(IO_bound);
156BFQ_BFQQ_FNS(in_large_burst);
157BFQ_BFQQ_FNS(coop);
158BFQ_BFQQ_FNS(split_coop);
159BFQ_BFQQ_FNS(softrt_update);
13a857a4 160BFQ_BFQQ_FNS(has_waker);
ea25da48 161#undef BFQ_BFQQ_FNS \
aee69d78 162
ea25da48
PV
163/* Expiration time of sync (0) and async (1) requests, in ns. */
164static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
aee69d78 165
ea25da48
PV
166/* Maximum backwards seek (magic number lifted from CFQ), in KiB. */
167static const int bfq_back_max = 16 * 1024;
aee69d78 168
ea25da48
PV
169/* Penalty of a backwards seek, in number of sectors. */
170static const int bfq_back_penalty = 2;
e21b7a0b 171
ea25da48
PV
172/* Idling period duration, in ns. */
173static u64 bfq_slice_idle = NSEC_PER_SEC / 125;
aee69d78 174
ea25da48
PV
175/* Minimum number of assigned budgets for which stats are safe to compute. */
176static const int bfq_stats_min_budgets = 194;
aee69d78 177
ea25da48
PV
178/* Default maximum budget values, in sectors and number of requests. */
179static const int bfq_default_max_budget = 16 * 1024;
e21b7a0b 180
ea25da48 181/*
d5801088
PV
182 * When a sync request is dispatched, the queue that contains that
183 * request, and all the ancestor entities of that queue, are charged
636b8fe8 184 * with the number of sectors of the request. In contrast, if the
d5801088
PV
185 * request is async, then the queue and its ancestor entities are
186 * charged with the number of sectors of the request, multiplied by
187 * the factor below. This throttles the bandwidth for async I/O,
188 * w.r.t. to sync I/O, and it is done to counter the tendency of async
189 * writes to steal I/O throughput to reads.
190 *
191 * The current value of this parameter is the result of a tuning with
192 * several hardware and software configurations. We tried to find the
193 * lowest value for which writes do not cause noticeable problems to
194 * reads. In fact, the lower this parameter, the stabler I/O control,
195 * in the following respect. The lower this parameter is, the less
196 * the bandwidth enjoyed by a group decreases
197 * - when the group does writes, w.r.t. to when it does reads;
198 * - when other groups do reads, w.r.t. to when they do writes.
ea25da48 199 */
d5801088 200static const int bfq_async_charge_factor = 3;
aee69d78 201
ea25da48
PV
202/* Default timeout values, in jiffies, approximating CFQ defaults. */
203const int bfq_timeout = HZ / 8;
aee69d78 204
7b8fa3b9
PV
205/*
206 * Time limit for merging (see comments in bfq_setup_cooperator). Set
207 * to the slowest value that, in our tests, proved to be effective in
208 * removing false positives, while not causing true positives to miss
209 * queue merging.
210 *
211 * As can be deduced from the low time limit below, queue merging, if
636b8fe8 212 * successful, happens at the very beginning of the I/O of the involved
7b8fa3b9
PV
213 * cooperating processes, as a consequence of the arrival of the very
214 * first requests from each cooperator. After that, there is very
215 * little chance to find cooperators.
216 */
217static const unsigned long bfq_merge_time_limit = HZ/10;
218
ea25da48 219static struct kmem_cache *bfq_pool;
e21b7a0b 220
ea25da48
PV
221/* Below this threshold (in ns), we consider thinktime immediate. */
222#define BFQ_MIN_TT (2 * NSEC_PER_MSEC)
e21b7a0b 223
ea25da48 224/* hw_tag detection: parallel requests threshold and min samples needed. */
a3c92560 225#define BFQ_HW_QUEUE_THRESHOLD 3
ea25da48 226#define BFQ_HW_QUEUE_SAMPLES 32
aee69d78 227
ea25da48
PV
228#define BFQQ_SEEK_THR (sector_t)(8 * 100)
229#define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
d87447d8
PV
230#define BFQ_RQ_SEEKY(bfqd, last_pos, rq) \
231 (get_sdist(last_pos, rq) > \
232 BFQQ_SEEK_THR && \
233 (!blk_queue_nonrot(bfqd->queue) || \
234 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT))
ea25da48 235#define BFQQ_CLOSE_THR (sector_t)(8 * 1024)
f0ba5ea2 236#define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19)
7074f076
PV
237/*
238 * Sync random I/O is likely to be confused with soft real-time I/O,
239 * because it is characterized by limited throughput and apparently
240 * isochronous arrival pattern. To avoid false positives, queues
241 * containing only random (seeky) I/O are prevented from being tagged
242 * as soft real-time.
243 */
e6feaf21 244#define BFQQ_TOTALLY_SEEKY(bfqq) (bfqq->seek_history == -1)
aee69d78 245
ea25da48
PV
246/* Min number of samples required to perform peak-rate update */
247#define BFQ_RATE_MIN_SAMPLES 32
248/* Min observation time interval required to perform a peak-rate update (ns) */
249#define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC)
250/* Target observation time interval for a peak-rate update (ns) */
251#define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC
aee69d78 252
bc56e2ca
PV
253/*
254 * Shift used for peak-rate fixed precision calculations.
255 * With
256 * - the current shift: 16 positions
257 * - the current type used to store rate: u32
258 * - the current unit of measure for rate: [sectors/usec], or, more precisely,
259 * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift,
260 * the range of rates that can be stored is
261 * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec =
262 * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec =
263 * [15, 65G] sectors/sec
264 * Which, assuming a sector size of 512B, corresponds to a range of
265 * [7.5K, 33T] B/sec
266 */
ea25da48 267#define BFQ_RATE_SHIFT 16
aee69d78 268
ea25da48 269/*
4029eef1
PV
270 * When configured for computing the duration of the weight-raising
271 * for interactive queues automatically (see the comments at the
272 * beginning of this file), BFQ does it using the following formula:
e24f1c24
PV
273 * duration = (ref_rate / r) * ref_wr_duration,
274 * where r is the peak rate of the device, and ref_rate and
275 * ref_wr_duration are two reference parameters. In particular,
276 * ref_rate is the peak rate of the reference storage device (see
277 * below), and ref_wr_duration is about the maximum time needed, with
278 * BFQ and while reading two files in parallel, to load typical large
279 * applications on the reference device (see the comments on
280 * max_service_from_wr below, for more details on how ref_wr_duration
281 * is obtained). In practice, the slower/faster the device at hand
282 * is, the more/less it takes to load applications with respect to the
4029eef1
PV
283 * reference device. Accordingly, the longer/shorter BFQ grants
284 * weight raising to interactive applications.
ea25da48 285 *
e24f1c24
PV
286 * BFQ uses two different reference pairs (ref_rate, ref_wr_duration),
287 * depending on whether the device is rotational or non-rotational.
ea25da48 288 *
e24f1c24
PV
289 * In the following definitions, ref_rate[0] and ref_wr_duration[0]
290 * are the reference values for a rotational device, whereas
291 * ref_rate[1] and ref_wr_duration[1] are the reference values for a
292 * non-rotational device. The reference rates are not the actual peak
293 * rates of the devices used as a reference, but slightly lower
294 * values. The reason for using slightly lower values is that the
295 * peak-rate estimator tends to yield slightly lower values than the
296 * actual peak rate (it can yield the actual peak rate only if there
297 * is only one process doing I/O, and the process does sequential
298 * I/O).
ea25da48 299 *
e24f1c24
PV
300 * The reference peak rates are measured in sectors/usec, left-shifted
301 * by BFQ_RATE_SHIFT.
ea25da48 302 */
e24f1c24 303static int ref_rate[2] = {14000, 33000};
ea25da48 304/*
e24f1c24
PV
305 * To improve readability, a conversion function is used to initialize
306 * the following array, which entails that the array can be
307 * initialized only in a function.
ea25da48 308 */
e24f1c24 309static int ref_wr_duration[2];
aee69d78 310
8a8747dc
PV
311/*
312 * BFQ uses the above-detailed, time-based weight-raising mechanism to
313 * privilege interactive tasks. This mechanism is vulnerable to the
314 * following false positives: I/O-bound applications that will go on
315 * doing I/O for much longer than the duration of weight
316 * raising. These applications have basically no benefit from being
317 * weight-raised at the beginning of their I/O. On the opposite end,
318 * while being weight-raised, these applications
319 * a) unjustly steal throughput to applications that may actually need
320 * low latency;
321 * b) make BFQ uselessly perform device idling; device idling results
322 * in loss of device throughput with most flash-based storage, and may
323 * increase latencies when used purposelessly.
324 *
325 * BFQ tries to reduce these problems, by adopting the following
326 * countermeasure. To introduce this countermeasure, we need first to
327 * finish explaining how the duration of weight-raising for
328 * interactive tasks is computed.
329 *
330 * For a bfq_queue deemed as interactive, the duration of weight
331 * raising is dynamically adjusted, as a function of the estimated
332 * peak rate of the device, so as to be equal to the time needed to
333 * execute the 'largest' interactive task we benchmarked so far. By
334 * largest task, we mean the task for which each involved process has
335 * to do more I/O than for any of the other tasks we benchmarked. This
336 * reference interactive task is the start-up of LibreOffice Writer,
337 * and in this task each process/bfq_queue needs to have at most ~110K
338 * sectors transferred.
339 *
340 * This last piece of information enables BFQ to reduce the actual
341 * duration of weight-raising for at least one class of I/O-bound
342 * applications: those doing sequential or quasi-sequential I/O. An
343 * example is file copy. In fact, once started, the main I/O-bound
344 * processes of these applications usually consume the above 110K
345 * sectors in much less time than the processes of an application that
346 * is starting, because these I/O-bound processes will greedily devote
347 * almost all their CPU cycles only to their target,
348 * throughput-friendly I/O operations. This is even more true if BFQ
349 * happens to be underestimating the device peak rate, and thus
350 * overestimating the duration of weight raising. But, according to
351 * our measurements, once transferred 110K sectors, these processes
352 * have no right to be weight-raised any longer.
353 *
354 * Basing on the last consideration, BFQ ends weight-raising for a
355 * bfq_queue if the latter happens to have received an amount of
356 * service at least equal to the following constant. The constant is
357 * set to slightly more than 110K, to have a minimum safety margin.
358 *
359 * This early ending of weight-raising reduces the amount of time
360 * during which interactive false positives cause the two problems
361 * described at the beginning of these comments.
362 */
363static const unsigned long max_service_from_wr = 120000;
364
12cd3a2f 365#define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0])
ea25da48 366#define RQ_BFQQ(rq) ((rq)->elv.priv[1])
aee69d78 367
ea25da48 368struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync)
e21b7a0b 369{
ea25da48 370 return bic->bfqq[is_sync];
aee69d78
PV
371}
372
ea25da48 373void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync)
aee69d78 374{
ea25da48 375 bic->bfqq[is_sync] = bfqq;
aee69d78
PV
376}
377
ea25da48 378struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic)
aee69d78 379{
ea25da48 380 return bic->icq.q->elevator->elevator_data;
e21b7a0b 381}
aee69d78 382
ea25da48
PV
383/**
384 * icq_to_bic - convert iocontext queue structure to bfq_io_cq.
385 * @icq: the iocontext queue.
386 */
387static struct bfq_io_cq *icq_to_bic(struct io_cq *icq)
e21b7a0b 388{
ea25da48
PV
389 /* bic->icq is the first member, %NULL will convert to %NULL */
390 return container_of(icq, struct bfq_io_cq, icq);
e21b7a0b 391}
aee69d78 392
ea25da48
PV
393/**
394 * bfq_bic_lookup - search into @ioc a bic associated to @bfqd.
395 * @bfqd: the lookup key.
396 * @ioc: the io_context of the process doing I/O.
397 * @q: the request queue.
398 */
399static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
400 struct io_context *ioc,
401 struct request_queue *q)
e21b7a0b 402{
ea25da48
PV
403 if (ioc) {
404 unsigned long flags;
405 struct bfq_io_cq *icq;
aee69d78 406
0d945c1f 407 spin_lock_irqsave(&q->queue_lock, flags);
ea25da48 408 icq = icq_to_bic(ioc_lookup_icq(ioc, q));
0d945c1f 409 spin_unlock_irqrestore(&q->queue_lock, flags);
aee69d78 410
ea25da48 411 return icq;
e21b7a0b 412 }
e21b7a0b 413
ea25da48 414 return NULL;
aee69d78
PV
415}
416
ea25da48
PV
417/*
418 * Scheduler run of queue, if there are requests pending and no one in the
419 * driver that will restart queueing.
420 */
421void bfq_schedule_dispatch(struct bfq_data *bfqd)
aee69d78 422{
ea25da48
PV
423 if (bfqd->queued != 0) {
424 bfq_log(bfqd, "schedule dispatch");
425 blk_mq_run_hw_queues(bfqd->queue, true);
e21b7a0b 426 }
aee69d78
PV
427}
428
429#define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
aee69d78
PV
430
431#define bfq_sample_valid(samples) ((samples) > 80)
432
aee69d78
PV
433/*
434 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
636b8fe8 435 * We choose the request that is closer to the head right now. Distance
aee69d78
PV
436 * 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
a52a69ea
PV
527/*
528 * 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{
a52a69ea 536 struct bfq_data *bfqd = data->q->elevator->elevator_data;
a52a69ea
PV
537
538 if (op_is_sync(op) && !op_is_write(op))
539 return;
540
a52a69ea
PV
541 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
36eca894
AA
549static 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
7b8fa3b9
PV
590static 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
8cacc5ab
PV
597/*
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)
36eca894
AA
607{
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
32c59e3a
PV
616 /* oom_bfqq does not participate in queue merging */
617 if (bfqq == &bfqd->oom_bfqq)
618 return;
619
7b8fa3b9
PV
620 /*
621 * bfqq cannot be merged any longer (see comments in
622 * bfq_setup_cooperator): no point in adding bfqq into the
623 * position tree.
624 */
625 if (bfq_too_late_for_merging(bfqq))
626 return;
627
36eca894
AA
628 if (bfq_class_idle(bfqq))
629 return;
630 if (!bfqq->next_rq)
631 return;
632
633 bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
634 __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root,
635 blk_rq_pos(bfqq->next_rq), &parent, &p);
636 if (!__bfqq) {
637 rb_link_node(&bfqq->pos_node, parent, p);
638 rb_insert_color(&bfqq->pos_node, bfqq->pos_root);
639 } else
640 bfqq->pos_root = NULL;
641}
642
1de0c4cd 643/*
fb53ac6c
PV
644 * The following function returns false either if every active queue
645 * must receive the same share of the throughput (symmetric scenario),
646 * or, as a special case, if bfqq must receive a share of the
647 * throughput lower than or equal to the share that every other active
648 * queue must receive. If bfqq does sync I/O, then these are the only
649 * two cases where bfqq happens to be guaranteed its share of the
650 * throughput even if I/O dispatching is not plugged when bfqq remains
651 * temporarily empty (for more details, see the comments in the
652 * function bfq_better_to_idle()). For this reason, the return value
653 * of this function is used to check whether I/O-dispatch plugging can
654 * be avoided.
1de0c4cd 655 *
fb53ac6c 656 * The above first case (symmetric scenario) occurs when:
1de0c4cd 657 * 1) all active queues have the same weight,
73d58118 658 * 2) all active queues belong to the same I/O-priority class,
1de0c4cd 659 * 3) all active groups at the same level in the groups tree have the same
73d58118
PV
660 * weight,
661 * 4) all active groups at the same level in the groups tree have the same
1de0c4cd
AA
662 * number of children.
663 *
2d29c9f8
FM
664 * Unfortunately, keeping the necessary state for evaluating exactly
665 * the last two symmetry sub-conditions above would be quite complex
73d58118
PV
666 * and time consuming. Therefore this function evaluates, instead,
667 * only the following stronger three sub-conditions, for which it is
2d29c9f8 668 * much easier to maintain the needed state:
1de0c4cd 669 * 1) all active queues have the same weight,
73d58118
PV
670 * 2) all active queues belong to the same I/O-priority class,
671 * 3) there are no active groups.
2d29c9f8
FM
672 * In particular, the last condition is always true if hierarchical
673 * support or the cgroups interface are not enabled, thus no state
674 * needs to be maintained in this case.
1de0c4cd 675 */
fb53ac6c
PV
676static bool bfq_asymmetric_scenario(struct bfq_data *bfqd,
677 struct bfq_queue *bfqq)
1de0c4cd 678{
fb53ac6c
PV
679 bool smallest_weight = bfqq &&
680 bfqq->weight_counter &&
681 bfqq->weight_counter ==
682 container_of(
683 rb_first_cached(&bfqd->queue_weights_tree),
684 struct bfq_weight_counter,
685 weights_node);
686
73d58118
PV
687 /*
688 * For queue weights to differ, queue_weights_tree must contain
689 * at least two nodes.
690 */
fb53ac6c
PV
691 bool varied_queue_weights = !smallest_weight &&
692 !RB_EMPTY_ROOT(&bfqd->queue_weights_tree.rb_root) &&
693 (bfqd->queue_weights_tree.rb_root.rb_node->rb_left ||
694 bfqd->queue_weights_tree.rb_root.rb_node->rb_right);
73d58118
PV
695
696 bool multiple_classes_busy =
697 (bfqd->busy_queues[0] && bfqd->busy_queues[1]) ||
698 (bfqd->busy_queues[0] && bfqd->busy_queues[2]) ||
699 (bfqd->busy_queues[1] && bfqd->busy_queues[2]);
700
fb53ac6c 701 return varied_queue_weights || multiple_classes_busy
42b1bd33 702#ifdef CONFIG_BFQ_GROUP_IOSCHED
73d58118
PV
703 || bfqd->num_groups_with_pending_reqs > 0
704#endif
fb53ac6c 705 ;
1de0c4cd
AA
706}
707
708/*
709 * If the weight-counter tree passed as input contains no counter for
2d29c9f8 710 * the weight of the input queue, then add that counter; otherwise just
1de0c4cd
AA
711 * increment the existing counter.
712 *
713 * Note that weight-counter trees contain few nodes in mostly symmetric
714 * scenarios. For example, if all queues have the same weight, then the
715 * weight-counter tree for the queues may contain at most one node.
716 * This holds even if low_latency is on, because weight-raised queues
717 * are not inserted in the tree.
718 * In most scenarios, the rate at which nodes are created/destroyed
719 * should be low too.
720 */
2d29c9f8 721void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_queue *bfqq,
fb53ac6c 722 struct rb_root_cached *root)
1de0c4cd 723{
2d29c9f8 724 struct bfq_entity *entity = &bfqq->entity;
fb53ac6c
PV
725 struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
726 bool leftmost = true;
1de0c4cd
AA
727
728 /*
2d29c9f8 729 * Do not insert if the queue is already associated with a
1de0c4cd 730 * counter, which happens if:
2d29c9f8 731 * 1) a request arrival has caused the queue to become both
1de0c4cd
AA
732 * non-weight-raised, and hence change its weight, and
733 * backlogged; in this respect, each of the two events
734 * causes an invocation of this function,
2d29c9f8 735 * 2) this is the invocation of this function caused by the
1de0c4cd
AA
736 * second event. This second invocation is actually useless,
737 * and we handle this fact by exiting immediately. More
738 * efficient or clearer solutions might possibly be adopted.
739 */
2d29c9f8 740 if (bfqq->weight_counter)
1de0c4cd
AA
741 return;
742
743 while (*new) {
744 struct bfq_weight_counter *__counter = container_of(*new,
745 struct bfq_weight_counter,
746 weights_node);
747 parent = *new;
748
749 if (entity->weight == __counter->weight) {
2d29c9f8 750 bfqq->weight_counter = __counter;
1de0c4cd
AA
751 goto inc_counter;
752 }
753 if (entity->weight < __counter->weight)
754 new = &((*new)->rb_left);
fb53ac6c 755 else {
1de0c4cd 756 new = &((*new)->rb_right);
fb53ac6c
PV
757 leftmost = false;
758 }
1de0c4cd
AA
759 }
760
2d29c9f8
FM
761 bfqq->weight_counter = kzalloc(sizeof(struct bfq_weight_counter),
762 GFP_ATOMIC);
1de0c4cd
AA
763
764 /*
765 * In the unlucky event of an allocation failure, we just
2d29c9f8 766 * exit. This will cause the weight of queue to not be
fb53ac6c 767 * considered in bfq_asymmetric_scenario, which, in its turn,
73d58118
PV
768 * causes the scenario to be deemed wrongly symmetric in case
769 * bfqq's weight would have been the only weight making the
770 * scenario asymmetric. On the bright side, no unbalance will
771 * however occur when bfqq becomes inactive again (the
772 * invocation of this function is triggered by an activation
773 * of queue). In fact, bfq_weights_tree_remove does nothing
774 * if !bfqq->weight_counter.
1de0c4cd 775 */
2d29c9f8 776 if (unlikely(!bfqq->weight_counter))
1de0c4cd
AA
777 return;
778
2d29c9f8
FM
779 bfqq->weight_counter->weight = entity->weight;
780 rb_link_node(&bfqq->weight_counter->weights_node, parent, new);
fb53ac6c
PV
781 rb_insert_color_cached(&bfqq->weight_counter->weights_node, root,
782 leftmost);
1de0c4cd
AA
783
784inc_counter:
2d29c9f8 785 bfqq->weight_counter->num_active++;
9dee8b3b 786 bfqq->ref++;
1de0c4cd
AA
787}
788
789/*
2d29c9f8 790 * Decrement the weight counter associated with the queue, and, if the
1de0c4cd
AA
791 * counter reaches 0, remove the counter from the tree.
792 * See the comments to the function bfq_weights_tree_add() for considerations
793 * about overhead.
794 */
0471559c 795void __bfq_weights_tree_remove(struct bfq_data *bfqd,
2d29c9f8 796 struct bfq_queue *bfqq,
fb53ac6c 797 struct rb_root_cached *root)
1de0c4cd 798{
2d29c9f8 799 if (!bfqq->weight_counter)
1de0c4cd
AA
800 return;
801
2d29c9f8
FM
802 bfqq->weight_counter->num_active--;
803 if (bfqq->weight_counter->num_active > 0)
1de0c4cd
AA
804 goto reset_entity_pointer;
805
fb53ac6c 806 rb_erase_cached(&bfqq->weight_counter->weights_node, root);
2d29c9f8 807 kfree(bfqq->weight_counter);
1de0c4cd
AA
808
809reset_entity_pointer:
2d29c9f8 810 bfqq->weight_counter = NULL;
9dee8b3b 811 bfq_put_queue(bfqq);
1de0c4cd
AA
812}
813
0471559c 814/*
2d29c9f8
FM
815 * Invoke __bfq_weights_tree_remove on bfqq and decrement the number
816 * of active groups for each queue's inactive parent entity.
0471559c
PV
817 */
818void bfq_weights_tree_remove(struct bfq_data *bfqd,
819 struct bfq_queue *bfqq)
820{
821 struct bfq_entity *entity = bfqq->entity.parent;
822
0471559c
PV
823 for_each_entity(entity) {
824 struct bfq_sched_data *sd = entity->my_sched_data;
825
826 if (sd->next_in_service || sd->in_service_entity) {
827 /*
828 * entity is still active, because either
829 * next_in_service or in_service_entity is not
830 * NULL (see the comments on the definition of
831 * next_in_service for details on why
832 * in_service_entity must be checked too).
833 *
2d29c9f8
FM
834 * As a consequence, its parent entities are
835 * active as well, and thus this loop must
836 * stop here.
0471559c
PV
837 */
838 break;
839 }
ba7aeae5
PV
840
841 /*
842 * The decrement of num_groups_with_pending_reqs is
843 * not performed immediately upon the deactivation of
844 * entity, but it is delayed to when it also happens
845 * that the first leaf descendant bfqq of entity gets
846 * all its pending requests completed. The following
847 * instructions perform this delayed decrement, if
848 * needed. See the comments on
849 * num_groups_with_pending_reqs for details.
850 */
851 if (entity->in_groups_with_pending_reqs) {
852 entity->in_groups_with_pending_reqs = false;
853 bfqd->num_groups_with_pending_reqs--;
854 }
0471559c 855 }
9dee8b3b
PV
856
857 /*
858 * Next function is invoked last, because it causes bfqq to be
859 * freed if the following holds: bfqq is not in service and
860 * has no dispatched request. DO NOT use bfqq after the next
861 * function invocation.
862 */
863 __bfq_weights_tree_remove(bfqd, bfqq,
864 &bfqd->queue_weights_tree);
0471559c
PV
865}
866
aee69d78
PV
867/*
868 * Return expired entry, or NULL to just start from scratch in rbtree.
869 */
870static struct request *bfq_check_fifo(struct bfq_queue *bfqq,
871 struct request *last)
872{
873 struct request *rq;
874
875 if (bfq_bfqq_fifo_expire(bfqq))
876 return NULL;
877
878 bfq_mark_bfqq_fifo_expire(bfqq);
879
880 rq = rq_entry_fifo(bfqq->fifo.next);
881
882 if (rq == last || ktime_get_ns() < rq->fifo_time)
883 return NULL;
884
885 bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq);
886 return rq;
887}
888
889static struct request *bfq_find_next_rq(struct bfq_data *bfqd,
890 struct bfq_queue *bfqq,
891 struct request *last)
892{
893 struct rb_node *rbnext = rb_next(&last->rb_node);
894 struct rb_node *rbprev = rb_prev(&last->rb_node);
895 struct request *next, *prev = NULL;
896
897 /* Follow expired path, else get first next available. */
898 next = bfq_check_fifo(bfqq, last);
899 if (next)
900 return next;
901
902 if (rbprev)
903 prev = rb_entry_rq(rbprev);
904
905 if (rbnext)
906 next = rb_entry_rq(rbnext);
907 else {
908 rbnext = rb_first(&bfqq->sort_list);
909 if (rbnext && rbnext != &last->rb_node)
910 next = rb_entry_rq(rbnext);
911 }
912
913 return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last));
914}
915
c074170e 916/* see the definition of bfq_async_charge_factor for details */
aee69d78
PV
917static unsigned long bfq_serv_to_charge(struct request *rq,
918 struct bfq_queue *bfqq)
919{
02a6d787 920 if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1 ||
fb53ac6c 921 bfq_asymmetric_scenario(bfqq->bfqd, bfqq))
c074170e
PV
922 return blk_rq_sectors(rq);
923
d5801088 924 return blk_rq_sectors(rq) * bfq_async_charge_factor;
aee69d78
PV
925}
926
927/**
928 * bfq_updated_next_req - update the queue after a new next_rq selection.
929 * @bfqd: the device data the queue belongs to.
930 * @bfqq: the queue to update.
931 *
932 * If the first request of a queue changes we make sure that the queue
933 * has enough budget to serve at least its first request (if the
934 * request has grown). We do this because if the queue has not enough
935 * budget for its first request, it has to go through two dispatch
936 * rounds to actually get it dispatched.
937 */
938static void bfq_updated_next_req(struct bfq_data *bfqd,
939 struct bfq_queue *bfqq)
940{
941 struct bfq_entity *entity = &bfqq->entity;
942 struct request *next_rq = bfqq->next_rq;
943 unsigned long new_budget;
944
945 if (!next_rq)
946 return;
947
948 if (bfqq == bfqd->in_service_queue)
949 /*
950 * In order not to break guarantees, budgets cannot be
951 * changed after an entity has been selected.
952 */
953 return;
954
f3218ad8
PV
955 new_budget = max_t(unsigned long,
956 max_t(unsigned long, bfqq->max_budget,
957 bfq_serv_to_charge(next_rq, bfqq)),
958 entity->service);
aee69d78
PV
959 if (entity->budget != new_budget) {
960 entity->budget = new_budget;
961 bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu",
962 new_budget);
80294c3b 963 bfq_requeue_bfqq(bfqd, bfqq, false);
aee69d78
PV
964 }
965}
966
3e2bdd6d
PV
967static unsigned int bfq_wr_duration(struct bfq_data *bfqd)
968{
969 u64 dur;
970
971 if (bfqd->bfq_wr_max_time > 0)
972 return bfqd->bfq_wr_max_time;
973
e24f1c24 974 dur = bfqd->rate_dur_prod;
3e2bdd6d
PV
975 do_div(dur, bfqd->peak_rate);
976
977 /*
d450542e
DS
978 * Limit duration between 3 and 25 seconds. The upper limit
979 * has been conservatively set after the following worst case:
980 * on a QEMU/KVM virtual machine
981 * - running in a slow PC
982 * - with a virtual disk stacked on a slow low-end 5400rpm HDD
983 * - serving a heavy I/O workload, such as the sequential reading
984 * of several files
985 * mplayer took 23 seconds to start, if constantly weight-raised.
986 *
636b8fe8 987 * As for higher values than that accommodating the above bad
d450542e
DS
988 * scenario, tests show that higher values would often yield
989 * the opposite of the desired result, i.e., would worsen
990 * responsiveness by allowing non-interactive applications to
991 * preserve weight raising for too long.
3e2bdd6d
PV
992 *
993 * On the other end, lower values than 3 seconds make it
994 * difficult for most interactive tasks to complete their jobs
995 * before weight-raising finishes.
996 */
d450542e 997 return clamp_val(dur, msecs_to_jiffies(3000), msecs_to_jiffies(25000));
3e2bdd6d
PV
998}
999
1000/* switch back from soft real-time to interactive weight raising */
1001static void switch_back_to_interactive_wr(struct bfq_queue *bfqq,
1002 struct bfq_data *bfqd)
1003{
1004 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1005 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1006 bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt;
1007}
1008
36eca894 1009static void
13c931bd
PV
1010bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd,
1011 struct bfq_io_cq *bic, bool bfq_already_existing)
36eca894 1012{
13c931bd
PV
1013 unsigned int old_wr_coeff = bfqq->wr_coeff;
1014 bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq);
1015
d5be3fef
PV
1016 if (bic->saved_has_short_ttime)
1017 bfq_mark_bfqq_has_short_ttime(bfqq);
36eca894 1018 else
d5be3fef 1019 bfq_clear_bfqq_has_short_ttime(bfqq);
36eca894
AA
1020
1021 if (bic->saved_IO_bound)
1022 bfq_mark_bfqq_IO_bound(bfqq);
1023 else
1024 bfq_clear_bfqq_IO_bound(bfqq);
1025
fffca087 1026 bfqq->entity.new_weight = bic->saved_weight;
36eca894
AA
1027 bfqq->ttime = bic->saved_ttime;
1028 bfqq->wr_coeff = bic->saved_wr_coeff;
1029 bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt;
1030 bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish;
1031 bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time;
1032
e1b2324d 1033 if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) ||
36eca894 1034 time_is_before_jiffies(bfqq->last_wr_start_finish +
e1b2324d 1035 bfqq->wr_cur_max_time))) {
3e2bdd6d
PV
1036 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
1037 !bfq_bfqq_in_large_burst(bfqq) &&
1038 time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt +
1039 bfq_wr_duration(bfqd))) {
1040 switch_back_to_interactive_wr(bfqq, bfqd);
1041 } else {
1042 bfqq->wr_coeff = 1;
1043 bfq_log_bfqq(bfqq->bfqd, bfqq,
1044 "resume state: switching off wr");
1045 }
36eca894
AA
1046 }
1047
1048 /* make sure weight will be updated, however we got here */
1049 bfqq->entity.prio_changed = 1;
13c931bd
PV
1050
1051 if (likely(!busy))
1052 return;
1053
1054 if (old_wr_coeff == 1 && bfqq->wr_coeff > 1)
1055 bfqd->wr_busy_queues++;
1056 else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1)
1057 bfqd->wr_busy_queues--;
36eca894
AA
1058}
1059
1060static int bfqq_process_refs(struct bfq_queue *bfqq)
1061{
33a16a98 1062 return bfqq->ref - bfqq->allocated - bfqq->entity.on_st_or_in_serv -
9dee8b3b 1063 (bfqq->weight_counter != NULL);
36eca894
AA
1064}
1065
e1b2324d
AA
1066/* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
1067static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1068{
1069 struct bfq_queue *item;
1070 struct hlist_node *n;
1071
1072 hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node)
1073 hlist_del_init(&item->burst_list_node);
84a74689
PV
1074
1075 /*
1076 * Start the creation of a new burst list only if there is no
1077 * active queue. See comments on the conditional invocation of
1078 * bfq_handle_burst().
1079 */
1080 if (bfq_tot_busy_queues(bfqd) == 0) {
1081 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1082 bfqd->burst_size = 1;
1083 } else
1084 bfqd->burst_size = 0;
1085
e1b2324d
AA
1086 bfqd->burst_parent_entity = bfqq->entity.parent;
1087}
1088
1089/* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */
1090static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1091{
1092 /* Increment burst size to take into account also bfqq */
1093 bfqd->burst_size++;
1094
1095 if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) {
1096 struct bfq_queue *pos, *bfqq_item;
1097 struct hlist_node *n;
1098
1099 /*
1100 * Enough queues have been activated shortly after each
1101 * other to consider this burst as large.
1102 */
1103 bfqd->large_burst = true;
1104
1105 /*
1106 * We can now mark all queues in the burst list as
1107 * belonging to a large burst.
1108 */
1109 hlist_for_each_entry(bfqq_item, &bfqd->burst_list,
1110 burst_list_node)
1111 bfq_mark_bfqq_in_large_burst(bfqq_item);
1112 bfq_mark_bfqq_in_large_burst(bfqq);
1113
1114 /*
1115 * From now on, and until the current burst finishes, any
1116 * new queue being activated shortly after the last queue
1117 * was inserted in the burst can be immediately marked as
1118 * belonging to a large burst. So the burst list is not
1119 * needed any more. Remove it.
1120 */
1121 hlist_for_each_entry_safe(pos, n, &bfqd->burst_list,
1122 burst_list_node)
1123 hlist_del_init(&pos->burst_list_node);
1124 } else /*
1125 * Burst not yet large: add bfqq to the burst list. Do
1126 * not increment the ref counter for bfqq, because bfqq
1127 * is removed from the burst list before freeing bfqq
1128 * in put_queue.
1129 */
1130 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list);
1131}
1132
1133/*
1134 * If many queues belonging to the same group happen to be created
1135 * shortly after each other, then the processes associated with these
1136 * queues have typically a common goal. In particular, bursts of queue
1137 * creations are usually caused by services or applications that spawn
1138 * many parallel threads/processes. Examples are systemd during boot,
1139 * or git grep. To help these processes get their job done as soon as
1140 * possible, it is usually better to not grant either weight-raising
84a74689
PV
1141 * or device idling to their queues, unless these queues must be
1142 * protected from the I/O flowing through other active queues.
e1b2324d
AA
1143 *
1144 * In this comment we describe, firstly, the reasons why this fact
1145 * holds, and, secondly, the next function, which implements the main
1146 * steps needed to properly mark these queues so that they can then be
1147 * treated in a different way.
1148 *
1149 * The above services or applications benefit mostly from a high
1150 * throughput: the quicker the requests of the activated queues are
1151 * cumulatively served, the sooner the target job of these queues gets
1152 * completed. As a consequence, weight-raising any of these queues,
1153 * which also implies idling the device for it, is almost always
84a74689
PV
1154 * counterproductive, unless there are other active queues to isolate
1155 * these new queues from. If there no other active queues, then
1156 * weight-raising these new queues just lowers throughput in most
1157 * cases.
e1b2324d
AA
1158 *
1159 * On the other hand, a burst of queue creations may be caused also by
1160 * the start of an application that does not consist of a lot of
1161 * parallel I/O-bound threads. In fact, with a complex application,
1162 * several short processes may need to be executed to start-up the
1163 * application. In this respect, to start an application as quickly as
1164 * possible, the best thing to do is in any case to privilege the I/O
1165 * related to the application with respect to all other
1166 * I/O. Therefore, the best strategy to start as quickly as possible
1167 * an application that causes a burst of queue creations is to
1168 * weight-raise all the queues created during the burst. This is the
1169 * exact opposite of the best strategy for the other type of bursts.
1170 *
1171 * In the end, to take the best action for each of the two cases, the
1172 * two types of bursts need to be distinguished. Fortunately, this
1173 * seems relatively easy, by looking at the sizes of the bursts. In
1174 * particular, we found a threshold such that only bursts with a
1175 * larger size than that threshold are apparently caused by
1176 * services or commands such as systemd or git grep. For brevity,
1177 * hereafter we call just 'large' these bursts. BFQ *does not*
1178 * weight-raise queues whose creation occurs in a large burst. In
1179 * addition, for each of these queues BFQ performs or does not perform
1180 * idling depending on which choice boosts the throughput more. The
1181 * exact choice depends on the device and request pattern at
1182 * hand.
1183 *
1184 * Unfortunately, false positives may occur while an interactive task
1185 * is starting (e.g., an application is being started). The
1186 * consequence is that the queues associated with the task do not
1187 * enjoy weight raising as expected. Fortunately these false positives
1188 * are very rare. They typically occur if some service happens to
1189 * start doing I/O exactly when the interactive task starts.
1190 *
84a74689
PV
1191 * Turning back to the next function, it is invoked only if there are
1192 * no active queues (apart from active queues that would belong to the
1193 * same, possible burst bfqq would belong to), and it implements all
1194 * the steps needed to detect the occurrence of a large burst and to
1195 * properly mark all the queues belonging to it (so that they can then
1196 * be treated in a different way). This goal is achieved by
1197 * maintaining a "burst list" that holds, temporarily, the queues that
1198 * belong to the burst in progress. The list is then used to mark
1199 * these queues as belonging to a large burst if the burst does become
1200 * large. The main steps are the following.
e1b2324d
AA
1201 *
1202 * . when the very first queue is created, the queue is inserted into the
1203 * list (as it could be the first queue in a possible burst)
1204 *
1205 * . if the current burst has not yet become large, and a queue Q that does
1206 * not yet belong to the burst is activated shortly after the last time
1207 * at which a new queue entered the burst list, then the function appends
1208 * Q to the burst list
1209 *
1210 * . if, as a consequence of the previous step, the burst size reaches
1211 * the large-burst threshold, then
1212 *
1213 * . all the queues in the burst list are marked as belonging to a
1214 * large burst
1215 *
1216 * . the burst list is deleted; in fact, the burst list already served
1217 * its purpose (keeping temporarily track of the queues in a burst,
1218 * so as to be able to mark them as belonging to a large burst in the
1219 * previous sub-step), and now is not needed any more
1220 *
1221 * . the device enters a large-burst mode
1222 *
1223 * . if a queue Q that does not belong to the burst is created while
1224 * the device is in large-burst mode and shortly after the last time
1225 * at which a queue either entered the burst list or was marked as
1226 * belonging to the current large burst, then Q is immediately marked
1227 * as belonging to a large burst.
1228 *
1229 * . if a queue Q that does not belong to the burst is created a while
1230 * later, i.e., not shortly after, than the last time at which a queue
1231 * either entered the burst list or was marked as belonging to the
1232 * current large burst, then the current burst is deemed as finished and:
1233 *
1234 * . the large-burst mode is reset if set
1235 *
1236 * . the burst list is emptied
1237 *
1238 * . Q is inserted in the burst list, as Q may be the first queue
1239 * in a possible new burst (then the burst list contains just Q
1240 * after this step).
1241 */
1242static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1243{
1244 /*
1245 * If bfqq is already in the burst list or is part of a large
1246 * burst, or finally has just been split, then there is
1247 * nothing else to do.
1248 */
1249 if (!hlist_unhashed(&bfqq->burst_list_node) ||
1250 bfq_bfqq_in_large_burst(bfqq) ||
1251 time_is_after_eq_jiffies(bfqq->split_time +
1252 msecs_to_jiffies(10)))
1253 return;
1254
1255 /*
1256 * If bfqq's creation happens late enough, or bfqq belongs to
1257 * a different group than the burst group, then the current
1258 * burst is finished, and related data structures must be
1259 * reset.
1260 *
1261 * In this respect, consider the special case where bfqq is
1262 * the very first queue created after BFQ is selected for this
1263 * device. In this case, last_ins_in_burst and
1264 * burst_parent_entity are not yet significant when we get
1265 * here. But it is easy to verify that, whether or not the
1266 * following condition is true, bfqq will end up being
1267 * inserted into the burst list. In particular the list will
1268 * happen to contain only bfqq. And this is exactly what has
1269 * to happen, as bfqq may be the first queue of the first
1270 * burst.
1271 */
1272 if (time_is_before_jiffies(bfqd->last_ins_in_burst +
1273 bfqd->bfq_burst_interval) ||
1274 bfqq->entity.parent != bfqd->burst_parent_entity) {
1275 bfqd->large_burst = false;
1276 bfq_reset_burst_list(bfqd, bfqq);
1277 goto end;
1278 }
1279
1280 /*
1281 * If we get here, then bfqq is being activated shortly after the
1282 * last queue. So, if the current burst is also large, we can mark
1283 * bfqq as belonging to this large burst immediately.
1284 */
1285 if (bfqd->large_burst) {
1286 bfq_mark_bfqq_in_large_burst(bfqq);
1287 goto end;
1288 }
1289
1290 /*
1291 * If we get here, then a large-burst state has not yet been
1292 * reached, but bfqq is being activated shortly after the last
1293 * queue. Then we add bfqq to the burst.
1294 */
1295 bfq_add_to_burst(bfqd, bfqq);
1296end:
1297 /*
1298 * At this point, bfqq either has been added to the current
1299 * burst or has caused the current burst to terminate and a
1300 * possible new burst to start. In particular, in the second
1301 * case, bfqq has become the first queue in the possible new
1302 * burst. In both cases last_ins_in_burst needs to be moved
1303 * forward.
1304 */
1305 bfqd->last_ins_in_burst = jiffies;
1306}
1307
aee69d78
PV
1308static int bfq_bfqq_budget_left(struct bfq_queue *bfqq)
1309{
1310 struct bfq_entity *entity = &bfqq->entity;
1311
1312 return entity->budget - entity->service;
1313}
1314
1315/*
1316 * If enough samples have been computed, return the current max budget
1317 * stored in bfqd, which is dynamically updated according to the
1318 * estimated disk peak rate; otherwise return the default max budget
1319 */
1320static int bfq_max_budget(struct bfq_data *bfqd)
1321{
1322 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1323 return bfq_default_max_budget;
1324 else
1325 return bfqd->bfq_max_budget;
1326}
1327
1328/*
1329 * Return min budget, which is a fraction of the current or default
1330 * max budget (trying with 1/32)
1331 */
1332static int bfq_min_budget(struct bfq_data *bfqd)
1333{
1334 if (bfqd->budgets_assigned < bfq_stats_min_budgets)
1335 return bfq_default_max_budget / 32;
1336 else
1337 return bfqd->bfq_max_budget / 32;
1338}
1339
aee69d78
PV
1340/*
1341 * The next function, invoked after the input queue bfqq switches from
1342 * idle to busy, updates the budget of bfqq. The function also tells
1343 * whether the in-service queue should be expired, by returning
1344 * true. The purpose of expiring the in-service queue is to give bfqq
1345 * the chance to possibly preempt the in-service queue, and the reason
44e44a1b
PV
1346 * for preempting the in-service queue is to achieve one of the two
1347 * goals below.
aee69d78 1348 *
44e44a1b
PV
1349 * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has
1350 * expired because it has remained idle. In particular, bfqq may have
1351 * expired for one of the following two reasons:
aee69d78
PV
1352 *
1353 * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling
1354 * and did not make it to issue a new request before its last
1355 * request was served;
1356 *
1357 * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue
1358 * a new request before the expiration of the idling-time.
1359 *
1360 * Even if bfqq has expired for one of the above reasons, the process
1361 * associated with the queue may be however issuing requests greedily,
1362 * and thus be sensitive to the bandwidth it receives (bfqq may have
1363 * remained idle for other reasons: CPU high load, bfqq not enjoying
1364 * idling, I/O throttling somewhere in the path from the process to
1365 * the I/O scheduler, ...). But if, after every expiration for one of
1366 * the above two reasons, bfqq has to wait for the service of at least
1367 * one full budget of another queue before being served again, then
1368 * bfqq is likely to get a much lower bandwidth or resource time than
1369 * its reserved ones. To address this issue, two countermeasures need
1370 * to be taken.
1371 *
1372 * First, the budget and the timestamps of bfqq need to be updated in
1373 * a special way on bfqq reactivation: they need to be updated as if
1374 * bfqq did not remain idle and did not expire. In fact, if they are
1375 * computed as if bfqq expired and remained idle until reactivation,
1376 * then the process associated with bfqq is treated as if, instead of
1377 * being greedy, it stopped issuing requests when bfqq remained idle,
1378 * and restarts issuing requests only on this reactivation. In other
1379 * words, the scheduler does not help the process recover the "service
1380 * hole" between bfqq expiration and reactivation. As a consequence,
1381 * the process receives a lower bandwidth than its reserved one. In
1382 * contrast, to recover this hole, the budget must be updated as if
1383 * bfqq was not expired at all before this reactivation, i.e., it must
1384 * be set to the value of the remaining budget when bfqq was
1385 * expired. Along the same line, timestamps need to be assigned the
1386 * value they had the last time bfqq was selected for service, i.e.,
1387 * before last expiration. Thus timestamps need to be back-shifted
1388 * with respect to their normal computation (see [1] for more details
1389 * on this tricky aspect).
1390 *
1391 * Secondly, to allow the process to recover the hole, the in-service
1392 * queue must be expired too, to give bfqq the chance to preempt it
1393 * immediately. In fact, if bfqq has to wait for a full budget of the
1394 * in-service queue to be completed, then it may become impossible to
1395 * let the process recover the hole, even if the back-shifted
1396 * timestamps of bfqq are lower than those of the in-service queue. If
1397 * this happens for most or all of the holes, then the process may not
1398 * receive its reserved bandwidth. In this respect, it is worth noting
1399 * that, being the service of outstanding requests unpreemptible, a
1400 * little fraction of the holes may however be unrecoverable, thereby
1401 * causing a little loss of bandwidth.
1402 *
1403 * The last important point is detecting whether bfqq does need this
1404 * bandwidth recovery. In this respect, the next function deems the
1405 * process associated with bfqq greedy, and thus allows it to recover
1406 * the hole, if: 1) the process is waiting for the arrival of a new
1407 * request (which implies that bfqq expired for one of the above two
1408 * reasons), and 2) such a request has arrived soon. The first
1409 * condition is controlled through the flag non_blocking_wait_rq,
1410 * while the second through the flag arrived_in_time. If both
1411 * conditions hold, then the function computes the budget in the
1412 * above-described special way, and signals that the in-service queue
1413 * should be expired. Timestamp back-shifting is done later in
1414 * __bfq_activate_entity.
44e44a1b
PV
1415 *
1416 * 2. Reduce latency. Even if timestamps are not backshifted to let
1417 * the process associated with bfqq recover a service hole, bfqq may
1418 * however happen to have, after being (re)activated, a lower finish
1419 * timestamp than the in-service queue. That is, the next budget of
1420 * bfqq may have to be completed before the one of the in-service
1421 * queue. If this is the case, then preempting the in-service queue
1422 * allows this goal to be achieved, apart from the unpreemptible,
1423 * outstanding requests mentioned above.
1424 *
1425 * Unfortunately, regardless of which of the above two goals one wants
1426 * to achieve, service trees need first to be updated to know whether
1427 * the in-service queue must be preempted. To have service trees
1428 * correctly updated, the in-service queue must be expired and
1429 * rescheduled, and bfqq must be scheduled too. This is one of the
1430 * most costly operations (in future versions, the scheduling
1431 * mechanism may be re-designed in such a way to make it possible to
1432 * know whether preemption is needed without needing to update service
1433 * trees). In addition, queue preemptions almost always cause random
96a291c3
PV
1434 * I/O, which may in turn cause loss of throughput. Finally, there may
1435 * even be no in-service queue when the next function is invoked (so,
1436 * no queue to compare timestamps with). Because of these facts, the
1437 * next function adopts the following simple scheme to avoid costly
1438 * operations, too frequent preemptions and too many dependencies on
1439 * the state of the scheduler: it requests the expiration of the
1440 * in-service queue (unconditionally) only for queues that need to
1441 * recover a hole. Then it delegates to other parts of the code the
1442 * responsibility of handling the above case 2.
aee69d78
PV
1443 */
1444static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd,
1445 struct bfq_queue *bfqq,
96a291c3 1446 bool arrived_in_time)
aee69d78
PV
1447{
1448 struct bfq_entity *entity = &bfqq->entity;
1449
218cb897
PV
1450 /*
1451 * In the next compound condition, we check also whether there
1452 * is some budget left, because otherwise there is no point in
1453 * trying to go on serving bfqq with this same budget: bfqq
1454 * would be expired immediately after being selected for
1455 * service. This would only cause useless overhead.
1456 */
1457 if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time &&
1458 bfq_bfqq_budget_left(bfqq) > 0) {
aee69d78
PV
1459 /*
1460 * We do not clear the flag non_blocking_wait_rq here, as
1461 * the latter is used in bfq_activate_bfqq to signal
1462 * that timestamps need to be back-shifted (and is
1463 * cleared right after).
1464 */
1465
1466 /*
1467 * In next assignment we rely on that either
1468 * entity->service or entity->budget are not updated
1469 * on expiration if bfqq is empty (see
1470 * __bfq_bfqq_recalc_budget). Thus both quantities
1471 * remain unchanged after such an expiration, and the
1472 * following statement therefore assigns to
1473 * entity->budget the remaining budget on such an
9fae8dd5 1474 * expiration.
aee69d78
PV
1475 */
1476 entity->budget = min_t(unsigned long,
1477 bfq_bfqq_budget_left(bfqq),
1478 bfqq->max_budget);
1479
9fae8dd5
PV
1480 /*
1481 * At this point, we have used entity->service to get
1482 * the budget left (needed for updating
1483 * entity->budget). Thus we finally can, and have to,
1484 * reset entity->service. The latter must be reset
1485 * because bfqq would otherwise be charged again for
1486 * the service it has received during its previous
1487 * service slot(s).
1488 */
1489 entity->service = 0;
1490
aee69d78
PV
1491 return true;
1492 }
1493
9fae8dd5
PV
1494 /*
1495 * We can finally complete expiration, by setting service to 0.
1496 */
1497 entity->service = 0;
aee69d78
PV
1498 entity->budget = max_t(unsigned long, bfqq->max_budget,
1499 bfq_serv_to_charge(bfqq->next_rq, bfqq));
1500 bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
96a291c3 1501 return false;
44e44a1b
PV
1502}
1503
4baa8bb1
PV
1504/*
1505 * Return the farthest past time instant according to jiffies
1506 * macros.
1507 */
1508static unsigned long bfq_smallest_from_now(void)
1509{
1510 return jiffies - MAX_JIFFY_OFFSET;
1511}
1512
44e44a1b
PV
1513static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd,
1514 struct bfq_queue *bfqq,
1515 unsigned int old_wr_coeff,
1516 bool wr_or_deserves_wr,
77b7dcea 1517 bool interactive,
e1b2324d 1518 bool in_burst,
77b7dcea 1519 bool soft_rt)
44e44a1b
PV
1520{
1521 if (old_wr_coeff == 1 && wr_or_deserves_wr) {
1522 /* start a weight-raising period */
77b7dcea 1523 if (interactive) {
8a8747dc 1524 bfqq->service_from_wr = 0;
77b7dcea
PV
1525 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1526 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
1527 } else {
4baa8bb1
PV
1528 /*
1529 * No interactive weight raising in progress
1530 * here: assign minus infinity to
1531 * wr_start_at_switch_to_srt, to make sure
1532 * that, at the end of the soft-real-time
1533 * weight raising periods that is starting
1534 * now, no interactive weight-raising period
1535 * may be wrongly considered as still in
1536 * progress (and thus actually started by
1537 * mistake).
1538 */
1539 bfqq->wr_start_at_switch_to_srt =
1540 bfq_smallest_from_now();
77b7dcea
PV
1541 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1542 BFQ_SOFTRT_WEIGHT_FACTOR;
1543 bfqq->wr_cur_max_time =
1544 bfqd->bfq_wr_rt_max_time;
1545 }
44e44a1b
PV
1546
1547 /*
1548 * If needed, further reduce budget to make sure it is
1549 * close to bfqq's backlog, so as to reduce the
1550 * scheduling-error component due to a too large
1551 * budget. Do not care about throughput consequences,
1552 * but only about latency. Finally, do not assign a
1553 * too small budget either, to avoid increasing
1554 * latency by causing too frequent expirations.
1555 */
1556 bfqq->entity.budget = min_t(unsigned long,
1557 bfqq->entity.budget,
1558 2 * bfq_min_budget(bfqd));
1559 } else if (old_wr_coeff > 1) {
77b7dcea
PV
1560 if (interactive) { /* update wr coeff and duration */
1561 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
1562 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
e1b2324d
AA
1563 } else if (in_burst)
1564 bfqq->wr_coeff = 1;
1565 else if (soft_rt) {
77b7dcea
PV
1566 /*
1567 * The application is now or still meeting the
1568 * requirements for being deemed soft rt. We
1569 * can then correctly and safely (re)charge
1570 * the weight-raising duration for the
1571 * application with the weight-raising
1572 * duration for soft rt applications.
1573 *
1574 * In particular, doing this recharge now, i.e.,
1575 * before the weight-raising period for the
1576 * application finishes, reduces the probability
1577 * of the following negative scenario:
1578 * 1) the weight of a soft rt application is
1579 * raised at startup (as for any newly
1580 * created application),
1581 * 2) since the application is not interactive,
1582 * at a certain time weight-raising is
1583 * stopped for the application,
1584 * 3) at that time the application happens to
1585 * still have pending requests, and hence
1586 * is destined to not have a chance to be
1587 * deemed soft rt before these requests are
1588 * completed (see the comments to the
1589 * function bfq_bfqq_softrt_next_start()
1590 * for details on soft rt detection),
1591 * 4) these pending requests experience a high
1592 * latency because the application is not
1593 * weight-raised while they are pending.
1594 */
1595 if (bfqq->wr_cur_max_time !=
1596 bfqd->bfq_wr_rt_max_time) {
1597 bfqq->wr_start_at_switch_to_srt =
1598 bfqq->last_wr_start_finish;
1599
1600 bfqq->wr_cur_max_time =
1601 bfqd->bfq_wr_rt_max_time;
1602 bfqq->wr_coeff = bfqd->bfq_wr_coeff *
1603 BFQ_SOFTRT_WEIGHT_FACTOR;
1604 }
1605 bfqq->last_wr_start_finish = jiffies;
1606 }
44e44a1b
PV
1607 }
1608}
1609
1610static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd,
1611 struct bfq_queue *bfqq)
1612{
1613 return bfqq->dispatched == 0 &&
1614 time_is_before_jiffies(
1615 bfqq->budget_timeout +
1616 bfqd->bfq_wr_min_idle_time);
aee69d78
PV
1617}
1618
96a291c3
PV
1619
1620/*
1621 * Return true if bfqq is in a higher priority class, or has a higher
1622 * weight than the in-service queue.
1623 */
1624static bool bfq_bfqq_higher_class_or_weight(struct bfq_queue *bfqq,
1625 struct bfq_queue *in_serv_bfqq)
1626{
1627 int bfqq_weight, in_serv_weight;
1628
1629 if (bfqq->ioprio_class < in_serv_bfqq->ioprio_class)
1630 return true;
1631
1632 if (in_serv_bfqq->entity.parent == bfqq->entity.parent) {
1633 bfqq_weight = bfqq->entity.weight;
1634 in_serv_weight = in_serv_bfqq->entity.weight;
1635 } else {
1636 if (bfqq->entity.parent)
1637 bfqq_weight = bfqq->entity.parent->weight;
1638 else
1639 bfqq_weight = bfqq->entity.weight;
1640 if (in_serv_bfqq->entity.parent)
1641 in_serv_weight = in_serv_bfqq->entity.parent->weight;
1642 else
1643 in_serv_weight = in_serv_bfqq->entity.weight;
1644 }
1645
1646 return bfqq_weight > in_serv_weight;
1647}
1648
aee69d78
PV
1649static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd,
1650 struct bfq_queue *bfqq,
44e44a1b
PV
1651 int old_wr_coeff,
1652 struct request *rq,
1653 bool *interactive)
aee69d78 1654{
e1b2324d
AA
1655 bool soft_rt, in_burst, wr_or_deserves_wr,
1656 bfqq_wants_to_preempt,
44e44a1b 1657 idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq),
aee69d78
PV
1658 /*
1659 * See the comments on
1660 * bfq_bfqq_update_budg_for_activation for
1661 * details on the usage of the next variable.
1662 */
1663 arrived_in_time = ktime_get_ns() <=
1664 bfqq->ttime.last_end_request +
1665 bfqd->bfq_slice_idle * 3;
1666
e21b7a0b 1667
aee69d78 1668 /*
44e44a1b
PV
1669 * bfqq deserves to be weight-raised if:
1670 * - it is sync,
e1b2324d 1671 * - it does not belong to a large burst,
36eca894
AA
1672 * - it has been idle for enough time or is soft real-time,
1673 * - is linked to a bfq_io_cq (it is not shared in any sense).
44e44a1b 1674 */
e1b2324d 1675 in_burst = bfq_bfqq_in_large_burst(bfqq);
77b7dcea 1676 soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 &&
7074f076 1677 !BFQQ_TOTALLY_SEEKY(bfqq) &&
e1b2324d 1678 !in_burst &&
f6c3ca0e
DS
1679 time_is_before_jiffies(bfqq->soft_rt_next_start) &&
1680 bfqq->dispatched == 0;
e1b2324d 1681 *interactive = !in_burst && idle_for_long_time;
44e44a1b
PV
1682 wr_or_deserves_wr = bfqd->low_latency &&
1683 (bfqq->wr_coeff > 1 ||
36eca894
AA
1684 (bfq_bfqq_sync(bfqq) &&
1685 bfqq->bic && (*interactive || soft_rt)));
44e44a1b
PV
1686
1687 /*
1688 * Using the last flag, update budget and check whether bfqq
1689 * may want to preempt the in-service queue.
aee69d78
PV
1690 */
1691 bfqq_wants_to_preempt =
1692 bfq_bfqq_update_budg_for_activation(bfqd, bfqq,
96a291c3 1693 arrived_in_time);
aee69d78 1694
e1b2324d
AA
1695 /*
1696 * If bfqq happened to be activated in a burst, but has been
1697 * idle for much more than an interactive queue, then we
1698 * assume that, in the overall I/O initiated in the burst, the
1699 * I/O associated with bfqq is finished. So bfqq does not need
1700 * to be treated as a queue belonging to a burst
1701 * anymore. Accordingly, we reset bfqq's in_large_burst flag
1702 * if set, and remove bfqq from the burst list if it's
1703 * there. We do not decrement burst_size, because the fact
1704 * that bfqq does not need to belong to the burst list any
1705 * more does not invalidate the fact that bfqq was created in
1706 * a burst.
1707 */
1708 if (likely(!bfq_bfqq_just_created(bfqq)) &&
1709 idle_for_long_time &&
1710 time_is_before_jiffies(
1711 bfqq->budget_timeout +
1712 msecs_to_jiffies(10000))) {
1713 hlist_del_init(&bfqq->burst_list_node);
1714 bfq_clear_bfqq_in_large_burst(bfqq);
1715 }
1716
1717 bfq_clear_bfqq_just_created(bfqq);
1718
1719
aee69d78
PV
1720 if (!bfq_bfqq_IO_bound(bfqq)) {
1721 if (arrived_in_time) {
1722 bfqq->requests_within_timer++;
1723 if (bfqq->requests_within_timer >=
1724 bfqd->bfq_requests_within_timer)
1725 bfq_mark_bfqq_IO_bound(bfqq);
1726 } else
1727 bfqq->requests_within_timer = 0;
1728 }
1729
44e44a1b 1730 if (bfqd->low_latency) {
36eca894
AA
1731 if (unlikely(time_is_after_jiffies(bfqq->split_time)))
1732 /* wraparound */
1733 bfqq->split_time =
1734 jiffies - bfqd->bfq_wr_min_idle_time - 1;
1735
1736 if (time_is_before_jiffies(bfqq->split_time +
1737 bfqd->bfq_wr_min_idle_time)) {
1738 bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq,
1739 old_wr_coeff,
1740 wr_or_deserves_wr,
1741 *interactive,
e1b2324d 1742 in_burst,
36eca894
AA
1743 soft_rt);
1744
1745 if (old_wr_coeff != bfqq->wr_coeff)
1746 bfqq->entity.prio_changed = 1;
1747 }
44e44a1b
PV
1748 }
1749
77b7dcea
PV
1750 bfqq->last_idle_bklogged = jiffies;
1751 bfqq->service_from_backlogged = 0;
1752 bfq_clear_bfqq_softrt_update(bfqq);
1753
aee69d78
PV
1754 bfq_add_bfqq_busy(bfqd, bfqq);
1755
1756 /*
1757 * Expire in-service queue only if preemption may be needed
96a291c3
PV
1758 * for guarantees. In particular, we care only about two
1759 * cases. The first is that bfqq has to recover a service
1760 * hole, as explained in the comments on
1761 * bfq_bfqq_update_budg_for_activation(), i.e., that
1762 * bfqq_wants_to_preempt is true. However, if bfqq does not
1763 * carry time-critical I/O, then bfqq's bandwidth is less
1764 * important than that of queues that carry time-critical I/O.
1765 * So, as a further constraint, we consider this case only if
1766 * bfqq is at least as weight-raised, i.e., at least as time
1767 * critical, as the in-service queue.
1768 *
1769 * The second case is that bfqq is in a higher priority class,
1770 * or has a higher weight than the in-service queue. If this
1771 * condition does not hold, we don't care because, even if
1772 * bfqq does not start to be served immediately, the resulting
1773 * delay for bfqq's I/O is however lower or much lower than
1774 * the ideal completion time to be guaranteed to bfqq's I/O.
1775 *
1776 * In both cases, preemption is needed only if, according to
1777 * the timestamps of both bfqq and of the in-service queue,
1778 * bfqq actually is the next queue to serve. So, to reduce
1779 * useless preemptions, the return value of
1780 * next_queue_may_preempt() is considered in the next compound
1781 * condition too. Yet next_queue_may_preempt() just checks a
1782 * simple, necessary condition for bfqq to be the next queue
1783 * to serve. In fact, to evaluate a sufficient condition, the
1784 * timestamps of the in-service queue would need to be
1785 * updated, and this operation is quite costly (see the
1786 * comments on bfq_bfqq_update_budg_for_activation()).
aee69d78 1787 */
96a291c3
PV
1788 if (bfqd->in_service_queue &&
1789 ((bfqq_wants_to_preempt &&
1790 bfqq->wr_coeff >= bfqd->in_service_queue->wr_coeff) ||
1791 bfq_bfqq_higher_class_or_weight(bfqq, bfqd->in_service_queue)) &&
aee69d78
PV
1792 next_queue_may_preempt(bfqd))
1793 bfq_bfqq_expire(bfqd, bfqd->in_service_queue,
1794 false, BFQQE_PREEMPTED);
1795}
1796
766d6141
PV
1797static void bfq_reset_inject_limit(struct bfq_data *bfqd,
1798 struct bfq_queue *bfqq)
1799{
1800 /* invalidate baseline total service time */
1801 bfqq->last_serv_time_ns = 0;
1802
1803 /*
1804 * Reset pointer in case we are waiting for
1805 * some request completion.
1806 */
1807 bfqd->waited_rq = NULL;
1808
1809 /*
1810 * If bfqq has a short think time, then start by setting the
1811 * inject limit to 0 prudentially, because the service time of
1812 * an injected I/O request may be higher than the think time
1813 * of bfqq, and therefore, if one request was injected when
1814 * bfqq remains empty, this injected request might delay the
1815 * service of the next I/O request for bfqq significantly. In
1816 * case bfqq can actually tolerate some injection, then the
1817 * adaptive update will however raise the limit soon. This
1818 * lucky circumstance holds exactly because bfqq has a short
1819 * think time, and thus, after remaining empty, is likely to
1820 * get new I/O enqueued---and then completed---before being
1821 * expired. This is the very pattern that gives the
1822 * limit-update algorithm the chance to measure the effect of
1823 * injection on request service times, and then to update the
1824 * limit accordingly.
1825 *
1826 * However, in the following special case, the inject limit is
1827 * left to 1 even if the think time is short: bfqq's I/O is
1828 * synchronized with that of some other queue, i.e., bfqq may
1829 * receive new I/O only after the I/O of the other queue is
1830 * completed. Keeping the inject limit to 1 allows the
1831 * blocking I/O to be served while bfqq is in service. And
1832 * this is very convenient both for bfqq and for overall
1833 * throughput, as explained in detail in the comments in
1834 * bfq_update_has_short_ttime().
1835 *
1836 * On the opposite end, if bfqq has a long think time, then
1837 * start directly by 1, because:
1838 * a) on the bright side, keeping at most one request in
1839 * service in the drive is unlikely to cause any harm to the
1840 * latency of bfqq's requests, as the service time of a single
1841 * request is likely to be lower than the think time of bfqq;
1842 * b) on the downside, after becoming empty, bfqq is likely to
1843 * expire before getting its next request. With this request
1844 * arrival pattern, it is very hard to sample total service
1845 * times and update the inject limit accordingly (see comments
1846 * on bfq_update_inject_limit()). So the limit is likely to be
1847 * never, or at least seldom, updated. As a consequence, by
1848 * setting the limit to 1, we avoid that no injection ever
1849 * occurs with bfqq. On the downside, this proactive step
1850 * further reduces chances to actually compute the baseline
1851 * total service time. Thus it reduces chances to execute the
1852 * limit-update algorithm and possibly raise the limit to more
1853 * than 1.
1854 */
1855 if (bfq_bfqq_has_short_ttime(bfqq))
1856 bfqq->inject_limit = 0;
1857 else
1858 bfqq->inject_limit = 1;
1859
1860 bfqq->decrease_time_jif = jiffies;
1861}
1862
aee69d78
PV
1863static void bfq_add_request(struct request *rq)
1864{
1865 struct bfq_queue *bfqq = RQ_BFQQ(rq);
1866 struct bfq_data *bfqd = bfqq->bfqd;
1867 struct request *next_rq, *prev;
44e44a1b
PV
1868 unsigned int old_wr_coeff = bfqq->wr_coeff;
1869 bool interactive = false;
aee69d78
PV
1870
1871 bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq));
1872 bfqq->queued[rq_is_sync(rq)]++;
1873 bfqd->queued++;
1874
2341d662 1875 if (RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_sync(bfqq)) {
13a857a4
PV
1876 /*
1877 * Detect whether bfqq's I/O seems synchronized with
1878 * that of some other queue, i.e., whether bfqq, after
1879 * remaining empty, happens to receive new I/O only
1880 * right after some I/O request of the other queue has
1881 * been completed. We call waker queue the other
1882 * queue, and we assume, for simplicity, that bfqq may
1883 * have at most one waker queue.
1884 *
1885 * A remarkable throughput boost can be reached by
1886 * unconditionally injecting the I/O of the waker
1887 * queue, every time a new bfq_dispatch_request
1888 * happens to be invoked while I/O is being plugged
1889 * for bfqq. In addition to boosting throughput, this
1890 * unblocks bfqq's I/O, thereby improving bandwidth
1891 * and latency for bfqq. Note that these same results
1892 * may be achieved with the general injection
1893 * mechanism, but less effectively. For details on
1894 * this aspect, see the comments on the choice of the
1895 * queue for injection in bfq_select_queue().
1896 *
1897 * Turning back to the detection of a waker queue, a
1898 * queue Q is deemed as a waker queue for bfqq if, for
1899 * two consecutive times, bfqq happens to become non
1900 * empty right after a request of Q has been
1901 * completed. In particular, on the first time, Q is
1902 * tentatively set as a candidate waker queue, while
1903 * on the second time, the flag
1904 * bfq_bfqq_has_waker(bfqq) is set to confirm that Q
1905 * is a waker queue for bfqq. These detection steps
1906 * are performed only if bfqq has a long think time,
1907 * so as to make it more likely that bfqq's I/O is
1908 * actually being blocked by a synchronization. This
1909 * last filter, plus the above two-times requirement,
1910 * make false positives less likely.
1911 *
1912 * NOTE
1913 *
1914 * The sooner a waker queue is detected, the sooner
1915 * throughput can be boosted by injecting I/O from the
1916 * waker queue. Fortunately, detection is likely to be
1917 * actually fast, for the following reasons. While
1918 * blocked by synchronization, bfqq has a long think
1919 * time. This implies that bfqq's inject limit is at
1920 * least equal to 1 (see the comments in
1921 * bfq_update_inject_limit()). So, thanks to
1922 * injection, the waker queue is likely to be served
1923 * during the very first I/O-plugging time interval
1924 * for bfqq. This triggers the first step of the
1925 * detection mechanism. Thanks again to injection, the
1926 * candidate waker queue is then likely to be
1927 * confirmed no later than during the next
1928 * I/O-plugging interval for bfqq.
1929 */
08d383a7
PV
1930 if (bfqd->last_completed_rq_bfqq &&
1931 !bfq_bfqq_has_short_ttime(bfqq) &&
13a857a4
PV
1932 ktime_get_ns() - bfqd->last_completion <
1933 200 * NSEC_PER_USEC) {
1934 if (bfqd->last_completed_rq_bfqq != bfqq &&
08d383a7
PV
1935 bfqd->last_completed_rq_bfqq !=
1936 bfqq->waker_bfqq) {
13a857a4
PV
1937 /*
1938 * First synchronization detected with
1939 * a candidate waker queue, or with a
1940 * different candidate waker queue
1941 * from the current one.
1942 */
1943 bfqq->waker_bfqq = bfqd->last_completed_rq_bfqq;
1944
1945 /*
1946 * If the waker queue disappears, then
1947 * bfqq->waker_bfqq must be reset. To
1948 * this goal, we maintain in each
1949 * waker queue a list, woken_list, of
1950 * all the queues that reference the
1951 * waker queue through their
1952 * waker_bfqq pointer. When the waker
1953 * queue exits, the waker_bfqq pointer
1954 * of all the queues in the woken_list
1955 * is reset.
1956 *
1957 * In addition, if bfqq is already in
1958 * the woken_list of a waker queue,
1959 * then, before being inserted into
1960 * the woken_list of a new waker
1961 * queue, bfqq must be removed from
1962 * the woken_list of the old waker
1963 * queue.
1964 */
1965 if (!hlist_unhashed(&bfqq->woken_list_node))
1966 hlist_del_init(&bfqq->woken_list_node);
1967 hlist_add_head(&bfqq->woken_list_node,
1968 &bfqd->last_completed_rq_bfqq->woken_list);
1969
1970 bfq_clear_bfqq_has_waker(bfqq);
1971 } else if (bfqd->last_completed_rq_bfqq ==
1972 bfqq->waker_bfqq &&
1973 !bfq_bfqq_has_waker(bfqq)) {
1974 /*
1975 * synchronization with waker_bfqq
1976 * seen for the second time
1977 */
1978 bfq_mark_bfqq_has_waker(bfqq);
1979 }
1980 }
1981
2341d662
PV
1982 /*
1983 * Periodically reset inject limit, to make sure that
1984 * the latter eventually drops in case workload
1985 * changes, see step (3) in the comments on
1986 * bfq_update_inject_limit().
1987 */
1988 if (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
766d6141
PV
1989 msecs_to_jiffies(1000)))
1990 bfq_reset_inject_limit(bfqd, bfqq);
2341d662
PV
1991
1992 /*
1993 * The following conditions must hold to setup a new
1994 * sampling of total service time, and then a new
1995 * update of the inject limit:
1996 * - bfqq is in service, because the total service
1997 * time is evaluated only for the I/O requests of
1998 * the queues in service;
1999 * - this is the right occasion to compute or to
2000 * lower the baseline total service time, because
2001 * there are actually no requests in the drive,
2002 * or
2003 * the baseline total service time is available, and
2004 * this is the right occasion to compute the other
2005 * quantity needed to update the inject limit, i.e.,
2006 * the total service time caused by the amount of
2007 * injection allowed by the current value of the
2008 * limit. It is the right occasion because injection
2009 * has actually been performed during the service
2010 * hole, and there are still in-flight requests,
2011 * which are very likely to be exactly the injected
2012 * requests, or part of them;
2013 * - the minimum interval for sampling the total
2014 * service time and updating the inject limit has
2015 * elapsed.
2016 */
2017 if (bfqq == bfqd->in_service_queue &&
2018 (bfqd->rq_in_driver == 0 ||
2019 (bfqq->last_serv_time_ns > 0 &&
2020 bfqd->rqs_injected && bfqd->rq_in_driver > 0)) &&
2021 time_is_before_eq_jiffies(bfqq->decrease_time_jif +
17c3d266 2022 msecs_to_jiffies(10))) {
2341d662
PV
2023 bfqd->last_empty_occupied_ns = ktime_get_ns();
2024 /*
2025 * Start the state machine for measuring the
2026 * total service time of rq: setting
2027 * wait_dispatch will cause bfqd->waited_rq to
2028 * be set when rq will be dispatched.
2029 */
2030 bfqd->wait_dispatch = true;
23ed570a
PV
2031 /*
2032 * If there is no I/O in service in the drive,
2033 * then possible injection occurred before the
2034 * arrival of rq will not affect the total
2035 * service time of rq. So the injection limit
2036 * must not be updated as a function of such
2037 * total service time, unless new injection
2038 * occurs before rq is completed. To have the
2039 * injection limit updated only in the latter
2040 * case, reset rqs_injected here (rqs_injected
2041 * will be set in case injection is performed
2042 * on bfqq before rq is completed).
2043 */
2044 if (bfqd->rq_in_driver == 0)
2045 bfqd->rqs_injected = false;
2341d662
PV
2046 }
2047 }
2048
aee69d78
PV
2049 elv_rb_add(&bfqq->sort_list, rq);
2050
2051 /*
2052 * Check if this request is a better next-serve candidate.
2053 */
2054 prev = bfqq->next_rq;
2055 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position);
2056 bfqq->next_rq = next_rq;
2057
36eca894
AA
2058 /*
2059 * Adjust priority tree position, if next_rq changes.
8cacc5ab 2060 * See comments on bfq_pos_tree_add_move() for the unlikely().
36eca894 2061 */
8cacc5ab 2062 if (unlikely(!bfqd->nonrot_with_queueing && prev != bfqq->next_rq))
36eca894
AA
2063 bfq_pos_tree_add_move(bfqd, bfqq);
2064
aee69d78 2065 if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */
44e44a1b
PV
2066 bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff,
2067 rq, &interactive);
2068 else {
2069 if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) &&
2070 time_is_before_jiffies(
2071 bfqq->last_wr_start_finish +
2072 bfqd->bfq_wr_min_inter_arr_async)) {
2073 bfqq->wr_coeff = bfqd->bfq_wr_coeff;
2074 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd);
2075
cfd69712 2076 bfqd->wr_busy_queues++;
44e44a1b
PV
2077 bfqq->entity.prio_changed = 1;
2078 }
2079 if (prev != bfqq->next_rq)
2080 bfq_updated_next_req(bfqd, bfqq);
2081 }
2082
2083 /*
2084 * Assign jiffies to last_wr_start_finish in the following
2085 * cases:
2086 *
2087 * . if bfqq is not going to be weight-raised, because, for
2088 * non weight-raised queues, last_wr_start_finish stores the
2089 * arrival time of the last request; as of now, this piece
2090 * of information is used only for deciding whether to
2091 * weight-raise async queues
2092 *
2093 * . if bfqq is not weight-raised, because, if bfqq is now
2094 * switching to weight-raised, then last_wr_start_finish
2095 * stores the time when weight-raising starts
2096 *
2097 * . if bfqq is interactive, because, regardless of whether
2098 * bfqq is currently weight-raised, the weight-raising
2099 * period must start or restart (this case is considered
2100 * separately because it is not detected by the above
2101 * conditions, if bfqq is already weight-raised)
77b7dcea
PV
2102 *
2103 * last_wr_start_finish has to be updated also if bfqq is soft
2104 * real-time, because the weight-raising period is constantly
2105 * restarted on idle-to-busy transitions for these queues, but
2106 * this is already done in bfq_bfqq_handle_idle_busy_switch if
2107 * needed.
44e44a1b
PV
2108 */
2109 if (bfqd->low_latency &&
2110 (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive))
2111 bfqq->last_wr_start_finish = jiffies;
aee69d78
PV
2112}
2113
2114static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd,
2115 struct bio *bio,
2116 struct request_queue *q)
2117{
2118 struct bfq_queue *bfqq = bfqd->bio_bfqq;
2119
2120
2121 if (bfqq)
2122 return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio));
2123
2124 return NULL;
2125}
2126
ab0e43e9
PV
2127static sector_t get_sdist(sector_t last_pos, struct request *rq)
2128{
2129 if (last_pos)
2130 return abs(blk_rq_pos(rq) - last_pos);
2131
2132 return 0;
2133}
2134
aee69d78
PV
2135#if 0 /* Still not clear if we can do without next two functions */
2136static void bfq_activate_request(struct request_queue *q, struct request *rq)
2137{
2138 struct bfq_data *bfqd = q->elevator->elevator_data;
2139
2140 bfqd->rq_in_driver++;
aee69d78
PV
2141}
2142
2143static void bfq_deactivate_request(struct request_queue *q, struct request *rq)
2144{
2145 struct bfq_data *bfqd = q->elevator->elevator_data;
2146
2147 bfqd->rq_in_driver--;
2148}
2149#endif
2150
2151static void bfq_remove_request(struct request_queue *q,
2152 struct request *rq)
2153{
2154 struct bfq_queue *bfqq = RQ_BFQQ(rq);
2155 struct bfq_data *bfqd = bfqq->bfqd;
2156 const int sync = rq_is_sync(rq);
2157
2158 if (bfqq->next_rq == rq) {
2159 bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq);
2160 bfq_updated_next_req(bfqd, bfqq);
2161 }
2162
2163 if (rq->queuelist.prev != &rq->queuelist)
2164 list_del_init(&rq->queuelist);
2165 bfqq->queued[sync]--;
2166 bfqd->queued--;
2167 elv_rb_del(&bfqq->sort_list, rq);
2168
2169 elv_rqhash_del(q, rq);
2170 if (q->last_merge == rq)
2171 q->last_merge = NULL;
2172
2173 if (RB_EMPTY_ROOT(&bfqq->sort_list)) {
2174 bfqq->next_rq = NULL;
2175
2176 if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) {
e21b7a0b 2177 bfq_del_bfqq_busy(bfqd, bfqq, false);
aee69d78
PV
2178 /*
2179 * bfqq emptied. In normal operation, when
2180 * bfqq is empty, bfqq->entity.service and
2181 * bfqq->entity.budget must contain,
2182 * respectively, the service received and the
2183 * budget used last time bfqq emptied. These
2184 * facts do not hold in this case, as at least
2185 * this last removal occurred while bfqq is
2186 * not in service. To avoid inconsistencies,
2187 * reset both bfqq->entity.service and
2188 * bfqq->entity.budget, if bfqq has still a
2189 * process that may issue I/O requests to it.
2190 */
2191 bfqq->entity.budget = bfqq->entity.service = 0;
2192 }
36eca894
AA
2193
2194 /*
2195 * Remove queue from request-position tree as it is empty.
2196 */
2197 if (bfqq->pos_root) {
2198 rb_erase(&bfqq->pos_node, bfqq->pos_root);
2199 bfqq->pos_root = NULL;
2200 }
05e90283 2201 } else {
8cacc5ab
PV
2202 /* see comments on bfq_pos_tree_add_move() for the unlikely() */
2203 if (unlikely(!bfqd->nonrot_with_queueing))
2204 bfq_pos_tree_add_move(bfqd, bfqq);
aee69d78
PV
2205 }
2206
2207 if (rq->cmd_flags & REQ_META)
2208 bfqq->meta_pending--;
e21b7a0b 2209
aee69d78
PV
2210}
2211
14ccb66b
CH
2212static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio,
2213 unsigned int nr_segs)
aee69d78
PV
2214{
2215 struct request_queue *q = hctx->queue;
2216 struct bfq_data *bfqd = q->elevator->elevator_data;
2217 struct request *free = NULL;
2218 /*
2219 * bfq_bic_lookup grabs the queue_lock: invoke it now and
2220 * store its return value for later use, to avoid nesting
2221 * queue_lock inside the bfqd->lock. We assume that the bic
2222 * returned by bfq_bic_lookup does not go away before
2223 * bfqd->lock is taken.
2224 */
2225 struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q);
2226 bool ret;
2227
2228 spin_lock_irq(&bfqd->lock);
2229
2230 if (bic)
2231 bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf));
2232 else
2233 bfqd->bio_bfqq = NULL;
2234 bfqd->bio_bic = bic;
2235
14ccb66b 2236 ret = blk_mq_sched_try_merge(q, bio, nr_segs, &free);
aee69d78
PV
2237
2238 if (free)
2239 blk_mq_free_request(free);
2240 spin_unlock_irq(&bfqd->lock);
2241
2242 return ret;
2243}
2244
2245static int bfq_request_merge(struct request_queue *q, struct request **req,
2246 struct bio *bio)
2247{
2248 struct bfq_data *bfqd = q->elevator->elevator_data;
2249 struct request *__rq;
2250
2251 __rq = bfq_find_rq_fmerge(bfqd, bio, q);
2252 if (__rq && elv_bio_merge_ok(__rq, bio)) {
2253 *req = __rq;
2254 return ELEVATOR_FRONT_MERGE;
2255 }
2256
2257 return ELEVATOR_NO_MERGE;
2258}
2259
18e5a57d
PV
2260static struct bfq_queue *bfq_init_rq(struct request *rq);
2261
aee69d78
PV
2262static void bfq_request_merged(struct request_queue *q, struct request *req,
2263 enum elv_merge type)
2264{
2265 if (type == ELEVATOR_FRONT_MERGE &&
2266 rb_prev(&req->rb_node) &&
2267 blk_rq_pos(req) <
2268 blk_rq_pos(container_of(rb_prev(&req->rb_node),
2269 struct request, rb_node))) {
18e5a57d 2270 struct bfq_queue *bfqq = bfq_init_rq(req);
fd03177c 2271 struct bfq_data *bfqd;
aee69d78
PV
2272 struct request *prev, *next_rq;
2273
fd03177c
PV
2274 if (!bfqq)
2275 return;
2276
2277 bfqd = bfqq->bfqd;
2278
aee69d78
PV
2279 /* Reposition request in its sort_list */
2280 elv_rb_del(&bfqq->sort_list, req);
2281 elv_rb_add(&bfqq->sort_list, req);
2282
2283 /* Choose next request to be served for bfqq */
2284 prev = bfqq->next_rq;
2285 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req,
2286 bfqd->last_position);
2287 bfqq->next_rq = next_rq;
2288 /*
36eca894
AA
2289 * If next_rq changes, update both the queue's budget to
2290 * fit the new request and the queue's position in its
2291 * rq_pos_tree.
aee69d78 2292 */
36eca894 2293 if (prev != bfqq->next_rq) {
aee69d78 2294 bfq_updated_next_req(bfqd, bfqq);
8cacc5ab
PV
2295 /*
2296 * See comments on bfq_pos_tree_add_move() for
2297 * the unlikely().
2298 */
2299 if (unlikely(!bfqd->nonrot_with_queueing))
2300 bfq_pos_tree_add_move(bfqd, bfqq);
36eca894 2301 }
aee69d78
PV
2302 }
2303}
2304
8abfa4d6
PV
2305/*
2306 * This function is called to notify the scheduler that the requests
2307 * rq and 'next' have been merged, with 'next' going away. BFQ
2308 * exploits this hook to address the following issue: if 'next' has a
2309 * fifo_time lower that rq, then the fifo_time of rq must be set to
2310 * the value of 'next', to not forget the greater age of 'next'.
8abfa4d6
PV
2311 *
2312 * NOTE: in this function we assume that rq is in a bfq_queue, basing
2313 * on that rq is picked from the hash table q->elevator->hash, which,
2314 * in its turn, is filled only with I/O requests present in
2315 * bfq_queues, while BFQ is in use for the request queue q. In fact,
2316 * the function that fills this hash table (elv_rqhash_add) is called
2317 * only by bfq_insert_request.
2318 */
aee69d78
PV
2319static void bfq_requests_merged(struct request_queue *q, struct request *rq,
2320 struct request *next)
2321{
18e5a57d
PV
2322 struct bfq_queue *bfqq = bfq_init_rq(rq),
2323 *next_bfqq = bfq_init_rq(next);
aee69d78 2324
fd03177c
PV
2325 if (!bfqq)
2326 return;
2327
aee69d78
PV
2328 /*
2329 * If next and rq belong to the same bfq_queue and next is older
2330 * than rq, then reposition rq in the fifo (by substituting next
2331 * with rq). Otherwise, if next and rq belong to different
2332 * bfq_queues, never reposition rq: in fact, we would have to
2333 * reposition it with respect to next's position in its own fifo,
2334 * which would most certainly be too expensive with respect to
2335 * the benefits.
2336 */
2337 if (bfqq == next_bfqq &&
2338 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
2339 next->fifo_time < rq->fifo_time) {
2340 list_del_init(&rq->queuelist);
2341 list_replace_init(&next->queuelist, &rq->queuelist);
2342 rq->fifo_time = next->fifo_time;
2343 }
2344
2345 if (bfqq->next_rq == next)
2346 bfqq->next_rq = rq;
2347
e21b7a0b 2348 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags);
aee69d78
PV
2349}
2350
44e44a1b
PV
2351/* Must be called with bfqq != NULL */
2352static void bfq_bfqq_end_wr(struct bfq_queue *bfqq)
2353{
cfd69712
PV
2354 if (bfq_bfqq_busy(bfqq))
2355 bfqq->bfqd->wr_busy_queues--;
44e44a1b
PV
2356 bfqq->wr_coeff = 1;
2357 bfqq->wr_cur_max_time = 0;
77b7dcea 2358 bfqq->last_wr_start_finish = jiffies;
44e44a1b
PV
2359 /*
2360 * Trigger a weight change on the next invocation of
2361 * __bfq_entity_update_weight_prio.
2362 */
2363 bfqq->entity.prio_changed = 1;
2364}
2365
ea25da48
PV
2366void bfq_end_wr_async_queues(struct bfq_data *bfqd,
2367 struct bfq_group *bfqg)
44e44a1b
PV
2368{
2369 int i, j;
2370
2371 for (i = 0; i < 2; i++)
2372 for (j = 0; j < IOPRIO_BE_NR; j++)
2373 if (bfqg->async_bfqq[i][j])
2374 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]);
2375 if (bfqg->async_idle_bfqq)
2376 bfq_bfqq_end_wr(bfqg->async_idle_bfqq);
2377}
2378
2379static void bfq_end_wr(struct bfq_data *bfqd)
2380{
2381 struct bfq_queue *bfqq;
2382
2383 spin_lock_irq(&bfqd->lock);
2384
2385 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
2386 bfq_bfqq_end_wr(bfqq);
2387 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list)
2388 bfq_bfqq_end_wr(bfqq);
2389 bfq_end_wr_async(bfqd);
2390
2391 spin_unlock_irq(&bfqd->lock);
2392}
2393
36eca894
AA
2394static sector_t bfq_io_struct_pos(void *io_struct, bool request)
2395{
2396 if (request)
2397 return blk_rq_pos(io_struct);
2398 else
2399 return ((struct bio *)io_struct)->bi_iter.bi_sector;
2400}
2401
2402static int bfq_rq_close_to_sector(void *io_struct, bool request,
2403 sector_t sector)
2404{
2405 return abs(bfq_io_struct_pos(io_struct, request) - sector) <=
2406 BFQQ_CLOSE_THR;
2407}
2408
2409static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd,
2410 struct bfq_queue *bfqq,
2411 sector_t sector)
2412{
2413 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree;
2414 struct rb_node *parent, *node;
2415 struct bfq_queue *__bfqq;
2416
2417 if (RB_EMPTY_ROOT(root))
2418 return NULL;
2419
2420 /*
2421 * First, if we find a request starting at the end of the last
2422 * request, choose it.
2423 */
2424 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL);
2425 if (__bfqq)
2426 return __bfqq;
2427
2428 /*
2429 * If the exact sector wasn't found, the parent of the NULL leaf
2430 * will contain the closest sector (rq_pos_tree sorted by
2431 * next_request position).
2432 */
2433 __bfqq = rb_entry(parent, struct bfq_queue, pos_node);
2434 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2435 return __bfqq;
2436
2437 if (blk_rq_pos(__bfqq->next_rq) < sector)
2438 node = rb_next(&__bfqq->pos_node);
2439 else
2440 node = rb_prev(&__bfqq->pos_node);
2441 if (!node)
2442 return NULL;
2443
2444 __bfqq = rb_entry(node, struct bfq_queue, pos_node);
2445 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector))
2446 return __bfqq;
2447
2448 return NULL;
2449}
2450
2451static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd,
2452 struct bfq_queue *cur_bfqq,
2453 sector_t sector)
2454{
2455 struct bfq_queue *bfqq;
2456
2457 /*
2458 * We shall notice if some of the queues are cooperating,
2459 * e.g., working closely on the same area of the device. In
2460 * that case, we can group them together and: 1) don't waste
2461 * time idling, and 2) serve the union of their requests in
2462 * the best possible order for throughput.
2463 */
2464 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector);
2465 if (!bfqq || bfqq == cur_bfqq)
2466 return NULL;
2467
2468 return bfqq;
2469}
2470
2471static struct bfq_queue *
2472bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2473{
2474 int process_refs, new_process_refs;
2475 struct bfq_queue *__bfqq;
2476
2477 /*
2478 * If there are no process references on the new_bfqq, then it is
2479 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain
2480 * may have dropped their last reference (not just their last process
2481 * reference).
2482 */
2483 if (!bfqq_process_refs(new_bfqq))
2484 return NULL;
2485
2486 /* Avoid a circular list and skip interim queue merges. */
2487 while ((__bfqq = new_bfqq->new_bfqq)) {
2488 if (__bfqq == bfqq)
2489 return NULL;
2490 new_bfqq = __bfqq;
2491 }
2492
2493 process_refs = bfqq_process_refs(bfqq);
2494 new_process_refs = bfqq_process_refs(new_bfqq);
2495 /*
2496 * If the process for the bfqq has gone away, there is no
2497 * sense in merging the queues.
2498 */
2499 if (process_refs == 0 || new_process_refs == 0)
2500 return NULL;
2501
2502 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d",
2503 new_bfqq->pid);
2504
2505 /*
2506 * Merging is just a redirection: the requests of the process
2507 * owning one of the two queues are redirected to the other queue.
2508 * The latter queue, in its turn, is set as shared if this is the
2509 * first time that the requests of some process are redirected to
2510 * it.
2511 *
6fa3e8d3
PV
2512 * We redirect bfqq to new_bfqq and not the opposite, because
2513 * we are in the context of the process owning bfqq, thus we
2514 * have the io_cq of this process. So we can immediately
2515 * configure this io_cq to redirect the requests of the
2516 * process to new_bfqq. In contrast, the io_cq of new_bfqq is
2517 * not available any more (new_bfqq->bic == NULL).
36eca894 2518 *
6fa3e8d3
PV
2519 * Anyway, even in case new_bfqq coincides with the in-service
2520 * queue, redirecting requests the in-service queue is the
2521 * best option, as we feed the in-service queue with new
2522 * requests close to the last request served and, by doing so,
2523 * are likely to increase the throughput.
36eca894
AA
2524 */
2525 bfqq->new_bfqq = new_bfqq;
2526 new_bfqq->ref += process_refs;
2527 return new_bfqq;
2528}
2529
2530static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq,
2531 struct bfq_queue *new_bfqq)
2532{
7b8fa3b9
PV
2533 if (bfq_too_late_for_merging(new_bfqq))
2534 return false;
2535
36eca894
AA
2536 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) ||
2537 (bfqq->ioprio_class != new_bfqq->ioprio_class))
2538 return false;
2539
2540 /*
2541 * If either of the queues has already been detected as seeky,
2542 * then merging it with the other queue is unlikely to lead to
2543 * sequential I/O.
2544 */
2545 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq))
2546 return false;
2547
2548 /*
2549 * Interleaved I/O is known to be done by (some) applications
2550 * only for reads, so it does not make sense to merge async
2551 * queues.
2552 */
2553 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq))
2554 return false;
2555
2556 return true;
2557}
2558
36eca894
AA
2559/*
2560 * Attempt to schedule a merge of bfqq with the currently in-service
2561 * queue or with a close queue among the scheduled queues. Return
2562 * NULL if no merge was scheduled, a pointer to the shared bfq_queue
2563 * structure otherwise.
2564 *
2565 * The OOM queue is not allowed to participate to cooperation: in fact, since
2566 * the requests temporarily redirected to the OOM queue could be redirected
2567 * again to dedicated queues at any time, the state needed to correctly
2568 * handle merging with the OOM queue would be quite complex and expensive
2569 * to maintain. Besides, in such a critical condition as an out of memory,
2570 * the benefits of queue merging may be little relevant, or even negligible.
2571 *
36eca894
AA
2572 * WARNING: queue merging may impair fairness among non-weight raised
2573 * queues, for at least two reasons: 1) the original weight of a
2574 * merged queue may change during the merged state, 2) even being the
2575 * weight the same, a merged queue may be bloated with many more
2576 * requests than the ones produced by its originally-associated
2577 * process.
2578 */
2579static struct bfq_queue *
2580bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq,
2581 void *io_struct, bool request)
2582{
2583 struct bfq_queue *in_service_bfqq, *new_bfqq;
2584
8cacc5ab
PV
2585 /*
2586 * Do not perform queue merging if the device is non
2587 * rotational and performs internal queueing. In fact, such a
2588 * device reaches a high speed through internal parallelism
2589 * and pipelining. This means that, to reach a high
2590 * throughput, it must have many requests enqueued at the same
2591 * time. But, in this configuration, the internal scheduling
2592 * algorithm of the device does exactly the job of queue
2593 * merging: it reorders requests so as to obtain as much as
2594 * possible a sequential I/O pattern. As a consequence, with
2595 * the workload generated by processes doing interleaved I/O,
2596 * the throughput reached by the device is likely to be the
2597 * same, with and without queue merging.
2598 *
2599 * Disabling merging also provides a remarkable benefit in
2600 * terms of throughput. Merging tends to make many workloads
2601 * artificially more uneven, because of shared queues
2602 * remaining non empty for incomparably more time than
2603 * non-merged queues. This may accentuate workload
2604 * asymmetries. For example, if one of the queues in a set of
2605 * merged queues has a higher weight than a normal queue, then
2606 * the shared queue may inherit such a high weight and, by
2607 * staying almost always active, may force BFQ to perform I/O
2608 * plugging most of the time. This evidently makes it harder
2609 * for BFQ to let the device reach a high throughput.
2610 *
2611 * Finally, the likely() macro below is not used because one
2612 * of the two branches is more likely than the other, but to
2613 * have the code path after the following if() executed as
2614 * fast as possible for the case of a non rotational device
2615 * with queueing. We want it because this is the fastest kind
2616 * of device. On the opposite end, the likely() may lengthen
2617 * the execution time of BFQ for the case of slower devices
2618 * (rotational or at least without queueing). But in this case
2619 * the execution time of BFQ matters very little, if not at
2620 * all.
2621 */
2622 if (likely(bfqd->nonrot_with_queueing))
2623 return NULL;
2624
7b8fa3b9
PV
2625 /*
2626 * Prevent bfqq from being merged if it has been created too
2627 * long ago. The idea is that true cooperating processes, and
2628 * thus their associated bfq_queues, are supposed to be
2629 * created shortly after each other. This is the case, e.g.,
2630 * for KVM/QEMU and dump I/O threads. Basing on this
2631 * assumption, the following filtering greatly reduces the
2632 * probability that two non-cooperating processes, which just
2633 * happen to do close I/O for some short time interval, have
2634 * their queues merged by mistake.
2635 */
2636 if (bfq_too_late_for_merging(bfqq))
2637 return NULL;
2638
36eca894
AA
2639 if (bfqq->new_bfqq)
2640 return bfqq->new_bfqq;
2641
4403e4e4 2642 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq))
36eca894
AA
2643 return NULL;
2644
2645 /* If there is only one backlogged queue, don't search. */
73d58118 2646 if (bfq_tot_busy_queues(bfqd) == 1)
36eca894
AA
2647 return NULL;
2648
2649 in_service_bfqq = bfqd->in_service_queue;
2650
4403e4e4
AR
2651 if (in_service_bfqq && in_service_bfqq != bfqq &&
2652 likely(in_service_bfqq != &bfqd->oom_bfqq) &&
058fdecc
PV
2653 bfq_rq_close_to_sector(io_struct, request,
2654 bfqd->in_serv_last_pos) &&
36eca894
AA
2655 bfqq->entity.parent == in_service_bfqq->entity.parent &&
2656 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) {
2657 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq);
2658 if (new_bfqq)
2659 return new_bfqq;
2660 }
2661 /*
2662 * Check whether there is a cooperator among currently scheduled
2663 * queues. The only thing we need is that the bio/request is not
2664 * NULL, as we need it to establish whether a cooperator exists.
2665 */
36eca894
AA
2666 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq,
2667 bfq_io_struct_pos(io_struct, request));
2668
4403e4e4 2669 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) &&
36eca894
AA
2670 bfq_may_be_close_cooperator(bfqq, new_bfqq))
2671 return bfq_setup_merge(bfqq, new_bfqq);
2672
2673 return NULL;
2674}
2675
2676static void bfq_bfqq_save_state(struct bfq_queue *bfqq)
2677{
2678 struct bfq_io_cq *bic = bfqq->bic;
2679
2680 /*
2681 * If !bfqq->bic, the queue is already shared or its requests
2682 * have already been redirected to a shared queue; both idle window
2683 * and weight raising state have already been saved. Do nothing.
2684 */
2685 if (!bic)
2686 return;
2687
fffca087 2688 bic->saved_weight = bfqq->entity.orig_weight;
36eca894 2689 bic->saved_ttime = bfqq->ttime;
d5be3fef 2690 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq);
36eca894 2691 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq);
e1b2324d
AA
2692 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq);
2693 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node);
894df937 2694 if (unlikely(bfq_bfqq_just_created(bfqq) &&
1be6e8a9
AR
2695 !bfq_bfqq_in_large_burst(bfqq) &&
2696 bfqq->bfqd->low_latency)) {
894df937
PV
2697 /*
2698 * bfqq being merged right after being created: bfqq
2699 * would have deserved interactive weight raising, but
2700 * did not make it to be set in a weight-raised state,
2701 * because of this early merge. Store directly the
2702 * weight-raising state that would have been assigned
2703 * to bfqq, so that to avoid that bfqq unjustly fails
2704 * to enjoy weight raising if split soon.
2705 */
2706 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff;
2b50f230 2707 bic->saved_wr_start_at_switch_to_srt = bfq_smallest_from_now();
894df937
PV
2708 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd);
2709 bic->saved_last_wr_start_finish = jiffies;
2710 } else {
2711 bic->saved_wr_coeff = bfqq->wr_coeff;
2712 bic->saved_wr_start_at_switch_to_srt =
2713 bfqq->wr_start_at_switch_to_srt;
2714 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish;
2715 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time;
2716 }
36eca894
AA
2717}
2718
478de338
PV
2719
2720static
2721void bfq_release_process_ref(struct bfq_data *bfqd, struct bfq_queue *bfqq)
2722{
2723 /*
2724 * To prevent bfqq's service guarantees from being violated,
2725 * bfqq may be left busy, i.e., queued for service, even if
2726 * empty (see comments in __bfq_bfqq_expire() for
2727 * details). But, if no process will send requests to bfqq any
2728 * longer, then there is no point in keeping bfqq queued for
2729 * service. In addition, keeping bfqq queued for service, but
2730 * with no process ref any longer, may have caused bfqq to be
2731 * freed when dequeued from service. But this is assumed to
2732 * never happen.
2733 */
2734 if (bfq_bfqq_busy(bfqq) && RB_EMPTY_ROOT(&bfqq->sort_list) &&
2735 bfqq != bfqd->in_service_queue)
2736 bfq_del_bfqq_busy(bfqd, bfqq, false);
2737
2738 bfq_put_queue(bfqq);
2739}
2740
36eca894
AA
2741static void
2742bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic,
2743 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq)
2744{
2745 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu",
2746 (unsigned long)new_bfqq->pid);
2747 /* Save weight raising and idle window of the merged queues */
2748 bfq_bfqq_save_state(bfqq);
2749 bfq_bfqq_save_state(new_bfqq);
2750 if (bfq_bfqq_IO_bound(bfqq))
2751 bfq_mark_bfqq_IO_bound(new_bfqq);
2752 bfq_clear_bfqq_IO_bound(bfqq);
2753
2754 /*
2755 * If bfqq is weight-raised, then let new_bfqq inherit
2756 * weight-raising. To reduce false positives, neglect the case
2757 * where bfqq has just been created, but has not yet made it
2758 * to be weight-raised (which may happen because EQM may merge
2759 * bfqq even before bfq_add_request is executed for the first
e1b2324d
AA
2760 * time for bfqq). Handling this case would however be very
2761 * easy, thanks to the flag just_created.
36eca894
AA
2762 */
2763 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) {
2764 new_bfqq->wr_coeff = bfqq->wr_coeff;
2765 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time;
2766 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish;
2767 new_bfqq->wr_start_at_switch_to_srt =
2768 bfqq->wr_start_at_switch_to_srt;
2769 if (bfq_bfqq_busy(new_bfqq))
2770 bfqd->wr_busy_queues++;
2771 new_bfqq->entity.prio_changed = 1;
2772 }
2773
2774 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */
2775 bfqq->wr_coeff = 1;
2776 bfqq->entity.prio_changed = 1;
2777 if (bfq_bfqq_busy(bfqq))
2778 bfqd->wr_busy_queues--;
2779 }
2780
2781 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d",
2782 bfqd->wr_busy_queues);
2783
36eca894
AA
2784 /*
2785 * Merge queues (that is, let bic redirect its requests to new_bfqq)
2786 */
2787 bic_set_bfqq(bic, new_bfqq, 1);
2788 bfq_mark_bfqq_coop(new_bfqq);
2789 /*
2790 * new_bfqq now belongs to at least two bics (it is a shared queue):
2791 * set new_bfqq->bic to NULL. bfqq either:
2792 * - does not belong to any bic any more, and hence bfqq->bic must
2793 * be set to NULL, or
2794 * - is a queue whose owning bics have already been redirected to a
2795 * different queue, hence the queue is destined to not belong to
2796 * any bic soon and bfqq->bic is already NULL (therefore the next
2797 * assignment causes no harm).
2798 */
2799 new_bfqq->bic = NULL;
1e66413c
FP
2800 /*
2801 * If the queue is shared, the pid is the pid of one of the associated
2802 * processes. Which pid depends on the exact sequence of merge events
2803 * the queue underwent. So printing such a pid is useless and confusing
2804 * because it reports a random pid between those of the associated
2805 * processes.
2806 * We mark such a queue with a pid -1, and then print SHARED instead of
2807 * a pid in logging messages.
2808 */
2809 new_bfqq->pid = -1;
36eca894 2810 bfqq->bic = NULL;
478de338 2811 bfq_release_process_ref(bfqd, bfqq);
36eca894
AA
2812}
2813
aee69d78
PV
2814static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2815 struct bio *bio)
2816{
2817 struct bfq_data *bfqd = q->elevator->elevator_data;
2818 bool is_sync = op_is_sync(bio->bi_opf);
36eca894 2819 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq;
aee69d78
PV
2820
2821 /*
2822 * Disallow merge of a sync bio into an async request.
2823 */
2824 if (is_sync && !rq_is_sync(rq))
2825 return false;
2826
2827 /*
2828 * Lookup the bfqq that this bio will be queued with. Allow
2829 * merge only if rq is queued there.
2830 */
2831 if (!bfqq)
2832 return false;
2833
36eca894
AA
2834 /*
2835 * We take advantage of this function to perform an early merge
2836 * of the queues of possible cooperating processes.
2837 */
2838 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false);
2839 if (new_bfqq) {
2840 /*
2841 * bic still points to bfqq, then it has not yet been
2842 * redirected to some other bfq_queue, and a queue
636b8fe8
AR
2843 * merge between bfqq and new_bfqq can be safely
2844 * fulfilled, i.e., bic can be redirected to new_bfqq
36eca894
AA
2845 * and bfqq can be put.
2846 */
2847 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq,
2848 new_bfqq);
2849 /*
2850 * If we get here, bio will be queued into new_queue,
2851 * so use new_bfqq to decide whether bio and rq can be
2852 * merged.
2853 */
2854 bfqq = new_bfqq;
2855
2856 /*
2857 * Change also bqfd->bio_bfqq, as
2858 * bfqd->bio_bic now points to new_bfqq, and
2859 * this function may be invoked again (and then may
2860 * use again bqfd->bio_bfqq).
2861 */
2862 bfqd->bio_bfqq = bfqq;
2863 }
2864
aee69d78
PV
2865 return bfqq == RQ_BFQQ(rq);
2866}
2867
44e44a1b
PV
2868/*
2869 * Set the maximum time for the in-service queue to consume its
2870 * budget. This prevents seeky processes from lowering the throughput.
2871 * In practice, a time-slice service scheme is used with seeky
2872 * processes.
2873 */
2874static void bfq_set_budget_timeout(struct bfq_data *bfqd,
2875 struct bfq_queue *bfqq)
2876{
77b7dcea
PV
2877 unsigned int timeout_coeff;
2878
2879 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time)
2880 timeout_coeff = 1;
2881 else
2882 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight;
2883
44e44a1b
PV
2884 bfqd->last_budget_start = ktime_get();
2885
2886 bfqq->budget_timeout = jiffies +
77b7dcea 2887 bfqd->bfq_timeout * timeout_coeff;
44e44a1b
PV
2888}
2889
aee69d78
PV
2890static void __bfq_set_in_service_queue(struct bfq_data *bfqd,
2891 struct bfq_queue *bfqq)
2892{
2893 if (bfqq) {
aee69d78
PV
2894 bfq_clear_bfqq_fifo_expire(bfqq);
2895
2896 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8;
2897
77b7dcea
PV
2898 if (time_is_before_jiffies(bfqq->last_wr_start_finish) &&
2899 bfqq->wr_coeff > 1 &&
2900 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
2901 time_is_before_jiffies(bfqq->budget_timeout)) {
2902 /*
2903 * For soft real-time queues, move the start
2904 * of the weight-raising period forward by the
2905 * time the queue has not received any
2906 * service. Otherwise, a relatively long
2907 * service delay is likely to cause the
2908 * weight-raising period of the queue to end,
2909 * because of the short duration of the
2910 * weight-raising period of a soft real-time
2911 * queue. It is worth noting that this move
2912 * is not so dangerous for the other queues,
2913 * because soft real-time queues are not
2914 * greedy.
2915 *
2916 * To not add a further variable, we use the
2917 * overloaded field budget_timeout to
2918 * determine for how long the queue has not
2919 * received service, i.e., how much time has
2920 * elapsed since the queue expired. However,
2921 * this is a little imprecise, because
2922 * budget_timeout is set to jiffies if bfqq
2923 * not only expires, but also remains with no
2924 * request.
2925 */
2926 if (time_after(bfqq->budget_timeout,
2927 bfqq->last_wr_start_finish))
2928 bfqq->last_wr_start_finish +=
2929 jiffies - bfqq->budget_timeout;
2930 else
2931 bfqq->last_wr_start_finish = jiffies;
2932 }
2933
44e44a1b 2934 bfq_set_budget_timeout(bfqd, bfqq);
aee69d78
PV
2935 bfq_log_bfqq(bfqd, bfqq,
2936 "set_in_service_queue, cur-budget = %d",
2937 bfqq->entity.budget);
2938 }
2939
2940 bfqd->in_service_queue = bfqq;
2941}
2942
2943/*
2944 * Get and set a new queue for service.
2945 */
2946static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd)
2947{
2948 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd);
2949
2950 __bfq_set_in_service_queue(bfqd, bfqq);
2951 return bfqq;
2952}
2953
aee69d78
PV
2954static void bfq_arm_slice_timer(struct bfq_data *bfqd)
2955{
2956 struct bfq_queue *bfqq = bfqd->in_service_queue;
aee69d78
PV
2957 u32 sl;
2958
aee69d78
PV
2959 bfq_mark_bfqq_wait_request(bfqq);
2960
2961 /*
2962 * We don't want to idle for seeks, but we do want to allow
2963 * fair distribution of slice time for a process doing back-to-back
2964 * seeks. So allow a little bit of time for him to submit a new rq.
2965 */
2966 sl = bfqd->bfq_slice_idle;
2967 /*
1de0c4cd
AA
2968 * Unless the queue is being weight-raised or the scenario is
2969 * asymmetric, grant only minimum idle time if the queue
2970 * is seeky. A long idling is preserved for a weight-raised
2971 * queue, or, more in general, in an asymmetric scenario,
2972 * because a long idling is needed for guaranteeing to a queue
2973 * its reserved share of the throughput (in particular, it is
2974 * needed if the queue has a higher weight than some other
2975 * queue).
aee69d78 2976 */
1de0c4cd 2977 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 &&
fb53ac6c 2978 !bfq_asymmetric_scenario(bfqd, bfqq))
aee69d78 2979 sl = min_t(u64, sl, BFQ_MIN_TT);
778c02a2
PV
2980 else if (bfqq->wr_coeff > 1)
2981 sl = max_t(u32, sl, 20ULL * NSEC_PER_MSEC);
aee69d78
PV
2982
2983 bfqd->last_idling_start = ktime_get();
2341d662
PV
2984 bfqd->last_idling_start_jiffies = jiffies;
2985
aee69d78
PV
2986 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl),
2987 HRTIMER_MODE_REL);
e21b7a0b 2988 bfqg_stats_set_start_idle_time(bfqq_group(bfqq));
aee69d78
PV
2989}
2990
ab0e43e9
PV
2991/*
2992 * In autotuning mode, max_budget is dynamically recomputed as the
2993 * amount of sectors transferred in timeout at the estimated peak
2994 * rate. This enables BFQ to utilize a full timeslice with a full
2995 * budget, even if the in-service queue is served at peak rate. And
2996 * this maximises throughput with sequential workloads.
2997 */
2998static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd)
2999{
3000 return (u64)bfqd->peak_rate * USEC_PER_MSEC *
3001 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT;
3002}
3003
44e44a1b
PV
3004/*
3005 * Update parameters related to throughput and responsiveness, as a
3006 * function of the estimated peak rate. See comments on
e24f1c24 3007 * bfq_calc_max_budget(), and on the ref_wr_duration array.
44e44a1b
PV
3008 */
3009static void update_thr_responsiveness_params(struct bfq_data *bfqd)
3010{
e24f1c24 3011 if (bfqd->bfq_user_max_budget == 0) {
44e44a1b
PV
3012 bfqd->bfq_max_budget =
3013 bfq_calc_max_budget(bfqd);
e24f1c24 3014 bfq_log(bfqd, "new max_budget = %d", bfqd->bfq_max_budget);
44e44a1b 3015 }
44e44a1b
PV
3016}
3017
ab0e43e9
PV
3018static void bfq_reset_rate_computation(struct bfq_data *bfqd,
3019 struct request *rq)
3020{
3021 if (rq != NULL) { /* new rq dispatch now, reset accordingly */
3022 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns();
3023 bfqd->peak_rate_samples = 1;
3024 bfqd->sequential_samples = 0;
3025 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size =
3026 blk_rq_sectors(rq);
3027 } else /* no new rq dispatched, just reset the number of samples */
3028 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */
3029
3030 bfq_log(bfqd,
3031 "reset_rate_computation at end, sample %u/%u tot_sects %llu",
3032 bfqd->peak_rate_samples, bfqd->sequential_samples,
3033 bfqd->tot_sectors_dispatched);
3034}
3035
3036static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq)
3037{
3038 u32 rate, weight, divisor;
3039
3040 /*
3041 * For the convergence property to hold (see comments on
3042 * bfq_update_peak_rate()) and for the assessment to be
3043 * reliable, a minimum number of samples must be present, and
3044 * a minimum amount of time must have elapsed. If not so, do
3045 * not compute new rate. Just reset parameters, to get ready
3046 * for a new evaluation attempt.
3047 */
3048 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES ||
3049 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL)
3050 goto reset_computation;
3051
3052 /*
3053 * If a new request completion has occurred after last
3054 * dispatch, then, to approximate the rate at which requests
3055 * have been served by the device, it is more precise to
3056 * extend the observation interval to the last completion.
3057 */
3058 bfqd->delta_from_first =
3059 max_t(u64, bfqd->delta_from_first,
3060 bfqd->last_completion - bfqd->first_dispatch);
3061
3062 /*
3063 * Rate computed in sects/usec, and not sects/nsec, for
3064 * precision issues.
3065 */
3066 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT,
3067 div_u64(bfqd->delta_from_first, NSEC_PER_USEC));
3068
3069 /*
3070 * Peak rate not updated if:
3071 * - the percentage of sequential dispatches is below 3/4 of the
3072 * total, and rate is below the current estimated peak rate
3073 * - rate is unreasonably high (> 20M sectors/sec)
3074 */
3075 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 &&
3076 rate <= bfqd->peak_rate) ||
3077 rate > 20<<BFQ_RATE_SHIFT)
3078 goto reset_computation;
3079
3080 /*
3081 * We have to update the peak rate, at last! To this purpose,
3082 * we use a low-pass filter. We compute the smoothing constant
3083 * of the filter as a function of the 'weight' of the new
3084 * measured rate.
3085 *
3086 * As can be seen in next formulas, we define this weight as a
3087 * quantity proportional to how sequential the workload is,
3088 * and to how long the observation time interval is.
3089 *
3090 * The weight runs from 0 to 8. The maximum value of the
3091 * weight, 8, yields the minimum value for the smoothing
3092 * constant. At this minimum value for the smoothing constant,
3093 * the measured rate contributes for half of the next value of
3094 * the estimated peak rate.
3095 *
3096 * So, the first step is to compute the weight as a function
3097 * of how sequential the workload is. Note that the weight
3098 * cannot reach 9, because bfqd->sequential_samples cannot
3099 * become equal to bfqd->peak_rate_samples, which, in its
3100 * turn, holds true because bfqd->sequential_samples is not
3101 * incremented for the first sample.
3102 */
3103 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples;
3104
3105 /*
3106 * Second step: further refine the weight as a function of the
3107 * duration of the observation interval.
3108 */
3109 weight = min_t(u32, 8,
3110 div_u64(weight * bfqd->delta_from_first,
3111 BFQ_RATE_REF_INTERVAL));
3112
3113 /*
3114 * Divisor ranging from 10, for minimum weight, to 2, for
3115 * maximum weight.
3116 */
3117 divisor = 10 - weight;
3118
3119 /*
3120 * Finally, update peak rate:
3121 *
3122 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor
3123 */
3124 bfqd->peak_rate *= divisor-1;
3125 bfqd->peak_rate /= divisor;
3126 rate /= divisor; /* smoothing constant alpha = 1/divisor */
3127
3128 bfqd->peak_rate += rate;
bc56e2ca
PV
3129
3130 /*
3131 * For a very slow device, bfqd->peak_rate can reach 0 (see
3132 * the minimum representable values reported in the comments
3133 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid
3134 * divisions by zero where bfqd->peak_rate is used as a
3135 * divisor.
3136 */
3137 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate);
3138
44e44a1b 3139 update_thr_responsiveness_params(bfqd);
ab0e43e9
PV
3140
3141reset_computation:
3142 bfq_reset_rate_computation(bfqd, rq);
3143}
3144
3145/*
3146 * Update the read/write peak rate (the main quantity used for
3147 * auto-tuning, see update_thr_responsiveness_params()).
3148 *
3149 * It is not trivial to estimate the peak rate (correctly): because of
3150 * the presence of sw and hw queues between the scheduler and the
3151 * device components that finally serve I/O requests, it is hard to
3152 * say exactly when a given dispatched request is served inside the
3153 * device, and for how long. As a consequence, it is hard to know
3154 * precisely at what rate a given set of requests is actually served
3155 * by the device.
3156 *
3157 * On the opposite end, the dispatch time of any request is trivially
3158 * available, and, from this piece of information, the "dispatch rate"
3159 * of requests can be immediately computed. So, the idea in the next
3160 * function is to use what is known, namely request dispatch times
3161 * (plus, when useful, request completion times), to estimate what is
3162 * unknown, namely in-device request service rate.
3163 *
3164 * The main issue is that, because of the above facts, the rate at
3165 * which a certain set of requests is dispatched over a certain time
3166 * interval can vary greatly with respect to the rate at which the
3167 * same requests are then served. But, since the size of any
3168 * intermediate queue is limited, and the service scheme is lossless
3169 * (no request is silently dropped), the following obvious convergence
3170 * property holds: the number of requests dispatched MUST become
3171 * closer and closer to the number of requests completed as the
3172 * observation interval grows. This is the key property used in
3173 * the next function to estimate the peak service rate as a function
3174 * of the observed dispatch rate. The function assumes to be invoked
3175 * on every request dispatch.
3176 */
3177static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq)
3178{
3179 u64 now_ns = ktime_get_ns();
3180
3181 if (bfqd->peak_rate_samples == 0) { /* first dispatch */
3182 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d",
3183 bfqd->peak_rate_samples);
3184 bfq_reset_rate_computation(bfqd, rq);
3185 goto update_last_values; /* will add one sample */
3186 }
3187
3188 /*
3189 * Device idle for very long: the observation interval lasting
3190 * up to this dispatch cannot be a valid observation interval
3191 * for computing a new peak rate (similarly to the late-
3192 * completion event in bfq_completed_request()). Go to
3193 * update_rate_and_reset to have the following three steps
3194 * taken:
3195 * - close the observation interval at the last (previous)
3196 * request dispatch or completion
3197 * - compute rate, if possible, for that observation interval
3198 * - start a new observation interval with this dispatch
3199 */
3200 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC &&
3201 bfqd->rq_in_driver == 0)
3202 goto update_rate_and_reset;
3203
3204 /* Update sampling information */
3205 bfqd->peak_rate_samples++;
3206
3207 if ((bfqd->rq_in_driver > 0 ||
3208 now_ns - bfqd->last_completion < BFQ_MIN_TT)
d87447d8 3209 && !BFQ_RQ_SEEKY(bfqd, bfqd->last_position, rq))
ab0e43e9
PV
3210 bfqd->sequential_samples++;
3211
3212 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq);
3213
3214 /* Reset max observed rq size every 32 dispatches */
3215 if (likely(bfqd->peak_rate_samples % 32))
3216 bfqd->last_rq_max_size =
3217 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size);
3218 else
3219 bfqd->last_rq_max_size = blk_rq_sectors(rq);
3220
3221 bfqd->delta_from_first = now_ns - bfqd->first_dispatch;
3222
3223 /* Target observation interval not yet reached, go on sampling */
3224 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL)
3225 goto update_last_values;
3226
3227update_rate_and_reset:
3228 bfq_update_rate_reset(bfqd, rq);
3229update_last_values:
3230 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
058fdecc
PV
3231 if (RQ_BFQQ(rq) == bfqd->in_service_queue)
3232 bfqd->in_serv_last_pos = bfqd->last_position;
ab0e43e9
PV
3233 bfqd->last_dispatch = now_ns;
3234}
3235
aee69d78
PV
3236/*
3237 * Remove request from internal lists.
3238 */
3239static void bfq_dispatch_remove(struct request_queue *q, struct request *rq)
3240{
3241 struct bfq_queue *bfqq = RQ_BFQQ(rq);
3242
3243 /*
3244 * For consistency, the next instruction should have been
3245 * executed after removing the request from the queue and
3246 * dispatching it. We execute instead this instruction before
3247 * bfq_remove_request() (and hence introduce a temporary
3248 * inconsistency), for efficiency. In fact, should this
3249 * dispatch occur for a non in-service bfqq, this anticipated
3250 * increment prevents two counters related to bfqq->dispatched
3251 * from risking to be, first, uselessly decremented, and then
3252 * incremented again when the (new) value of bfqq->dispatched
3253 * happens to be taken into account.
3254 */
3255 bfqq->dispatched++;
ab0e43e9 3256 bfq_update_peak_rate(q->elevator->elevator_data, rq);
aee69d78
PV
3257
3258 bfq_remove_request(q, rq);
3259}
3260
3726112e
PV
3261/*
3262 * There is a case where idling does not have to be performed for
3263 * throughput concerns, but to preserve the throughput share of
3264 * the process associated with bfqq.
3265 *
3266 * To introduce this case, we can note that allowing the drive
3267 * to enqueue more than one request at a time, and hence
3268 * delegating de facto final scheduling decisions to the
3269 * drive's internal scheduler, entails loss of control on the
3270 * actual request service order. In particular, the critical
3271 * situation is when requests from different processes happen
3272 * to be present, at the same time, in the internal queue(s)
3273 * of the drive. In such a situation, the drive, by deciding
3274 * the service order of the internally-queued requests, does
3275 * determine also the actual throughput distribution among
3276 * these processes. But the drive typically has no notion or
3277 * concern about per-process throughput distribution, and
3278 * makes its decisions only on a per-request basis. Therefore,
3279 * the service distribution enforced by the drive's internal
3280 * scheduler is likely to coincide with the desired throughput
3281 * distribution only in a completely symmetric, or favorably
3282 * skewed scenario where:
3283 * (i-a) each of these processes must get the same throughput as
3284 * the others,
3285 * (i-b) in case (i-a) does not hold, it holds that the process
3286 * associated with bfqq must receive a lower or equal
3287 * throughput than any of the other processes;
3288 * (ii) the I/O of each process has the same properties, in
3289 * terms of locality (sequential or random), direction
3290 * (reads or writes), request sizes, greediness
3291 * (from I/O-bound to sporadic), and so on;
3292
3293 * In fact, in such a scenario, the drive tends to treat the requests
3294 * of each process in about the same way as the requests of the
3295 * others, and thus to provide each of these processes with about the
3296 * same throughput. This is exactly the desired throughput
3297 * distribution if (i-a) holds, or, if (i-b) holds instead, this is an
3298 * even more convenient distribution for (the process associated with)
3299 * bfqq.
3300 *
3301 * In contrast, in any asymmetric or unfavorable scenario, device
3302 * idling (I/O-dispatch plugging) is certainly needed to guarantee
3303 * that bfqq receives its assigned fraction of the device throughput
3304 * (see [1] for details).
3305 *
3306 * The problem is that idling may significantly reduce throughput with
3307 * certain combinations of types of I/O and devices. An important
3308 * example is sync random I/O on flash storage with command
3309 * queueing. So, unless bfqq falls in cases where idling also boosts
3310 * throughput, it is important to check conditions (i-a), i(-b) and
3311 * (ii) accurately, so as to avoid idling when not strictly needed for
3312 * service guarantees.
3313 *
3314 * Unfortunately, it is extremely difficult to thoroughly check
3315 * condition (ii). And, in case there are active groups, it becomes
3316 * very difficult to check conditions (i-a) and (i-b) too. In fact,
3317 * if there are active groups, then, for conditions (i-a) or (i-b) to
3318 * become false 'indirectly', it is enough that an active group
3319 * contains more active processes or sub-groups than some other active
3320 * group. More precisely, for conditions (i-a) or (i-b) to become
3321 * false because of such a group, it is not even necessary that the
3322 * group is (still) active: it is sufficient that, even if the group
3323 * has become inactive, some of its descendant processes still have
3324 * some request already dispatched but still waiting for
3325 * completion. In fact, requests have still to be guaranteed their
3326 * share of the throughput even after being dispatched. In this
3327 * respect, it is easy to show that, if a group frequently becomes
3328 * inactive while still having in-flight requests, and if, when this
3329 * happens, the group is not considered in the calculation of whether
3330 * the scenario is asymmetric, then the group may fail to be
3331 * guaranteed its fair share of the throughput (basically because
3332 * idling may not be performed for the descendant processes of the
3333 * group, but it had to be). We address this issue with the following
3334 * bi-modal behavior, implemented in the function
3335 * bfq_asymmetric_scenario().
3336 *
3337 * If there are groups with requests waiting for completion
3338 * (as commented above, some of these groups may even be
3339 * already inactive), then the scenario is tagged as
3340 * asymmetric, conservatively, without checking any of the
3341 * conditions (i-a), (i-b) or (ii). So the device is idled for bfqq.
3342 * This behavior matches also the fact that groups are created
3343 * exactly if controlling I/O is a primary concern (to
3344 * preserve bandwidth and latency guarantees).
3345 *
3346 * On the opposite end, if there are no groups with requests waiting
3347 * for completion, then only conditions (i-a) and (i-b) are actually
3348 * controlled, i.e., provided that conditions (i-a) or (i-b) holds,
3349 * idling is not performed, regardless of whether condition (ii)
3350 * holds. In other words, only if conditions (i-a) and (i-b) do not
3351 * hold, then idling is allowed, and the device tends to be prevented
3352 * from queueing many requests, possibly of several processes. Since
3353 * there are no groups with requests waiting for completion, then, to
3354 * control conditions (i-a) and (i-b) it is enough to check just
3355 * whether all the queues with requests waiting for completion also
3356 * have the same weight.
3357 *
3358 * Not checking condition (ii) evidently exposes bfqq to the
3359 * risk of getting less throughput than its fair share.
3360 * However, for queues with the same weight, a further
3361 * mechanism, preemption, mitigates or even eliminates this
3362 * problem. And it does so without consequences on overall
3363 * throughput. This mechanism and its benefits are explained
3364 * in the next three paragraphs.
3365 *
3366 * Even if a queue, say Q, is expired when it remains idle, Q
3367 * can still preempt the new in-service queue if the next
3368 * request of Q arrives soon (see the comments on
3369 * bfq_bfqq_update_budg_for_activation). If all queues and
3370 * groups have the same weight, this form of preemption,
3371 * combined with the hole-recovery heuristic described in the
3372 * comments on function bfq_bfqq_update_budg_for_activation,
3373 * are enough to preserve a correct bandwidth distribution in
3374 * the mid term, even without idling. In fact, even if not
3375 * idling allows the internal queues of the device to contain
3376 * many requests, and thus to reorder requests, we can rather
3377 * safely assume that the internal scheduler still preserves a
3378 * minimum of mid-term fairness.
3379 *
3380 * More precisely, this preemption-based, idleless approach
3381 * provides fairness in terms of IOPS, and not sectors per
3382 * second. This can be seen with a simple example. Suppose
3383 * that there are two queues with the same weight, but that
3384 * the first queue receives requests of 8 sectors, while the
3385 * second queue receives requests of 1024 sectors. In
3386 * addition, suppose that each of the two queues contains at
3387 * most one request at a time, which implies that each queue
3388 * always remains idle after it is served. Finally, after
3389 * remaining idle, each queue receives very quickly a new
3390 * request. It follows that the two queues are served
3391 * alternatively, preempting each other if needed. This
3392 * implies that, although both queues have the same weight,
3393 * the queue with large requests receives a service that is
3394 * 1024/8 times as high as the service received by the other
3395 * queue.
3396 *
3397 * The motivation for using preemption instead of idling (for
3398 * queues with the same weight) is that, by not idling,
3399 * service guarantees are preserved (completely or at least in
3400 * part) without minimally sacrificing throughput. And, if
3401 * there is no active group, then the primary expectation for
3402 * this device is probably a high throughput.
3403 *
b5e02b48
PV
3404 * We are now left only with explaining the two sub-conditions in the
3405 * additional compound condition that is checked below for deciding
3406 * whether the scenario is asymmetric. To explain the first
3407 * sub-condition, we need to add that the function
3726112e 3408 * bfq_asymmetric_scenario checks the weights of only
b5e02b48
PV
3409 * non-weight-raised queues, for efficiency reasons (see comments on
3410 * bfq_weights_tree_add()). Then the fact that bfqq is weight-raised
3411 * is checked explicitly here. More precisely, the compound condition
3412 * below takes into account also the fact that, even if bfqq is being
3413 * weight-raised, the scenario is still symmetric if all queues with
3414 * requests waiting for completion happen to be
3415 * weight-raised. Actually, we should be even more precise here, and
3416 * differentiate between interactive weight raising and soft real-time
3417 * weight raising.
3418 *
3419 * The second sub-condition checked in the compound condition is
3420 * whether there is a fair amount of already in-flight I/O not
3421 * belonging to bfqq. If so, I/O dispatching is to be plugged, for the
3422 * following reason. The drive may decide to serve in-flight
3423 * non-bfqq's I/O requests before bfqq's ones, thereby delaying the
3424 * arrival of new I/O requests for bfqq (recall that bfqq is sync). If
3425 * I/O-dispatching is not plugged, then, while bfqq remains empty, a
3426 * basically uncontrolled amount of I/O from other queues may be
3427 * dispatched too, possibly causing the service of bfqq's I/O to be
3428 * delayed even longer in the drive. This problem gets more and more
3429 * serious as the speed and the queue depth of the drive grow,
3430 * because, as these two quantities grow, the probability to find no
3431 * queue busy but many requests in flight grows too. By contrast,
3432 * plugging I/O dispatching minimizes the delay induced by already
3433 * in-flight I/O, and enables bfqq to recover the bandwidth it may
3434 * lose because of this delay.
3726112e
PV
3435 *
3436 * As a side note, it is worth considering that the above
b5e02b48
PV
3437 * device-idling countermeasures may however fail in the following
3438 * unlucky scenario: if I/O-dispatch plugging is (correctly) disabled
3439 * in a time period during which all symmetry sub-conditions hold, and
3440 * therefore the device is allowed to enqueue many requests, but at
3441 * some later point in time some sub-condition stops to hold, then it
3442 * may become impossible to make requests be served in the desired
3443 * order until all the requests already queued in the device have been
3444 * served. The last sub-condition commented above somewhat mitigates
3445 * this problem for weight-raised queues.
3726112e
PV
3446 */
3447static bool idling_needed_for_service_guarantees(struct bfq_data *bfqd,
3448 struct bfq_queue *bfqq)
3449{
f718b093
PV
3450 /* No point in idling for bfqq if it won't get requests any longer */
3451 if (unlikely(!bfqq_process_refs(bfqq)))
3452 return false;
3453
3726112e 3454 return (bfqq->wr_coeff > 1 &&
b5e02b48
PV
3455 (bfqd->wr_busy_queues <
3456 bfq_tot_busy_queues(bfqd) ||
3457 bfqd->rq_in_driver >=
3458 bfqq->dispatched + 4)) ||
3726112e
PV
3459 bfq_asymmetric_scenario(bfqd, bfqq);
3460}
3461
3462static bool __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq,
3463 enum bfqq_expiration reason)
aee69d78 3464{
36eca894
AA
3465 /*
3466 * If this bfqq is shared between multiple processes, check
3467 * to make sure that those processes are still issuing I/Os
3468 * within the mean seek distance. If not, it may be time to
3469 * break the queues apart again.
3470 */
3471 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq))
3472 bfq_mark_bfqq_split_coop(bfqq);
3473
3726112e
PV
3474 /*
3475 * Consider queues with a higher finish virtual time than
3476 * bfqq. If idling_needed_for_service_guarantees(bfqq) returns
3477 * true, then bfqq's bandwidth would be violated if an
3478 * uncontrolled amount of I/O from these queues were
3479 * dispatched while bfqq is waiting for its new I/O to
3480 * arrive. This is exactly what may happen if this is a forced
3481 * expiration caused by a preemption attempt, and if bfqq is
3482 * not re-scheduled. To prevent this from happening, re-queue
3483 * bfqq if it needs I/O-dispatch plugging, even if it is
3484 * empty. By doing so, bfqq is granted to be served before the
3485 * above queues (provided that bfqq is of course eligible).
3486 */
3487 if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
3488 !(reason == BFQQE_PREEMPTED &&
3489 idling_needed_for_service_guarantees(bfqd, bfqq))) {
44e44a1b
PV
3490 if (bfqq->dispatched == 0)
3491 /*
3492 * Overloading budget_timeout field to store
3493 * the time at which the queue remains with no
3494 * backlog and no outstanding request; used by
3495 * the weight-raising mechanism.
3496 */
3497 bfqq->budget_timeout = jiffies;
3498
e21b7a0b 3499 bfq_del_bfqq_busy(bfqd, bfqq, true);
36eca894 3500 } else {
80294c3b 3501 bfq_requeue_bfqq(bfqd, bfqq, true);
36eca894
AA
3502 /*
3503 * Resort priority tree of potential close cooperators.
8cacc5ab 3504 * See comments on bfq_pos_tree_add_move() for the unlikely().
36eca894 3505 */
3726112e
PV
3506 if (unlikely(!bfqd->nonrot_with_queueing &&
3507 !RB_EMPTY_ROOT(&bfqq->sort_list)))
8cacc5ab 3508 bfq_pos_tree_add_move(bfqd, bfqq);
36eca894 3509 }
e21b7a0b
AA
3510
3511 /*
3512 * All in-service entities must have been properly deactivated
3513 * or requeued before executing the next function, which
eed47d19
PV
3514 * resets all in-service entities as no more in service. This
3515 * may cause bfqq to be freed. If this happens, the next
3516 * function returns true.
e21b7a0b 3517 */
eed47d19 3518 return __bfq_bfqd_reset_in_service(bfqd);
aee69d78
PV
3519}
3520
3521/**
3522 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior.
3523 * @bfqd: device data.
3524 * @bfqq: queue to update.
3525 * @reason: reason for expiration.
3526 *
3527 * Handle the feedback on @bfqq budget at queue expiration.
3528 * See the body for detailed comments.
3529 */
3530static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd,
3531 struct bfq_queue *bfqq,
3532 enum bfqq_expiration reason)
3533{
3534 struct request *next_rq;
3535 int budget, min_budget;
3536
aee69d78
PV
3537 min_budget = bfq_min_budget(bfqd);
3538
44e44a1b
PV
3539 if (bfqq->wr_coeff == 1)
3540 budget = bfqq->max_budget;
3541 else /*
3542 * Use a constant, low budget for weight-raised queues,
3543 * to help achieve a low latency. Keep it slightly higher
3544 * than the minimum possible budget, to cause a little
3545 * bit fewer expirations.
3546 */
3547 budget = 2 * min_budget;
3548
aee69d78
PV
3549 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d",
3550 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq));
3551 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d",
3552 budget, bfq_min_budget(bfqd));
3553 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d",
3554 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue));
3555
44e44a1b 3556 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) {
aee69d78
PV
3557 switch (reason) {
3558 /*
3559 * Caveat: in all the following cases we trade latency
3560 * for throughput.
3561 */
3562 case BFQQE_TOO_IDLE:
54b60456
PV
3563 /*
3564 * This is the only case where we may reduce
3565 * the budget: if there is no request of the
3566 * process still waiting for completion, then
3567 * we assume (tentatively) that the timer has
3568 * expired because the batch of requests of
3569 * the process could have been served with a
3570 * smaller budget. Hence, betting that
3571 * process will behave in the same way when it
3572 * becomes backlogged again, we reduce its
3573 * next budget. As long as we guess right,
3574 * this budget cut reduces the latency
3575 * experienced by the process.
3576 *
3577 * However, if there are still outstanding
3578 * requests, then the process may have not yet
3579 * issued its next request just because it is
3580 * still waiting for the completion of some of
3581 * the still outstanding ones. So in this
3582 * subcase we do not reduce its budget, on the
3583 * contrary we increase it to possibly boost
3584 * the throughput, as discussed in the
3585 * comments to the BUDGET_TIMEOUT case.
3586 */
3587 if (bfqq->dispatched > 0) /* still outstanding reqs */
3588 budget = min(budget * 2, bfqd->bfq_max_budget);
3589 else {
3590 if (budget > 5 * min_budget)
3591 budget -= 4 * min_budget;
3592 else
3593 budget = min_budget;
3594 }
aee69d78
PV
3595 break;
3596 case BFQQE_BUDGET_TIMEOUT:
54b60456
PV
3597 /*
3598 * We double the budget here because it gives
3599 * the chance to boost the throughput if this
3600 * is not a seeky process (and has bumped into
3601 * this timeout because of, e.g., ZBR).
3602 */
3603 budget = min(budget * 2, bfqd->bfq_max_budget);
aee69d78
PV
3604 break;
3605 case BFQQE_BUDGET_EXHAUSTED:
3606 /*
3607 * The process still has backlog, and did not
3608 * let either the budget timeout or the disk
3609 * idling timeout expire. Hence it is not
3610 * seeky, has a short thinktime and may be
3611 * happy with a higher budget too. So
3612 * definitely increase the budget of this good
3613 * candidate to boost the disk throughput.
3614 */
54b60456 3615 budget = min(budget * 4, bfqd->bfq_max_budget);
aee69d78
PV
3616 break;
3617 case BFQQE_NO_MORE_REQUESTS:
3618 /*
3619 * For queues that expire for this reason, it
3620 * is particularly important to keep the
3621 * budget close to the actual service they
3622 * need. Doing so reduces the timestamp
3623 * misalignment problem described in the
3624 * comments in the body of
3625 * __bfq_activate_entity. In fact, suppose
3626 * that a queue systematically expires for
3627 * BFQQE_NO_MORE_REQUESTS and presents a
3628 * new request in time to enjoy timestamp
3629 * back-shifting. The larger the budget of the
3630 * queue is with respect to the service the
3631 * queue actually requests in each service
3632 * slot, the more times the queue can be
3633 * reactivated with the same virtual finish
3634 * time. It follows that, even if this finish
3635 * time is pushed to the system virtual time
3636 * to reduce the consequent timestamp
3637 * misalignment, the queue unjustly enjoys for
3638 * many re-activations a lower finish time
3639 * than all newly activated queues.
3640 *
3641 * The service needed by bfqq is measured
3642 * quite precisely by bfqq->entity.service.
3643 * Since bfqq does not enjoy device idling,
3644 * bfqq->entity.service is equal to the number
3645 * of sectors that the process associated with
3646 * bfqq requested to read/write before waiting
3647 * for request completions, or blocking for
3648 * other reasons.
3649 */
3650 budget = max_t(int, bfqq->entity.service, min_budget);
3651 break;
3652 default:
3653 return;
3654 }
44e44a1b 3655 } else if (!bfq_bfqq_sync(bfqq)) {
aee69d78
PV
3656 /*
3657 * Async queues get always the maximum possible
3658 * budget, as for them we do not care about latency
3659 * (in addition, their ability to dispatch is limited
3660 * by the charging factor).
3661 */
3662 budget = bfqd->bfq_max_budget;
3663 }
3664
3665 bfqq->max_budget = budget;
3666
3667 if (bfqd->budgets_assigned >= bfq_stats_min_budgets &&
3668 !bfqd->bfq_user_max_budget)
3669 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget);
3670
3671 /*
3672 * If there is still backlog, then assign a new budget, making
3673 * sure that it is large enough for the next request. Since
3674 * the finish time of bfqq must be kept in sync with the
3675 * budget, be sure to call __bfq_bfqq_expire() *after* this
3676 * update.
3677 *
3678 * If there is no backlog, then no need to update the budget;
3679 * it will be updated on the arrival of a new request.
3680 */
3681 next_rq = bfqq->next_rq;
3682 if (next_rq)
3683 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget,
3684 bfq_serv_to_charge(next_rq, bfqq));
3685
3686 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d",
3687 next_rq ? blk_rq_sectors(next_rq) : 0,
3688 bfqq->entity.budget);
3689}
3690
aee69d78 3691/*
ab0e43e9
PV
3692 * Return true if the process associated with bfqq is "slow". The slow
3693 * flag is used, in addition to the budget timeout, to reduce the
3694 * amount of service provided to seeky processes, and thus reduce
3695 * their chances to lower the throughput. More details in the comments
3696 * on the function bfq_bfqq_expire().
3697 *
3698 * An important observation is in order: as discussed in the comments
3699 * on the function bfq_update_peak_rate(), with devices with internal
3700 * queues, it is hard if ever possible to know when and for how long
3701 * an I/O request is processed by the device (apart from the trivial
3702 * I/O pattern where a new request is dispatched only after the
3703 * previous one has been completed). This makes it hard to evaluate
3704 * the real rate at which the I/O requests of each bfq_queue are
3705 * served. In fact, for an I/O scheduler like BFQ, serving a
3706 * bfq_queue means just dispatching its requests during its service
3707 * slot (i.e., until the budget of the queue is exhausted, or the
3708 * queue remains idle, or, finally, a timeout fires). But, during the
3709 * service slot of a bfq_queue, around 100 ms at most, the device may
3710 * be even still processing requests of bfq_queues served in previous
3711 * service slots. On the opposite end, the requests of the in-service
3712 * bfq_queue may be completed after the service slot of the queue
3713 * finishes.
3714 *
3715 * Anyway, unless more sophisticated solutions are used
3716 * (where possible), the sum of the sizes of the requests dispatched
3717 * during the service slot of a bfq_queue is probably the only
3718 * approximation available for the service received by the bfq_queue
3719 * during its service slot. And this sum is the quantity used in this
3720 * function to evaluate the I/O speed of a process.
aee69d78 3721 */
ab0e43e9
PV
3722static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq,
3723 bool compensate, enum bfqq_expiration reason,
3724 unsigned long *delta_ms)
aee69d78 3725{
ab0e43e9
PV
3726 ktime_t delta_ktime;
3727 u32 delta_usecs;
3728 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */
aee69d78 3729
ab0e43e9 3730 if (!bfq_bfqq_sync(bfqq))
aee69d78
PV
3731 return false;
3732
3733 if (compensate)
ab0e43e9 3734 delta_ktime = bfqd->last_idling_start;
aee69d78 3735 else
ab0e43e9
PV
3736 delta_ktime = ktime_get();
3737 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start);
3738 delta_usecs = ktime_to_us(delta_ktime);
aee69d78
PV
3739
3740 /* don't use too short time intervals */
ab0e43e9
PV
3741 if (delta_usecs < 1000) {
3742 if (blk_queue_nonrot(bfqd->queue))
3743 /*
3744 * give same worst-case guarantees as idling
3745 * for seeky
3746 */
3747 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC;
3748 else /* charge at least one seek */
3749 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC;
3750
3751 return slow;
3752 }
aee69d78 3753
ab0e43e9 3754 *delta_ms = delta_usecs / USEC_PER_MSEC;
aee69d78
PV
3755
3756 /*
ab0e43e9
PV
3757 * Use only long (> 20ms) intervals to filter out excessive
3758 * spikes in service rate estimation.
aee69d78 3759 */
ab0e43e9
PV
3760 if (delta_usecs > 20000) {
3761 /*
3762 * Caveat for rotational devices: processes doing I/O
3763 * in the slower disk zones tend to be slow(er) even
3764 * if not seeky. In this respect, the estimated peak
3765 * rate is likely to be an average over the disk
3766 * surface. Accordingly, to not be too harsh with
3767 * unlucky processes, a process is deemed slow only if
3768 * its rate has been lower than half of the estimated
3769 * peak rate.
3770 */
3771 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2;
aee69d78
PV
3772 }
3773
ab0e43e9 3774 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow);
aee69d78 3775
ab0e43e9 3776 return slow;
aee69d78
PV
3777}
3778
77b7dcea
PV
3779/*
3780 * To be deemed as soft real-time, an application must meet two
3781 * requirements. First, the application must not require an average
3782 * bandwidth higher than the approximate bandwidth required to playback or
3783 * record a compressed high-definition video.
3784 * The next function is invoked on the completion of the last request of a
3785 * batch, to compute the next-start time instant, soft_rt_next_start, such
3786 * that, if the next request of the application does not arrive before
3787 * soft_rt_next_start, then the above requirement on the bandwidth is met.
3788 *
3789 * The second requirement is that the request pattern of the application is
3790 * isochronous, i.e., that, after issuing a request or a batch of requests,
3791 * the application stops issuing new requests until all its pending requests
3792 * have been completed. After that, the application may issue a new batch,
3793 * and so on.
3794 * For this reason the next function is invoked to compute
3795 * soft_rt_next_start only for applications that meet this requirement,
3796 * whereas soft_rt_next_start is set to infinity for applications that do
3797 * not.
3798 *
a34b0244
PV
3799 * Unfortunately, even a greedy (i.e., I/O-bound) application may
3800 * happen to meet, occasionally or systematically, both the above
3801 * bandwidth and isochrony requirements. This may happen at least in
3802 * the following circumstances. First, if the CPU load is high. The
3803 * application may stop issuing requests while the CPUs are busy
3804 * serving other processes, then restart, then stop again for a while,
3805 * and so on. The other circumstances are related to the storage
3806 * device: the storage device is highly loaded or reaches a low-enough
3807 * throughput with the I/O of the application (e.g., because the I/O
3808 * is random and/or the device is slow). In all these cases, the
3809 * I/O of the application may be simply slowed down enough to meet
3810 * the bandwidth and isochrony requirements. To reduce the probability
3811 * that greedy applications are deemed as soft real-time in these
3812 * corner cases, a further rule is used in the computation of
3813 * soft_rt_next_start: the return value of this function is forced to
3814 * be higher than the maximum between the following two quantities.
3815 *
3816 * (a) Current time plus: (1) the maximum time for which the arrival
3817 * of a request is waited for when a sync queue becomes idle,
3818 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We
3819 * postpone for a moment the reason for adding a few extra
3820 * jiffies; we get back to it after next item (b). Lower-bounding
3821 * the return value of this function with the current time plus
3822 * bfqd->bfq_slice_idle tends to filter out greedy applications,
3823 * because the latter issue their next request as soon as possible
3824 * after the last one has been completed. In contrast, a soft
3825 * real-time application spends some time processing data, after a
3826 * batch of its requests has been completed.
3827 *
3828 * (b) Current value of bfqq->soft_rt_next_start. As pointed out
3829 * above, greedy applications may happen to meet both the
3830 * bandwidth and isochrony requirements under heavy CPU or
3831 * storage-device load. In more detail, in these scenarios, these
3832 * applications happen, only for limited time periods, to do I/O
3833 * slowly enough to meet all the requirements described so far,
3834 * including the filtering in above item (a). These slow-speed
3835 * time intervals are usually interspersed between other time
3836 * intervals during which these applications do I/O at a very high
3837 * speed. Fortunately, exactly because of the high speed of the
3838 * I/O in the high-speed intervals, the values returned by this
3839 * function happen to be so high, near the end of any such
3840 * high-speed interval, to be likely to fall *after* the end of
3841 * the low-speed time interval that follows. These high values are
3842 * stored in bfqq->soft_rt_next_start after each invocation of
3843 * this function. As a consequence, if the last value of
3844 * bfqq->soft_rt_next_start is constantly used to lower-bound the
3845 * next value that this function may return, then, from the very
3846 * beginning of a low-speed interval, bfqq->soft_rt_next_start is
3847 * likely to be constantly kept so high that any I/O request
3848 * issued during the low-speed interval is considered as arriving
3849 * to soon for the application to be deemed as soft
3850 * real-time. Then, in the high-speed interval that follows, the
3851 * application will not be deemed as soft real-time, just because
3852 * it will do I/O at a high speed. And so on.
3853 *
3854 * Getting back to the filtering in item (a), in the following two
3855 * cases this filtering might be easily passed by a greedy
3856 * application, if the reference quantity was just
3857 * bfqd->bfq_slice_idle:
3858 * 1) HZ is so low that the duration of a jiffy is comparable to or
3859 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow
3860 * devices with HZ=100. The time granularity may be so coarse
3861 * that the approximation, in jiffies, of bfqd->bfq_slice_idle
3862 * is rather lower than the exact value.
77b7dcea
PV
3863 * 2) jiffies, instead of increasing at a constant rate, may stop increasing
3864 * for a while, then suddenly 'jump' by several units to recover the lost
3865 * increments. This seems to happen, e.g., inside virtual machines.
a34b0244
PV
3866 * To address this issue, in the filtering in (a) we do not use as a
3867 * reference time interval just bfqd->bfq_slice_idle, but
3868 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the
3869 * minimum number of jiffies for which the filter seems to be quite
3870 * precise also in embedded systems and KVM/QEMU virtual machines.
77b7dcea
PV
3871 */
3872static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd,
3873 struct bfq_queue *bfqq)
3874{
a34b0244
PV
3875 return max3(bfqq->soft_rt_next_start,
3876 bfqq->last_idle_bklogged +
3877 HZ * bfqq->service_from_backlogged /
3878 bfqd->bfq_wr_max_softrt_rate,
3879 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4);
77b7dcea
PV
3880}
3881
aee69d78
PV
3882/**
3883 * bfq_bfqq_expire - expire a queue.
3884 * @bfqd: device owning the queue.
3885 * @bfqq: the queue to expire.
3886 * @compensate: if true, compensate for the time spent idling.
3887 * @reason: the reason causing the expiration.
3888 *
c074170e
PV
3889 * If the process associated with bfqq does slow I/O (e.g., because it
3890 * issues random requests), we charge bfqq with the time it has been
3891 * in service instead of the service it has received (see
3892 * bfq_bfqq_charge_time for details on how this goal is achieved). As
3893 * a consequence, bfqq will typically get higher timestamps upon
3894 * reactivation, and hence it will be rescheduled as if it had
3895 * received more service than what it has actually received. In the
3896 * end, bfqq receives less service in proportion to how slowly its
3897 * associated process consumes its budgets (and hence how seriously it
3898 * tends to lower the throughput). In addition, this time-charging
3899 * strategy guarantees time fairness among slow processes. In
3900 * contrast, if the process associated with bfqq is not slow, we
3901 * charge bfqq exactly with the service it has received.
aee69d78 3902 *
c074170e
PV
3903 * Charging time to the first type of queues and the exact service to
3904 * the other has the effect of using the WF2Q+ policy to schedule the
3905 * former on a timeslice basis, without violating service domain
3906 * guarantees among the latter.
aee69d78 3907 */
ea25da48
PV
3908void bfq_bfqq_expire(struct bfq_data *bfqd,
3909 struct bfq_queue *bfqq,
3910 bool compensate,
3911 enum bfqq_expiration reason)
aee69d78
PV
3912{
3913 bool slow;
ab0e43e9
PV
3914 unsigned long delta = 0;
3915 struct bfq_entity *entity = &bfqq->entity;
aee69d78
PV
3916
3917 /*
ab0e43e9 3918 * Check whether the process is slow (see bfq_bfqq_is_slow).
aee69d78 3919 */
ab0e43e9 3920 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta);
aee69d78
PV
3921
3922 /*
c074170e
PV
3923 * As above explained, charge slow (typically seeky) and
3924 * timed-out queues with the time and not the service
3925 * received, to favor sequential workloads.
3926 *
3927 * Processes doing I/O in the slower disk zones will tend to
3928 * be slow(er) even if not seeky. Therefore, since the
3929 * estimated peak rate is actually an average over the disk
3930 * surface, these processes may timeout just for bad luck. To
3931 * avoid punishing them, do not charge time to processes that
3932 * succeeded in consuming at least 2/3 of their budget. This
3933 * allows BFQ to preserve enough elasticity to still perform
3934 * bandwidth, and not time, distribution with little unlucky
3935 * or quasi-sequential processes.
aee69d78 3936 */
44e44a1b
PV
3937 if (bfqq->wr_coeff == 1 &&
3938 (slow ||
3939 (reason == BFQQE_BUDGET_TIMEOUT &&
3940 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3)))
c074170e 3941 bfq_bfqq_charge_time(bfqd, bfqq, delta);
aee69d78
PV
3942
3943 if (reason == BFQQE_TOO_IDLE &&
ab0e43e9 3944 entity->service <= 2 * entity->budget / 10)
aee69d78
PV
3945 bfq_clear_bfqq_IO_bound(bfqq);
3946
44e44a1b
PV
3947 if (bfqd->low_latency && bfqq->wr_coeff == 1)
3948 bfqq->last_wr_start_finish = jiffies;
3949
77b7dcea
PV
3950 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 &&
3951 RB_EMPTY_ROOT(&bfqq->sort_list)) {
3952 /*
3953 * If we get here, and there are no outstanding
3954 * requests, then the request pattern is isochronous
3955 * (see the comments on the function
3956 * bfq_bfqq_softrt_next_start()). Thus we can compute
20cd3245
PV
3957 * soft_rt_next_start. And we do it, unless bfqq is in
3958 * interactive weight raising. We do not do it in the
3959 * latter subcase, for the following reason. bfqq may
3960 * be conveying the I/O needed to load a soft
3961 * real-time application. Such an application will
3962 * actually exhibit a soft real-time I/O pattern after
3963 * it finally starts doing its job. But, if
3964 * soft_rt_next_start is computed here for an
3965 * interactive bfqq, and bfqq had received a lot of
3966 * service before remaining with no outstanding
3967 * request (likely to happen on a fast device), then
3968 * soft_rt_next_start would be assigned such a high
3969 * value that, for a very long time, bfqq would be
3970 * prevented from being possibly considered as soft
3971 * real time.
3972 *
3973 * If, instead, the queue still has outstanding
3974 * requests, then we have to wait for the completion
3975 * of all the outstanding requests to discover whether
3976 * the request pattern is actually isochronous.
77b7dcea 3977 */
20cd3245
PV
3978 if (bfqq->dispatched == 0 &&
3979 bfqq->wr_coeff != bfqd->bfq_wr_coeff)
77b7dcea
PV
3980 bfqq->soft_rt_next_start =
3981 bfq_bfqq_softrt_next_start(bfqd, bfqq);
20cd3245 3982 else if (bfqq->dispatched > 0) {
77b7dcea
PV
3983 /*
3984 * Schedule an update of soft_rt_next_start to when
3985 * the task may be discovered to be isochronous.
3986 */
3987 bfq_mark_bfqq_softrt_update(bfqq);
3988 }
3989 }
3990
aee69d78 3991 bfq_log_bfqq(bfqd, bfqq,
d5be3fef
PV
3992 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason,
3993 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq));
aee69d78 3994
2341d662
PV
3995 /*
3996 * bfqq expired, so no total service time needs to be computed
3997 * any longer: reset state machine for measuring total service
3998 * times.
3999 */
4000 bfqd->rqs_injected = bfqd->wait_dispatch = false;
4001 bfqd->waited_rq = NULL;
4002
aee69d78
PV
4003 /*
4004 * Increase, decrease or leave budget unchanged according to
4005 * reason.
4006 */
4007 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason);
3726112e 4008 if (__bfq_bfqq_expire(bfqd, bfqq, reason))
eed47d19 4009 /* bfqq is gone, no more actions on it */
9fae8dd5
PV
4010 return;
4011
aee69d78 4012 /* mark bfqq as waiting a request only if a bic still points to it */
9fae8dd5 4013 if (!bfq_bfqq_busy(bfqq) &&
aee69d78 4014 reason != BFQQE_BUDGET_TIMEOUT &&
9fae8dd5 4015 reason != BFQQE_BUDGET_EXHAUSTED) {
aee69d78 4016 bfq_mark_bfqq_non_blocking_wait_rq(bfqq);
9fae8dd5
PV
4017 /*
4018 * Not setting service to 0, because, if the next rq
4019 * arrives in time, the queue will go on receiving
4020 * service with this same budget (as if it never expired)
4021 */
4022 } else
4023 entity->service = 0;
8a511ba5
PV
4024
4025 /*
4026 * Reset the received-service counter for every parent entity.
4027 * Differently from what happens with bfqq->entity.service,
4028 * the resetting of this counter never needs to be postponed
4029 * for parent entities. In fact, in case bfqq may have a
4030 * chance to go on being served using the last, partially
4031 * consumed budget, bfqq->entity.service needs to be kept,
4032 * because if bfqq then actually goes on being served using
4033 * the same budget, the last value of bfqq->entity.service is
4034 * needed to properly decrement bfqq->entity.budget by the
4035 * portion already consumed. In contrast, it is not necessary
4036 * to keep entity->service for parent entities too, because
4037 * the bubble up of the new value of bfqq->entity.budget will
4038 * make sure that the budgets of parent entities are correct,
4039 * even in case bfqq and thus parent entities go on receiving
4040 * service with the same budget.
4041 */
4042 entity = entity->parent;
4043 for_each_entity(entity)
4044 entity->service = 0;
aee69d78
PV
4045}
4046
4047/*
4048 * Budget timeout is not implemented through a dedicated timer, but
4049 * just checked on request arrivals and completions, as well as on
4050 * idle timer expirations.
4051 */
4052static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq)
4053{
44e44a1b 4054 return time_is_before_eq_jiffies(bfqq->budget_timeout);
aee69d78
PV
4055}
4056
4057/*
4058 * If we expire a queue that is actively waiting (i.e., with the
4059 * device idled) for the arrival of a new request, then we may incur
4060 * the timestamp misalignment problem described in the body of the
4061 * function __bfq_activate_entity. Hence we return true only if this
4062 * condition does not hold, or if the queue is slow enough to deserve
4063 * only to be kicked off for preserving a high throughput.
4064 */
4065static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
4066{
4067 bfq_log_bfqq(bfqq->bfqd, bfqq,
4068 "may_budget_timeout: wait_request %d left %d timeout %d",
4069 bfq_bfqq_wait_request(bfqq),
4070 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3,
4071 bfq_bfqq_budget_timeout(bfqq));
4072
4073 return (!bfq_bfqq_wait_request(bfqq) ||
4074 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3)
4075 &&
4076 bfq_bfqq_budget_timeout(bfqq);
4077}
4078
05c2f5c3
PV
4079static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd,
4080 struct bfq_queue *bfqq)
aee69d78 4081{
edaf9428
PV
4082 bool rot_without_queueing =
4083 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag,
4084 bfqq_sequential_and_IO_bound,
05c2f5c3 4085 idling_boosts_thr;
d5be3fef 4086
f718b093
PV
4087 /* No point in idling for bfqq if it won't get requests any longer */
4088 if (unlikely(!bfqq_process_refs(bfqq)))
4089 return false;
4090
edaf9428
PV
4091 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) &&
4092 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq);
4093
aee69d78 4094 /*
44e44a1b
PV
4095 * The next variable takes into account the cases where idling
4096 * boosts the throughput.
4097 *
e01eff01
PV
4098 * The value of the variable is computed considering, first, that
4099 * idling is virtually always beneficial for the throughput if:
edaf9428
PV
4100 * (a) the device is not NCQ-capable and rotational, or
4101 * (b) regardless of the presence of NCQ, the device is rotational and
4102 * the request pattern for bfqq is I/O-bound and sequential, or
4103 * (c) regardless of whether it is rotational, the device is
4104 * not NCQ-capable and the request pattern for bfqq is
4105 * I/O-bound and sequential.
bf2b79e7
PV
4106 *
4107 * Secondly, and in contrast to the above item (b), idling an
4108 * NCQ-capable flash-based device would not boost the
e01eff01 4109 * throughput even with sequential I/O; rather it would lower
bf2b79e7
PV
4110 * the throughput in proportion to how fast the device
4111 * is. Accordingly, the next variable is true if any of the
edaf9428
PV
4112 * above conditions (a), (b) or (c) is true, and, in
4113 * particular, happens to be false if bfqd is an NCQ-capable
4114 * flash-based device.
aee69d78 4115 */
edaf9428
PV
4116 idling_boosts_thr = rot_without_queueing ||
4117 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) &&
4118 bfqq_sequential_and_IO_bound);
aee69d78 4119
cfd69712 4120 /*
05c2f5c3 4121 * The return value of this function is equal to that of
cfd69712
PV
4122 * idling_boosts_thr, unless a special case holds. In this
4123 * special case, described below, idling may cause problems to
4124 * weight-raised queues.
4125 *
4126 * When the request pool is saturated (e.g., in the presence
4127 * of write hogs), if the processes associated with
4128 * non-weight-raised queues ask for requests at a lower rate,
4129 * then processes associated with weight-raised queues have a
4130 * higher probability to get a request from the pool
4131 * immediately (or at least soon) when they need one. Thus
4132 * they have a higher probability to actually get a fraction
4133 * of the device throughput proportional to their high
4134 * weight. This is especially true with NCQ-capable drives,
4135 * which enqueue several requests in advance, and further
4136 * reorder internally-queued requests.
4137 *
05c2f5c3
PV
4138 * For this reason, we force to false the return value if
4139 * there are weight-raised busy queues. In this case, and if
4140 * bfqq is not weight-raised, this guarantees that the device
4141 * is not idled for bfqq (if, instead, bfqq is weight-raised,
4142 * then idling will be guaranteed by another variable, see
4143 * below). Combined with the timestamping rules of BFQ (see
4144 * [1] for details), this behavior causes bfqq, and hence any
4145 * sync non-weight-raised queue, to get a lower number of
4146 * requests served, and thus to ask for a lower number of
4147 * requests from the request pool, before the busy
4148 * weight-raised queues get served again. This often mitigates
4149 * starvation problems in the presence of heavy write
4150 * workloads and NCQ, thereby guaranteeing a higher
4151 * application and system responsiveness in these hostile
4152 * scenarios.
4153 */
4154 return idling_boosts_thr &&
cfd69712 4155 bfqd->wr_busy_queues == 0;
05c2f5c3 4156}
cfd69712 4157
05c2f5c3
PV
4158/*
4159 * For a queue that becomes empty, device idling is allowed only if
4160 * this function returns true for that queue. As a consequence, since
4161 * device idling plays a critical role for both throughput boosting
4162 * and service guarantees, the return value of this function plays a
4163 * critical role as well.
4164 *
4165 * In a nutshell, this function returns true only if idling is
4166 * beneficial for throughput or, even if detrimental for throughput,
4167 * idling is however necessary to preserve service guarantees (low
4168 * latency, desired throughput distribution, ...). In particular, on
4169 * NCQ-capable devices, this function tries to return false, so as to
4170 * help keep the drives' internal queues full, whenever this helps the
4171 * device boost the throughput without causing any service-guarantee
4172 * issue.
4173 *
4174 * Most of the issues taken into account to get the return value of
4175 * this function are not trivial. We discuss these issues in the two
4176 * functions providing the main pieces of information needed by this
4177 * function.
4178 */
4179static bool bfq_better_to_idle(struct bfq_queue *bfqq)
4180{
4181 struct bfq_data *bfqd = bfqq->bfqd;
4182 bool idling_boosts_thr_with_no_issue, idling_needed_for_service_guar;
4183
f718b093
PV
4184 /* No point in idling for bfqq if it won't get requests any longer */
4185 if (unlikely(!bfqq_process_refs(bfqq)))
4186 return false;
4187
05c2f5c3
PV
4188 if (unlikely(bfqd->strict_guarantees))
4189 return true;
4190
4191 /*
4192 * Idling is performed only if slice_idle > 0. In addition, we
4193 * do not idle if
4194 * (a) bfqq is async
4195 * (b) bfqq is in the idle io prio class: in this case we do
4196 * not idle because we want to minimize the bandwidth that
4197 * queues in this class can steal to higher-priority queues
4198 */
4199 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) ||
4200 bfq_class_idle(bfqq))
4201 return false;
4202
4203 idling_boosts_thr_with_no_issue =
4204 idling_boosts_thr_without_issues(bfqd, bfqq);
4205
4206 idling_needed_for_service_guar =
4207 idling_needed_for_service_guarantees(bfqd, bfqq);
e1b2324d 4208
44e44a1b 4209 /*
05c2f5c3 4210 * We have now the two components we need to compute the
d5be3fef
PV
4211 * return value of the function, which is true only if idling
4212 * either boosts the throughput (without issues), or is
4213 * necessary to preserve service guarantees.
aee69d78 4214 */
05c2f5c3
PV
4215 return idling_boosts_thr_with_no_issue ||
4216 idling_needed_for_service_guar;
aee69d78
PV
4217}
4218
4219/*
277a4a9b 4220 * If the in-service queue is empty but the function bfq_better_to_idle
aee69d78
PV
4221 * returns true, then:
4222 * 1) the queue must remain in service and cannot be expired, and
4223 * 2) the device must be idled to wait for the possible arrival of a new
4224 * request for the queue.
277a4a9b 4225 * See the comments on the function bfq_better_to_idle for the reasons
aee69d78 4226 * why performing device idling is the best choice to boost the throughput
277a4a9b 4227 * and preserve service guarantees when bfq_better_to_idle itself
aee69d78
PV
4228 * returns true.
4229 */
4230static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq)
4231{
277a4a9b 4232 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_better_to_idle(bfqq);
aee69d78
PV
4233}
4234
2341d662
PV
4235/*
4236 * This function chooses the queue from which to pick the next extra
4237 * I/O request to inject, if it finds a compatible queue. See the
4238 * comments on bfq_update_inject_limit() for details on the injection
4239 * mechanism, and for the definitions of the quantities mentioned
4240 * below.
4241 */
4242static struct bfq_queue *
4243bfq_choose_bfqq_for_injection(struct bfq_data *bfqd)
d0edc247 4244{
2341d662
PV
4245 struct bfq_queue *bfqq, *in_serv_bfqq = bfqd->in_service_queue;
4246 unsigned int limit = in_serv_bfqq->inject_limit;
4247 /*
4248 * If
4249 * - bfqq is not weight-raised and therefore does not carry
4250 * time-critical I/O,
4251 * or
4252 * - regardless of whether bfqq is weight-raised, bfqq has
4253 * however a long think time, during which it can absorb the
4254 * effect of an appropriate number of extra I/O requests
4255 * from other queues (see bfq_update_inject_limit for
4256 * details on the computation of this number);
4257 * then injection can be performed without restrictions.
4258 */
4259 bool in_serv_always_inject = in_serv_bfqq->wr_coeff == 1 ||
4260 !bfq_bfqq_has_short_ttime(in_serv_bfqq);
d0edc247
PV
4261
4262 /*
2341d662
PV
4263 * If
4264 * - the baseline total service time could not be sampled yet,
4265 * so the inject limit happens to be still 0, and
4266 * - a lot of time has elapsed since the plugging of I/O
4267 * dispatching started, so drive speed is being wasted
4268 * significantly;
4269 * then temporarily raise inject limit to one request.
4270 */
4271 if (limit == 0 && in_serv_bfqq->last_serv_time_ns == 0 &&
4272 bfq_bfqq_wait_request(in_serv_bfqq) &&
4273 time_is_before_eq_jiffies(bfqd->last_idling_start_jiffies +
4274 bfqd->bfq_slice_idle)
4275 )
4276 limit = 1;
4277
4278 if (bfqd->rq_in_driver >= limit)
4279 return NULL;
4280
4281 /*
4282 * Linear search of the source queue for injection; but, with
4283 * a high probability, very few steps are needed to find a
4284 * candidate queue, i.e., a queue with enough budget left for
4285 * its next request. In fact:
d0edc247
PV
4286 * - BFQ dynamically updates the budget of every queue so as
4287 * to accommodate the expected backlog of the queue;
4288 * - if a queue gets all its requests dispatched as injected
4289 * service, then the queue is removed from the active list
2341d662
PV
4290 * (and re-added only if it gets new requests, but then it
4291 * is assigned again enough budget for its new backlog).
d0edc247
PV
4292 */
4293 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list)
4294 if (!RB_EMPTY_ROOT(&bfqq->sort_list) &&
2341d662 4295 (in_serv_always_inject || bfqq->wr_coeff > 1) &&
d0edc247 4296 bfq_serv_to_charge(bfqq->next_rq, bfqq) <=
2341d662
PV
4297 bfq_bfqq_budget_left(bfqq)) {
4298 /*
4299 * Allow for only one large in-flight request
4300 * on non-rotational devices, for the
4301 * following reason. On non-rotationl drives,
4302 * large requests take much longer than
4303 * smaller requests to be served. In addition,
4304 * the drive prefers to serve large requests
4305 * w.r.t. to small ones, if it can choose. So,
4306 * having more than one large requests queued
4307 * in the drive may easily make the next first
4308 * request of the in-service queue wait for so
4309 * long to break bfqq's service guarantees. On
4310 * the bright side, large requests let the
4311 * drive reach a very high throughput, even if
4312 * there is only one in-flight large request
4313 * at a time.
4314 */
4315 if (blk_queue_nonrot(bfqd->queue) &&
4316 blk_rq_sectors(bfqq->next_rq) >=
4317 BFQQ_SECT_THR_NONROT)
4318 limit = min_t(unsigned int, 1, limit);
4319 else
4320 limit = in_serv_bfqq->inject_limit;
4321
4322 if (bfqd->rq_in_driver < limit) {
4323 bfqd->rqs_injected = true;
4324 return bfqq;
4325 }
4326 }
d0edc247
PV
4327
4328 return NULL;
4329}
4330
aee69d78
PV
4331/*
4332 * Select a queue for service. If we have a current queue in service,
4333 * check whether to continue servicing it, or retrieve and set a new one.
4334 */
4335static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd)
4336{
4337 struct bfq_queue *bfqq;
4338 struct request *next_rq;
4339 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT;
4340
4341 bfqq = bfqd->in_service_queue;
4342 if (!bfqq)
4343 goto new_queue;
4344
4345 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue");
4346
4420b095
PV
4347 /*
4348 * Do not expire bfqq for budget timeout if bfqq may be about
4349 * to enjoy device idling. The reason why, in this case, we
4350 * prevent bfqq from expiring is the same as in the comments
4351 * on the case where bfq_bfqq_must_idle() returns true, in
4352 * bfq_completed_request().
4353 */
aee69d78 4354 if (bfq_may_expire_for_budg_timeout(bfqq) &&
aee69d78
PV
4355 !bfq_bfqq_must_idle(bfqq))
4356 goto expire;
4357
4358check_queue:
4359 /*
4360 * This loop is rarely executed more than once. Even when it
4361 * happens, it is much more convenient to re-execute this loop
4362 * than to return NULL and trigger a new dispatch to get a
4363 * request served.
4364 */
4365 next_rq = bfqq->next_rq;
4366 /*
4367 * If bfqq has requests queued and it has enough budget left to
4368 * serve them, keep the queue, otherwise expire it.
4369 */
4370 if (next_rq) {
4371 if (bfq_serv_to_charge(next_rq, bfqq) >
4372 bfq_bfqq_budget_left(bfqq)) {
4373 /*
4374 * Expire the queue for budget exhaustion,
4375 * which makes sure that the next budget is
4376 * enough to serve the next request, even if
4377 * it comes from the fifo expired path.
4378 */
4379 reason = BFQQE_BUDGET_EXHAUSTED;
4380 goto expire;
4381 } else {
4382 /*
4383 * The idle timer may be pending because we may
4384 * not disable disk idling even when a new request
4385 * arrives.
4386 */
4387 if (bfq_bfqq_wait_request(bfqq)) {
4388 /*
4389 * If we get here: 1) at least a new request
4390 * has arrived but we have not disabled the
4391 * timer because the request was too small,
4392 * 2) then the block layer has unplugged
4393 * the device, causing the dispatch to be
4394 * invoked.
4395 *
4396 * Since the device is unplugged, now the
4397 * requests are probably large enough to
4398 * provide a reasonable throughput.
4399 * So we disable idling.
4400 */
4401 bfq_clear_bfqq_wait_request(bfqq);
4402 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
4403 }
4404 goto keep_queue;
4405 }
4406 }
4407
4408 /*
4409 * No requests pending. However, if the in-service queue is idling
4410 * for a new request, or has requests waiting for a completion and
4411 * may idle after their completion, then keep it anyway.
d0edc247 4412 *
2341d662
PV
4413 * Yet, inject service from other queues if it boosts
4414 * throughput and is possible.
aee69d78
PV
4415 */
4416 if (bfq_bfqq_wait_request(bfqq) ||
277a4a9b 4417 (bfqq->dispatched != 0 && bfq_better_to_idle(bfqq))) {
2341d662
PV
4418 struct bfq_queue *async_bfqq =
4419 bfqq->bic && bfqq->bic->bfqq[0] &&
3726112e
PV
4420 bfq_bfqq_busy(bfqq->bic->bfqq[0]) &&
4421 bfqq->bic->bfqq[0]->next_rq ?
2341d662
PV
4422 bfqq->bic->bfqq[0] : NULL;
4423
4424 /*
13a857a4
PV
4425 * The next three mutually-exclusive ifs decide
4426 * whether to try injection, and choose the queue to
4427 * pick an I/O request from.
4428 *
4429 * The first if checks whether the process associated
4430 * with bfqq has also async I/O pending. If so, it
4431 * injects such I/O unconditionally. Injecting async
4432 * I/O from the same process can cause no harm to the
4433 * process. On the contrary, it can only increase
4434 * bandwidth and reduce latency for the process.
4435 *
4436 * The second if checks whether there happens to be a
4437 * non-empty waker queue for bfqq, i.e., a queue whose
4438 * I/O needs to be completed for bfqq to receive new
4439 * I/O. This happens, e.g., if bfqq is associated with
4440 * a process that does some sync. A sync generates
4441 * extra blocking I/O, which must be completed before
4442 * the process associated with bfqq can go on with its
4443 * I/O. If the I/O of the waker queue is not served,
4444 * then bfqq remains empty, and no I/O is dispatched,
4445 * until the idle timeout fires for bfqq. This is
4446 * likely to result in lower bandwidth and higher
4447 * latencies for bfqq, and in a severe loss of total
4448 * throughput. The best action to take is therefore to
4449 * serve the waker queue as soon as possible. So do it
4450 * (without relying on the third alternative below for
4451 * eventually serving waker_bfqq's I/O; see the last
4452 * paragraph for further details). This systematic
4453 * injection of I/O from the waker queue does not
4454 * cause any delay to bfqq's I/O. On the contrary,
4455 * next bfqq's I/O is brought forward dramatically,
4456 * for it is not blocked for milliseconds.
4457 *
4458 * The third if checks whether bfqq is a queue for
4459 * which it is better to avoid injection. It is so if
4460 * bfqq delivers more throughput when served without
4461 * any further I/O from other queues in the middle, or
4462 * if the service times of bfqq's I/O requests both
4463 * count more than overall throughput, and may be
4464 * easily increased by injection (this happens if bfqq
4465 * has a short think time). If none of these
4466 * conditions holds, then a candidate queue for
4467 * injection is looked for through
4468 * bfq_choose_bfqq_for_injection(). Note that the
4469 * latter may return NULL (for example if the inject
4470 * limit for bfqq is currently 0).
4471 *
4472 * NOTE: motivation for the second alternative
4473 *
4474 * Thanks to the way the inject limit is updated in
4475 * bfq_update_has_short_ttime(), it is rather likely
4476 * that, if I/O is being plugged for bfqq and the
4477 * waker queue has pending I/O requests that are
4478 * blocking bfqq's I/O, then the third alternative
4479 * above lets the waker queue get served before the
4480 * I/O-plugging timeout fires. So one may deem the
4481 * second alternative superfluous. It is not, because
4482 * the third alternative may be way less effective in
4483 * case of a synchronization. For two main
4484 * reasons. First, throughput may be low because the
4485 * inject limit may be too low to guarantee the same
4486 * amount of injected I/O, from the waker queue or
4487 * other queues, that the second alternative
4488 * guarantees (the second alternative unconditionally
4489 * injects a pending I/O request of the waker queue
4490 * for each bfq_dispatch_request()). Second, with the
4491 * third alternative, the duration of the plugging,
4492 * i.e., the time before bfqq finally receives new I/O,
4493 * may not be minimized, because the waker queue may
4494 * happen to be served only after other queues.
2341d662
PV
4495 */
4496 if (async_bfqq &&
4497 icq_to_bic(async_bfqq->next_rq->elv.icq) == bfqq->bic &&
4498 bfq_serv_to_charge(async_bfqq->next_rq, async_bfqq) <=
4499 bfq_bfqq_budget_left(async_bfqq))
4500 bfqq = bfqq->bic->bfqq[0];
13a857a4
PV
4501 else if (bfq_bfqq_has_waker(bfqq) &&
4502 bfq_bfqq_busy(bfqq->waker_bfqq) &&
3726112e 4503 bfqq->next_rq &&
13a857a4
PV
4504 bfq_serv_to_charge(bfqq->waker_bfqq->next_rq,
4505 bfqq->waker_bfqq) <=
4506 bfq_bfqq_budget_left(bfqq->waker_bfqq)
4507 )
4508 bfqq = bfqq->waker_bfqq;
2341d662
PV
4509 else if (!idling_boosts_thr_without_issues(bfqd, bfqq) &&
4510 (bfqq->wr_coeff == 1 || bfqd->wr_busy_queues > 1 ||
4511 !bfq_bfqq_has_short_ttime(bfqq)))
d0edc247
PV
4512 bfqq = bfq_choose_bfqq_for_injection(bfqd);
4513 else
4514 bfqq = NULL;
4515
aee69d78
PV
4516 goto keep_queue;
4517 }
4518
4519 reason = BFQQE_NO_MORE_REQUESTS;
4520expire:
4521 bfq_bfqq_expire(bfqd, bfqq, false, reason);
4522new_queue:
4523 bfqq = bfq_set_in_service_queue(bfqd);
4524 if (bfqq) {
4525 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue");
4526 goto check_queue;
4527 }
4528keep_queue:
4529 if (bfqq)
4530 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue");
4531 else
4532 bfq_log(bfqd, "select_queue: no queue returned");
4533
4534 return bfqq;
4535}
4536
44e44a1b
PV
4537static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4538{
4539 struct bfq_entity *entity = &bfqq->entity;
4540
4541 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */
4542 bfq_log_bfqq(bfqd, bfqq,
4543 "raising period dur %u/%u msec, old coeff %u, w %d(%d)",
4544 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish),
4545 jiffies_to_msecs(bfqq->wr_cur_max_time),
4546 bfqq->wr_coeff,
4547 bfqq->entity.weight, bfqq->entity.orig_weight);
4548
4549 if (entity->prio_changed)
4550 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change");
4551
4552 /*
e1b2324d
AA
4553 * If the queue was activated in a burst, or too much
4554 * time has elapsed from the beginning of this
4555 * weight-raising period, then end weight raising.
44e44a1b 4556 */
e1b2324d
AA
4557 if (bfq_bfqq_in_large_burst(bfqq))
4558 bfq_bfqq_end_wr(bfqq);
4559 else if (time_is_before_jiffies(bfqq->last_wr_start_finish +
4560 bfqq->wr_cur_max_time)) {
77b7dcea
PV
4561 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time ||
4562 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt +
e1b2324d 4563 bfq_wr_duration(bfqd)))
77b7dcea
PV
4564 bfq_bfqq_end_wr(bfqq);
4565 else {
3e2bdd6d 4566 switch_back_to_interactive_wr(bfqq, bfqd);
77b7dcea
PV
4567 bfqq->entity.prio_changed = 1;
4568 }
44e44a1b 4569 }
8a8747dc
PV
4570 if (bfqq->wr_coeff > 1 &&
4571 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time &&
4572 bfqq->service_from_wr > max_service_from_wr) {
4573 /* see comments on max_service_from_wr */
4574 bfq_bfqq_end_wr(bfqq);
4575 }
44e44a1b 4576 }
431b17f9
PV
4577 /*
4578 * To improve latency (for this or other queues), immediately
4579 * update weight both if it must be raised and if it must be
4580 * lowered. Since, entity may be on some active tree here, and
4581 * might have a pending change of its ioprio class, invoke
4582 * next function with the last parameter unset (see the
4583 * comments on the function).
4584 */
44e44a1b 4585 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1))
431b17f9
PV
4586 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity),
4587 entity, false);
44e44a1b
PV
4588}
4589
aee69d78
PV
4590/*
4591 * Dispatch next request from bfqq.
4592 */
4593static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd,
4594 struct bfq_queue *bfqq)
4595{
4596 struct request *rq = bfqq->next_rq;
4597 unsigned long service_to_charge;
4598
4599 service_to_charge = bfq_serv_to_charge(rq, bfqq);
4600
4601 bfq_bfqq_served(bfqq, service_to_charge);
4602
2341d662
PV
4603 if (bfqq == bfqd->in_service_queue && bfqd->wait_dispatch) {
4604 bfqd->wait_dispatch = false;
4605 bfqd->waited_rq = rq;
4606 }
aee69d78 4607
2341d662 4608 bfq_dispatch_remove(bfqd->queue, rq);
d0edc247 4609
2341d662 4610 if (bfqq != bfqd->in_service_queue)
d0edc247 4611 goto return_rq;
d0edc247 4612
44e44a1b
PV
4613 /*
4614 * If weight raising has to terminate for bfqq, then next
4615 * function causes an immediate update of bfqq's weight,
4616 * without waiting for next activation. As a consequence, on
4617 * expiration, bfqq will be timestamped as if has never been
4618 * weight-raised during this service slot, even if it has
4619 * received part or even most of the service as a
4620 * weight-raised queue. This inflates bfqq's timestamps, which
4621 * is beneficial, as bfqq is then more willing to leave the
4622 * device immediately to possible other weight-raised queues.
4623 */
4624 bfq_update_wr_data(bfqd, bfqq);
4625
aee69d78
PV
4626 /*
4627 * Expire bfqq, pretending that its budget expired, if bfqq
4628 * belongs to CLASS_IDLE and other queues are waiting for
4629 * service.
4630 */
73d58118 4631 if (!(bfq_tot_busy_queues(bfqd) > 1 && bfq_class_idle(bfqq)))
d0edc247 4632 goto return_rq;
aee69d78 4633
aee69d78 4634 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED);
d0edc247
PV
4635
4636return_rq:
aee69d78
PV
4637 return rq;
4638}
4639
4640static bool bfq_has_work(struct blk_mq_hw_ctx *hctx)
4641{
4642 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4643
4644 /*
4645 * Avoiding lock: a race on bfqd->busy_queues should cause at
4646 * most a call to dispatch for nothing
4647 */
4648 return !list_empty_careful(&bfqd->dispatch) ||
73d58118 4649 bfq_tot_busy_queues(bfqd) > 0;
aee69d78
PV
4650}
4651
4652static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
4653{
4654 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4655 struct request *rq = NULL;
4656 struct bfq_queue *bfqq = NULL;
4657
4658 if (!list_empty(&bfqd->dispatch)) {
4659 rq = list_first_entry(&bfqd->dispatch, struct request,
4660 queuelist);
4661 list_del_init(&rq->queuelist);
4662
4663 bfqq = RQ_BFQQ(rq);
4664
4665 if (bfqq) {
4666 /*
4667 * Increment counters here, because this
4668 * dispatch does not follow the standard
4669 * dispatch flow (where counters are
4670 * incremented)
4671 */
4672 bfqq->dispatched++;
4673
4674 goto inc_in_driver_start_rq;
4675 }
4676
4677 /*
a7877390
PV
4678 * We exploit the bfq_finish_requeue_request hook to
4679 * decrement rq_in_driver, but
4680 * bfq_finish_requeue_request will not be invoked on
4681 * this request. So, to avoid unbalance, just start
4682 * this request, without incrementing rq_in_driver. As
4683 * a negative consequence, rq_in_driver is deceptively
4684 * lower than it should be while this request is in
4685 * service. This may cause bfq_schedule_dispatch to be
4686 * invoked uselessly.
aee69d78
PV
4687 *
4688 * As for implementing an exact solution, the
a7877390
PV
4689 * bfq_finish_requeue_request hook, if defined, is
4690 * probably invoked also on this request. So, by
4691 * exploiting this hook, we could 1) increment
4692 * rq_in_driver here, and 2) decrement it in
4693 * bfq_finish_requeue_request. Such a solution would
4694 * let the value of the counter be always accurate,
4695 * but it would entail using an extra interface
4696 * function. This cost seems higher than the benefit,
4697 * being the frequency of non-elevator-private
aee69d78
PV
4698 * requests very low.
4699 */
4700 goto start_rq;
4701 }
4702
73d58118
PV
4703 bfq_log(bfqd, "dispatch requests: %d busy queues",
4704 bfq_tot_busy_queues(bfqd));
aee69d78 4705
73d58118 4706 if (bfq_tot_busy_queues(bfqd) == 0)
aee69d78
PV
4707 goto exit;
4708
4709 /*
4710 * Force device to serve one request at a time if
4711 * strict_guarantees is true. Forcing this service scheme is
4712 * currently the ONLY way to guarantee that the request
4713 * service order enforced by the scheduler is respected by a
4714 * queueing device. Otherwise the device is free even to make
4715 * some unlucky request wait for as long as the device
4716 * wishes.
4717 *
4718 * Of course, serving one request at at time may cause loss of
4719 * throughput.
4720 */
4721 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0)
4722 goto exit;
4723
4724 bfqq = bfq_select_queue(bfqd);
4725 if (!bfqq)
4726 goto exit;
4727
4728 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq);
4729
4730 if (rq) {
4731inc_in_driver_start_rq:
4732 bfqd->rq_in_driver++;
4733start_rq:
4734 rq->rq_flags |= RQF_STARTED;
4735 }
4736exit:
4737 return rq;
4738}
4739
8060c47b 4740#ifdef CONFIG_BFQ_CGROUP_DEBUG
9b25bd03
PV
4741static void bfq_update_dispatch_stats(struct request_queue *q,
4742 struct request *rq,
4743 struct bfq_queue *in_serv_queue,
4744 bool idle_timer_disabled)
4745{
4746 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL;
aee69d78 4747
24bfd19b 4748 if (!idle_timer_disabled && !bfqq)
9b25bd03 4749 return;
24bfd19b
PV
4750
4751 /*
4752 * rq and bfqq are guaranteed to exist until this function
4753 * ends, for the following reasons. First, rq can be
4754 * dispatched to the device, and then can be completed and
4755 * freed, only after this function ends. Second, rq cannot be
4756 * merged (and thus freed because of a merge) any longer,
4757 * because it has already started. Thus rq cannot be freed
4758 * before this function ends, and, since rq has a reference to
4759 * bfqq, the same guarantee holds for bfqq too.
4760 *
4761 * In addition, the following queue lock guarantees that
4762 * bfqq_group(bfqq) exists as well.
4763 */
0d945c1f 4764 spin_lock_irq(&q->queue_lock);
24bfd19b
PV
4765 if (idle_timer_disabled)
4766 /*
4767 * Since the idle timer has been disabled,
4768 * in_serv_queue contained some request when
4769 * __bfq_dispatch_request was invoked above, which
4770 * implies that rq was picked exactly from
4771 * in_serv_queue. Thus in_serv_queue == bfqq, and is
4772 * therefore guaranteed to exist because of the above
4773 * arguments.
4774 */
4775 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue));
4776 if (bfqq) {
4777 struct bfq_group *bfqg = bfqq_group(bfqq);
4778
4779 bfqg_stats_update_avg_queue_size(bfqg);
4780 bfqg_stats_set_start_empty_time(bfqg);
4781 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags);
4782 }
0d945c1f 4783 spin_unlock_irq(&q->queue_lock);
9b25bd03
PV
4784}
4785#else
4786static inline void bfq_update_dispatch_stats(struct request_queue *q,
4787 struct request *rq,
4788 struct bfq_queue *in_serv_queue,
4789 bool idle_timer_disabled) {}
8060c47b 4790#endif /* CONFIG_BFQ_CGROUP_DEBUG */
24bfd19b 4791
9b25bd03
PV
4792static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx)
4793{
4794 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
4795 struct request *rq;
4796 struct bfq_queue *in_serv_queue;
4797 bool waiting_rq, idle_timer_disabled;
4798
4799 spin_lock_irq(&bfqd->lock);
4800
4801 in_serv_queue = bfqd->in_service_queue;
4802 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue);
4803
4804 rq = __bfq_dispatch_request(hctx);
4805
4806 idle_timer_disabled =
4807 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue);
4808
4809 spin_unlock_irq(&bfqd->lock);
4810
4811 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue,
4812 idle_timer_disabled);
4813
aee69d78
PV
4814 return rq;
4815}
4816
4817/*
4818 * Task holds one reference to the queue, dropped when task exits. Each rq
4819 * in-flight on this queue also holds a reference, dropped when rq is freed.
4820 *
4821 * Scheduler lock must be held here. Recall not to use bfqq after calling
4822 * this function on it.
4823 */
ea25da48 4824void bfq_put_queue(struct bfq_queue *bfqq)
aee69d78 4825{
3f758e84
PV
4826 struct bfq_queue *item;
4827 struct hlist_node *n;
e21b7a0b 4828 struct bfq_group *bfqg = bfqq_group(bfqq);
e21b7a0b 4829
aee69d78
PV
4830 if (bfqq->bfqd)
4831 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d",
4832 bfqq, bfqq->ref);
4833
4834 bfqq->ref--;
4835 if (bfqq->ref)
4836 return;
4837
99fead8d 4838 if (!hlist_unhashed(&bfqq->burst_list_node)) {
e1b2324d 4839 hlist_del_init(&bfqq->burst_list_node);
99fead8d
PV
4840 /*
4841 * Decrement also burst size after the removal, if the
4842 * process associated with bfqq is exiting, and thus
4843 * does not contribute to the burst any longer. This
4844 * decrement helps filter out false positives of large
4845 * bursts, when some short-lived process (often due to
4846 * the execution of commands by some service) happens
4847 * to start and exit while a complex application is
4848 * starting, and thus spawning several processes that
4849 * do I/O (and that *must not* be treated as a large
4850 * burst, see comments on bfq_handle_burst).
4851 *
4852 * In particular, the decrement is performed only if:
4853 * 1) bfqq is not a merged queue, because, if it is,
4854 * then this free of bfqq is not triggered by the exit
4855 * of the process bfqq is associated with, but exactly
4856 * by the fact that bfqq has just been merged.
4857 * 2) burst_size is greater than 0, to handle
4858 * unbalanced decrements. Unbalanced decrements may
4859 * happen in te following case: bfqq is inserted into
4860 * the current burst list--without incrementing
4861 * bust_size--because of a split, but the current
4862 * burst list is not the burst list bfqq belonged to
4863 * (see comments on the case of a split in
4864 * bfq_set_request).
4865 */
4866 if (bfqq->bic && bfqq->bfqd->burst_size > 0)
4867 bfqq->bfqd->burst_size--;
7cb04004 4868 }
e21b7a0b 4869
3f758e84
PV
4870 /*
4871 * bfqq does not exist any longer, so it cannot be woken by
4872 * any other queue, and cannot wake any other queue. Then bfqq
4873 * must be removed from the woken list of its possible waker
4874 * queue, and all queues in the woken list of bfqq must stop
4875 * having a waker queue. Strictly speaking, these updates
4876 * should be performed when bfqq remains with no I/O source
4877 * attached to it, which happens before bfqq gets freed. In
4878 * particular, this happens when the last process associated
4879 * with bfqq exits or gets associated with a different
4880 * queue. However, both events lead to bfqq being freed soon,
4881 * and dangling references would come out only after bfqq gets
4882 * freed. So these updates are done here, as a simple and safe
4883 * way to handle all cases.
4884 */
4885 /* remove bfqq from woken list */
4886 if (!hlist_unhashed(&bfqq->woken_list_node))
4887 hlist_del_init(&bfqq->woken_list_node);
4888
4889 /* reset waker for all queues in woken list */
4890 hlist_for_each_entry_safe(item, n, &bfqq->woken_list,
4891 woken_list_node) {
4892 item->waker_bfqq = NULL;
4893 bfq_clear_bfqq_has_waker(item);
4894 hlist_del_init(&item->woken_list_node);
4895 }
4896
08d383a7
PV
4897 if (bfqq->bfqd && bfqq->bfqd->last_completed_rq_bfqq == bfqq)
4898 bfqq->bfqd->last_completed_rq_bfqq = NULL;
4899
aee69d78 4900 kmem_cache_free(bfq_pool, bfqq);
8f9bebc3 4901 bfqg_and_blkg_put(bfqg);
aee69d78
PV
4902}
4903
36eca894
AA
4904static void bfq_put_cooperator(struct bfq_queue *bfqq)
4905{
4906 struct bfq_queue *__bfqq, *next;
4907
4908 /*
4909 * If this queue was scheduled to merge with another queue, be
4910 * sure to drop the reference taken on that queue (and others in
4911 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs.
4912 */
4913 __bfqq = bfqq->new_bfqq;
4914 while (__bfqq) {
4915 if (__bfqq == bfqq)
4916 break;
4917 next = __bfqq->new_bfqq;
4918 bfq_put_queue(__bfqq);
4919 __bfqq = next;
4920 }
4921}
4922
aee69d78
PV
4923static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
4924{
4925 if (bfqq == bfqd->in_service_queue) {
3726112e 4926 __bfq_bfqq_expire(bfqd, bfqq, BFQQE_BUDGET_TIMEOUT);
aee69d78
PV
4927 bfq_schedule_dispatch(bfqd);
4928 }
4929
4930 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref);
4931
36eca894
AA
4932 bfq_put_cooperator(bfqq);
4933
478de338 4934 bfq_release_process_ref(bfqd, bfqq);
aee69d78
PV
4935}
4936
4937static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync)
4938{
4939 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
4940 struct bfq_data *bfqd;
4941
4942 if (bfqq)
4943 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */
4944
4945 if (bfqq && bfqd) {
4946 unsigned long flags;
4947
4948 spin_lock_irqsave(&bfqd->lock, flags);
dbc3117d 4949 bfqq->bic = NULL;
aee69d78
PV
4950 bfq_exit_bfqq(bfqd, bfqq);
4951 bic_set_bfqq(bic, NULL, is_sync);
6fa3e8d3 4952 spin_unlock_irqrestore(&bfqd->lock, flags);
aee69d78
PV
4953 }
4954}
4955
4956static void bfq_exit_icq(struct io_cq *icq)
4957{
4958 struct bfq_io_cq *bic = icq_to_bic(icq);
4959
4960 bfq_exit_icq_bfqq(bic, true);
4961 bfq_exit_icq_bfqq(bic, false);
4962}
4963
4964/*
4965 * Update the entity prio values; note that the new values will not
4966 * be used until the next (re)activation.
4967 */
4968static void
4969bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic)
4970{
4971 struct task_struct *tsk = current;
4972 int ioprio_class;
4973 struct bfq_data *bfqd = bfqq->bfqd;
4974
4975 if (!bfqd)
4976 return;
4977
4978 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
4979 switch (ioprio_class) {
4980 default:
4981 dev_err(bfqq->bfqd->queue->backing_dev_info->dev,
4982 "bfq: bad prio class %d\n", ioprio_class);
fa393d1b 4983 /* fall through */
aee69d78
PV
4984 case IOPRIO_CLASS_NONE:
4985 /*
4986 * No prio set, inherit CPU scheduling settings.
4987 */
4988 bfqq->new_ioprio = task_nice_ioprio(tsk);
4989 bfqq->new_ioprio_class = task_nice_ioclass(tsk);
4990 break;
4991 case IOPRIO_CLASS_RT:
4992 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4993 bfqq->new_ioprio_class = IOPRIO_CLASS_RT;
4994 break;
4995 case IOPRIO_CLASS_BE:
4996 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
4997 bfqq->new_ioprio_class = IOPRIO_CLASS_BE;
4998 break;
4999 case IOPRIO_CLASS_IDLE:
5000 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE;
5001 bfqq->new_ioprio = 7;
aee69d78
PV
5002 break;
5003 }
5004
5005 if (bfqq->new_ioprio >= IOPRIO_BE_NR) {
5006 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n",
5007 bfqq->new_ioprio);
5008 bfqq->new_ioprio = IOPRIO_BE_NR;
5009 }
5010
5011 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio);
5012 bfqq->entity.prio_changed = 1;
5013}
5014
ea25da48
PV
5015static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
5016 struct bio *bio, bool is_sync,
5017 struct bfq_io_cq *bic);
5018
aee69d78
PV
5019static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio)
5020{
5021 struct bfq_data *bfqd = bic_to_bfqd(bic);
5022 struct bfq_queue *bfqq;
5023 int ioprio = bic->icq.ioc->ioprio;
5024
5025 /*
5026 * This condition may trigger on a newly created bic, be sure to
5027 * drop the lock before returning.
5028 */
5029 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio))
5030 return;
5031
5032 bic->ioprio = ioprio;
5033
5034 bfqq = bic_to_bfqq(bic, false);
5035 if (bfqq) {
478de338 5036 bfq_release_process_ref(bfqd, bfqq);
aee69d78
PV
5037 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic);
5038 bic_set_bfqq(bic, bfqq, false);
5039 }
5040
5041 bfqq = bic_to_bfqq(bic, true);
5042 if (bfqq)
5043 bfq_set_next_ioprio_data(bfqq, bic);
5044}
5045
5046static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
5047 struct bfq_io_cq *bic, pid_t pid, int is_sync)
5048{
5049 RB_CLEAR_NODE(&bfqq->entity.rb_node);
5050 INIT_LIST_HEAD(&bfqq->fifo);
e1b2324d 5051 INIT_HLIST_NODE(&bfqq->burst_list_node);
13a857a4
PV
5052 INIT_HLIST_NODE(&bfqq->woken_list_node);
5053 INIT_HLIST_HEAD(&bfqq->woken_list);
aee69d78
PV
5054
5055 bfqq->ref = 0;
5056 bfqq->bfqd = bfqd;
5057
5058 if (bic)
5059 bfq_set_next_ioprio_data(bfqq, bic);
5060
5061 if (is_sync) {
d5be3fef
PV
5062 /*
5063 * No need to mark as has_short_ttime if in
5064 * idle_class, because no device idling is performed
5065 * for queues in idle class
5066 */
aee69d78 5067 if (!bfq_class_idle(bfqq))
d5be3fef
PV
5068 /* tentatively mark as has_short_ttime */
5069 bfq_mark_bfqq_has_short_ttime(bfqq);
aee69d78 5070 bfq_mark_bfqq_sync(bfqq);
e1b2324d 5071 bfq_mark_bfqq_just_created(bfqq);
aee69d78
PV
5072 } else
5073 bfq_clear_bfqq_sync(bfqq);
5074
5075 /* set end request to minus infinity from now */
5076 bfqq->ttime.last_end_request = ktime_get_ns() + 1;
5077
5078 bfq_mark_bfqq_IO_bound(bfqq);
5079
5080 bfqq->pid = pid;
5081
5082 /* Tentative initial value to trade off between thr and lat */
54b60456 5083 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3;
aee69d78 5084 bfqq->budget_timeout = bfq_smallest_from_now();
aee69d78 5085
44e44a1b 5086 bfqq->wr_coeff = 1;
36eca894 5087 bfqq->last_wr_start_finish = jiffies;
77b7dcea 5088 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now();
36eca894 5089 bfqq->split_time = bfq_smallest_from_now();
77b7dcea
PV
5090
5091 /*
a34b0244
PV
5092 * To not forget the possibly high bandwidth consumed by a
5093 * process/queue in the recent past,
5094 * bfq_bfqq_softrt_next_start() returns a value at least equal
5095 * to the current value of bfqq->soft_rt_next_start (see
5096 * comments on bfq_bfqq_softrt_next_start). Set
5097 * soft_rt_next_start to now, to mean that bfqq has consumed
5098 * no bandwidth so far.
77b7dcea 5099 */
a34b0244 5100 bfqq->soft_rt_next_start = jiffies;
44e44a1b 5101
aee69d78
PV
5102 /* first request is almost certainly seeky */
5103 bfqq->seek_history = 1;
5104}
5105
5106static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd,
e21b7a0b 5107 struct bfq_group *bfqg,
aee69d78
PV
5108 int ioprio_class, int ioprio)
5109{
5110 switch (ioprio_class) {
5111 case IOPRIO_CLASS_RT:
e21b7a0b 5112 return &bfqg->async_bfqq[0][ioprio];
aee69d78
PV
5113 case IOPRIO_CLASS_NONE:
5114 ioprio = IOPRIO_NORM;
5115 /* fall through */
5116 case IOPRIO_CLASS_BE:
e21b7a0b 5117 return &bfqg->async_bfqq[1][ioprio];
aee69d78 5118 case IOPRIO_CLASS_IDLE:
e21b7a0b 5119 return &bfqg->async_idle_bfqq;
aee69d78
PV
5120 default:
5121 return NULL;
5122 }
5123}
5124
5125static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd,
5126 struct bio *bio, bool is_sync,
5127 struct bfq_io_cq *bic)
5128{
5129 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio);
5130 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio);
5131 struct bfq_queue **async_bfqq = NULL;
5132 struct bfq_queue *bfqq;
e21b7a0b 5133 struct bfq_group *bfqg;
aee69d78
PV
5134
5135 rcu_read_lock();
5136
0fe061b9 5137 bfqg = bfq_find_set_group(bfqd, __bio_blkcg(bio));
e21b7a0b
AA
5138 if (!bfqg) {
5139 bfqq = &bfqd->oom_bfqq;
5140 goto out;
5141 }
5142
aee69d78 5143 if (!is_sync) {
e21b7a0b 5144 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class,
aee69d78
PV
5145 ioprio);
5146 bfqq = *async_bfqq;
5147 if (bfqq)
5148 goto out;
5149 }
5150
5151 bfqq = kmem_cache_alloc_node(bfq_pool,
5152 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
5153 bfqd->queue->node);
5154
5155 if (bfqq) {
5156 bfq_init_bfqq(bfqd, bfqq, bic, current->pid,
5157 is_sync);
e21b7a0b 5158 bfq_init_entity(&bfqq->entity, bfqg);
aee69d78
PV
5159 bfq_log_bfqq(bfqd, bfqq, "allocated");
5160 } else {
5161 bfqq = &bfqd->oom_bfqq;
5162 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq");
5163 goto out;
5164 }
5165
5166 /*
5167 * Pin the queue now that it's allocated, scheduler exit will
5168 * prune it.
5169 */
5170 if (async_bfqq) {
e21b7a0b
AA
5171 bfqq->ref++; /*
5172 * Extra group reference, w.r.t. sync
5173 * queue. This extra reference is removed
5174 * only if bfqq->bfqg disappears, to
5175 * guarantee that this queue is not freed
5176 * until its group goes away.
5177 */
5178 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d",
aee69d78
PV
5179 bfqq, bfqq->ref);
5180 *async_bfqq = bfqq;
5181 }
5182
5183out:
5184 bfqq->ref++; /* get a process reference to this queue */
5185 bfq_log_bfqq(bfqd, bfqq, "get_queue, at end: %p, %d", bfqq, bfqq->ref);
5186 rcu_read_unlock();
5187 return bfqq;
5188}
5189
5190static void bfq_update_io_thinktime(struct bfq_data *bfqd,
5191 struct bfq_queue *bfqq)
5192{
5193 struct bfq_ttime *ttime = &bfqq->ttime;
5194 u64 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request;
5195
5196 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle);
5197
5198 ttime->ttime_samples = (7*bfqq->ttime.ttime_samples + 256) / 8;
5199 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
5200 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
5201 ttime->ttime_samples);
5202}
5203
5204static void
5205bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq,
5206 struct request *rq)
5207{
aee69d78 5208 bfqq->seek_history <<= 1;
d87447d8 5209 bfqq->seek_history |= BFQ_RQ_SEEKY(bfqd, bfqq->last_request_pos, rq);
7074f076
PV
5210
5211 if (bfqq->wr_coeff > 1 &&
5212 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time &&
5213 BFQQ_TOTALLY_SEEKY(bfqq))
5214 bfq_bfqq_end_wr(bfqq);
aee69d78
PV
5215}
5216
d5be3fef
PV
5217static void bfq_update_has_short_ttime(struct bfq_data *bfqd,
5218 struct bfq_queue *bfqq,
5219 struct bfq_io_cq *bic)
aee69d78 5220{
766d6141 5221 bool has_short_ttime = true, state_changed;
aee69d78 5222
d5be3fef
PV
5223 /*
5224 * No need to update has_short_ttime if bfqq is async or in
5225 * idle io prio class, or if bfq_slice_idle is zero, because
5226 * no device idling is performed for bfqq in this case.
5227 */
5228 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) ||
5229 bfqd->bfq_slice_idle == 0)
aee69d78
PV
5230 return;
5231
36eca894
AA
5232 /* Idle window just restored, statistics are meaningless. */
5233 if (time_is_after_eq_jiffies(bfqq->split_time +
5234 bfqd->bfq_wr_min_idle_time))
5235 return;
5236
d5be3fef
PV
5237 /* Think time is infinite if no process is linked to
5238 * bfqq. Otherwise check average think time to
5239 * decide whether to mark as has_short_ttime
5240 */
aee69d78 5241 if (atomic_read(&bic->icq.ioc->active_ref) == 0 ||
d5be3fef
PV
5242 (bfq_sample_valid(bfqq->ttime.ttime_samples) &&
5243 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle))
5244 has_short_ttime = false;
5245
766d6141 5246 state_changed = has_short_ttime != bfq_bfqq_has_short_ttime(bfqq);
aee69d78 5247
d5be3fef
PV
5248 if (has_short_ttime)
5249 bfq_mark_bfqq_has_short_ttime(bfqq);
aee69d78 5250 else
d5be3fef 5251 bfq_clear_bfqq_has_short_ttime(bfqq);
766d6141
PV
5252
5253 /*
5254 * Until the base value for the total service time gets
5255 * finally computed for bfqq, the inject limit does depend on
5256 * the think-time state (short|long). In particular, the limit
5257 * is 0 or 1 if the think time is deemed, respectively, as
5258 * short or long (details in the comments in
5259 * bfq_update_inject_limit()). Accordingly, the next
5260 * instructions reset the inject limit if the think-time state
5261 * has changed and the above base value is still to be
5262 * computed.
5263 *
5264 * However, the reset is performed only if more than 100 ms
5265 * have elapsed since the last update of the inject limit, or
5266 * (inclusive) if the change is from short to long think
5267 * time. The reason for this waiting is as follows.
5268 *
5269 * bfqq may have a long think time because of a
5270 * synchronization with some other queue, i.e., because the
5271 * I/O of some other queue may need to be completed for bfqq
13a857a4
PV
5272 * to receive new I/O. Details in the comments on the choice
5273 * of the queue for injection in bfq_select_queue().
766d6141 5274 *
13a857a4
PV
5275 * As stressed in those comments, if such a synchronization is
5276 * actually in place, then, without injection on bfqq, the
5277 * blocking I/O cannot happen to served while bfqq is in
5278 * service. As a consequence, if bfqq is granted
5279 * I/O-dispatch-plugging, then bfqq remains empty, and no I/O
5280 * is dispatched, until the idle timeout fires. This is likely
5281 * to result in lower bandwidth and higher latencies for bfqq,
5282 * and in a severe loss of total throughput.
766d6141
PV
5283 *
5284 * On the opposite end, a non-zero inject limit may allow the
5285 * I/O that blocks bfqq to be executed soon, and therefore
13a857a4
PV
5286 * bfqq to receive new I/O soon.
5287 *
5288 * But, if the blocking gets actually eliminated, then the
5289 * next think-time sample for bfqq may be very low. This in
5290 * turn may cause bfqq's think time to be deemed
5291 * short. Without the 100 ms barrier, this new state change
5292 * would cause the body of the next if to be executed
766d6141
PV
5293 * immediately. But this would set to 0 the inject
5294 * limit. Without injection, the blocking I/O would cause the
5295 * think time of bfqq to become long again, and therefore the
5296 * inject limit to be raised again, and so on. The only effect
5297 * of such a steady oscillation between the two think-time
5298 * states would be to prevent effective injection on bfqq.
5299 *
5300 * In contrast, if the inject limit is not reset during such a
5301 * long time interval as 100 ms, then the number of short
5302 * think time samples can grow significantly before the reset
13a857a4
PV
5303 * is performed. As a consequence, the think time state can
5304 * become stable before the reset. Therefore there will be no
5305 * state change when the 100 ms elapse, and no reset of the
5306 * inject limit. The inject limit remains steadily equal to 1
5307 * both during and after the 100 ms. So injection can be
766d6141
PV
5308 * performed at all times, and throughput gets boosted.
5309 *
5310 * An inject limit equal to 1 is however in conflict, in
5311 * general, with the fact that the think time of bfqq is
5312 * short, because injection may be likely to delay bfqq's I/O
5313 * (as explained in the comments in
5314 * bfq_update_inject_limit()). But this does not happen in
5315 * this special case, because bfqq's low think time is due to
5316 * an effective handling of a synchronization, through
5317 * injection. In this special case, bfqq's I/O does not get
5318 * delayed by injection; on the contrary, bfqq's I/O is
5319 * brought forward, because it is not blocked for
5320 * milliseconds.
5321 *
13a857a4
PV
5322 * In addition, serving the blocking I/O much sooner, and much
5323 * more frequently than once per I/O-plugging timeout, makes
5324 * it much quicker to detect a waker queue (the concept of
5325 * waker queue is defined in the comments in
5326 * bfq_add_request()). This makes it possible to start sooner
5327 * to boost throughput more effectively, by injecting the I/O
5328 * of the waker queue unconditionally on every
5329 * bfq_dispatch_request().
5330 *
5331 * One last, important benefit of not resetting the inject
5332 * limit before 100 ms is that, during this time interval, the
5333 * base value for the total service time is likely to get
5334 * finally computed for bfqq, freeing the inject limit from
5335 * its relation with the think time.
766d6141
PV
5336 */
5337 if (state_changed && bfqq->last_serv_time_ns == 0 &&
5338 (time_is_before_eq_jiffies(bfqq->decrease_time_jif +
5339 msecs_to_jiffies(100)) ||
5340 !has_short_ttime))
5341 bfq_reset_inject_limit(bfqd, bfqq);
aee69d78
PV
5342}
5343
5344/*
5345 * Called when a new fs request (rq) is added to bfqq. Check if there's
5346 * something we should do about it.
5347 */
5348static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq,
5349 struct request *rq)
5350{
aee69d78
PV
5351 if (rq->cmd_flags & REQ_META)
5352 bfqq->meta_pending++;
5353
aee69d78
PV
5354 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
5355
5356 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) {
5357 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 &&
5358 blk_rq_sectors(rq) < 32;
5359 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq);
5360
5361 /*
ac8b0cb4
PV
5362 * There is just this request queued: if
5363 * - the request is small, and
5364 * - we are idling to boost throughput, and
5365 * - the queue is not to be expired,
5366 * then just exit.
aee69d78
PV
5367 *
5368 * In this way, if the device is being idled to wait
5369 * for a new request from the in-service queue, we
5370 * avoid unplugging the device and committing the
ac8b0cb4
PV
5371 * device to serve just a small request. In contrast
5372 * we wait for the block layer to decide when to
5373 * unplug the device: hopefully, new requests will be
5374 * merged to this one quickly, then the device will be
5375 * unplugged and larger requests will be dispatched.
aee69d78 5376 */
ac8b0cb4
PV
5377 if (small_req && idling_boosts_thr_without_issues(bfqd, bfqq) &&
5378 !budget_timeout)
aee69d78
PV
5379 return;
5380
5381 /*
ac8b0cb4
PV
5382 * A large enough request arrived, or idling is being
5383 * performed to preserve service guarantees, or
5384 * finally the queue is to be expired: in all these
5385 * cases disk idling is to be stopped, so clear
5386 * wait_request flag and reset timer.
aee69d78
PV
5387 */
5388 bfq_clear_bfqq_wait_request(bfqq);
5389 hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
5390
5391 /*
5392 * The queue is not empty, because a new request just
5393 * arrived. Hence we can safely expire the queue, in
5394 * case of budget timeout, without risking that the
5395 * timestamps of the queue are not updated correctly.
5396 * See [1] for more details.
5397 */
5398 if (budget_timeout)
5399 bfq_bfqq_expire(bfqd, bfqq, false,
5400 BFQQE_BUDGET_TIMEOUT);
5401 }
5402}
5403
24bfd19b
PV
5404/* returns true if it causes the idle timer to be disabled */
5405static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq)
aee69d78 5406{
36eca894
AA
5407 struct bfq_queue *bfqq = RQ_BFQQ(rq),
5408 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true);
24bfd19b 5409 bool waiting, idle_timer_disabled = false;
36eca894
AA
5410
5411 if (new_bfqq) {
36eca894
AA
5412 /*
5413 * Release the request's reference to the old bfqq
5414 * and make sure one is taken to the shared queue.
5415 */
5416 new_bfqq->allocated++;
5417 bfqq->allocated--;
5418 new_bfqq->ref++;
5419 /*
5420 * If the bic associated with the process
5421 * issuing this request still points to bfqq
5422 * (and thus has not been already redirected
5423 * to new_bfqq or even some other bfq_queue),
5424 * then complete the merge and redirect it to
5425 * new_bfqq.
5426 */
5427 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq)
5428 bfq_merge_bfqqs(bfqd, RQ_BIC(rq),
5429 bfqq, new_bfqq);
894df937
PV
5430
5431 bfq_clear_bfqq_just_created(bfqq);
36eca894
AA
5432 /*
5433 * rq is about to be enqueued into new_bfqq,
5434 * release rq reference on bfqq
5435 */
5436 bfq_put_queue(bfqq);
5437 rq->elv.priv[1] = new_bfqq;
5438 bfqq = new_bfqq;
5439 }
aee69d78 5440
a3f9bce3
PV
5441 bfq_update_io_thinktime(bfqd, bfqq);
5442 bfq_update_has_short_ttime(bfqd, bfqq, RQ_BIC(rq));
5443 bfq_update_io_seektime(bfqd, bfqq, rq);
5444
24bfd19b 5445 waiting = bfqq && bfq_bfqq_wait_request(bfqq);
aee69d78 5446 bfq_add_request(rq);
24bfd19b 5447 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq);
aee69d78
PV
5448
5449 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)];
5450 list_add_tail(&rq->queuelist, &bfqq->fifo);
5451
5452 bfq_rq_enqueued(bfqd, bfqq, rq);
24bfd19b
PV
5453
5454 return idle_timer_disabled;
aee69d78
PV
5455}
5456
8060c47b 5457#ifdef CONFIG_BFQ_CGROUP_DEBUG
9b25bd03
PV
5458static void bfq_update_insert_stats(struct request_queue *q,
5459 struct bfq_queue *bfqq,
5460 bool idle_timer_disabled,
5461 unsigned int cmd_flags)
5462{
5463 if (!bfqq)
5464 return;
5465
5466 /*
5467 * bfqq still exists, because it can disappear only after
5468 * either it is merged with another queue, or the process it
5469 * is associated with exits. But both actions must be taken by
5470 * the same process currently executing this flow of
5471 * instructions.
5472 *
5473 * In addition, the following queue lock guarantees that
5474 * bfqq_group(bfqq) exists as well.
5475 */
0d945c1f 5476 spin_lock_irq(&q->queue_lock);
9b25bd03
PV
5477 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags);
5478 if (idle_timer_disabled)
5479 bfqg_stats_update_idle_time(bfqq_group(bfqq));
0d945c1f 5480 spin_unlock_irq(&q->queue_lock);
9b25bd03
PV
5481}
5482#else
5483static inline void bfq_update_insert_stats(struct request_queue *q,
5484 struct bfq_queue *bfqq,
5485 bool idle_timer_disabled,
5486 unsigned int cmd_flags) {}
8060c47b 5487#endif /* CONFIG_BFQ_CGROUP_DEBUG */
9b25bd03 5488
aee69d78
PV
5489static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
5490 bool at_head)
5491{
5492 struct request_queue *q = hctx->queue;
5493 struct bfq_data *bfqd = q->elevator->elevator_data;
18e5a57d 5494 struct bfq_queue *bfqq;
24bfd19b
PV
5495 bool idle_timer_disabled = false;
5496 unsigned int cmd_flags;
aee69d78 5497
fd41e603
TH
5498#ifdef CONFIG_BFQ_GROUP_IOSCHED
5499 if (!cgroup_subsys_on_dfl(io_cgrp_subsys) && rq->bio)
5500 bfqg_stats_update_legacy_io(q, rq);
5501#endif
aee69d78
PV
5502 spin_lock_irq(&bfqd->lock);
5503 if (blk_mq_sched_try_insert_merge(q, rq)) {
5504 spin_unlock_irq(&bfqd->lock);
5505 return;
5506 }
5507
5508 spin_unlock_irq(&bfqd->lock);
5509
5510 blk_mq_sched_request_inserted(rq);
5511
5512 spin_lock_irq(&bfqd->lock);
18e5a57d 5513 bfqq = bfq_init_rq(rq);
fd03177c 5514 if (!bfqq || at_head || blk_rq_is_passthrough(rq)) {
aee69d78
PV
5515 if (at_head)
5516 list_add(&rq->queuelist, &bfqd->dispatch);
5517 else
5518 list_add_tail(&rq->queuelist, &bfqd->dispatch);
fd03177c 5519 } else {
24bfd19b 5520 idle_timer_disabled = __bfq_insert_request(bfqd, rq);
614822f8
LM
5521 /*
5522 * Update bfqq, because, if a queue merge has occurred
5523 * in __bfq_insert_request, then rq has been
5524 * redirected into a new queue.
5525 */
5526 bfqq = RQ_BFQQ(rq);
aee69d78
PV
5527
5528 if (rq_mergeable(rq)) {
5529 elv_rqhash_add(q, rq);
5530 if (!q->last_merge)
5531 q->last_merge = rq;
5532 }
5533 }
5534
24bfd19b
PV
5535 /*
5536 * Cache cmd_flags before releasing scheduler lock, because rq
5537 * may disappear afterwards (for example, because of a request
5538 * merge).
5539 */
5540 cmd_flags = rq->cmd_flags;
9b25bd03 5541
6fa3e8d3 5542 spin_unlock_irq(&bfqd->lock);
24bfd19b 5543
9b25bd03
PV
5544 bfq_update_insert_stats(q, bfqq, idle_timer_disabled,
5545 cmd_flags);
aee69d78
PV
5546}
5547
5548static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx,
5549 struct list_head *list, bool at_head)
5550{
5551 while (!list_empty(list)) {
5552 struct request *rq;
5553
5554 rq = list_first_entry(list, struct request, queuelist);
5555 list_del_init(&rq->queuelist);
5556 bfq_insert_request(hctx, rq, at_head);
5557 }
5558}
5559
5560static void bfq_update_hw_tag(struct bfq_data *bfqd)
5561{
b3c34981
PV
5562 struct bfq_queue *bfqq = bfqd->in_service_queue;
5563
aee69d78
PV
5564 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver,
5565 bfqd->rq_in_driver);
5566
5567 if (bfqd->hw_tag == 1)
5568 return;
5569
5570 /*
5571 * This sample is valid if the number of outstanding requests
5572 * is large enough to allow a queueing behavior. Note that the
5573 * sum is not exact, as it's not taking into account deactivated
5574 * requests.
5575 */
a3c92560 5576 if (bfqd->rq_in_driver + bfqd->queued <= BFQ_HW_QUEUE_THRESHOLD)
aee69d78
PV
5577 return;
5578
b3c34981
PV
5579 /*
5580 * If active queue hasn't enough requests and can idle, bfq might not
5581 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
5582 * case
5583 */
5584 if (bfqq && bfq_bfqq_has_short_ttime(bfqq) &&
5585 bfqq->dispatched + bfqq->queued[0] + bfqq->queued[1] <
5586 BFQ_HW_QUEUE_THRESHOLD &&
5587 bfqd->rq_in_driver < BFQ_HW_QUEUE_THRESHOLD)
5588 return;
5589
aee69d78
PV
5590 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES)
5591 return;
5592
5593 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD;
5594 bfqd->max_rq_in_driver = 0;
5595 bfqd->hw_tag_samples = 0;
8cacc5ab
PV
5596
5597 bfqd->nonrot_with_queueing =
5598 blk_queue_nonrot(bfqd->queue) && bfqd->hw_tag;
aee69d78
PV
5599}
5600
5601static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd)
5602{
ab0e43e9
PV
5603 u64 now_ns;
5604 u32 delta_us;
5605
aee69d78
PV
5606 bfq_update_hw_tag(bfqd);
5607
5608 bfqd->rq_in_driver--;
5609 bfqq->dispatched--;
5610
44e44a1b
PV
5611 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) {
5612 /*
5613 * Set budget_timeout (which we overload to store the
5614 * time at which the queue remains with no backlog and
5615 * no outstanding request; used by the weight-raising
5616 * mechanism).
5617 */
5618 bfqq->budget_timeout = jiffies;
1de0c4cd 5619
0471559c 5620 bfq_weights_tree_remove(bfqd, bfqq);
44e44a1b
PV
5621 }
5622
ab0e43e9
PV
5623 now_ns = ktime_get_ns();
5624
5625 bfqq->ttime.last_end_request = now_ns;
5626
5627 /*
5628 * Using us instead of ns, to get a reasonable precision in
5629 * computing rate in next check.
5630 */
5631 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC);
5632
5633 /*
5634 * If the request took rather long to complete, and, according
5635 * to the maximum request size recorded, this completion latency
5636 * implies that the request was certainly served at a very low
5637 * rate (less than 1M sectors/sec), then the whole observation
5638 * interval that lasts up to this time instant cannot be a
5639 * valid time interval for computing a new peak rate. Invoke
5640 * bfq_update_rate_reset to have the following three steps
5641 * taken:
5642 * - close the observation interval at the last (previous)
5643 * request dispatch or completion
5644 * - compute rate, if possible, for that observation interval
5645 * - reset to zero samples, which will trigger a proper
5646 * re-initialization of the observation interval on next
5647 * dispatch
5648 */
5649 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC &&
5650 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us <
5651 1UL<<(BFQ_RATE_SHIFT - 10))
5652 bfq_update_rate_reset(bfqd, NULL);
5653 bfqd->last_completion = now_ns;
13a857a4 5654 bfqd->last_completed_rq_bfqq = bfqq;
aee69d78 5655
77b7dcea
PV
5656 /*
5657 * If we are waiting to discover whether the request pattern
5658 * of the task associated with the queue is actually
5659 * isochronous, and both requisites for this condition to hold
5660 * are now satisfied, then compute soft_rt_next_start (see the
5661 * comments on the function bfq_bfqq_softrt_next_start()). We
20cd3245
PV
5662 * do not compute soft_rt_next_start if bfqq is in interactive
5663 * weight raising (see the comments in bfq_bfqq_expire() for
5664 * an explanation). We schedule this delayed update when bfqq
5665 * expires, if it still has in-flight requests.
77b7dcea
PV
5666 */
5667 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 &&
20cd3245
PV
5668 RB_EMPTY_ROOT(&bfqq->sort_list) &&
5669 bfqq->wr_coeff != bfqd->bfq_wr_coeff)
77b7dcea
PV
5670 bfqq->soft_rt_next_start =
5671 bfq_bfqq_softrt_next_start(bfqd, bfqq);
5672
aee69d78
PV
5673 /*
5674 * If this is the in-service queue, check if it needs to be expired,
5675 * or if we want to idle in case it has no pending requests.
5676 */
5677 if (bfqd->in_service_queue == bfqq) {
4420b095
PV
5678 if (bfq_bfqq_must_idle(bfqq)) {
5679 if (bfqq->dispatched == 0)
5680 bfq_arm_slice_timer(bfqd);
5681 /*
5682 * If we get here, we do not expire bfqq, even
5683 * if bfqq was in budget timeout or had no
5684 * more requests (as controlled in the next
5685 * conditional instructions). The reason for
5686 * not expiring bfqq is as follows.
5687 *
5688 * Here bfqq->dispatched > 0 holds, but
5689 * bfq_bfqq_must_idle() returned true. This
5690 * implies that, even if no request arrives
5691 * for bfqq before bfqq->dispatched reaches 0,
5692 * bfqq will, however, not be expired on the
5693 * completion event that causes bfqq->dispatch
5694 * to reach zero. In contrast, on this event,
5695 * bfqq will start enjoying device idling
5696 * (I/O-dispatch plugging).
5697 *
5698 * But, if we expired bfqq here, bfqq would
5699 * not have the chance to enjoy device idling
5700 * when bfqq->dispatched finally reaches
5701 * zero. This would expose bfqq to violation
5702 * of its reserved service guarantees.
5703 */
aee69d78
PV
5704 return;
5705 } else if (bfq_may_expire_for_budg_timeout(bfqq))
5706 bfq_bfqq_expire(bfqd, bfqq, false,
5707 BFQQE_BUDGET_TIMEOUT);
5708 else if (RB_EMPTY_ROOT(&bfqq->sort_list) &&
5709 (bfqq->dispatched == 0 ||
277a4a9b 5710 !bfq_better_to_idle(bfqq)))
aee69d78
PV
5711 bfq_bfqq_expire(bfqd, bfqq, false,
5712 BFQQE_NO_MORE_REQUESTS);
5713 }
3f7cb4f4
HT
5714
5715 if (!bfqd->rq_in_driver)
5716 bfq_schedule_dispatch(bfqd);
aee69d78
PV
5717}
5718
a7877390 5719static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq)
aee69d78
PV
5720{
5721 bfqq->allocated--;
5722
5723 bfq_put_queue(bfqq);
5724}
5725
2341d662
PV
5726/*
5727 * The processes associated with bfqq may happen to generate their
5728 * cumulative I/O at a lower rate than the rate at which the device
5729 * could serve the same I/O. This is rather probable, e.g., if only
5730 * one process is associated with bfqq and the device is an SSD. It
5731 * results in bfqq becoming often empty while in service. In this
5732 * respect, if BFQ is allowed to switch to another queue when bfqq
5733 * remains empty, then the device goes on being fed with I/O requests,
5734 * and the throughput is not affected. In contrast, if BFQ is not
5735 * allowed to switch to another queue---because bfqq is sync and
5736 * I/O-dispatch needs to be plugged while bfqq is temporarily
5737 * empty---then, during the service of bfqq, there will be frequent
5738 * "service holes", i.e., time intervals during which bfqq gets empty
5739 * and the device can only consume the I/O already queued in its
5740 * hardware queues. During service holes, the device may even get to
5741 * remaining idle. In the end, during the service of bfqq, the device
5742 * is driven at a lower speed than the one it can reach with the kind
5743 * of I/O flowing through bfqq.
5744 *
5745 * To counter this loss of throughput, BFQ implements a "request
5746 * injection mechanism", which tries to fill the above service holes
5747 * with I/O requests taken from other queues. The hard part in this
5748 * mechanism is finding the right amount of I/O to inject, so as to
5749 * both boost throughput and not break bfqq's bandwidth and latency
5750 * guarantees. In this respect, the mechanism maintains a per-queue
5751 * inject limit, computed as below. While bfqq is empty, the injection
5752 * mechanism dispatches extra I/O requests only until the total number
5753 * of I/O requests in flight---i.e., already dispatched but not yet
5754 * completed---remains lower than this limit.
5755 *
5756 * A first definition comes in handy to introduce the algorithm by
5757 * which the inject limit is computed. We define as first request for
5758 * bfqq, an I/O request for bfqq that arrives while bfqq is in
5759 * service, and causes bfqq to switch from empty to non-empty. The
5760 * algorithm updates the limit as a function of the effect of
5761 * injection on the service times of only the first requests of
5762 * bfqq. The reason for this restriction is that these are the
5763 * requests whose service time is affected most, because they are the
5764 * first to arrive after injection possibly occurred.
5765 *
5766 * To evaluate the effect of injection, the algorithm measures the
5767 * "total service time" of first requests. We define as total service
5768 * time of an I/O request, the time that elapses since when the
5769 * request is enqueued into bfqq, to when it is completed. This
5770 * quantity allows the whole effect of injection to be measured. It is
5771 * easy to see why. Suppose that some requests of other queues are
5772 * actually injected while bfqq is empty, and that a new request R
5773 * then arrives for bfqq. If the device does start to serve all or
5774 * part of the injected requests during the service hole, then,
5775 * because of this extra service, it may delay the next invocation of
5776 * the dispatch hook of BFQ. Then, even after R gets eventually
5777 * dispatched, the device may delay the actual service of R if it is
5778 * still busy serving the extra requests, or if it decides to serve,
5779 * before R, some extra request still present in its queues. As a
5780 * conclusion, the cumulative extra delay caused by injection can be
5781 * easily evaluated by just comparing the total service time of first
5782 * requests with and without injection.
5783 *
5784 * The limit-update algorithm works as follows. On the arrival of a
5785 * first request of bfqq, the algorithm measures the total time of the
5786 * request only if one of the three cases below holds, and, for each
5787 * case, it updates the limit as described below:
5788 *
5789 * (1) If there is no in-flight request. This gives a baseline for the
5790 * total service time of the requests of bfqq. If the baseline has
5791 * not been computed yet, then, after computing it, the limit is
5792 * set to 1, to start boosting throughput, and to prepare the
5793 * ground for the next case. If the baseline has already been
5794 * computed, then it is updated, in case it results to be lower
5795 * than the previous value.
5796 *
5797 * (2) If the limit is higher than 0 and there are in-flight
5798 * requests. By comparing the total service time in this case with
5799 * the above baseline, it is possible to know at which extent the
5800 * current value of the limit is inflating the total service
5801 * time. If the inflation is below a certain threshold, then bfqq
5802 * is assumed to be suffering from no perceivable loss of its
5803 * service guarantees, and the limit is even tentatively
5804 * increased. If the inflation is above the threshold, then the
5805 * limit is decreased. Due to the lack of any hysteresis, this
5806 * logic makes the limit oscillate even in steady workload
5807 * conditions. Yet we opted for it, because it is fast in reaching
5808 * the best value for the limit, as a function of the current I/O
5809 * workload. To reduce oscillations, this step is disabled for a
5810 * short time interval after the limit happens to be decreased.
5811 *
5812 * (3) Periodically, after resetting the limit, to make sure that the
5813 * limit eventually drops in case the workload changes. This is
5814 * needed because, after the limit has gone safely up for a
5815 * certain workload, it is impossible to guess whether the
5816 * baseline total service time may have changed, without measuring
5817 * it again without injection. A more effective version of this
5818 * step might be to just sample the baseline, by interrupting
5819 * injection only once, and then to reset/lower the limit only if
5820 * the total service time with the current limit does happen to be
5821 * too large.
5822 *
5823 * More details on each step are provided in the comments on the
5824 * pieces of code that implement these steps: the branch handling the
5825 * transition from empty to non empty in bfq_add_request(), the branch
5826 * handling injection in bfq_select_queue(), and the function
5827 * bfq_choose_bfqq_for_injection(). These comments also explain some
5828 * exceptions, made by the injection mechanism in some special cases.
5829 */
5830static void bfq_update_inject_limit(struct bfq_data *bfqd,
5831 struct bfq_queue *bfqq)
5832{
5833 u64 tot_time_ns = ktime_get_ns() - bfqd->last_empty_occupied_ns;
5834 unsigned int old_limit = bfqq->inject_limit;
5835
23ed570a 5836 if (bfqq->last_serv_time_ns > 0 && bfqd->rqs_injected) {
2341d662
PV
5837 u64 threshold = (bfqq->last_serv_time_ns * 3)>>1;
5838
5839 if (tot_time_ns >= threshold && old_limit > 0) {
5840 bfqq->inject_limit--;
5841 bfqq->decrease_time_jif = jiffies;
5842 } else if (tot_time_ns < threshold &&
c1e0a182 5843 old_limit <= bfqd->max_rq_in_driver)
2341d662
PV
5844 bfqq->inject_limit++;
5845 }
5846
5847 /*
5848 * Either we still have to compute the base value for the
5849 * total service time, and there seem to be the right
5850 * conditions to do it, or we can lower the last base value
5851 * computed.
db599f9e
PV
5852 *
5853 * NOTE: (bfqd->rq_in_driver == 1) means that there is no I/O
5854 * request in flight, because this function is in the code
5855 * path that handles the completion of a request of bfqq, and,
5856 * in particular, this function is executed before
5857 * bfqd->rq_in_driver is decremented in such a code path.
2341d662 5858 */
db599f9e 5859 if ((bfqq->last_serv_time_ns == 0 && bfqd->rq_in_driver == 1) ||
2341d662 5860 tot_time_ns < bfqq->last_serv_time_ns) {
58494c98
PV
5861 if (bfqq->last_serv_time_ns == 0) {
5862 /*
5863 * Now we certainly have a base value: make sure we
5864 * start trying injection.
5865 */
5866 bfqq->inject_limit = max_t(unsigned int, 1, old_limit);
5867 }
2341d662 5868 bfqq->last_serv_time_ns = tot_time_ns;
24792ad0
PV
5869 } else if (!bfqd->rqs_injected && bfqd->rq_in_driver == 1)
5870 /*
5871 * No I/O injected and no request still in service in
5872 * the drive: these are the exact conditions for
5873 * computing the base value of the total service time
5874 * for bfqq. So let's update this value, because it is
5875 * rather variable. For example, it varies if the size
5876 * or the spatial locality of the I/O requests in bfqq
5877 * change.
5878 */
5879 bfqq->last_serv_time_ns = tot_time_ns;
5880
2341d662
PV
5881
5882 /* update complete, not waiting for any request completion any longer */
5883 bfqd->waited_rq = NULL;
23ed570a 5884 bfqd->rqs_injected = false;
2341d662
PV
5885}
5886
a7877390
PV
5887/*
5888 * Handle either a requeue or a finish for rq. The things to do are
5889 * the same in both cases: all references to rq are to be dropped. In
5890 * particular, rq is considered completed from the point of view of
5891 * the scheduler.
5892 */
5893static void bfq_finish_requeue_request(struct request *rq)
aee69d78 5894{
a7877390 5895 struct bfq_queue *bfqq = RQ_BFQQ(rq);
5bbf4e5a
CH
5896 struct bfq_data *bfqd;
5897
a7877390
PV
5898 /*
5899 * Requeue and finish hooks are invoked in blk-mq without
5900 * checking whether the involved request is actually still
5901 * referenced in the scheduler. To handle this fact, the
5902 * following two checks make this function exit in case of
5903 * spurious invocations, for which there is nothing to do.
5904 *
5905 * First, check whether rq has nothing to do with an elevator.
5906 */
5907 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV)))
5908 return;
5909
5910 /*
5911 * rq either is not associated with any icq, or is an already
5912 * requeued request that has not (yet) been re-inserted into
5913 * a bfq_queue.
5914 */
5915 if (!rq->elv.icq || !bfqq)
5bbf4e5a
CH
5916 return;
5917
5bbf4e5a 5918 bfqd = bfqq->bfqd;
aee69d78 5919
e21b7a0b
AA
5920 if (rq->rq_flags & RQF_STARTED)
5921 bfqg_stats_update_completion(bfqq_group(bfqq),
522a7775
OS
5922 rq->start_time_ns,
5923 rq->io_start_time_ns,
e21b7a0b 5924 rq->cmd_flags);
aee69d78
PV
5925
5926 if (likely(rq->rq_flags & RQF_STARTED)) {
5927 unsigned long flags;
5928
5929 spin_lock_irqsave(&bfqd->lock, flags);
5930
2341d662
PV
5931 if (rq == bfqd->waited_rq)
5932 bfq_update_inject_limit(bfqd, bfqq);
5933
aee69d78 5934 bfq_completed_request(bfqq, bfqd);
a7877390 5935 bfq_finish_requeue_request_body(bfqq);
aee69d78 5936
6fa3e8d3 5937 spin_unlock_irqrestore(&bfqd->lock, flags);
aee69d78
PV
5938 } else {
5939 /*
5940 * Request rq may be still/already in the scheduler,
a7877390
PV
5941 * in which case we need to remove it (this should
5942 * never happen in case of requeue). And we cannot
aee69d78
PV
5943 * defer such a check and removal, to avoid
5944 * inconsistencies in the time interval from the end
5945 * of this function to the start of the deferred work.
5946 * This situation seems to occur only in process
5947 * context, as a consequence of a merge. In the
5948 * current version of the code, this implies that the
5949 * lock is held.
5950 */
5951
614822f8 5952 if (!RB_EMPTY_NODE(&rq->rb_node)) {
7b9e9361 5953 bfq_remove_request(rq->q, rq);
614822f8
LM
5954 bfqg_stats_update_io_remove(bfqq_group(bfqq),
5955 rq->cmd_flags);
5956 }
a7877390 5957 bfq_finish_requeue_request_body(bfqq);
aee69d78
PV
5958 }
5959
a7877390
PV
5960 /*
5961 * Reset private fields. In case of a requeue, this allows
5962 * this function to correctly do nothing if it is spuriously
5963 * invoked again on this same request (see the check at the
5964 * beginning of the function). Probably, a better general
5965 * design would be to prevent blk-mq from invoking the requeue
5966 * or finish hooks of an elevator, for a request that is not
5967 * referred by that elevator.
5968 *
5969 * Resetting the following fields would break the
5970 * request-insertion logic if rq is re-inserted into a bfq
5971 * internal queue, without a re-preparation. Here we assume
5972 * that re-insertions of requeued requests, without
5973 * re-preparation, can happen only for pass_through or at_head
5974 * requests (which are not re-inserted into bfq internal
5975 * queues).
5976 */
aee69d78
PV
5977 rq->elv.priv[0] = NULL;
5978 rq->elv.priv[1] = NULL;
5979}
5980
36eca894
AA
5981/*
5982 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this
5983 * was the last process referring to that bfqq.
5984 */
5985static struct bfq_queue *
5986bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq)
5987{
5988 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue");
5989
5990 if (bfqq_process_refs(bfqq) == 1) {
5991 bfqq->pid = current->pid;
5992 bfq_clear_bfqq_coop(bfqq);
5993 bfq_clear_bfqq_split_coop(bfqq);
5994 return bfqq;
5995 }
5996
5997 bic_set_bfqq(bic, NULL, 1);
5998
5999 bfq_put_cooperator(bfqq);
6000
478de338 6001 bfq_release_process_ref(bfqq->bfqd, bfqq);
36eca894
AA
6002 return NULL;
6003}
6004
6005static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd,
6006 struct bfq_io_cq *bic,
6007 struct bio *bio,
6008 bool split, bool is_sync,
6009 bool *new_queue)
6010{
6011 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync);
6012
6013 if (likely(bfqq && bfqq != &bfqd->oom_bfqq))
6014 return bfqq;
6015
6016 if (new_queue)
6017 *new_queue = true;
6018
6019 if (bfqq)
6020 bfq_put_queue(bfqq);
6021 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic);
6022
6023 bic_set_bfqq(bic, bfqq, is_sync);
e1b2324d
AA
6024 if (split && is_sync) {
6025 if ((bic->was_in_burst_list && bfqd->large_burst) ||
6026 bic->saved_in_large_burst)
6027 bfq_mark_bfqq_in_large_burst(bfqq);
6028 else {
6029 bfq_clear_bfqq_in_large_burst(bfqq);
6030 if (bic->was_in_burst_list)
99fead8d
PV
6031 /*
6032 * If bfqq was in the current
6033 * burst list before being
6034 * merged, then we have to add
6035 * it back. And we do not need
6036 * to increase burst_size, as
6037 * we did not decrement
6038 * burst_size when we removed
6039 * bfqq from the burst list as
6040 * a consequence of a merge
6041 * (see comments in
6042 * bfq_put_queue). In this
6043 * respect, it would be rather
6044 * costly to know whether the
6045 * current burst list is still
6046 * the same burst list from
6047 * which bfqq was removed on
6048 * the merge. To avoid this
6049 * cost, if bfqq was in a
6050 * burst list, then we add
6051 * bfqq to the current burst
6052 * list without any further
6053 * check. This can cause
6054 * inappropriate insertions,
6055 * but rarely enough to not
6056 * harm the detection of large
6057 * bursts significantly.
6058 */
e1b2324d
AA
6059 hlist_add_head(&bfqq->burst_list_node,
6060 &bfqd->burst_list);
6061 }
36eca894 6062 bfqq->split_time = jiffies;
e1b2324d 6063 }
36eca894
AA
6064
6065 return bfqq;
6066}
6067
aee69d78 6068/*
18e5a57d
PV
6069 * Only reset private fields. The actual request preparation will be
6070 * performed by bfq_init_rq, when rq is either inserted or merged. See
6071 * comments on bfq_init_rq for the reason behind this delayed
6072 * preparation.
aee69d78 6073 */
5bbf4e5a 6074static void bfq_prepare_request(struct request *rq, struct bio *bio)
18e5a57d
PV
6075{
6076 /*
6077 * Regardless of whether we have an icq attached, we have to
6078 * clear the scheduler pointers, as they might point to
6079 * previously allocated bic/bfqq structs.
6080 */
6081 rq->elv.priv[0] = rq->elv.priv[1] = NULL;
6082}
6083
6084/*
6085 * If needed, init rq, allocate bfq data structures associated with
6086 * rq, and increment reference counters in the destination bfq_queue
6087 * for rq. Return the destination bfq_queue for rq, or NULL is rq is
6088 * not associated with any bfq_queue.
6089 *
6090 * This function is invoked by the functions that perform rq insertion
6091 * or merging. One may have expected the above preparation operations
6092 * to be performed in bfq_prepare_request, and not delayed to when rq
6093 * is inserted or merged. The rationale behind this delayed
6094 * preparation is that, after the prepare_request hook is invoked for
6095 * rq, rq may still be transformed into a request with no icq, i.e., a
6096 * request not associated with any queue. No bfq hook is invoked to
636b8fe8 6097 * signal this transformation. As a consequence, should these
18e5a57d
PV
6098 * preparation operations be performed when the prepare_request hook
6099 * is invoked, and should rq be transformed one moment later, bfq
6100 * would end up in an inconsistent state, because it would have
6101 * incremented some queue counters for an rq destined to
6102 * transformation, without any chance to correctly lower these
6103 * counters back. In contrast, no transformation can still happen for
6104 * rq after rq has been inserted or merged. So, it is safe to execute
6105 * these preparation operations when rq is finally inserted or merged.
6106 */
6107static struct bfq_queue *bfq_init_rq(struct request *rq)
aee69d78 6108{
5bbf4e5a 6109 struct request_queue *q = rq->q;
18e5a57d 6110 struct bio *bio = rq->bio;
aee69d78 6111 struct bfq_data *bfqd = q->elevator->elevator_data;
9f210738 6112 struct bfq_io_cq *bic;
aee69d78
PV
6113 const int is_sync = rq_is_sync(rq);
6114 struct bfq_queue *bfqq;
36eca894 6115 bool new_queue = false;
13c931bd 6116 bool bfqq_already_existing = false, split = false;
aee69d78 6117
18e5a57d
PV
6118 if (unlikely(!rq->elv.icq))
6119 return NULL;
6120
72961c4e 6121 /*
18e5a57d
PV
6122 * Assuming that elv.priv[1] is set only if everything is set
6123 * for this rq. This holds true, because this function is
6124 * invoked only for insertion or merging, and, after such
6125 * events, a request cannot be manipulated any longer before
6126 * being removed from bfq.
72961c4e 6127 */
18e5a57d
PV
6128 if (rq->elv.priv[1])
6129 return rq->elv.priv[1];
72961c4e 6130
9f210738 6131 bic = icq_to_bic(rq->elv.icq);
aee69d78 6132
8c9ff1ad
CIK
6133 bfq_check_ioprio_change(bic, bio);
6134
e21b7a0b
AA
6135 bfq_bic_update_cgroup(bic, bio);
6136
36eca894
AA
6137 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync,
6138 &new_queue);
6139
6140 if (likely(!new_queue)) {
6141 /* If the queue was seeky for too long, break it apart. */
6142 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq)) {
6143 bfq_log_bfqq(bfqd, bfqq, "breaking apart bfqq");
e1b2324d
AA
6144
6145 /* Update bic before losing reference to bfqq */
6146 if (bfq_bfqq_in_large_burst(bfqq))
6147 bic->saved_in_large_burst = true;
6148
36eca894 6149 bfqq = bfq_split_bfqq(bic, bfqq);
6fa3e8d3 6150 split = true;
36eca894
AA
6151
6152 if (!bfqq)
6153 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio,
6154 true, is_sync,
6155 NULL);
13c931bd
PV
6156 else
6157 bfqq_already_existing = true;
36eca894 6158 }
aee69d78
PV
6159 }
6160
6161 bfqq->allocated++;
6162 bfqq->ref++;
6163 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d",
6164 rq, bfqq, bfqq->ref);
6165
6166 rq->elv.priv[0] = bic;
6167 rq->elv.priv[1] = bfqq;
6168
36eca894
AA
6169 /*
6170 * If a bfq_queue has only one process reference, it is owned
6171 * by only this bic: we can then set bfqq->bic = bic. in
6172 * addition, if the queue has also just been split, we have to
6173 * resume its state.
6174 */
6175 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) {
6176 bfqq->bic = bic;
6fa3e8d3 6177 if (split) {
36eca894
AA
6178 /*
6179 * The queue has just been split from a shared
6180 * queue: restore the idle window and the
6181 * possible weight raising period.
6182 */
13c931bd
PV
6183 bfq_bfqq_resume_state(bfqq, bfqd, bic,
6184 bfqq_already_existing);
36eca894
AA
6185 }
6186 }
6187
84a74689
PV
6188 /*
6189 * Consider bfqq as possibly belonging to a burst of newly
6190 * created queues only if:
6191 * 1) A burst is actually happening (bfqd->burst_size > 0)
6192 * or
6193 * 2) There is no other active queue. In fact, if, in
6194 * contrast, there are active queues not belonging to the
6195 * possible burst bfqq may belong to, then there is no gain
6196 * in considering bfqq as belonging to a burst, and
6197 * therefore in not weight-raising bfqq. See comments on
6198 * bfq_handle_burst().
6199 *
6200 * This filtering also helps eliminating false positives,
6201 * occurring when bfqq does not belong to an actual large
6202 * burst, but some background task (e.g., a service) happens
6203 * to trigger the creation of new queues very close to when
6204 * bfqq and its possible companion queues are created. See
6205 * comments on bfq_handle_burst() for further details also on
6206 * this issue.
6207 */
6208 if (unlikely(bfq_bfqq_just_created(bfqq) &&
6209 (bfqd->burst_size > 0 ||
6210 bfq_tot_busy_queues(bfqd) == 0)))
e1b2324d
AA
6211 bfq_handle_burst(bfqd, bfqq);
6212
18e5a57d 6213 return bfqq;
aee69d78
PV
6214}
6215
6216static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq)
6217{
6218 struct bfq_data *bfqd = bfqq->bfqd;
6219 enum bfqq_expiration reason;
6220 unsigned long flags;
6221
6222 spin_lock_irqsave(&bfqd->lock, flags);
6223 bfq_clear_bfqq_wait_request(bfqq);
6224
6225 if (bfqq != bfqd->in_service_queue) {
6226 spin_unlock_irqrestore(&bfqd->lock, flags);
6227 return;
6228 }
6229
6230 if (bfq_bfqq_budget_timeout(bfqq))
6231 /*
6232 * Also here the queue can be safely expired
6233 * for budget timeout without wasting
6234 * guarantees
6235 */
6236 reason = BFQQE_BUDGET_TIMEOUT;
6237 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0)
6238 /*
6239 * The queue may not be empty upon timer expiration,
6240 * because we may not disable the timer when the
6241 * first request of the in-service queue arrives
6242 * during disk idling.
6243 */
6244 reason = BFQQE_TOO_IDLE;
6245 else
6246 goto schedule_dispatch;
6247
6248 bfq_bfqq_expire(bfqd, bfqq, true, reason);
6249
6250schedule_dispatch:
6fa3e8d3 6251 spin_unlock_irqrestore(&bfqd->lock, flags);
aee69d78
PV
6252 bfq_schedule_dispatch(bfqd);
6253}
6254
6255/*
6256 * Handler of the expiration of the timer running if the in-service queue
6257 * is idling inside its time slice.
6258 */
6259static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer)
6260{
6261 struct bfq_data *bfqd = container_of(timer, struct bfq_data,
6262 idle_slice_timer);
6263 struct bfq_queue *bfqq = bfqd->in_service_queue;
6264
6265 /*
6266 * Theoretical race here: the in-service queue can be NULL or
6267 * different from the queue that was idling if a new request
6268 * arrives for the current queue and there is a full dispatch
6269 * cycle that changes the in-service queue. This can hardly
6270 * happen, but in the worst case we just expire a queue too
6271 * early.
6272 */
6273 if (bfqq)
6274 bfq_idle_slice_timer_body(bfqq);
6275
6276 return HRTIMER_NORESTART;
6277}
6278
6279static void __bfq_put_async_bfqq(struct bfq_data *bfqd,
6280 struct bfq_queue **bfqq_ptr)
6281{
6282 struct bfq_queue *bfqq = *bfqq_ptr;
6283
6284 bfq_log(bfqd, "put_async_bfqq: %p", bfqq);
6285 if (bfqq) {
e21b7a0b
AA
6286 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group);
6287
aee69d78
PV
6288 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d",
6289 bfqq, bfqq->ref);
6290 bfq_put_queue(bfqq);
6291 *bfqq_ptr = NULL;
6292 }
6293}
6294
6295/*
e21b7a0b
AA
6296 * Release all the bfqg references to its async queues. If we are
6297 * deallocating the group these queues may still contain requests, so
6298 * we reparent them to the root cgroup (i.e., the only one that will
6299 * exist for sure until all the requests on a device are gone).
aee69d78 6300 */
ea25da48 6301void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg)
aee69d78
PV
6302{
6303 int i, j;
6304
6305 for (i = 0; i < 2; i++)
6306 for (j = 0; j < IOPRIO_BE_NR; j++)
e21b7a0b 6307 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]);
aee69d78 6308
e21b7a0b 6309 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq);
aee69d78
PV
6310}
6311
f0635b8a
JA
6312/*
6313 * See the comments on bfq_limit_depth for the purpose of
483b7bf2 6314 * the depths set in the function. Return minimum shallow depth we'll use.
f0635b8a 6315 */
483b7bf2
JA
6316static unsigned int bfq_update_depths(struct bfq_data *bfqd,
6317 struct sbitmap_queue *bt)
f0635b8a 6318{
483b7bf2
JA
6319 unsigned int i, j, min_shallow = UINT_MAX;
6320
f0635b8a
JA
6321 /*
6322 * In-word depths if no bfq_queue is being weight-raised:
6323 * leaving 25% of tags only for sync reads.
6324 *
6325 * In next formulas, right-shift the value
bd7d4ef6
JA
6326 * (1U<<bt->sb.shift), instead of computing directly
6327 * (1U<<(bt->sb.shift - something)), to be robust against
6328 * any possible value of bt->sb.shift, without having to
f0635b8a
JA
6329 * limit 'something'.
6330 */
6331 /* no more than 50% of tags for async I/O */
bd7d4ef6 6332 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U);
f0635b8a
JA
6333 /*
6334 * no more than 75% of tags for sync writes (25% extra tags
6335 * w.r.t. async I/O, to prevent async I/O from starving sync
6336 * writes)
6337 */
bd7d4ef6 6338 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U);
f0635b8a
JA
6339
6340 /*
6341 * In-word depths in case some bfq_queue is being weight-
6342 * raised: leaving ~63% of tags for sync reads. This is the
6343 * highest percentage for which, in our tests, application
6344 * start-up times didn't suffer from any regression due to tag
6345 * shortage.
6346 */
6347 /* no more than ~18% of tags for async I/O */
bd7d4ef6 6348 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U);
f0635b8a 6349 /* no more than ~37% of tags for sync writes (~20% extra tags) */
bd7d4ef6 6350 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U);
483b7bf2
JA
6351
6352 for (i = 0; i < 2; i++)
6353 for (j = 0; j < 2; j++)
6354 min_shallow = min(min_shallow, bfqd->word_depths[i][j]);
6355
6356 return min_shallow;
f0635b8a
JA
6357}
6358
77f1e0a5 6359static void bfq_depth_updated(struct blk_mq_hw_ctx *hctx)
f0635b8a
JA
6360{
6361 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data;
6362 struct blk_mq_tags *tags = hctx->sched_tags;
483b7bf2 6363 unsigned int min_shallow;
f0635b8a 6364
483b7bf2
JA
6365 min_shallow = bfq_update_depths(bfqd, &tags->bitmap_tags);
6366 sbitmap_queue_min_shallow_depth(&tags->bitmap_tags, min_shallow);
77f1e0a5
JA
6367}
6368
6369static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index)
6370{
6371 bfq_depth_updated(hctx);
f0635b8a
JA
6372 return 0;
6373}
6374
aee69d78
PV
6375static void bfq_exit_queue(struct elevator_queue *e)
6376{
6377 struct bfq_data *bfqd = e->elevator_data;
6378 struct bfq_queue *bfqq, *n;
6379
6380 hrtimer_cancel(&bfqd->idle_slice_timer);
6381
6382 spin_lock_irq(&bfqd->lock);
6383 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list)
e21b7a0b 6384 bfq_deactivate_bfqq(bfqd, bfqq, false, false);
aee69d78
PV
6385 spin_unlock_irq(&bfqd->lock);
6386
6387 hrtimer_cancel(&bfqd->idle_slice_timer);
6388
0d52af59
PV
6389 /* release oom-queue reference to root group */
6390 bfqg_and_blkg_put(bfqd->root_group);
6391
4d8340d0 6392#ifdef CONFIG_BFQ_GROUP_IOSCHED
e21b7a0b
AA
6393 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq);
6394#else
6395 spin_lock_irq(&bfqd->lock);
6396 bfq_put_async_queues(bfqd, bfqd->root_group);
6397 kfree(bfqd->root_group);
6398 spin_unlock_irq(&bfqd->lock);
6399#endif
6400
aee69d78
PV
6401 kfree(bfqd);
6402}
6403
e21b7a0b
AA
6404static void bfq_init_root_group(struct bfq_group *root_group,
6405 struct bfq_data *bfqd)
6406{
6407 int i;
6408
6409#ifdef CONFIG_BFQ_GROUP_IOSCHED
6410 root_group->entity.parent = NULL;
6411 root_group->my_entity = NULL;
6412 root_group->bfqd = bfqd;
6413#endif
36eca894 6414 root_group->rq_pos_tree = RB_ROOT;
e21b7a0b
AA
6415 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++)
6416 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT;
6417 root_group->sched_data.bfq_class_idle_last_service = jiffies;
6418}
6419
aee69d78
PV
6420static int bfq_init_queue(struct request_queue *q, struct elevator_type *e)
6421{
6422 struct bfq_data *bfqd;
6423 struct elevator_queue *eq;
aee69d78
PV
6424
6425 eq = elevator_alloc(q, e);
6426 if (!eq)
6427 return -ENOMEM;
6428
6429 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node);
6430 if (!bfqd) {
6431 kobject_put(&eq->kobj);
6432 return -ENOMEM;
6433 }
6434 eq->elevator_data = bfqd;
6435
0d945c1f 6436 spin_lock_irq(&q->queue_lock);
e21b7a0b 6437 q->elevator = eq;
0d945c1f 6438 spin_unlock_irq(&q->queue_lock);
e21b7a0b 6439
aee69d78
PV
6440 /*
6441 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues.
6442 * Grab a permanent reference to it, so that the normal code flow
6443 * will not attempt to free it.
6444 */
6445 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0);
6446 bfqd->oom_bfqq.ref++;
6447 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO;
6448 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE;
6449 bfqd->oom_bfqq.entity.new_weight =
6450 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio);
e1b2324d
AA
6451
6452 /* oom_bfqq does not participate to bursts */
6453 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq);
6454
aee69d78
PV
6455 /*
6456 * Trigger weight initialization, according to ioprio, at the
6457 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio
6458 * class won't be changed any more.
6459 */
6460 bfqd->oom_bfqq.entity.prio_changed = 1;
6461
6462 bfqd->queue = q;
6463
e21b7a0b 6464 INIT_LIST_HEAD(&bfqd->dispatch);
aee69d78
PV
6465
6466 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC,
6467 HRTIMER_MODE_REL);
6468 bfqd->idle_slice_timer.function = bfq_idle_slice_timer;
6469
fb53ac6c 6470 bfqd->queue_weights_tree = RB_ROOT_CACHED;
ba7aeae5 6471 bfqd->num_groups_with_pending_reqs = 0;
1de0c4cd 6472
aee69d78
PV
6473 INIT_LIST_HEAD(&bfqd->active_list);
6474 INIT_LIST_HEAD(&bfqd->idle_list);
e1b2324d 6475 INIT_HLIST_HEAD(&bfqd->burst_list);
aee69d78
PV
6476
6477 bfqd->hw_tag = -1;
8cacc5ab 6478 bfqd->nonrot_with_queueing = blk_queue_nonrot(bfqd->queue);
aee69d78
PV
6479
6480 bfqd->bfq_max_budget = bfq_default_max_budget;
6481
6482 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0];
6483 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1];
6484 bfqd->bfq_back_max = bfq_back_max;
6485 bfqd->bfq_back_penalty = bfq_back_penalty;
6486 bfqd->bfq_slice_idle = bfq_slice_idle;
aee69d78
PV
6487 bfqd->bfq_timeout = bfq_timeout;
6488
6489 bfqd->bfq_requests_within_timer = 120;
6490
e1b2324d
AA
6491 bfqd->bfq_large_burst_thresh = 8;
6492 bfqd->bfq_burst_interval = msecs_to_jiffies(180);
6493
44e44a1b
PV
6494 bfqd->low_latency = true;
6495
6496 /*
6497 * Trade-off between responsiveness and fairness.
6498 */
6499 bfqd->bfq_wr_coeff = 30;
77b7dcea 6500 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300);
44e44a1b
PV
6501 bfqd->bfq_wr_max_time = 0;
6502 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000);
6503 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500);
77b7dcea
PV
6504 bfqd->bfq_wr_max_softrt_rate = 7000; /*
6505 * Approximate rate required
6506 * to playback or record a
6507 * high-definition compressed
6508 * video.
6509 */
cfd69712 6510 bfqd->wr_busy_queues = 0;
44e44a1b
PV
6511
6512 /*
e24f1c24
PV
6513 * Begin by assuming, optimistically, that the device peak
6514 * rate is equal to 2/3 of the highest reference rate.
44e44a1b 6515 */
e24f1c24
PV
6516 bfqd->rate_dur_prod = ref_rate[blk_queue_nonrot(bfqd->queue)] *
6517 ref_wr_duration[blk_queue_nonrot(bfqd->queue)];
6518 bfqd->peak_rate = ref_rate[blk_queue_nonrot(bfqd->queue)] * 2 / 3;
44e44a1b 6519
aee69d78 6520 spin_lock_init(&bfqd->lock);
aee69d78 6521
e21b7a0b
AA
6522 /*
6523 * The invocation of the next bfq_create_group_hierarchy
6524 * function is the head of a chain of function calls
6525 * (bfq_create_group_hierarchy->blkcg_activate_policy->
6526 * blk_mq_freeze_queue) that may lead to the invocation of the
6527 * has_work hook function. For this reason,
6528 * bfq_create_group_hierarchy is invoked only after all
6529 * scheduler data has been initialized, apart from the fields
6530 * that can be initialized only after invoking
6531 * bfq_create_group_hierarchy. This, in particular, enables
6532 * has_work to correctly return false. Of course, to avoid
6533 * other inconsistencies, the blk-mq stack must then refrain
6534 * from invoking further scheduler hooks before this init
6535 * function is finished.
6536 */
6537 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node);
6538 if (!bfqd->root_group)
6539 goto out_free;
6540 bfq_init_root_group(bfqd->root_group, bfqd);
6541 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group);
6542
b5dc5d4d 6543 wbt_disable_default(q);
aee69d78 6544 return 0;
e21b7a0b
AA
6545
6546out_free:
6547 kfree(bfqd);
6548 kobject_put(&eq->kobj);
6549 return -ENOMEM;
aee69d78
PV
6550}
6551
6552static void bfq_slab_kill(void)
6553{
6554 kmem_cache_destroy(bfq_pool);
6555}
6556
6557static int __init bfq_slab_setup(void)
6558{
6559 bfq_pool = KMEM_CACHE(bfq_queue, 0);
6560 if (!bfq_pool)
6561 return -ENOMEM;
6562 return 0;
6563}
6564
6565static ssize_t bfq_var_show(unsigned int var, char *page)
6566{
6567 return sprintf(page, "%u\n", var);
6568}
6569
2f79136b 6570static int bfq_var_store(unsigned long *var, const char *page)
aee69d78
PV
6571{
6572 unsigned long new_val;
6573 int ret = kstrtoul(page, 10, &new_val);
6574
2f79136b
BVA
6575 if (ret)
6576 return ret;
6577 *var = new_val;
6578 return 0;
aee69d78
PV
6579}
6580
6581#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
6582static ssize_t __FUNC(struct elevator_queue *e, char *page) \
6583{ \
6584 struct bfq_data *bfqd = e->elevator_data; \
6585 u64 __data = __VAR; \
6586 if (__CONV == 1) \
6587 __data = jiffies_to_msecs(__data); \
6588 else if (__CONV == 2) \
6589 __data = div_u64(__data, NSEC_PER_MSEC); \
6590 return bfq_var_show(__data, (page)); \
6591}
6592SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2);
6593SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2);
6594SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0);
6595SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0);
6596SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2);
6597SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0);
6598SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1);
6599SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0);
44e44a1b 6600SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0);
aee69d78
PV
6601#undef SHOW_FUNCTION
6602
6603#define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
6604static ssize_t __FUNC(struct elevator_queue *e, char *page) \
6605{ \
6606 struct bfq_data *bfqd = e->elevator_data; \
6607 u64 __data = __VAR; \
6608 __data = div_u64(__data, NSEC_PER_USEC); \
6609 return bfq_var_show(__data, (page)); \
6610}
6611USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle);
6612#undef USEC_SHOW_FUNCTION
6613
6614#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
6615static ssize_t \
6616__FUNC(struct elevator_queue *e, const char *page, size_t count) \
6617{ \
6618 struct bfq_data *bfqd = e->elevator_data; \
1530486c 6619 unsigned long __data, __min = (MIN), __max = (MAX); \
2f79136b
BVA
6620 int ret; \
6621 \
6622 ret = bfq_var_store(&__data, (page)); \
6623 if (ret) \
6624 return ret; \
1530486c
BVA
6625 if (__data < __min) \
6626 __data = __min; \
6627 else if (__data > __max) \
6628 __data = __max; \
aee69d78
PV
6629 if (__CONV == 1) \
6630 *(__PTR) = msecs_to_jiffies(__data); \
6631 else if (__CONV == 2) \
6632 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
6633 else \
6634 *(__PTR) = __data; \
235f8da1 6635 return count; \
aee69d78
PV
6636}
6637STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1,
6638 INT_MAX, 2);
6639STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1,
6640 INT_MAX, 2);
6641STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0);
6642STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1,
6643 INT_MAX, 0);
6644STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2);
6645#undef STORE_FUNCTION
6646
6647#define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
6648static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\
6649{ \
6650 struct bfq_data *bfqd = e->elevator_data; \
1530486c 6651 unsigned long __data, __min = (MIN), __max = (MAX); \
2f79136b
BVA
6652 int ret; \
6653 \
6654 ret = bfq_var_store(&__data, (page)); \
6655 if (ret) \
6656 return ret; \
1530486c
BVA
6657 if (__data < __min) \
6658 __data = __min; \
6659 else if (__data > __max) \
6660 __data = __max; \
aee69d78 6661 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
235f8da1 6662 return count; \
aee69d78
PV
6663}
6664USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0,
6665 UINT_MAX);
6666#undef USEC_STORE_FUNCTION
6667
aee69d78
PV
6668static ssize_t bfq_max_budget_store(struct elevator_queue *e,
6669 const char *page, size_t count)
6670{
6671 struct bfq_data *bfqd = e->elevator_data;
2f79136b
BVA
6672 unsigned long __data;
6673 int ret;
235f8da1 6674
2f79136b
BVA
6675 ret = bfq_var_store(&__data, (page));
6676 if (ret)
6677 return ret;
aee69d78
PV
6678
6679 if (__data == 0)
ab0e43e9 6680 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
aee69d78
PV
6681 else {
6682 if (__data > INT_MAX)
6683 __data = INT_MAX;
6684 bfqd->bfq_max_budget = __data;
6685 }
6686
6687 bfqd->bfq_user_max_budget = __data;
6688
235f8da1 6689 return count;
aee69d78
PV
6690}
6691
6692/*
6693 * Leaving this name to preserve name compatibility with cfq
6694 * parameters, but this timeout is used for both sync and async.
6695 */
6696static ssize_t bfq_timeout_sync_store(struct elevator_queue *e,
6697 const char *page, size_t count)
6698{
6699 struct bfq_data *bfqd = e->elevator_data;
2f79136b
BVA
6700 unsigned long __data;
6701 int ret;
235f8da1 6702
2f79136b
BVA
6703 ret = bfq_var_store(&__data, (page));
6704 if (ret)
6705 return ret;
aee69d78
PV
6706
6707 if (__data < 1)
6708 __data = 1;
6709 else if (__data > INT_MAX)
6710 __data = INT_MAX;
6711
6712 bfqd->bfq_timeout = msecs_to_jiffies(__data);
6713 if (bfqd->bfq_user_max_budget == 0)
ab0e43e9 6714 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd);
aee69d78 6715
235f8da1 6716 return count;
aee69d78
PV
6717}
6718
6719static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e,
6720 const char *page, size_t count)
6721{
6722 struct bfq_data *bfqd = e->elevator_data;
2f79136b
BVA
6723 unsigned long __data;
6724 int ret;
235f8da1 6725
2f79136b
BVA
6726 ret = bfq_var_store(&__data, (page));
6727 if (ret)
6728 return ret;
aee69d78
PV
6729
6730 if (__data > 1)
6731 __data = 1;
6732 if (!bfqd->strict_guarantees && __data == 1
6733 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC)
6734 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC;
6735
6736 bfqd->strict_guarantees = __data;
6737
235f8da1 6738 return count;
aee69d78
PV
6739}
6740
44e44a1b
PV
6741static ssize_t bfq_low_latency_store(struct elevator_queue *e,
6742 const char *page, size_t count)
6743{
6744 struct bfq_data *bfqd = e->elevator_data;
2f79136b
BVA
6745 unsigned long __data;
6746 int ret;
235f8da1 6747
2f79136b
BVA
6748 ret = bfq_var_store(&__data, (page));
6749 if (ret)
6750 return ret;
44e44a1b
PV
6751
6752 if (__data > 1)
6753 __data = 1;
6754 if (__data == 0 && bfqd->low_latency != 0)
6755 bfq_end_wr(bfqd);
6756 bfqd->low_latency = __data;
6757
235f8da1 6758 return count;
44e44a1b
PV
6759}
6760
aee69d78
PV
6761#define BFQ_ATTR(name) \
6762 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store)
6763
6764static struct elv_fs_entry bfq_attrs[] = {
6765 BFQ_ATTR(fifo_expire_sync),
6766 BFQ_ATTR(fifo_expire_async),
6767 BFQ_ATTR(back_seek_max),
6768 BFQ_ATTR(back_seek_penalty),
6769 BFQ_ATTR(slice_idle),
6770 BFQ_ATTR(slice_idle_us),
6771 BFQ_ATTR(max_budget),
6772 BFQ_ATTR(timeout_sync),
6773 BFQ_ATTR(strict_guarantees),
44e44a1b 6774 BFQ_ATTR(low_latency),
aee69d78
PV
6775 __ATTR_NULL
6776};
6777
6778static struct elevator_type iosched_bfq_mq = {
f9cd4bfe 6779 .ops = {
a52a69ea 6780 .limit_depth = bfq_limit_depth,
5bbf4e5a 6781 .prepare_request = bfq_prepare_request,
a7877390
PV
6782 .requeue_request = bfq_finish_requeue_request,
6783 .finish_request = bfq_finish_requeue_request,
aee69d78
PV
6784 .exit_icq = bfq_exit_icq,
6785 .insert_requests = bfq_insert_requests,
6786 .dispatch_request = bfq_dispatch_request,
6787 .next_request = elv_rb_latter_request,
6788 .former_request = elv_rb_former_request,
6789 .allow_merge = bfq_allow_bio_merge,
6790 .bio_merge = bfq_bio_merge,
6791 .request_merge = bfq_request_merge,
6792 .requests_merged = bfq_requests_merged,
6793 .request_merged = bfq_request_merged,
6794 .has_work = bfq_has_work,
77f1e0a5 6795 .depth_updated = bfq_depth_updated,
f0635b8a 6796 .init_hctx = bfq_init_hctx,
aee69d78
PV
6797 .init_sched = bfq_init_queue,
6798 .exit_sched = bfq_exit_queue,
6799 },
6800
aee69d78
PV
6801 .icq_size = sizeof(struct bfq_io_cq),
6802 .icq_align = __alignof__(struct bfq_io_cq),
6803 .elevator_attrs = bfq_attrs,
6804 .elevator_name = "bfq",
6805 .elevator_owner = THIS_MODULE,
6806};
26b4cf24 6807MODULE_ALIAS("bfq-iosched");
aee69d78
PV
6808
6809static int __init bfq_init(void)
6810{
6811 int ret;
6812
e21b7a0b
AA
6813#ifdef CONFIG_BFQ_GROUP_IOSCHED
6814 ret = blkcg_policy_register(&blkcg_policy_bfq);
6815 if (ret)
6816 return ret;
6817#endif
6818
aee69d78
PV
6819 ret = -ENOMEM;
6820 if (bfq_slab_setup())
6821 goto err_pol_unreg;
6822
44e44a1b
PV
6823 /*
6824 * Times to load large popular applications for the typical
6825 * systems installed on the reference devices (see the
e24f1c24
PV
6826 * comments before the definition of the next
6827 * array). Actually, we use slightly lower values, as the
44e44a1b
PV
6828 * estimated peak rate tends to be smaller than the actual
6829 * peak rate. The reason for this last fact is that estimates
6830 * are computed over much shorter time intervals than the long
6831 * intervals typically used for benchmarking. Why? First, to
6832 * adapt more quickly to variations. Second, because an I/O
6833 * scheduler cannot rely on a peak-rate-evaluation workload to
6834 * be run for a long time.
6835 */
e24f1c24
PV
6836 ref_wr_duration[0] = msecs_to_jiffies(7000); /* actually 8 sec */
6837 ref_wr_duration[1] = msecs_to_jiffies(2500); /* actually 3 sec */
44e44a1b 6838
aee69d78
PV
6839 ret = elv_register(&iosched_bfq_mq);
6840 if (ret)
37dcd657 6841 goto slab_kill;
aee69d78
PV
6842
6843 return 0;
6844
37dcd657 6845slab_kill:
6846 bfq_slab_kill();
aee69d78 6847err_pol_unreg:
e21b7a0b
AA
6848#ifdef CONFIG_BFQ_GROUP_IOSCHED
6849 blkcg_policy_unregister(&blkcg_policy_bfq);
6850#endif
aee69d78
PV
6851 return ret;
6852}
6853
6854static void __exit bfq_exit(void)
6855{
6856 elv_unregister(&iosched_bfq_mq);
e21b7a0b
AA
6857#ifdef CONFIG_BFQ_GROUP_IOSCHED
6858 blkcg_policy_unregister(&blkcg_policy_bfq);
6859#endif
aee69d78
PV
6860 bfq_slab_kill();
6861}
6862
6863module_init(bfq_init);
6864module_exit(bfq_exit);
6865
6866MODULE_AUTHOR("Paolo Valente");
6867MODULE_LICENSE("GPL");
6868MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler");